flutter_agent_harness library

Cross-platform AI agent harness for Dart and Flutter.

Ported architecture of pi-mono (packages/ai + packages/agent): streaming provider adapters with an errors-as-events contract, an agent loop with native tool calling, JSONL session persistence, and context compaction. See GOAL.md for the full roadmap.

Classes

A2aArtifact
A task artifact (output).
A2aClient
An A2A client: discovers agents, sends messages, streams responses, and manages task lifecycles — all over injectable package:http.
A2aMailEnvelope
One fabric-mail envelope over the A2A wire.
A2aMailGateway
Delivers fabric mail across machines through the configured A2A servers.
A2aMessage
A message in an A2A task.
A2aPart
A message part: text or structured data.
A2aRequestHandler
A transport-agnostic A2A request handler. Each incoming JSON-RPC request is dispatched to runner; the task state is tracked in-memory keyed by task id. When mailSink is set, message/send requests carrying the faMailMetadataKey metadata are fabric mail (issue #27 phase 3): the envelope is deposited via the sink and the task completes with the ack — the runner is never invoked.
A2aTask
A2A Task: a stateful unit of work with messages and artifacts.
ActiveToolsChangeRecord
Records a change of the active tool set.
AfterToolCallContext
Context passed to AfterToolCallHook.
AfterToolCallResult
Partial override returned from AfterToolCallHook.
Agent
Agent owns the current transcript, emits lifecycle events, executes tools, and exposes queueing APIs for steering and follow-up messages. Port of pi's Agent.
AgentCapability
One announced capability in the discovery surface (issue #27 phase 2): a namespaced string (yoclip.render) plus an optional short description and payload hint. Discovery metadata only — invocation stays a plain DM; nothing here routes or invokes anything.
AgentCard
The capabilities an A2A agent advertises in its Agent Card.
AgentCli
The CLI harness: agent + built-in tools + session persistence + compaction, driven by a CliIO.
AgentCliConfig
One DAP/1 hub snapshot shared with the app (DapHubSnapshot in src/dap/dap_hub_snapshot.dart): the live probe outcome (connected, agentId) plus the resolved config url and agent name (env > .fah/packages.yaml hub: > ~/.dap/config.json > defaults — resolved by the host through the hub client package, so lib/ stays dart:io-free). connected false means the hub plugin is not connected right now. Static configuration for an AgentCli session.
AgentCliExtState
Per-instance state of the JS-extension wiring (extensions cannot add fields; AgentCli holds exactly this one object).
AgentCliMcpWiring
Owns the MCP connection pool (null when no mcp: config was provided), the names of the currently registered MCP tools, and the re-registration flow (mirrors the checkpoint-tools registration pattern: registry first, then the agent's tool list).
AgentEndEvent
The loop finished. Always the last event; carries every message produced by this run (prompts included for agentLoop, excluded for agentLoopContinue).
AgentEvent
Events emitted by the agent loop.
AgentEventStream
The event stream returned by agentLoop and agentLoopContinue.
AgentLoopConfig
Configuration for one agent loop run.
AgentLoopTurnUpdate
Replacement runtime state used by the loop before another provider request. Ported subset of pi's AgentLoopTurnUpdate (no thinkingLevel: reasoning levels are not ported yet).
AgentMessage
One message between two agents.
AgentMode
A system-prompt mode for the CLI (e.g. /architect, /code, /review).
AgentOutputManager
Manages agent output id allocation to ensure uniqueness (port of omp's AgentOutputManager).
AgentOutputStore
Session-scoped store of subagent outputs addressable via agent://.
AgentSessionManager
Manages several concurrent agent sessions.
AgentSettledEvent
The agent is fully idle: the run AND every queued follow-up have drained and all awaited listeners for the run's events (including agent_end) have settled (pi's agent_settled).
AgentSkill
One skill advertised in the Agent Card.
AgentStartEvent
The loop started processing a prompt or continuation.
AgentState
Public agent state. Ported from pi's AgentState.
AgentTool
A tool the model may invoke: name, description, JSON-schema parameters, and the Dart callback that executes it.
AgentUrlResolution
A resolved agent:// resource.
AiinApiKey
A registered AIIN API key. The raw secret (raw) is shown exactly once — store it before leaving the flow.
AiinConnectResult
The outcome of a completed AIIN connect flow.
AiinOAuthInitiate
The result of initiateAiinOAuth: the URL to open in the browser plus the server-issued state that binds the redirect back to us.
AiinOAuthTokens
AIIN access + refresh JWTs from exchangeAiinOAuthCode.
AnthropicOptions
Options for streamAnthropic.
ApiKeyCredential
One credential in an ApiKeyRing: its secrets-store name and secret value. The value must never be logged or sent to the model.
ApiKeyRing
A rotating view over one provider's API-key stack.
ApprovalManager
Holds the approval state of a session and resolves policy per tool call.
ApprovalOutcome
The outcome of an ApprovalManager.authorize check.
ApprovalRequest
One approval prompt, handed to the ApprovalPrompt callback.
ArchiveDirectoryEntry
A direct child of an archive directory (omp's ArchiveDirectoryEntry).
ArchiveNode
Metadata for one archive node (omp's ArchiveNode).
ArchivePathCandidate
One {archivePath, subPath} split of an archive.ext:inner/path reference (omp's ArchivePathCandidate).
ArchiveReader
An indexed, read-only view over a single archive (omp's ArchiveReader, reduced to read/list). Decoding happens up front in ArchiveReader.decode via package:archive; member bytes are inflated on demand by readFileBytes.
AskAnswer
The user's answer to one AskQuestion: selected option labels and/or free text.
AskOption
One selectable option of an AskQuestion.
AskQuestion
One structured question for the host's AskCallback.
AssistantMessage
A message produced by the assistant (the model), final or partial.
AssistantMessageEvent
Event protocol for AssistantMessageEventStream.
AssistantMessageEventStream
The event stream returned by provider stream calls.
AssistantMetricDetail
Recorded inputs needed to derive assistant TTFT and decode throughput.
AttachedMessage
One rendered transcript row of an attached session: enough for a client to render 1:1 what the owning process (the CLI) shows.
AttachedSessionEvent
One batch of appended session content.
AutoCompactor
Compact helper that owns the multi-pass + retry + smol→main logic. Hosts register a single AutoCompactor.run call after each run; the helper handles everything else.
AutoCompactorFactory
Hosts plug in their own AutoCompactorSources, hooks, and settings; the factory wires the smol/main summarizers with the configured CompactionPrompts and optional memory hook, then runs the loop.
AutoCompactorHooks
Hooks for a host UI to observe progress. Implementations should not throw — the compactor swallows and logs around them.
AutoCompactorPass
Per-pass outcome surfaced through AutoCompactorHooks.onPass.
AutoCompactorSources
Source for the AutoCompactor smol/main summarizers. Hosts plug in their own resolver:
BackgroundShell
Optional Shell capability: detached, log-file-backed jobs that outlive the initiating tool call. Implemented by process-backed environments (local shell); sandboxed/web environments simply do not implement it and callers answer a clean "not supported here" note instead.
BeforeToolCallContext
Context passed to BeforeToolCallHook.
BeforeToolCallResult
Result returned from BeforeToolCallHook.
BranchPreparation
Messages and file operations extracted for a branch summary (omp's BranchPreparation).
BranchSummaryRecord
Marks a branch the conversation navigated away from, with an optional summary projected into the context of the new branch.
BranchSummaryResult
Outcome of generateBranchSummary (omp's BranchSummaryResult): success carries summary plus the tracked file lists; failure carries error (or aborted) instead of throwing.
BraveSearchProvider
Brave web search via the official REST API, keyed by BRAVE_API_KEY.
BridgeFrame
One decoded wire frame. v/id/op are pulled out of fields; the rest of the payload stays addressable there.
BridgeLlmRelay
The llmReqllmRes frame glue. Shared per server; stateless.
BridgeOps
Client → server and server → client op names (the full v1 set).
BrowserBridgeHandle
The host-side bridge seam: start/rotate + status, implemented by the executable over the bridge server. Null on hosts without io — /browser then reports it cleanly.
BrowserBridgeSession
One pairing session: where to point the extension and the fresh one-time token it must present in its hello. alreadyRunning distinguishes a newly started bridge from a reused one.
BrowserBridgeStatus
Live bridge status: connected extensions plus a fabric mailbox listing.
BrowserController
The controller seam behind every browser_* tool: one typed method per bridge browser op. Implementations throw BrowserToolException with the contract error codes.
CancelToken
Cooperative cancellation, the Dart counterpart of the web AbortSignal.
CancelTokenSource
The writable side of a CancelToken. Keep it private to the caller that owns the operation; hand only the token to callees.
ChainEntry
One entry of a FallbackStreamFunction's chain: the model to call, its key ring, and the per-key stream factory.
ChatGptOAuthCredentials
OAuth credentials issued for a ChatGPT account.
CheckpointRecord
Marks a self-service context checkpoint created by the checkpoint tool so a later rewind can collapse the exploratory detour into a report.
CheckpointRewindController
Orchestrates the checkpoint/rewind flow for one Agent.
CheckpointSessionSink
The host seam for session persistence the controller drives.
CheckpointState
The captured checkpoint mark (omp's CheckpointState).
CliArgs
A parsed run configuration (interactive or headless).
CliArgsHelp
--help/-h was passed: print usage and exit 0.
CliArgsResult
The outcome of parsing the fah argument list.
CliArgsVersion
--version was passed: print the version and exit 0. output carries --output json (issue #155): machine-readable version + HEP version.
CliConfig
Persisted CLI configuration.
CliIO
Terminal IO abstracted for testability.
CodeMieSsoCredentials
The result of a successful CodeMie SSO login: the session cookies plus the resolved API base URL.
CodexCookieJar
In-memory jar holding only allowlisted Cloudflare cookies, keyed by host.
CodexRateLimits
Codex usage limits from a ChatGPT backend response.
CodexRateLimitWindow
One Codex usage window, as advertised by the ChatGPT backend.
CompactCheckpointRecord
A text checkpoint the structured compaction engine compacts a range into (issue #148, pass 2). The checkpoint's text replaces the range in the context projection, but every segment it covers stays listed with its expand id — nothing becomes unreachable (the anti-#81 pin).
CompactExpandController
Owns the per-turn expand budget and the compact_expand tool for one agent. Created next to builtinTools (see CheckpointRewindController); the budget resets when a new user turn starts.
CompactionManager
The compaction pipeline over a Session, mirroring pi's harness-level compact().
CompactionPreparation
Prepared inputs for a compaction run.
CompactionPrompts
The compaction prompts used by both engines, bundled so CLI prompt overrides (the prompts: config section, see lib/src/prompts/prompt_overrides.dart) can replace them without changing the pipeline's shape. The defaults are the built-in prompts: defaultCompactionPrompts is byte-identical to the historical constants.
CompactionRecord
Marks a compaction point: summary replaces everything before firstKeptEntryId when the context is rebuilt.
CompactionResult
Generated compaction data ready to persist as a CompactionRecord.
CompactionSettings
Compaction thresholds and retention settings.
CompletedRewind
A completed rewind retained for the repeat-call guard (omp's CompletedRewindState).
ConfigCheckReport
Result of ConfigService.check.
ConfigCliCommand
The fa config subcommand: headless config management.
ConfigDiagnostic
One config problem (or dead-config note) found by ConfigService.check.
ConfigGetResult
Result of ConfigService.get.
ConfigPathInfo
One config file location reported by ConfigService.paths.
ConfigService
The config service over one ExecutionEnv. See the library docs.
ConfigSetResult
Result of ConfigService.set.
ContentBlock
A content block of a Message.
Context
Everything a provider needs to produce the next assistant message.
ContextUsageEstimate
Estimated context-token usage for a message list.
CopilotApiToken
A short-lived Copilot API token (lifetime ~30 min).
CopilotDeviceGrant
One granted device-code session: what the user sees (userCode at verificationUri) plus what the poller needs (deviceCode, expiresIn, interval).
CopilotOptions
Options for streamCopilot.
CopilotPollFailure
A terminal failure; error carries the typed kind and message.
CopilotPollOutcome
One classified device-flow poll response — the poll state machine's states. classifyCopilotPollResponse maps a raw response onto one of these; the poll loop just switches over them.
CopilotPollPending
Still waiting for the user (authorization_pending).
CopilotPollSlowDown
The server asked to slow down (slow_down) — the wait grows.
CopilotPollSuccess
The user approved: token is the GitHub token.
CopilotTokenManager
In-memory cache of the short-lived Copilot API token for one GitHub token: single-flight exchange, proactive refresh refreshLead before expiry, and at most one exchange per minSpacing (proxy semantics: ~30 min tokens, refresh ~2 min early, never more often than 30 s).
CriticalBashPattern
A destructive shell pattern with a human-readable label, surfaced in the approval prompt's reason.
CubeCacheManager
Saves, restores and clears a cube's cache directories.
CubeCachePolicy
The spec.cache: section of a cube.
CubeEnvHidden
A variable explicitly removed from the child environment (e.g. HOME).
CubeEnvPolicy
The spec.env: section: the ordered variable list.
CubeEnvValue
A variable with a literal value.
CubeEnvValueFrom
A variable resolved from the host environment at CubeEnvPolicy.apply time. source has the form env:NAME.
CubeEnvVar
One declared environment variable. Sealed: a literal CubeEnvValue, a host-resolved CubeEnvValueFrom, or a removed CubeEnvHidden.
CubeFsGuard
A FileSystem whose operations are gated by a cube's filesystem policy.
CubeFsPolicy
The spec.filesystem: section: workspace root plus mount overrides.
CubeMount
One mount entry: a path prefix and the access level granted under it.
CubeNetworkGate
Decides whether a URL may be fetched under the live cube policy.
CubeNetworkPolicy
The spec.network: section: ordered allow/deny rule lists.
CubeNetworkRule
One network rule: a host pattern plus an optional port set.
CubePolicyDecision
The outcome of a CubePolicyEngine.checkCommand evaluation.
CubePolicyEngine
Evaluates a shell command line against a cube's tool and network policies.
CubePreset
One built-in security level preset.
CubePresets
The built-in preset catalog and its manifest generator.
CubeProfileStaging
A backend whose kernel confinement is driven by a profile artifact that must exist on disk before the wrapped command runs. SandboxedShell probes for this capability and stages buildProfile's output to .fah/cube-profiles/<cacheKey>.sb (once per spec) before the first wrapped exec.
CubeRegistryClient
The cube registry client.
CubeRegistryTemplate
One catalog entry of the cube registry.
CubeResolver
Resolves CubeSpec manifests by path, name or built-in preset.
CubeResourceLimits
The spec.resources: section: optional cpu string, byte limits and a wall-clock timeout.
CubeSandboxBackend
A platform strategy for confining a cube's processes at the OS level.
CubeSettings
The cube: config section: opt-in switch plus the default manifest.
CubeSpec
A parsed cube manifest: identity plus the five policy sections.
CubeToolPolicy
The spec.tools: section of a cube: the allow/deny command-word sets.
CustomMessageRecord
An application-defined record that projects into model context as a user message.
CustomModelDefinition
A named custom model definition (models.custom.<name>): a concrete provider/endpoint/model triple with optional token-limit and modality overrides, switchable at runtime with /model <name>.
CustomProviderEntry
One saved custom provider.
CustomProviderRegistry
The live list of saved custom providers (shared by the CLI, which mutates it, and the executable, which persists it).
CustomRecord
An application-defined record that is omitted from model context by default.
CutPointResult
Cut point selected for compaction.
DapHubSnapshot
One DAP/1 hub snapshot — everything a host shows about the hub connection in one immutable value (docs/dap.md §9): the resolved connection, the agent identity, and the channels this machine holds keys for.
DialOptions
Options for streamDial.
DoneEvent
Terminal event: the message completed successfully.
DuckDuckGoSearchProvider
DuckDuckGo search via the keyless no-JS HTML frontend.
DynamicMessageRequest
The widget definition the agent asked the host to present.
EnvProviderPreconfig
One resolved FA_PROVIDER_* preconfig: the catalog spec the type maps to plus the boot-ready name/endpoint/model/key tuple.
Err<T, E>
A failed Result.
ErrorEvent
Terminal event: the stream failed or was aborted.
EventStream<T, R>
A push-based stream of events with an awaitable final result.
ExecutionEnv
Filesystem and process execution environment used by the harness.
ExtCliCommand
The fa ext subcommand: headless management of JS extensions.
ExternalInbox
A plugin-provided inbox drained into the agent loop as steering messages, oldest first. Sources may be remote (a hub connection), so both callbacks must be cheap and drain must never throw — a failing drain returns an empty list instead.
FabricConfig
The host's announced identity metadata for the messaging fabric.
FahPlugin
Base interface for a fah plugin / package extension.
FallbackMessagingRepository
A MessagingRepository composing a primary (hub) transport with a fallback (file) fabric. See the library docs for the routing rules.
FallbackNotice
The no-silent-degrade note: emitted through the listener callback before every retry/rotation/failover so the degradation is always visible.
FallbackStreamFunction
A StreamFunction over an ordered ChainEntry list with omp's rate-limit policy: rotate keys for free, retry the entry with capped exponential backoff, then fail over to the next entry — every step announced through onNotice.
FileInfo
Metadata for one filesystem object.
FileMessagingRepository
File-based messaging repository. Layout:
FileOperations
File paths touched by a compaction range.
FileSessionEventSource
FileSessionInputChannel
Hands user input to the session's owning process through the agent messaging fabric: an AgentMessageKind.user envelope addressed to the session's main mailbox. The CLI's inbox watcher wakes and delivers it as a user turn.
FileSessionLeaseStore
File-backed ownership lease over an ExecutionEnv: the _owner.json sidecar next to the session JSONL. All failures are fail-open (E4): a lease that cannot be read is no lease; nothing here ever blocks opening a session for reading.
FileSessionPresenceStore
FileSystem
Filesystem capability used by the harness.
FolderModelState
The model/provider triple saved for one project folder.
FsSnapshotExporter
A filesystem that can export a point-in-time deep copy of its whole tree in ONE synchronous pass.
GatedHttpClient
An http.Client enforcing a CubeNetworkGate before every request leaves the process (defense in depth behind the tools' pre-checks).
GoogleOptions
Options for streamGoogle.
GoogleThinking
Thinking configuration for Gemini models.
HarnessLlmProvider
An LlmProvider over the harness StreamFunction contract. extends (not implements) so the interface's default chatStream / chatMessagesStream / cancel bodies carry over.
HashlineAnchor
A line-number anchor (1-indexed).
HashlineApplyResult
Result of applying a parsed set of edits to a text body.
HashlineCursor
Where an insert edit should land relative to existing content.
HashlineCursorAfter
Insert immediately after anchor (INS.POST N:).
HashlineCursorBefore
Insert immediately before anchor (INS.PRE N:).
HashlineCursorBof
Insert at the very start of the file (INS.HEAD:).
HashlineCursorEof
Insert at the very end of the file (INS.TAIL:).
HashlineDelete
Delete the line at anchor.
HashlineEdit
A single low-level edit produced by the parser and consumed by the applier. Multi-line replacements decompose to one insert per replacement line plus one delete per consumed line. Replacement payloads are tagged so the applier can distinguish literal insertion from new content for a deleted line.
HashlineInsert
Insert text at cursor. replacement marks payload lines lowered from a SWAP N.=M: hunk (new content for the deleted range).
HashlineParseResult
Result of parsing one section body: the flat edit list plus diagnostics.
HashlinePatch
A parsed hashline patch — zero or more HashlinePatchSections, each rooted at a [PATH#HASH] header.
HashlinePatcher
High-level patcher. Wires an ExecutionEnv and a HashlineSnapshotStore together with the parsing + applying core. Construct once per session; reuse across patches.
HashlinePatcherApplyResult
Aggregate result of HashlinePatcher.apply.
HashlinePatchSection
One section of a parsed HashlinePatch: a target file plus the lazily-parsed list of edits that should land on it.
HashlinePreparedSection
Opaque token returned by HashlinePatcher.prepare. Carries the section, the raw file content read off the filesystem, and the in-memory apply result. HashlinePatcher.commit just writes it.
HashlineRange
A parsed [A.=B] line range (1-indexed, inclusive on both ends).
HashlineSectionResult
Per-section result returned by HashlinePatcher.apply / HashlinePatcher.commit.
HashlineSnapshot
One full-file version observed at a point in time. The tag the model sees is hash; diagnostics replay against text.
HashlineSnapshotStore
In-memory snapshot store: a bounded set of paths, each with a short history of full-file versions so in-session edit chains can still recover against the version a stale tag names.
HepEventsIO
In --output events the HEP stream owns stdout: streaming deltas (CliIO.write) are dropped — they ride message_delta frames — while diagnostics (CliIO.writeln: banners, tool traces, errors) keep flowing to the host's channel (stderr in headless mode).
HepWriter
Streams AgentEvents as HEP v1 JSONL frames — one emit per line.
HiddenRangeRecord
Marks records hidden in place by the structured compaction engine (issue #148, pass 1). Hiding is lossless: the referenced records stay in the session file and project into context as one-line placeholder markers at their original position, expandable on demand via compact_expand.
HtmlTag
One scanned HTML tag (open, close, or self-closing).
HtmlText
A plain-text chunk between tags.
HubIdentity
The DAP/1 agent identity (signing + DH keypairs, derived agent id).
HubMessagingRepository
The DAP/1 hub as a MessagingRepository.
HubPeer
One roster entry from a presence query or whois.
HubSocket
One live hub connection.
HubTransport
Dials a hub URL (ws://host:port/ws) — the only network operation the hub fabric performs. Implementations throw when the hub is unreachable or rejects the upgrade (wrong pairing token); the repository treats any throw as "not connected" and retries with backoff.
ImageContent
An image supplied by the user or a tool result.
ImageRegistry
The per-window image registry: content-keyed, rebuilt deterministically from a message list (issue #171 I2).
ImageRegistryConfig
Settings for the images: config section (~/.fah/config.yaml).
ImageRegistryEntry
One unique image in the window.
InMemorySecretsStore
A SecretsStore backed by a plain map. This is the web/default implementation and is convenient in tests.
InspectImageConfig
Configuration for the inspectImageTool vision model.
InspectImagePlugin
Plugin that contributes the inspect_image tool.
JsonlSessionCreateOptions
Options for JsonlSessionRepo.create.
JsonlSessionRepo
JSONL session repository on top of a FileSystem.
JsonlSessionStorage
Append-only JSONL session storage on top of a FileSystem.
KeyEvent
A single key press from an interactive terminal in raw mode.
LabelRecord
Attaches (or removes, when label is null) a human-readable label to another record, e.g. a bookmark in the tree UI.
LeafRecord
Marks the active leaf of the tree after a branch navigation.
LeaseAcquire
The outcome of FileSessionLeaseStore.acquire.
LeaseAcquired
This process now owns the session: heartbeat + release with bootId.
LeaseBlocked
A live lease blocked the drive-open: this opener is a VIEWER. No takeover exists — the viewer messages the owner through the fabric.
LeaseInspect
The lease state a drive-open finds on disk.
LeaseUnenforced
This process opened for drive, but the lease could not be enforced (a write/rename/verify failure — E4): the drive proceeds WITHOUT a lease. Honest fail-open: nothing blocks a session over lease IO, and the caller may warn.
LineRange
Inclusive line range described by one selector segment (e.g. 50-100, 301-, or 50+10). A null endLine means open-ended ("to EOF").
LinksConfig
The links: config section.
LinuxUnshareBackend
The Linux backend: unshare argv generation plus command wrapping.
LiveStdinChannel
A live stdin write channel for a RUNNING process (issue #367): the caller creates the channel, passes it in ShellExecOptions.liveStdin, and the shell implementation binds it to the spawned process's stdin. While bound, the process's stdin pipe stays OPEN for the process's lifetime (the password ask may arrive long after launch) instead of the default close-right-after-start.
LlmRelayRequest
One decoded relay request: {req: {baseUrl, model, messages, provider?}}. provider (the saved entry name) disambiguates the key slot when several accounts share an endpoint.
LspAppliedChange
One applied change, for the tool's report (omp's applied-change lines).
LspClient
A live connection to one language server process.
LspClientManager
Owns the LspClient pool for one lsp tool instance.
LspConfig
The resolved server configuration for a workspace (omp's LspConfig).
LspDiagnostic
LSP diagnostic.
LspLocation
LSP location: a range inside a document.
LspMessageFramer
Incremental Content-Length framer. Not thread-safe (Dart is single threaded); one framer per server connection.
LspPosition
LSP position (0-indexed line and character on the wire).
LspRange
LSP range.
LspServerConfig
One language server definition (omp's ServerConfig, reduced).
LspTextEdit
LSP text edit: replace range with newText.
LspToolConfig
Configuration for the lsp tool; one per agent session (the client pool is session-scoped through it, like the task tool's stores).
LspTransport
A live byte channel to a language server process: framed JSON-RPC goes out through write, raw server output arrives on messages.
LspWorkspaceEdit
A parsed WorkspaceEdit (omp's WorkspaceEdit, reduced to text edits).
MacOsSandboxBackend
The macOS backend: SBPL profile generation plus sandbox-exec wrapping.
MailboxEntry
One entry in the messaging-fabric directory.
MailDeduper
Bounded LRU dedupe over fabric message ids: a re-observed id inside the window is a duplicate (drop it); the oldest id falls out at capacity.
ManagedSession
One managed session: the Agent, its persistent Session, and the metadata that identifies it.
McpByteChannel
The raw byte channel an McpStdioTransport frames: stdout bytes in, stdin bytes out. The dart:io implementation wraps a spawned process; tests substitute in-memory fakes.
McpClient
A live connection to one MCP server.
McpConfig
The mcp: config section: the server map plus the tool-call timeout.
McpHttpServerConfig
A remote MCP server reached over HTTP.
McpInitializeResult
The result of the initialize handshake.
McpLineFramer
Incremental newline framer. One framer per server connection.
McpManager
Owns the McpClient pool and the dynamic MCP tool surface.
McpServerConfig
One configured MCP server. Sealed: either a stdio process (McpStdioServerConfig) or a remote HTTP endpoint (McpHttpServerConfig).
McpServerState
The live state of one configured server.
McpSseTransport
The legacy HTTP+SSE MCP transport (GET stream + POST channel).
McpStdioServerConfig
A stdio MCP server: a spawned process speaking newline-delimited JSON-RPC over stdin/stdout.
McpStdioTransport
A stdio McpTransport: newline-delimited JSON-RPC over a McpByteChannel. Malformed lines are skipped (a wrapper script's stdout noise must not kill the reader); the process exiting closes the channel.
McpStreamableHttpTransport
The streamable-HTTP MCP transport (one endpoint, POST per message).
McpToolConfig
Bundle enabling MCP for an agent session: the parsed config plus the host capabilities. Mirrors LspToolConfig.
McpToolInfo
One tool advertised by tools/list.
McpTransport
A live message channel to an MCP server: JSON-RPC messages go out through send, decoded server messages arrive on messages.
MediaSlotModelConfig
One media slot override in the CLI's models: config section: where ONE media modality is served when the main connection should not handle it.
MemoryConfig
Parsed memory: section. Both fields optional; null = default path.
MemoryController
Controls the agent's durable memory across sessions and projects.
MemoryEntry
A single memory entry returned by MemoryController.search / list.
MemoryExecutionEnv
In-memory ExecutionEnv: MemoryFileSystem plus a Shell.
MemoryFileSystem
In-memory FileSystem with POSIX-style (/-separated) paths.
MemoryFsSnapshot
A point-in-time deep copy of a MemoryFileSystem tree — see FsSnapshotExporter.exportSnapshot.
Message
A message in a conversation context.
MessageEndEvent
A message is complete: the final assistant message, a prompt, or a tool result.
MessageRecord
A conversation message appended to the tree.
MessageStartEvent
A message entered the transcript: a prompt, a (partial) assistant message, or a tool result.
MessageUpdateEvent
The streamed assistant message advanced. Only emitted for assistant messages; message is the live partial snapshot carried by assistantMessageEvent.
MessagingRepository
Isolated messaging backend for agent inboxes.
MobileAppEntry
One installed app in an inventory listing.
MobileAutomationBackend
Observe-and-act backend: the god tier only (AccessibilityService + MediaProjection). Every call probes the service first (E2) and raises MobileAutomationException.offline when it is gone.
MobileElement
One filtered, index-addressable element of the on-device screen (artemis's filter idea: keep informative-or-interactive nodes, drop pure containers and zero-area nodes).
MobileElementIndex
The filtered element index of one screen observation.
MobileErrorCode
Codes of the named mobile automation states.
MobileLaunchBackend
Launch/inventory backend: works in BOTH flavors. The store flavor launches apps and deep links and lists launcher-visible apps; the QUERY_ALL_PACKAGES inventory exists only in god.
MobileLogsBackend
Own-app log tail backend (all tiers): the app's own buffer — other apps' logs are invisible to a third-party package by Android design.
MobileObserveResult
The outcome of one observe step.
MobileScreenshot
A screenshot capture: PNG bytes (session-local; never leaves the device except inline to the model under the image registry rules).
MobileShellBackend
The Shizuku shell bridge backend (god flavor, opt-in).
MobileShellResult
The outcome of a Shizuku shell command.
MobileTapAtPoint
Tap raw screen coordinates (the artemis fallback when no element fits).
MobileTapById
Tap the center of the element with this index id (e12).
MobileTapTarget
How a tap targets an element: by index id or by raw coordinates.
Model
A model the harness can call.
ModelChangeRecord
Records a change of the active model.
ModelCost
Per-million-token pricing for a model, in USD.
ModelListDialect
One provider's "how to list models" implementation. Each dialect encapsulates its own detection (does this endpoint belong to me?) and its own fetch (what URL, what auth, what shape the response has, how to normalise ids). Pickers never see the internals — they just call fetchModelsForEndpoint which delegates.
ModelRef
One entry of a role's fallback chain: a concrete model plus an optional API-key base-name override.
ModelRequestEvent
The outbound request summary captured before a provider call.
ModelRolesConfig
Model-role configuration: role → ordered fallback chains, path-scoped overrides, and the retry policy.
ModelRolesResolver
Builds per-role fallback chains from configuration and secrets.
ModelRolesRetryPolicy
Knobs for the rate-limit retry/fallback engine, mirroring omp's non-compaction retry policy (retry.* settings).
ModelsConfig
The parsed models: section: media slot overrides plus named custom model definitions. Mutable like CustomProviderRegistry — the REPL (/models set//models remove) updates the live instance and the executable persists it with the usual config save.
NextTurnContext
Context passed to PrepareNextTurnHook after a turn fully completes.
NoOpCubeBackend
A CubeSandboxBackend that changes nothing — the Dart-layer policies (tool policy, filesystem guard, network scan) are the only enforcement in this mode.
NoopPowerAssertionHandle
A handle that never held anything: the clean degradation for platforms without a power-inhibition helper (the documented Windows stub, exotic hosts).
NoopPowerAssertionRunner
The platform runner of last resort: "acquires" a no-op handle whose description explains why. Sleep prevention is best-effort everywhere — never a boot blocker.
Ok<T, E>
A successful Result.
OpenAICompletionsCompat
Compatibility flags for OpenAI-compatible chat-completions endpoints.
OpenAICompletionsOptions
Options for streamOpenAICompletions.
OpenRouterOAuthKey
Result of a successful OAuth code exchange.
ParsedProviderQueue
One parsed queue source: the entries plus whatever the parser wants the boot log to say (unknown-key warnings, dedup notes).
PasswordPromptDetector
Watches a command's output stream for password asks and resolves them through onPrompt. One answer at a time: while an answer is pending the detector stays muted; after it resolves the next detected ask re-arms (a wrong-password retry opens the sheet again — GOAL #367 E1).
PathRoleOverride
A path-scoped set of role chains, applied when the cwd matches pattern.
PendingSteering
One mid-run steering delivery in flight: the queued message, the session record it was persisted under, and its panel. Consumed by identity at the step-boundary merge (the agent loop appends the SAME UserMessage object), or reconciled by text in the leftover settle.
PluginContext
Context passed to FahPlugin.register. Plugins use it to contribute capabilities to the running agent session.
PluginIO
IO surface exposed to plugins for writing to the terminal.
PowerAssertionController
Session-scoped owner of one power assertion. NOT a lifecycle-fidelity port of oh-my-pi's #acquirePowerAssertion/#releasePowerAssertion: oh-my-pi holds per session, but a session-open hold pins the machine awake for whole idle hours between runs (issue #326) — so the DEFAULT here is per-run (PowerAssertionHold.perRun): hosts fire onRunStarted/onRunSettled around every run and the assertion exists only while work is in flight. Session-held (PowerAssertionHold.session) keeps oh-my-pi's behaviour as an explicit opt-in via onSessionOpened/onSessionClosed. Both directions stay idempotent and warn-not-crash: a failure on either side is a WARNING — the run/session continues unguarded rather than dying because the platform would not let us stay awake.
PowerAssertionHandle
One held power assertion. release is idempotent and never throws for an already-gone helper process; held flips false once released or when the helper died on its own, so status surfaces stay honest.
PowerAssertionOptions
The capabilities one power assertion requests — the Dart mirror of oh-my-pi's native PowerAssertionOptions: one flag per capability, all released together when the handle is stopped.
PowerAssertionRunner
Acquires power assertions when the configured hold asks for one (per-run at turn start by default, per-session as the opt-in, #326). Implementations spawn the platform helper (macOS caffeinate, Linux systemd-inhibit) or degrade to a no-op note on platforms without one.
PowerAssertionStatus
/power's one-line answer: the configured level, whether an assertion is held right now, and what is holding it.
PowerSection
The parsed power: section: which sleep-prevention capabilities to request and when to hold the assertion for them. Absent members keep their defaults (PowerAssertionLevel.idle is applied by the host, PowerAssertionHold.perRun is this file's own default).
ProjectContextFile
One discovered context file.
PromptOverrides
Resolved prompt overrides: canonical prompt name → override text.
PromptTemplate
A prompt template loaded from a markdown file.
PromptToolOptions
Options for promptToolStreamFunction.
ProviderModelChoice
A completed provider → model pick: the endpoint, the wire spec, the chosen model id, and the saved registry entry when the provider is a custom one.
ProviderQueueEntry
One ordered entry of the provider queue: an adapter kind, the model to call on it, and the key indirection (apiKeyEnv — the env NAME, never the value).
ProviderQueueResolution
The scope-resolution result: the winning queue plus the boot notices (winning scope named, shadowed scopes listed — the tools: stack discipline; identical lower scopes collapse into one notice).
ProviderQueueRuntime
The wired queue: the sticky RAM state, the driven stream function, and the entries it was built from. Hosts keep ONE instance per session (the stickiness); editors mutate the yaml and re-resolve — the next rebuild() swaps the chain live (AC7/UT-31).
ProviderQueueScopeInput
One queue scope's raw availability: a set scope carries its parsed entries (parse errors of ANY set scope fail the boot — a broken shadowed scope is still a misconfiguration worth failing on).
ProviderQueueState
The sticky RAM cursor and per-entry health of a provider-queue-driven FallbackStreamFunction (issue #418). Volatile by contract — restart constructs a fresh wrapper and the queue restarts at its head (AC6); nothing ever persists this object.
ProviderSpec
Static description of a supported provider.
ProvidersSyncPayload
The full providersSync frame payload.
ProvidersSyncProvider
One synced provider's metadata (never a key).
ProviderStreamState
Mutable accumulation state for one streamed assistant message.
ProviderTimeoutsOverride
Provider watchdog overrides from the providerTimeouts: section of ~/.fah/config.yaml (strict ConfigException parsing in cli_config.dart).
PubDevHandler
Renders pub.dev package pages (/packages/<name>) from the pub.dev API instead of scraping the HTML page (ported from omp's scrapers/pub-dev.ts): metadata, score metrics, SDK constraints, dependencies, and recent versions as structured markdown.
QueueDeath
One classified provider death: what killed the entry and how the chain should react.
RangedReadFileSystem
Optional FileSystem capability: byte-range reads.
ReadSelector
The parsed trailing selector of a read path (omp's ParsedSelector).
ReadSelectorLines
One or more (sorted, merged) line ranges, optionally with raw output (:range:raw / :raw:range).
ReadSelectorNone
No selector (or an unrecognized one left for archive/SQLite/URL readers).
ReadSelectorRaw
:raw alone — verbatim whole-resource output.
RedactCommandOutcome
The outcome of a /redact [args] line: the lines to print and the pipeline config to install (newConfig null = keep the current one).
RedactionConfig
RedactionMatch
A single sensitive span reported by one redaction layer.
RedactionPipeline
The layered redaction pipeline.
RedactionStats
Per-layer and per-tool counters for the pipeline.
RedactionToolPolicy
Immutable configuration for the redaction pipeline.
RemoteCatalogEnrichment
Holds the preloaded RemoteModelsCatalog for the lifetime of the process. Hosts (CLI startup, app boot) inject the catalog once; the rest of the code calls mergeFor and mediaFor to fold catalog hints into the endpoint-reported model list without re-fetching.
RemoteModelPricing
Flat per-million-token pricing for one model, in USD.
RemoteModelsCatalog
The remote catalog payload. All fields optional — a partial update can ship just a new chat provider without touching media lists.
RemoteProviderEntry
RenamableFileSystem
Optional FileSystem capability: atomic same-filesystem rename.
RequestSecretResult
The credential the user granted through the host's secret prompt.
ResolvedToolAvailability
The availability decision for one tool id.
Result<T, E>
Result of a fallible operation. Expected failures are returned as Err instead of thrown — FileSystem operations must never throw.
RoutingMessagingRepository
Capability of a primary repository that routes by recipient: it can say whether toId is deliverable through it and return the CANONICAL target id (a display name resolved to the peer id, a channel passed through). Null means "not mine" — the recipient belongs to the file fabric (or the primary is not connected). Implementations must be cheap to call and never throw for a null answer.
SandboxedExecutionEnv
An ExecutionEnv confined by a cube's policies.
SandboxedShell
ScheduledMessageQueue
SecretRedactor
Holds secret values and replaces them with SecretRedactor.mask in text.
SecretsExecutionEnv
An ExecutionEnv that injects secret env vars into every exec.
SecretsStore
A read-only bulk source of secrets, name → value.
SecureKeyCache
A synchronous, session-scoped snapshot over a SecureKeyStore.
SecureKeyStore
A platform secure enclave for secrets, addressed by name.
Semaphore
Simple counting semaphore for limiting concurrency across independently scheduled async work (port of omp's Semaphore).
ServerSentEvent
A parsed Server-Sent Event.
Session
A session: an append-only tree of records with an active leaf.
SessionChunk
One chunk read off the session file: records oldest-first plus the file facts the window cache needs (staleness re-anchors, "N above" labels).
SessionChunkEntry
One parsed record with the byte range it occupies in the session file.
SessionChunkReader
Backward/forward byte-scan reader over one JSONL session file.
SessionCliCommand
The fa session subcommand (issue #198): tree-grouped session listing.
SessionContext
The model-derived state of a session along the active branch.
SessionEventSource
A broadcast of the messages appended to a watched session. The session JSONL is the single source of truth; an implementation tails it (poll or push) and emits what changed.
SessionGroup
One main session with the subagent sessions nested under it (issue #198's shared grouping model). An orphaned subagent — its parent is deleted or simply absent from the listed set — renders as its own group with main carrying the subagent marker and no children.
SessionHeader
The session header — always the first line of a JSONL session file.
SessionHeaderCache
A SessionStorage whose header is parsed at construction and exposed synchronously — prompt-cache affinity and the session-scoped .tools/<id>.yaml path read it without an async hop.
SessionInfoRecord
Records session-level information such as a display name.
SessionInputChannel
The channel a client hands user input through to the process owning the session. The file impl rides the agent messaging fabric (an AgentMessage with AgentMessageKind.user); a network impl later carries the same semantics over the wire.
SessionIoRetryConfig
Retry wiring for one session store: the policy caps the window, the logger receives one session_io_retry line per retry, and delay replaces the wall-clock sleep (tests inject an instant recorder).
SessionIoRetryPolicy
Capped exponential-backoff schedule for session-file retries.
SessionLease
One ownership lease: who drives a session, since when, last seen when.
SessionMetadata
Metadata describing a stored session.
SessionParseBatch
One bounded batch of raw JSONL entry lines (never the header line).
SessionParseExecutor
Where CPU-bound session JSONL parsing runs (issue #199).
SessionParseResult
Per-line parse outcomes, parallel to SessionParseBatch.lines.
SessionPresence
One live-session heartbeat record.
SessionPresenceStore
Registry of live sessions: a running agent process registers on start, touches on every heartbeat tick, unregisters on exit. Readers (SessionPresenceStore.list) see only fresh entries — a crashed process is covered by staleness, not by cleanup.
SessionRecord
One entry in the append-only session tree.
SessionRepo
The repository contract for sessions.
SessionStorage
The storage contract behind a Session tree.
SessionVarsExecutionEnv
An ExecutionEnv that injects session-correlation env vars into every exec. See the library doc for the contract.
SettingSurfaces
Which app surfaces carry a shared setting: the Flutter app on macOS, iOS and web, plus the browser extension panel (issue #288 AC3/AC5). Absent surfaces must name the CAPABILITY gap in SettingSurfaces.gapWhy (E3) — never "didn't get to it".
SettledContextEstimate
Memoized context estimate for the SETTLED part of a transcript.
Shell
Shell execution capability used by the harness.
ShellExecOptions
Options for Shell.exec.
ShellExecResult
Outcome of a completed Shell.exec invocation.
ShellJob
A detached shell job: a process that keeps running after the tool call that started it has returned. Output is appended to the job's log file (the path is chosen by the caller of BackgroundShell.startShellJob).
ShellJobEntry
One registered background shell job.
ShellJobRegistry
The session's background shell jobs. See the library doc.
Skill
One discovered skill (metadata + parsed manifest; the body stays on disk for progressive disclosure via the read tool / skill renderer).
SkillManifest
One parsed skill frontmatter.
SkillRoot
One discovery root: a directory to scan plus its SkillSource. commandDir roots (Claude's .claude/commands/) contain flat <name>.md command files only — no <name>/SKILL.md pass.
SpillsConfig
The spills: config section (issue #678).
SpillStore
Writes the full redacted body to .fah/spills/<sessionId>/<n>.txt, unique per-session counter names (AC7). Returns the relative spill path, or null when the write failed (AC6 fallback) or no session id is known yet.
SplitReadPath
Result of splitting a read path into its filesystem path and an optional trailing selector string (omp's { path, sel? }).
SqliteDatabase
An open SQLite database. All methods are synchronous: the underlying FFI calls are synchronous too.
SqliteEngine
Opens SQLite databases for the read tool. The FFI-backed implementation lives behind lib/io.dart; web hosts pass no engine.
SqliteListSelector
db.sqlite — list non-sqlite_% tables with row counts.
SqlitePathCandidate
One {sqlitePath, subPath, queryString} split of a db.sqlite:table?query reference (omp's SqlitePathCandidate).
SqlitePkLookup
Lookup by primary-key column.
SqliteQuerySelector
db.sqlite:table?limit=…&offset=…&order=…&where=… — paged table query.
SqliteRawSelector
db.sqlite?q=SELECT … — raw read-only SQL.
SqliteRowidLookup
Lookup by rowid (tables without a primary key).
SqliteRowLookup
How a row lookup resolves: by the single primary-key column, or by rowid (omp's SqliteRowLookup).
SqliteRows
A query result: column names plus rows as column→value maps.
SqliteRowSelector
db.sqlite:table:key — row lookup by primary key (or rowid).
SqliteSchemaSelector
db.sqlite:table — schema plus sample rows.
SqliteSelector
The parsed SQLite target selector (omp's SqliteSelector).
SqliteTablePage
A paged table query result with the total row count for continuation notes (omp's queryRows return shape).
SqliteTableSummary
Row count for a table in the listing: exact when the table is provably small, otherwise a lower bound (omp's TableRowCount, minus the sqlite_stat1 estimate variant).
SseDecoder
Decodes a stream of text chunks into ServerSentEvents.
SseParser
Incrementally parses a UTF-8 SSE byte stream into SseEvents.
StartEvent
Emitted once before any content events.
StoreBannerView
The view-model of the in-app Get banner (AC4): every URL and label the web/macOS banner renders. Built from a LinksConfig — the widget never hard-codes a store URL.
StreamCacheRouting
Per-call prompt-cache routing overrides, consulted by the provider stream functions built with providerStreamFunction.
StreamingBlock
Mutable streaming accumulation for one content block. Converted into an immutable ContentBlock for every event snapshot.
StreamJsonWriter
Streams AgentEvents as stream-json lines — one emit per line.
StructuredTaskOutput
Parsed structured completion plus its validation metadata (omp's StructuredSubagentOutput, reduced: no source/mode — v1 schemas always come from the call item).
SubagentEvent
One observable event from a subagent (status transition, output preview, or an inbound message — Phase 3b).
SubagentHandle
A retained subagent handle: the parent (and the user) can query status, send follow-up messages, and observe the child's transcript at any time.
SubagentHeartbeat
Periodic status digests for running background subagents.
SubagentManager
SubagentMessage
One inter-agent message (Phase 3b agent_message / reply payloads).
SubagentsConfig
The subagents: yaml section: heartbeat cadence and stall threshold. Parsed strictly — a bad schema throws ConfigException-shaped errors (the config layer surfaces them at boot). 0 disables the respective mechanism; negative values are rejected.
SummarizationRequest
A single summarization request handed to a SummarizeFn.
SummarizationResult
Result of a SummarizeFn call. Success carries text; failure carries error and optionally marks the call as isAborted.
SwappableMessagingRepository
A MessagingRepository whose backing implementation can be replaced at runtime. The CLI uses this so the agent messaging fabric can follow the EFFECTIVE session root: when session creation falls back from the shared root (macOS App Group) to ~/.fah/sessions, the mailboxes must move with it — a fabric pinned to the old root would let an attached app write into inboxes no running process ever drains.
TaskAgentDefinition
Definition of a subagent type spawnable through the task tool (omp's AgentDefinition, reduced: no spawns, thinkingLevel, frontmatter output, or file source).
TaskAgentRegistry
Resolves agent types for task calls: TaskAgentRegistry.resolve finds a type by name, TaskAgentRegistry.toolSurfaceFor computes a type's restricted child tool surface.
TaskExecutor
Runs task batch items as child Agents under a session Semaphore.
TaskItem
One unit of work in a task batch call (omp's TaskItem, reduced: no isolated, no schemaMode).
TaskJob
One background subagent job (omp's type: "task" async job, reduced). The job id IS the allocated agent id (omp semantics), so a settling job's result stays addressable as agent://<id>.
TaskJobManager
Session-scoped registry of background task jobs (reduced port of omp's AsyncJobManager role for task spawns).
TaskSingleResult
Result of a single subagent execution (omp's SingleResult, reduced).
TaskToolConfig
Configuration for taskTool. One config per session: the semaphore, outputs store, and jobManager are session-scoped through it, so repeated (and concurrent) task calls share the concurrency bound and the agent:// id space (omp's session-scoped TaskTool instance).
TavilySearchProvider
Tavily search via the agent-focused API, keyed by TAVILY_API_KEY.
TeeCliIO
CliIO decorator teeing the rendered session trace to a file (--log-file): every write/writeln chunk is appended to sink verbatim and then delegated unchanged, so the log mirrors the trace — assistant text, tool lines, diagnostics — while stdout/stderr behave exactly as before. Input, interrupts and the rest of the CliIO surface delegate straight through.
TextContent
Plain text produced by the model.
TextDeltaEvent
Incremental text for the block at contentIndex.
TextEndEvent
The text block at contentIndex is complete.
TextStartEvent
A text content block started at contentIndex.
TextStreamingBlock
Accumulating text content block.
ThinkingContent
Model reasoning ("thinking") produced before or alongside the answer.
ThinkingDeltaEvent
Incremental thinking text for the block at contentIndex.
ThinkingEndEvent
The thinking block at contentIndex is complete.
ThinkingLevelChangeRecord
Records a change of the model's thinking level.
ThinkingStartEvent
A thinking content block started at contentIndex.
ThinkingStreamingBlock
Accumulating thinking (reasoning) content block.
ThrottledTrajectorySearchIndex
Trailing-throttle wrapper around TrajectorySearchIndex: the first update after an idle gap is immediate, later updates coalesce into a single trailing flush that always applies the latest layouts.
Tool
A tool the model may invoke, with a JSON Schema for its parameters.
ToolAvailabilityGate
Enforces a ToolAvailabilityResolution against a registry + agent.
ToolAvailabilityResolution
The full resolution of every known tool id against a scope stack.
ToolCall
A request by the model to invoke a tool.
ToolCallDeltaEvent
Incremental JSON argument text for the tool call at contentIndex.
ToolCallEndEvent
The tool call at contentIndex is complete; toolCall has fully parsed ToolCall.arguments.
ToolCallStartEvent
A tool call started at contentIndex.
ToolCallStreamingBlock
Accumulating tool-call block with partial JSON arguments.
ToolCapability
A tool family's host-side capability: whether the current platform/wiring can actually provide the tool at all.
ToolExecutionEndEvent
Execution of a tool call finished (successfully or with an error result).
ToolExecutionResult
Final or partial result produced by a tool execution.
ToolExecutionStartEvent
Execution of a tool call started.
ToolExecutionUpdateEvent
A tool reported a partial execution result.
ToolPairingRepairEvent
Emitted when the outbound request context needed tool-pairing surgery (issue #85): orphaned tool results dropped, missing results synthesized, or duplicate ids renamed. Repairs are never silent — report carries the counts and affected ids, and providerError is set when the pass ran in response to a provider pairing error (the self-healing retry).
ToolPairingRepairReport
What a repairToolPairing pass changed. Empty means nothing was touched.
ToolPairingViolation
One wire-level pairing violation found by validateToolPairing.
ToolRegistry
A named collection of AgentTools with a ready-made executor for the agent loop.
ToolResultMessage
The result of executing a tool the model asked to invoke.
ToolsConfig
One scope's tools: section: tool id → user intent.
TrajectoryAssistantRecord
A finalized assistant response row (message kind).
TrajectoryBlobPersister
Host-side persistence helper for request blobs (issue #385): turns one outbound-request capture into the custom records to append, in chain order — unseen prompt blob, unseen manifest blob, wire dump (when the request carries a raw one), then the model_request_summary with its pointers. Per-session instance: the seen-hash sets implement the F1/F2 dedup (a unique prompt or manifest version is persisted ONCE).
TrajectoryBlobTable
The per-session blob table: hash → blob for each blob kind, folded from the session's blob records. Renderers resolve request pointers (systemPromptHash etc.) through it; entries not present mean "not captured for this session" (E6) — old sessions render exactly as today.
TrajectoryCliCommand
The fa trajectory subcommand: a read-only trajectory view over a stored session.
TrajectoryCompactedRecord
A compaction or branch-summary row (compacted kind).
TrajectoryContextRecord
An application context-injection row (context kind).
TrajectoryDiffLine
One line of a bounded text diff (the section that changed, with a few context lines on each side).
TrajectoryGroupModel
One Message or Step group inside a turn.
TrajectoryHiddenRecordPreview
One drill-in row of a hidden range (issue #385 F4): a bounded preview of a record the compaction evicted from the context but the session file still holds.
TrajectoryPartialAssistant
An assistant message that is still streaming.
TrajectoryPartialBlock
An in-flight streaming content block of a partial assistant message.
TrajectoryPromptBlob
One full system-prompt version (F1). The text is stored whole — no cap (E2: a giant AGENTS.md merge is exactly the case worth auditing).
TrajectoryRecord
Base of the trajectory ledger hierarchy.
TrajectoryRequestDetail
Cheap outbound-request summary recorded before each provider call.
TrajectoryRequestMessageBlock
One parsed content block of an outbound request message (F3): block structure with a generous bounded full text and [image WxH] markers.
TrajectoryRequestMessageSummary
One outbound request message, summarized for the details panel.
TrajectoryRequestNumber
Request-header facts retained by the trajectory ledger.
TrajectoryRunningToolCall
A tool call observed but not yet answered.
TrajectorySearchIndex
Session-view-local index that reparses Markdown only when one record's sources change.
TrajectorySnapshot
Immutable stage-oriented trajectory data assembled from session records.
TrajectorySnapshotBuilder
Walks session records and live agent events, projecting them into immutable TrajectorySnapshots.
TrajectorySourceBlock
One source content block preserved in model order for the details panel.
TrajectorySystemRecord
A session-state change row (system kind).
TrajectoryTimelineModel
Full-domain model used by the overview.
TrajectoryTimelineSpan
One ledger record projected into the active timeline domain.
TrajectoryTimelineTurnBoundary
One turn boundary in the active timeline domain.
TrajectoryTimeRange
Inclusive selection in the active timeline projection's domain.
TrajectoryToolManifestBlob
One full tool-manifest version (F2), content-addressed over the serialized entries so equal tool sets dedup.
TrajectoryToolManifestEntry
One tool of a manifest blob: the manifest is exactly what the tools array of the request carried (F2).
TrajectoryToolRecord
A tool (or nested subtool) call row with its result once it arrives.
TrajectoryTurnModel
One sticky turn, or a standalone compaction section between turns.
TrajectoryUserRecord
A user message row (user kind).
TrajectoryWireDump
One opt-in raw wire dump (F5): the exact outbound request payload, redacted and capped before persist. Keyed by the dump's own content hash; the request summary points at it via wireDumpHash.
TranscribeAudioConfig
Configuration for the transcribeAudioTool transcription endpoint.
TranscribeAudioPlugin
Plugin that contributes the transcribe_audio tool.
TtsrConfig
A parsed TTSR configuration: manager settings plus the rules to monitor.
TtsrController
Orchestrates TTSR for one Agent.
TtsrManager
Registry + matcher for time-traveling stream rules.
TtsrMatchContext
Context about the stream content currently checked against TTSR rules (omp's TtsrMatchContext, minus file-path candidates).
TtsrRule
A time-traveling stream rule (omp's Rule, reduced to regex conditions).
TtsrScope
The streams a rule monitors (omp's parsed TtsrScope).
TtsrSessionSink
The host seam for session persistence the controller drives.
TtsrSettings
TTSR settings (omp's TtsrSettings, reduced).
TurnEndEvent
A turn finished: the assistant message completed and its tool calls (if any) produced toolResults.
TurnStartEvent
A new turn (assistant response + tool calls) started.
UnavailableShell
A Shell that reports ExecutionErrorCode.shellUnavailable for every command — the correct behavior on platforms without a process shell (web, or any sandboxed environment).
Usage
Token accounting for one assistant response, reported inline by providers.
UsageAccumulator
Mutable accumulator summing Usage across turns of an agent run.
UsageCost
Monetary cost of a request, in USD.
UserMessage
A message authored by the user.
WaiterSnapshot
One waiter-aggregate snapshot: what the agent is waiting for right now.
WebFetchContext
The extraction context handed to WebSiteHandlers: shared HTTP plumbing so handlers reuse the tool's client, timeout, and byte cap.
WebFetchResult
One extracted page: structured markdown plus the method that produced it (omp's RenderResult, reduced).
WebPage
A fetched web page: status, content type, and decoded body.
WebSearchConfig
Configuration for webSearchTool and webFetchTool.
WebSearchProvider
A search backend the web_search tool can walk in its fallback chain.
WebSearchRequest
One search request passed down the provider chain.
WebSearchResponse
One provider's answer to a search query (omp's SearchResponse).
WebSearchSource
One ranked search result: title, URL, and an optional snippet.
WebSiteHandler
A site-specific extraction handler (omp's SpecialHandler). Handlers are tried in order before the generic HTML→markdown converter; the first non-null result wins.
WindowedSessionStorage
Append-only session storage over a byte-scanned window of the file.
WindowsJobBackend
The Windows backend: Job Object descriptor generation (execution needs FFI — Phase 4 follow-up).

Enums

A2aTaskState
A2A Task states.
AgentLoadMode
The tool-load preset the harness boots with.
AgentMessageKind
The delivery intent of an AgentMessage.
AgentPresence
Presence of a mailbox owner, as REPORTED by its transport — the hub roster (AgentInfo.online analog) is authoritative for live/offline (registration/connection, not mtime heuristics); the file fabric reports busy from the instance's own marker and leaves the rest to the activity heuristics above it.
ApprovalDecision
The user's answer to an approval prompt.
ApprovalMode
Session-wide approval posture.
ApprovalPolicy
The resolved policy for one tool call.
ApprovalTier
How much damage a tool call can do, worst case.
ArchiveFormat
Recognized archive containers.
AttachedMessageRole
The roles an attached view renders.
BridgeErrorCode
Wire error codes. Envelope-level codes (proto, badToken, badFrame, badOp) travel on error frames; the rest are browser-op results carried inside browserRes payloads.
CheckpointAutoCloseReason
Why an active checkpoint was auto-closed instead of blocking a new one (issue #286: a checkpoint never outlives its detour scope).
CompactionEngine
Which compaction engine a compaction run uses.
CompactionErrorCode
Stable error codes for CompactionException, ported from pi's CompactionError kinds.
ConfigScope
Write scope of a set.
CopilotDeviceFlowErrorKind
Why a device flow failed. endpointDisabled is the Phase-0 live state: GitHub routes the endpoint but rejects the app's flow (404 JSON error).
CubeBackendMode
How a cube's commands are confined: policy (the Dart policy layers only) or kernel (wrapped in the OS sandbox primitive of the host platform — sandbox-exec on macOS, unshare on Linux).
CubePathAccess
Access level granted for a path.
CustomProviderAuthMethod
How a saved custom provider authenticates. Distinguishes regular API-key entries from SSO/JWT-backed ones (e.g. CodeMie) so the CLI can pick the right auth path when switching to a saved entry.
DapInboundMode
Where a host routes inbound hub mail (the DAP boundSession.mode config value):
ExecutionErrorCode
Stable, backend-independent error codes returned by Shell.exec.
FallbackNoticeKind
What the wrapper is about to do after a rate-limit failure.
FileErrorCode
Stable, backend-independent error codes returned by FileSystem operations.
FileKind
Kind of filesystem object addressed by a FileSystem.
FinishReasonClass
finish_reason retryability classification (issue #312).
ForkPosition
Where a fork cut point sits relative to JsonlSessionRepo.fork's entryId.
HashlineSectionOp
Per-section outcome of HashlinePatcher.commit.
HepToolArgs
Tool-argument verbosity for tool_start frames.
HubLinkState
The link state surfaced for host UI (the app's "Agent network" row): honest connection status, never a silent half-state.
KeyType
Kinds of keys recognized by the TUI input loop.
LeaseState
The outcome states of FileSessionLeaseStore.inspect.
LineEnding
Line-ending style of a text body.
LspClientStatus
Client lifecycle state (omp's status).
LspDiagnosticSeverity
LSP diagnostic severity (1=error, 2=warning, 3=information, 4=hint).
McpClientStatus
Client lifecycle state (mirrors LspClientStatus).
McpHttpTransportKind
The remote transport spoken by an McpHttpServerConfig.
McpServerStatus
Per-server lifecycle status.
MobileTier
The build tier of the Android app.
PowerAssertionHold
When the sleep-prevention assertion is held (power.hold, #326): per-run by default — an agent idling between turns must not pin the machine awake for hours (battery/thermal); holding the whole session is an explicit opt-in.
PowerAssertionLevel
The power.sleepPrevention levels. Cumulative: each level adds the capabilities of all lower levels (display also prevents idle sleep, system also prevents display sleep).
PromptToolFormat
Which wire format the wrapper teaches the model and parses back.
ProviderQueueScope
Which source won the scope resolution.
ProvidersSyncMode
Key-handling mode of one sync push.
QueueDeathKind
Why a queue entry died (issue #418 UT-kind-labeling): the exact string a switch event carries. Ordered by classification precedence.
QueueMode
Controls how many queued messages are injected when the loop reaches a queue drain point. Ported from pi's QueueMode.
RedactionLayer
Redaction layers, listed in strict priority order.
SessionErrorCode
Stable error codes for SessionException, ported from pi's SessionErrorCode union.
SharedSetting
Every shared settings concept that must exist on both platforms unless explicitly exempted.
SigintAction
What the SIGINT handler should do for one Ctrl+C press.
SkillsAccess
The consent state for third-party skill/agent discovery.
SkillScope
Where a skill was discovered (listing order in the prompt).
SkillSource
Which tool's directory layout the skill came from. First-party roots (.fah, .agents) are always readable; third-party roots (.claude/.github/.codex) are gated by the user's skills-access consent (see skills_access.dart).
StopReason
Why the assistant message stream terminated.
StructuredValidationStatus
Final validation state of a schema-bearing spawn (omp's StructuredSubagentValidationStatus).
SubagentStatus
The lifecycle state of a retained subagent.
TaskJobStatus
Background job states (omp's async job states, reduced).
TaskSpawnPhase
Lifecycle phases reported through TaskSpawnProgressCallback.
TaskSpawnStatus
Terminal state of one spawn (omp's exitCode/aborted pair as an enum: completed ↔ 0, failed ↔ 1, aborted ↔ caller cancellation).
ThinkingFormat
How a provider expects the reasoning/thinking parameter to be shaped.
ToolExecutionMode
How tool calls from a single assistant message are executed.
ToolPairingViolationKind
What a validateToolPairing violation is, in provider terms.
ToolScope
Where a tool decision can come from: the scope stack, ordered from the shallowest (broadest) to the harness's platform default.
TrajectoryCellKind
Closed set of trajectory record kinds.
TrajectoryGroupKind
What a group aggregates: a loose message run, a numbered assistant step, or a compaction.
TrajectoryRequestPurpose
What a captured provider request was issued for.
TrajectoryRequestStatus
Lifecycle state of a captured provider request.
TrajectorySystemChange
Why a TrajectorySystemRecord was written.
TrajectoryTimelineMode
Horizontal projection used by the trajectory timeline.
TtsrContextMode
What happens to the violating partial assistant output before the retry (omp's ttsr.contextMode).
TtsrMatchSource
Which stream a TTSR delta belongs to (omp's TtsrMatchSource).
TtsrRepeatMode
How often a rule may re-trigger (omp's ttsr.repeatMode).
TuiMouseMode
Mouse-scroll behaviour for the Fa TUI.

Extensions

AgentCliAgentExt on AgentCli
Implementation members of AgentCli for agent-type discovery and listing.
AgentCliBusyPhase on AgentCli
The busy-row phase push (issue #653): a plain passthrough. The busy row names the CURRENT activity — Compacting context… while the fold runs, then the post-fold handback ('') clears the marker the moment the compaction finishes, and later tool/stream labels stay marker-free. The «auto-compacted · continuing» badge used to be appended to every label here, so after any fold the row led with the stale marker for the rest of the run (owner screenshot: [auto-compacted ×7 · c… over active tool work). The badge lives on the status row only (_statusLine, until the turn settles — issue #438 AC3).
AgentCliCompactionRun on AgentCli
AgentCliExt on AgentCli
Bootstraps, sinks, and the /ext surface on AgentCli.
AgentCliHeadlessEvents on AgentCli
Headless structured-output header writes (issues #155/#695): the HEP hep_header frame and the stream-json session line are each the FIRST stdout line of their mode, emitted the moment the session id exists — before any agent event can race them. Split into this part (same library) so AgentCli.runHeadless stays under the CRAP gate.
AgentCliHubDriver on AgentCli
AgentCliLease on AgentCli
AgentCli lease/viewer half (private members of the CLI library).
AgentCliMcpStatusPrint on AgentCli
AgentCliMessagingFlow on AgentCli
AgentCliPersist on AgentCli
AgentCliPromptComposition on AgentCli
AgentCliRunNotices on AgentCli
Run-notice wiring for AgentCli, split from agent_cli.dart to keep it under the repo's 2800-line size gate. Same library (a part of), so the extension sees the class's private members.
AgentCliShellJobSettle on AgentCli
Settle notifications for session-scoped background shell jobs: the transcript/board note plus the model-facing system-notice (steered mid-run, a fresh run while idle). Lives here with the rest of the job-settle flow (issue #450) to keep the host class under the 2800-line gate.
AgentCliSkillsExt on AgentCli
Implementation members of AgentCli for skills: third-party access gating (the startup consent dialog and /skills access), /skill:<name> invocation (rendering, per-turn tool grants, context: fork), and the /skills management command.
AgentCliSpillWiring on AgentCli
AgentCliSteering on AgentCli
Steering persistence + delivery lifecycle members of AgentCli (issue #437). Named so the driver-test seams below stay reachable from the test suite (the private members stay library-private).
AgentCliTools on AgentCli
The /tools command, capability mapping, and live scope resolution.
AgentCliWaitingSeams on AgentCli
Test seams for the visible-waiting layer (issue #450).
AgentLoadModeLabel on AgentLoadMode
ApprovalCommands on AgentCli
Implementation members of AgentCli for approval prompts.
ApprovalModeLabel on ApprovalMode
The CLI/config spelling of an ApprovalMode (always-ask, write, yolo, unattended).
ComposerChipsSubmit on AgentCli
CubeCommands on AgentCli
The /cube command family on AgentCli.
EffectiveContextWindow on AgentCli
AutoCompactorHooks impl that drives the CLI TUI / stderr and the diagnostic log file (~/.fah/logs/fa.log). One per run; cheap to allocate. The memory LLM slot resolution — an extension so agent_cli.dart stays under the repo's 2800-line size gate. The effective context window of the live model under the owner cap (agent.contextWindowCap, issue #273): the compaction thresholds, the ctx meter/footer, and the loop's over-window guard all key off this basis — one clamp point (effectiveContextWindow), not one per consumer. Lives in this part file so agent_cli.dart stays under the 2800-line size gate.
HarnessModeSettings on AgentCli
Harness-mode settings members of AgentCli (issue #679).
MemoryLlmSlotResolution on AgentCli
MobileElementRender on MobileElement
Renders one element line for MobileElementIndex.render.
OverWindowGuardRelief on AgentCli
Issue #387: emergency relief for the loop's over-window guard — an extension so agent_cli.dart stays under the 2800-line size gate.
ProviderQueueEditor on AgentCli
SettingsFlow on AgentCli
Implementation members of AgentCli for the settings-hub flows. Named (not anonymous) so hosts and tests can drive the flows directly.
SlashCommandDispatch on AgentCli
Slash-command dispatch on AgentCli.
ThemeCommands on AgentCli
Theme management on AgentCli (issue #279).

Constants

agentLoadModeLabels → const List<String>
Every valid label, for error messages and the settings picker.
agentUrlScheme → const String
The internal URL scheme addressing subagent outputs.
aiinApiBaseUrl → const String
The production AIIN OpenAI-compatible API root (/v1 appended).
aiinAuthBaseUrl → const String
The production AIIN auth service (sign-in, OAuth proxy flow).
aiinDefaultOAuthProvider → const String
The default identity provider offered when the live provider list cannot be fetched (offline, standalone mode).
anthropicMessagesApi → const String
The Anthropic API dialect family the Claude ceiling table was derived from: the table is only consulted for models riding this api — a claude id served over any other dialect (openrouter routing, a claude-named model on an OpenAI-compatible proxy) keeps its provider's own default.
appOnlySettings → const Set<SharedSetting>
Settings that are currently app-only.
appStoreBlockEndMarker → const String
Marks the end of the generated App Store block in site/index.html.
appStoreBlockStartMarker → const String
Marks the start of the generated App Store block in site/index.html.
architectModePromptName → const String
Canonical prompt name for the CLI architect mode.
asn1BlobLabel → const String
Marker label used for standalone DER blobs.
authExpiredMarkerPrefix → const String
Marker used by UIs to detect an "auth session expired" provider error and offer a re-authorize button. The format is [[auth-expired:<id>]] and it is appended at the end of the formatted message.
bareBodyAutoPipedWarning → const String
Bare body rows auto-converted to literal + rows.
bashToolMaxRetries → const int
Transient-failure retries for foreground bash runs: timeout-class failures (a hung transport, or the model's own per-call cap) are retried up to this many times — 3 attempts total — before the error surfaces. Aborts and real command failures never retry.
bashToolName → const String
The canonical name of the shell tool the interceptor applies to (shellTool in builtin_tools.dart registers under this name).
branchSummaryPrefix → const String
Prefix wrapping a branch summary when it is projected into the model context. Ported from pi's BRANCH_SUMMARY_PREFIX.
branchSummaryPrompt → const String
Structured summary instructions for the branch abandoned during session-tree navigation, ported verbatim from oh-my-pi's branch-summary compaction prompt.
branchSummarySuffix → const String
Suffix closing branchSummaryPrefix. Ported from pi's BRANCH_SUMMARY_SUFFIX.
braveSearchUrl → const String
Brave Search API endpoint (omp's BRAVE_SEARCH_URL).
bridgeBadTokenCloseCode → const int
WebSocket close code used when the pairing token is rejected.
bridgeBrowserOpField → const String
Payload key carrying the browser op name inside a browserReq frame. The envelope op is browserReq itself, so the browser op cannot ride the same key (JSON objects have flat, unique keys); the contract's browserReq {id, op, args} maps id → envelope id and op → this field.
bridgeDedupeCapacity → const int
Bounded dedupe window: at most this many message ids are remembered (LRU — re-seeing an old id after eviction forwards it again).
bridgeDefaultPort → const int
Default TCP port of the loopback bridge (fa serve --bridge).
bridgeDispatchTimeout → const Duration
How long a BridgeConnection.dispatch waits for the correlated browserRes before resolving with a timeout error result.
bridgeHeartbeatInterval → const Duration
Fabric heartbeat (messaging.touch) interval while connected — keeps the mailbox live in directory views(formatA2aStatusLines-style listings).
bridgeKnownOps → const Set<String>
Every op a v1 peer may send; anything else decodes fine but is answered with BridgeErrorCode.badOp.
bridgeMailboxPrefix → const String
Fabric mailbox namespace for paired extensions: browser-ext/<agentId>.
bridgePollInterval → const Duration
Fabric mailbox poll interval while an extension is connected.
bridgeProtocolVersion → const int
The only protocol version this build speaks. A mismatching envelope v (or hello proto) is rejected with BridgeErrorCode.proto.
bridgeWsPath → const String
The single WebSocket endpoint served by the bridge.
certificateDnLabel → const String
Marker label used for certificate DN component values.
chatGptCodexBaseUrl → const String
chatGptIssuer → const String
chatGptOAuthClientId → const String
chatGptOAuthScope → const String
checkpointAutoClosedCustomType → const String
The custom_message type marking an auto-closed stale checkpoint (the audit trail for issue #286: why protection ended, with reason, goal, and anchors in details).
checkpointToolName → const String
The checkpoint tool name.
cliOnlyJustifications → const Map<SharedSetting, String>
User-readable justifications for the cliOnlySettings exemptions.
cliOnlySettings → const Set<SharedSetting>
Settings that are currently CLI-only.
cliProviderKinds → const Set<String>
The provider kinds accepted by --provider. Static — the set of every headless-capable catalog kind; a build filtered through the FA_PROVIDERS dart-define rejects the filtered kinds at resolution time (buildCliDefaultModel resolves through the filtered catalogProvider).
codeModePromptName → const String
Canonical prompt name for the CLI code mode (the default mode).
codexOriginator → const String
Originator value Codex CLI clients send with ChatGPT backend requests.
compactExpandToolName → const String
The compact_expand tool name.
compactionSummaryPrefix → const String
Prefix wrapping a compaction summary when it is projected into the model context. Ported from pi's COMPACTION_SUMMARY_PREFIX.
compactionSummarySuffix → const String
Suffix closing compactionSummaryPrefix. Ported from pi's COMPACTION_SUMMARY_SUFFIX.
configThinkingLevels → const List<String>
The rungs a config surface (issue #734: FA_PROVIDER_CONFIG, roles: chain entries) may declare: the ladder plus xhigh/max, which fold to high exactly like clampThinkingLevel — forward-compatible like pi. This list's order IS the error-message order.
configTopLevelKeys → const Set<String>
Every top-level key the runtime config actually reads (the keys CliConfig.fromYaml consumes, plus the roles: group members). The source-text pin keeping this set honest lives in test/config/config_service_test.dart.
configVerbs → const Set<String>
The verbs accepted by fa config.
connectionPasswordLabel → const String
Marker label used for connection-string passwords.
contextWindowExhaustedMarker → const String
Marker embedded in the over-window guard's error message (see _streamAssistantResponse): hosts match it to recognize "the loop refused to send because the outgoing context exceeded the model window" and can then auto-compact + continue the interrupted turn.
copilotBusinessBaseUrl → const String
copilotDeviceClientId → const String
The public client id of the VS Code Copilot Chat plugin (goal/copilot_provider.md, internal/api/config.go).
copilotDeviceGrantUrl → const String
The device-code request endpoint.
copilotDevicePollUrl → const String
The token-poll endpoint.
copilotDeviceScope → const String
The device-flow scope (enough to resolve the login and mint Copilot tokens).
copilotEnterpriseBaseUrl → const String
copilotIndividualBaseUrl → const String
Copilot API base URLs per account type (goal: copilot-proxy-go internal/api/config.go: GetBaseURL). Any new/corporate address works via an explicit baseUrl override in config.
copilotTokenExchangeUrl → const String
The token exchange endpoint — the same for all account types (individual/business/enterprise differ only in the API base URL).
coreToolFamilies → const Map<String, Set<String>>
The canonical host-agnostic availability-id → member tool-NAMES table: aggregate families map several registered tool names onto one tools: id. Singletons are single-entry sets so every consumer treats the shape uniformly. Host-specific ids — lsp, sqlite, mcp (plus mcp:<server>), and dap — stay host-wired: dynamic tool-name prefixes (dap_*, mcp__*) cannot live in a static name table.
credentialFileLabel → const String
Marker label used for credential-file spans.
credentialLabel → const String
Marker label used for credential field values.
criticalCommandToolNames → const Set<String>
Tool names whose command argument the critical patterns guard: the bash tool and the on-device mobile.shell (issue #622 — the Shizuku bridge executes at adb-shell privilege, so rm -rf /-class shapes must still force a prompt there).
customProviderApiTypes → const List<String>
The api types a custom provider can take (the adapter dialect), mapping one-to-one to catalog specs. Includes OAuth/SSO-backed catalog providers (openrouter, codemie) — their connect flows save registry entries so connected providers show in the /provider picker — and kimi, whose /provider kimi key flow saves a named entry per account.
defaultAppStoreUrl → const String
Baked-in defaults for our own products; user-overridable like any config key.
defaultArchiveListLimit → const int
Default entry cap for archive directory listings (omp's #readArchiveDirectory DEFAULT_LIMIT).
defaultChunkBytes → const int
Default byte cap per chunk: a record-count cap alone does not bound memory (one image record can be megabytes), so a chunk stops at whichever cap fills first.
defaultChunkRecords → const int
Default records per chunk (issue #135 open question — 200 recommended).
defaultCodeMieBaseUrl → const String
The hosted CodeMie default (an on-prem org URL can always be typed).
defaultCompactionPrompts → const CompactionPrompts
The built-in compaction prompts (no overrides).
defaultCompactionSettings → const CompactionSettings
Default compaction settings (pi's DEFAULT_COMPACTION_SETTINGS): reserve 16384 tokens, keep ~20000 recent tokens.
defaultDiagnosticsWait → const Duration
How long diagnostics waits for a fresh publish after opening a file (omp's SINGLE_DIAGNOSTICS_WAIT_TIMEOUT_MS).
defaultLsEntryLimit → const int
Default entry cap for the ls tool (pi's DEFAULT_LIMIT).
defaultLspRequestTimeout → const Duration
Default per-request timeout (omp's DEFAULT_REQUEST_TIMEOUT_MS).
defaultMaxImagesPerRequest → const int
Default per-request cap on unique images (images.maxPerRequest). Generous enough that ordinary sessions never hit it; photo-heavy long threads stay flat instead of growing linearly. ~20 inline images is well inside every current vision model's budget.
defaultMobileElementCap → const int
Default cap on kept elements (one screen rarely exceeds ~100).
defaultMobileObserveBudget → const Duration
Default per-step wall-clock budget (artemis's 3–5 s/step envelope).
defaultModelRole → const String
The role used for ordinary agent runs.
defaultPowerAssertionReason → const String
Default text shown in platform power diagnostics ("why is this machine awake?"). caffeinate(8) has no reason flag — the CLI banner cannot carry it — but systemd-inhibit --why and any future native IOKit assertion do.
defaultProviderQueueCooldown → const Duration
Cooldown applied to a quota death when the provider sent no Retry-After (issue #418 open question 1 — proposed 60s; flip to 30s here for snappier rotation).
defaultRemoteCatalogUrl → const String
The catalog endpoint — overridable via fa1.dev/models-catalog-url (the models: yaml section keys ride the same resolver) for staging or self-hosted mirrors.
defaultRunIdleTimeout → const Duration
Stateful wrapper around the low-level agent loop.
defaultSiteUrl → const String
defaultSqliteQueryLimit → const int
Default row limit for table queries (omp's DEFAULT_QUERY_LIMIT).
defaultSqliteSchemaSampleLimit → const int
Sample row count shown with a table schema (omp's DEFAULT_SCHEMA_SAMPLE_LIMIT).
defaultSubagentHeartbeatMinutes → const int
Default digest cadence: one digest every 10 minutes (subagents.heartbeatMinutes; 0 = kill switch).
defaultSubagentStallMinutes → const int
Default stall threshold: 20 minutes without provider activity (subagents.stallMinutes; 0 = stall flagging off).
defaultTaskAgentName → const String
Default agent type when an item omits agent (omp's DEFAULT_SPAWN_AGENT).
defaultTaskMaxConcurrent → const int
Default session concurrency cap (omp's task.maxConcurrency default; 0 means unbounded — see normalizeConcurrencyLimit).
defaultTestFlightUrl → const String
defaultThinkingBudgets → const Map<String, int>
pi's DEFAULT_THINKING_BUDGETS — the per-level budget ladder.
defaultToolMaxBytes → const int
Default byte limit for tool output truncation (pi's DEFAULT_MAX_BYTES).
defaultToolMaxLines → const int
Default line limit for tool output truncation (pi's DEFAULT_MAX_LINES).
defaultWebSearchCount → const int
Default number of results per search (omp's DEFAULT_NUM_RESULTS).
deliverySlo → const Duration
The one delivery SLO: a message lands end-to-end within it, whatever the recipient's state (running, idle, completed) and however many subagents are in flight.
discoveryEnabledByLoadMode → const Map<AgentLoadMode, bool>
Whether a preset ships the discover_tools discovery surface (issue #680): omp demotes everything non-essential and discovers it back on demand; pi is pi-mono's exact benchmark shape (issue #679) — 4 tools, discovery off, no meta tool; the default mode has no demotion at all (REG) and therefore nothing to discover.
duckDuckGoHtmlUrl → const String
DuckDuckGo's no-JS HTML search frontend. POST q=… to receive a static results page we can parse without a real browser (omp's endpoint choice; see the note on DuckDuckGoSearchProvider).
dynamicMessageMaxSourceBytes → const int
Maximum UTF-8 byte length of a widget's jsSource — a chat-message hygiene cap, not a sandbox limit.
essentialToolIdsByLoadMode → const Map<AgentLoadMode, Set<String>>
The availability ids each non-default preset keeps ESSENTIAL (always in the schema, pinned). Everything else known becomes discoverable.
estimatedImageChars → const int
Estimated character cost of an image block (pi's ESTIMATED_IMAGE_CHARS: 4800 chars ≈ 1200 tokens at 4 chars/token).
estimatedRepeatImageChars → const int
Wire-replacement charge for an image the registry already rides earlier in the request (an [Image N] label plus overhead).
extVerbs → const Set<String>
The verbs accepted by fa ext.
fallbackContextWindow → const int
Fallback limits when the endpoint reports nothing — the CLI catalog and the app share this floor (pi's smallest modern per-model values; the cap is a ceiling, not a target).
fallbackMaxTokens → const int
faMailMetadataKey → const String
The message-metadata key that marks an A2A message/send as fabric mail. Its value is A2aMailEnvelope's JSON.
fileOnlyConfigKeys → const Map<String, String>
Top-level yaml keys that are intentionally NOT interactive settings on ANY surface — structural or infrastructure config, edited in the file by design. Every entry carries its WHY (issue #288 AC1: a documented structural-only key, reviewed).
githubTokenLabel → const String
Marker labels for the vendor layer.
harnessModeValues → const Set<String>
Values accepted for the config agent.mode key. omp joins this set with issue #680 (it shares the same settings slot).
headTailDriftWarning → const String
INS.HEAD:/INS.TAIL: applied despite a stale snapshot tag.
hepVersion → const String
The HEP protocol version emitted in hep_header frames.
hiddenCustomRecordTypes → const Set<String>
Custom-record types the trajectory ledger deliberately does NOT render: hosts' non-row payloads consumed by other surfaces (request summaries and issue-385 blobs are handled above this set; anything else renders as an unknown record context row — F6, the ledger stays lossless).
hiddenRecordPreviewChars → const int
Character bound of a hidden-record preview.
hiddenRecordPreviewLimit → const int
Maximum drill-in rows served for one hidden range (E4: an open tail range and a giant range both resolve bounded).
hideJudgeSystemPrompt → const String
System prompt for the structured-compaction hide judge (the smol-role LLM call that picks which context records to hide). Validated on a real 14.5 MB session (issue
highEntropyLabel → const String
Marker label used for high-entropy spans.
hlDeleteBlockKeyword → const String
Hunk-header keyword: DEL.BLK N (tree-sitter block delete; unsupported).
hlDeleteKeyword → const String
Hunk-header keyword for concrete line deletion.
hlFileHashExamples → const List<String>
Representative file-hash tags for use in user-facing error messages and prompt examples.
hlFileHashLength → const int
Number of hex characters in a content-derived file-hash tag.
hlFileHashReRaw → const String
Canonical uppercase hexadecimal content-hash tag carried by a hashline section header.
hlFileHashSep → const String
Separator between a hashline file path and its snapshot tag.
hlFilePrefix → const String
File-section header delimiters: [path#hash].
hlFileSuffix → const String
hlHeaderColon → const String
Colon terminating a hunk header that takes a body.
hlInsertAfter → const String
Insert position keyword for inserting after a concrete line.
hlInsertAfterBlockKeyword → const String
Hunk-header keyword: INS.BLK.POST N: (insert after a tree-sitter block; unsupported).
hlInsertBefore → const String
Insert position keyword for inserting before a concrete line.
hlInsertHead → const String
Insert position keyword for inserting at the start of the file.
hlInsertKeyword → const String
Hunk-header keyword for insertion operations.
hlInsertTail → const String
Insert position keyword for inserting at the end of the file.
hlLineBodySep → const String
Separator between a line number and displayed line content in hashline mode.
hlMoveKeyword → const String
File-level keyword: MV DEST moves the file (unsupported).
hlPayloadReplace → const String
Payload sigil for literal body rows.
hlRangeSep → const String
Separator between two line numbers in a range, e.g. 5.=10.
hlRemKeyword → const String
File-level keyword: REM deletes the whole file (unsupported).
hlReplaceBlockKeyword → const String
Hunk-header keyword: SWAP.BLK N: (tree-sitter block replace; recognized by the parser but rejected as unsupported by this port).
hlReplaceKeyword → const String
Hunk-header keyword for concrete line replacement.
kMaxStageUploadBytes → const int
Hard cap for ONE staged upload: 20 MB (issue #313, review minor 3 — single-sourced here so every surface agrees). The extension's memory FS holds everything in RAM and mirrors it into chrome.storage, so the staging surface refuses oversized payloads BEFORE writing; the app's IndexedDB quota story does not apply there. Text pastes and normal attachments fit with an order of magnitude to spare. The panel-side pre-check (RelayAgentService.stageAttachment for the extension, the composer for picked files) uses the same constant — an oversized paste is refused before any base64 expansion, not after a wasted encode.
knownHtmlTags → const Set<String>
HTML tag names the scanner recognizes. Unknown names without a dash are treated as literal text so code generics (List<String>) inside <pre> survive conversion; custom elements (which always carry a dash) still parse as tags. SVG names are included so subtree skipping matches open/close tags correctly.
knownToolIds → const Set<String>
Tool ids the harness knows about, including aggregate families (mcp, bash_job) and per-host optionals (dap, generate_video). The web_search id is itself a family: it gates BOTH the web_search and web_fetch tools (no standalone web_fetch key).
lspConfigFileName → const String
Config file consulted in the workspace root (documented location; see LspConfig.load).
mailboxSourceHub → const String
The transport that sourced a directory entry (issue #304 AC3): hub roster entries render a [hub] marker in agent_directory so the model can tell DAP peers from file-inbox mailboxes; file/legacy entries carry null and render exactly as before.
maxArchiveBytes → const int
Cap on the on-disk size of an archive read into memory for indexing (omp's MAX_TAR_ARCHIVE_BYTES, applied to every format here because all decoding is in-memory).
maxArchiveMemberBytes → const int
Cap on a single archive member's declared (uncompressed) size — the declared size is attacker-controlled metadata (omp's MAX_ARCHIVE_MEMBER_BYTES).
maxConcurrentSessionParseBatches → const int
Max parse batches in flight on the executor path of parseSessionLines (issue #503): enough to keep the cores busy on a marathon walk, bounded so concurrent callers (windowed open + listing fan-out) never spawn an unbounded isolate storm.
maxSqliteColumnWidth → const int
Maximum per-column render width (omp's MAX_COLUMN_WIDTH).
maxSqliteQueryLimit → const int
Hard cap on an explicit ?limit= (omp's MAX_QUERY_LIMIT).
maxSqliteRawQueryRows → const int
Row cap for raw ?q= SQL — protects against SELECT * on multi-million-row tables (omp's MAX_RAW_QUERY_ROWS).
maxSqliteRenderWidth → const int
Maximum ASCII-table render width (omp's MAX_RENDER_WIDTH).
maxSqliteTableListEntries → const int
Cap on the rendered table list (omp's #readSqlite list limit).
maxTaskOutputBytes → const int
Maximum bytes of a subagent's raw output kept in the in-memory store and the per-item result (omp's MAX_OUTPUT_BYTES).
maxTaskOutputLines → const int
Maximum lines of a subagent's raw output (omp's MAX_OUTPUT_LINES).
maxTranscribeAudioBytes → const int
Largest accepted audio payload: 25MB, matching OpenAI's upload cap for the transcription endpoint.
maxWebSearchCount → const int
Maximum number of results per search (omp's MAX_NUM_RESULTS).
mcpClientInfo → const Map<String, String>
The client identity advertised in initialize.
mcpProtocolVersion → const String
The MCP protocol revision the client advertises.
mcpResultTextBudget → const int
Shared character budget for the TEXT of one MCP tool result.
mediaModelSlotIds → const List<String>
Every known media slot name, in declaration order.
mediaSlotOverrideFields → const List<String>
The fields one media slot override carries (same names in the app's media_models.json and the CLI's models: yaml section).
memoryModelRole → const String
The role long-term-memory LLM work (consolidation, semantic search) resolves through when configured. Falls back to smol, then the main model — the memory call shapes match the smol cost class.
minAnswerTokens → const int
pi's MIN_ANSWER_TOKENS: a thinking budget may never squeeze the answer below this many tokens.
mobileHierarchyToolName → const String
mobileLaunchToolName → const String
Tool names (the mobile.* contract).
mobileLogsToolName → const String
mobileScreenshotToolName → const String
mobileShellToolName → const String
mobileSideloadGateReason → const String
The honest gate reason for tools the store flavor cannot provide: names the tier and the sideload link (UT-floor-2 reason golden).
mobileSwipeToolName → const String
mobileTapToolName → const String
mobileTextToolName → const String
modelEnvVar → const String
Env var name carrying the active model id.
modelRoleIds → const List<String>
The model roles supported by ModelRolesConfig, in declaration order.
nonVisionToolImagePlaceholder → const String
Placeholder substituted for tool-result images when the target model has no image input (pi's NON_VISION_TOOL_IMAGE_PLACEHOLDER).
nonVisionUserImagePlaceholder → const String
Placeholder substituted for user-message images when the target model has no image input (pi's NON_VISION_USER_IMAGE_PLACEHOLDER).
nonYamlSettings → const Set<SharedSetting>
SharedSettings that own NO ~/.fah/config.yaml key because their storage lives elsewhere. The completeness gate allows exactly these to have empty yamlKeys (issue #288 E1: secrets never ride the yaml).
openRouterAuthEndpoint → const String
The OpenRouter authorization endpoint.
openRouterDefaultKeyLabel → const String
Default app label shown to the user on the OpenRouter authorization page.
openRouterTokenEndpoint → const String
The OpenRouter token/key exchange endpoint.
overridablePromptNames → const Map<String, String>
The prompt names accepted in the CLI config prompts: section, mapped to a short description. Names mirror the prompts/ tree ids used by scripts/gen_prompts.dart; systemPromptAlias is an alias for codeModePromptName.
piModeEnvVar → const String
The FA_PI_MODE=1 env twin of the --pi flag. The flag wins (AC3: flag > env > config).
piToolIds → const Set<String>
The pi benchmark tool surface (issue #679): exactly pi's four tools - read, write, edit, bash (ls/grep live under bash in pi's benchmark shape). Everything else - subagents, memory, web, messaging, scheduling, checkpoint/rewind, lsp, generate_*, MCP, plugins - is off.
projectContextFileNames → const List<String>
The context filenames collected per directory, in priority order (all present files are included, each as its own block).
projectContextMaxBytes → const int
The merged-content budget, allocated leaf-first so deeper (more specific) files are never truncated in favor of shallower ones (kimi's _AGENTS_MD_MAX_BYTES).
providerCatalog → const Map<String, ProviderSpec>
The built-in provider table.
providerConnectTimeout → const Duration
Connect/first-headers watchdog for provider calls: an endpoint that never answers the request would otherwise hang the turn forever. Three minutes on purpose: loaded reasoning endpoints (kimi-k3 et al.) may hold a big request for over a minute before the first byte.
providerEnvVar → const String
Env var name carrying the active provider kind.
providerNameAliases → const Map<String, String>
Auth-domain aliases (#706): several spellings can name the SAME provider account — the ChatGPT OAuth flow derives chatgpt.com from the endpoint host while the catalog provider is chatgpt, so one auth domain ended up with two picker identities, both marked current. The map folds an alias spelling onto its canonical id; entries keep their registry name (switching, key slots), identities canonicalize.
providerQueueDefaultCooldown → const Duration
The default cooldown when a 429 carries no Retry-After (issue #418 open question 1: 60s proposed; one-line change if the owner prefers 30s).
providerQueueKinds → const List<String>
The adapter kinds a queue entry's provider_type may name — the same dispatch providerStreamFunction accepts. Kept as a literal list so parse errors can enumerate the candidates without importing the catalog (and its transitive provider adapters) into every consumer.
providerQueueMaxBackoffDoublings → const int
Consecutive-failure cooldown doubling cap: base * 2^n until this many doublings, then the clamp holds (UT-backoff-doubling).
providerQueueMaxCooldown → const Duration
Cooldown clamp ceiling: a Retry-After beyond this (or a backoff doubling past it) clamps here (UT-cooldown-borders).
providersSyncCapability → const String
The hello caps entry a client advertises to receive the sync push. Older extensions do not send it and never see the frame.
providersSyncVersion → const int
Payload version. Bump only for breaking shape changes; additive fields keep 1.
providerStreamIdleTimeout → const Duration
Idle watchdog for provider streams: with no bytes for this long the endpoint is considered wedged — the stream errors (and the roles resolver may fail over) instead of hanging the turn forever. Generous on purpose: reasoning models may think long BETWEEN chunks (kimi-k3 thinks for minutes), so this only trips on a truly silent connection.
redactionExemptTools → const Set<String>
Tool outputs that are model-authored: their content is the code/config the MODEL produced, so key-shaped strings in them are the deliverable, not leaks. Never redacted (issue #24 AC7, mirroring pi-redact-all's scoped hooks).
registeredSecretLabel → const String
Marker label used for registered exact-value matches.
requestBlockChars → const int
Character bound of one request-message block's full text (F3) — generous (vs the 200-char single-line preview) but bounded.
requestPreviewChars → const int
Character bound of a TrajectoryRequestMessageSummary.preview.
responsesOmittedToolResultNote → const String
The note text that replaces a tool result with no convertible content once history is re-shaped for the responses wire (issue #705).
reviewModePromptName → const String
Canonical prompt name for the CLI review mode.
rewindReportCustomType → const String
The custom_message type carrying the retained rewind report in the session tree (omp's rewind-report custom message).
rewindToolName → const String
The rewind tool name.
rowCountProbeCap → const int
Upper bound on rows scanned when counting a table for the listing. SQLite has no stored row count, so COUNT(*) is a full b-tree scan; the listing counts exactly only when a table is provably small, reading at most this many rows (omp's ROW_COUNT_PROBE_CAP).
searchIndexThrottleMs → const int
Minimum gap between throttled index flushes, mirroring the TS SEARCH_INDEX_THROTTLE_MS.
seenLineRevealCap → const int
Upper bound on the number of unseen anchor lines whose actual file content is inlined into a rejection error (omp's SEEN_LINE_REVEAL_CAP).
seenLineRevealMaxColumns → const int
Per-revealed-line character cap, so a revealed anchor line can never dump a minified megabyte-wide line into the tool error and model context (omp's SEEN_LINE_REVEAL_MAX_COLUMNS).
sensitiveValueLabel → const String
Marker label used for generic context values.
sessionFileEnvVar → const String
Env var name carrying the current session's JSONL file path.
sessionIdEnvVar → const String
Env var name carrying the current session id.
sessionParseBatchMaxBytes → const int
Max chars per parse transfer.
sessionParseBatchMaxLines → const int
Max lines per parse transfer.
sessionVerbs → const Set<String>
settingSurfaces → const Map<SharedSetting, SettingSurfaces>
The {macOS, iOS, web, extension} applicability audit (issue #288 AC3).
shallowCustomRecordThreshold → const int
Size gate for the shallow custom path (64 KiB) — smaller lines decode whole, the header extraction is not worth it.
sharedSettingMetadata → const Map<SharedSetting, _SettingMeta>
Metadata for each SharedSetting: what to search for in each platform's source tree. The parity test greps the cliRef pattern inside lib/src/cli/ (recursively) and the appRef pattern inside flutter_app/lib/ (recursively). A non-null pattern that is absent from the target tree fails the test.
smolModelRole → const String
The role compaction summarization resolves through when configured.
spillReadHint → const String
The preview trailer naming what to do with the spill file.
spillsMinPreviewChars → const int
The smallest preview excerpt bound accepted from config. A section asking for less is clamped up to this (with a note) so a preview can never degenerate into a single unreadable line (issue #678 AC11).
sqliteBusyTimeoutMs → const int
PRAGMA busy_timeout applied on open (omp: 3000 ms).
steeringAttributionPrefix → const String
The user-role attribution prefix, mail-parity with inbound mail.
steeringConsumedType → const String
steeringRecordType → const String
Session-record types of the steering persistence (issue #437). One steering record per accepted steer (data['text'] = the attributed message; context-hidden: a CustomRecord never projects into model context), one steering_consumed marker per delivery.
streamJsonImagePlaceholder → const String
Placeholder emitted for image content blocks (E5): non-UTF8-safe payloads never ride the stream as base64 blobs.
streamJsonMaxToolResultChars → const int
Cap on a single tool-result text block in the stream (E3), matching the house truncation idiom (…(+N chars)).
streamJsonVersion → const int
The wire version in the session header line (fa's own stream schema; pi's current header says 3 for its superset).
structuredCheckpointPrompt → const String
Instruction tail for the structured-compaction checkpoint LLM call (pass 2). The checkpoint text must list every covered expand id and carry open user requests verbatim (issue
subagentAgentMarker → const String
Header metadata value marking a session as a subagent's transcript (written by both hosts' childSessionFactory: the CLI's agent_cli.dart and the app's agent_service.dart).
subagentModelRole → const String
The role spawned subagents resolve through when configured (items without a specialist role — explore keeps smol, review keeps slow). Falls back to the parent model when unset.
subagentRegistryRecordType → const String
The session-record type of the registry snapshot: one full row list per write, in the parent session's JSONL (a side-leaf custom record).
summarizationPrompt → const String
Lossless context-checkpoint prompt for a first-time compaction. Forked from pi's SUMMARIZATION_PROMPT; body wording diverges deliberately (no s-word framing).
summarizationSystemPrompt → const String
System prompt for the compaction summarization LLM. Ported verbatim from pi SUMMARIZATION_SYSTEM_PROMPT.
supportedAudioExtensions → const Set<String>
Audio file extensions accepted by the tool (Whisper-compatible formats).
systemPromptAlias → const String
The system config key: an alias for codeModePromptName (the base CLI system prompt).
taskOutputPreviewChars → const int
Per-item output preview cap inside the blocking tool result text; the full output stays addressable as agent://<id> (omp's fullOutputThreshold).
taskToolName → const String
The task tool name.
tavilySearchUrl → const String
Tavily search endpoint (omp's TAVILY_SEARCH_URL).
toolSchemaMaxChars → const int
Character bound of one tool schema inside a manifest blob (E3).
toolScopeStack → const List<ToolScope>
The scope stack in resolution precedence order, shallow→deep: global, project, session, runtime. Hosts building a resolveToolAvailability scopes: list map over this instead of hand-writing the quadruple. ToolScope.builtin is the implicit capability floor and never a list entry.
trajectoryVerbs → const Set<String>
The verbs accepted by fa trajectory.
ttsrInjectionCustomType → const String
The custom_message type carrying the injected reminder in the session tree (omp's ttsr-injection custom message).
ttsrInjectionRecordType → const String
The custom record type persisting injected rule names (omp's ttsr_injection entry).
turnPrefixSummarizationPrompt → const String
Prompt for checkpointing the prefix of a split turn during compaction. Forked from pi's TURN_PREFIX_SUMMARIZATION_PROMPT; body wording diverges deliberately (no s-word framing).
unavailableImageNote → const String
The note replacing image refs whose original is not in the request (compaction interplay / cap drops — never a dangling ref).
undecodableToolImagePlaceholder → const String
Tool-result counterpart of undecodableUserImagePlaceholder.
undecodableUserImagePlaceholder → const String
Placeholder substituted for user-message images after the backend rejected the request as undecodable (e.g. Gemini's 400 Unable to process input image): the retry tells the model WHY the image is gone instead of silently dropping it.
updateSummarizationPrompt → const String
Prompt for folding new messages into an existing compaction checkpoint. Forked from pi's UPDATE_SUMMARIZATION_PROMPT; body wording diverges deliberately (no s-word framing).
uploadsDirName → const String
Directory (relative to the env's working directory) where chat attachments are staged before the outgoing message references them.
vendorPrefixes → const List<String>
Distinctive prefixes of every vendor pattern, in scan order.
voidHtmlTags → const Set<String>
Tags that have no content model and never need a close tag.
wakePromptText → const String
The prompt the headless wake run starts with — the inbox drain delivers the pending mail into the turn; the session file is shared.
webSearchUserAgent → const String
Shared browser-profiled user agent for the keyless scrape endpoints.
wireDumpMaxChars → const int
Character cap of a persisted wire dump (F5). The payload is cut at the cap with a truncation marker; only wire dumps are capped — system prompts and manifests are not (E2).
wireDumpTruncationMarker → const String
Marker appended to a wire dump cut at wireDumpMaxChars.
yieldTokenZoneKey → const Symbol
Zone key under which the agent loop publishes the current tool phase's soft-yield token (see currentYieldToken).

Properties

builtinExploreAgent TaskAgentDefinition
omp's scout ported under the name explore: read-only research on the smol role.
final
builtinPlanAgent TaskAgentDefinition
The read-only planning specialist on the plan role.
final
builtinReviewAgent TaskAgentDefinition
omp's reviewer ported under the name review: read-only code review on the slow role.
final
builtinTaskAgent TaskAgentDefinition
omp's general-purpose worker (prompts/agents/task.md): full tool surface, inherits the parent model.
final
builtinTaskAgentTypes List<TaskAgentDefinition>
The built-in agent types, in registry order.
final
bundledCatalogEndpoints Set<String>
Provider base URLs the CLI can show WITHOUT any user config — the catalog's default endpoints above. The cli_visual leak guard subtracts these from the real-config markers so a hermetic screen rendering the provider picker is never flagged for bundled-catalog content (issue #508).
no setter
bundledCatalogModelIds Set<String>
Model ids the CLI can put on screen WITHOUT any user config — the offline fallback catalog above. The cli_visual leak guard subtracts these from the real-config markers so a hermetic screen is never flagged for bundled-catalog content (issue #508).
no setter
bundledRemoteModelsCatalog RemoteModelsCatalog
Bundled fallback catalog — ships in-process so the picker still works when the remote URL is down (the user just reported "только одна m3 захардкожена" because the GitHub Pages site at fa1.dev didn't ship the catalog JSON yet). The remote fetch is the source of truth; this is the offline seed. The catalog contains ONLY metadata the chat endpoint doesn't publish (context windows, media slots) and the chat ids the picker falls back on when /v1/models is unreachable. Keep it data-shaped (a single JSON literal) so the remote catalog can replace it 1:1 the day fa1.dev ships.
final
chatGptCodexContextWindows Map<String, int>
Per-model context window (input cap) keyed by slug.
final
chatGptCodexDefaultModel String
Default model — first entry of chatGptCodexBundledModels, kept as a separate constant so the OAuth flow and the picker agree.
final
chatGptCodexMaxTokens Map<String, int>
Per-model output cap (max tokens) keyed by slug.
final
chatGptCodexModels List<String>
Slugs only — same shape callers used to read from the hand-rolled list before the sync script existed.
final
criticalBashPatterns List<CriticalBashPattern>
Patterns that force an approval prompt for any matching bash command.
final
defaultWebSearchProviders List<WebSearchProvider>
The default provider set in chain order: keyless DuckDuckGo first, then the keyed providers (filtered by key availability when the chain runs).
final
deliverySloSink ↔ void Function(String line)?
Host sink for delivery stage lines. Null keeps the core silent.
getter/setter pair
effectiveProviderConnectTimeout Duration
The effective connect watchdog: the config override or the default.
no setter
effectiveProviderStreamIdleTimeout Duration
The effective stream-idle watchdog: the config override or the default.
no setter
imageDropNotice ImageDropNotice?
Set by hosts that surface drops (the CLI prints a dim transcript line
getter/setter pair
imageRefPattern RegExp
The reference grammar: [Image 3] inline text.
final
imageRegistryConfig ImageRegistryConfig
Process-wide image-registry settings, published by hosts at boot from the images: config section (same pattern as providerTimeoutsOverride): the rewrite happens deep inside the agent loop's request build, far from any host config object.
getter/setter pair
modelListDialects List<ModelListDialect>
The registered dialects, in precedence order. First match wins. Adding a new provider = one new class + one entry here.
final
onUnknownFinishReason ↔ void Function(String line)?
The loud log for UNKNOWN finish_reasons (the #312 cataloguing hook): fires once per occurrence at mapping time with the raw reason so new vendor words can join the classification table. Null keeps it silent.
getter/setter pair
providerFilterEnvOverride String?
The runtime FA_PROVIDERS environment variable, resolved by the host (bin/fah.dart or the app wiring) and injected once at startup. The compile-time define WINS over this runtime value when both are set. Unset (null) on hosts without a concept of process env (web).
getter/setter pair
providerHttpClientFactory ↔ Client Function()?
Optional HTTP-client factory for platform-specific networking.
getter/setter pair
providerTimeoutsOverride ProviderTimeoutsOverride?
Process-wide watchdog override, set once at startup from the config file (same pattern as providerFilterEnvOverride); tests may set it directly. Null keeps providerConnectTimeout/providerStreamIdleTimeout.
getter/setter pair
remoteCatalogEnrichment RemoteCatalogEnrichment
Process-wide RemoteCatalogEnrichment singleton. Hosts preload once at boot and the rest of the code reads from this instance. Tests swap it via setRemoteCatalogEnrichmentForTesting.
getter/setter pair
textOnlyImageDropNotice TextOnlyImageDropNotice?
The active text-only drop reporter - wired once by the host at boot.
getter/setter pair
transientRetryNotice TransientRetryNotice?
The host-visible retry hook (the CLI prints it + logs to fa.log). Null keeps retries silent. Global like providerTimeoutsOverride: the wrap happens deep inside providerStreamFunction, far from any host io.
getter/setter pair
transientRetrySleeper Future<bool> Function(Duration delay, CancelToken? cancelToken)
The retry sleep — injectable so tests don't wait real seconds. Returns false when the wait was cancelled (the retry is abandoned).
getter/setter pair

Functions

accumulateUsage(Usage? cumulative, Usage? next) Usage?
Sums token/cost accounting across requests for the cumulative fold.
adjustMaxTokensForThinking({int? baseMaxTokens, required int modelMaxTokens, String? level, Map<String, int>? customBudgets}) → ({int maxTokens, int thinkingBudget})
pi's adjustMaxTokensForThinking: pair the wire max_tokens with a thinking budget that fits inside it.
agentLoadModeFromLabel(String? label) AgentLoadMode?
Parses a default|pi|omp label (config agent.mode, FA_AGENT_MODE). Returns null for null/empty (no intent); an unknown label is the caller's error to report (ConfigException at boot).
agentLoadModeValidationError(Object? value) String?
Validates one agent.mode value (issue #680): null when value is a legal agentLoadModeLabels label, else the error text. The single source shared by the boot parser (cli_config.dart) and the settings validator (config_service.dart) — both throw it as a ConfigException, so the rule cannot drift between the two parsers.
agentLoop({required List<Message> prompts, required Context context, required AgentLoopConfig config, required StreamFunction streamFunction, required ToolExecutor toolExecutor, CancelToken? cancelToken}) AgentEventStream
Starts an agent loop with new prompt messages.
agentLoopContinue({required Context context, required AgentLoopConfig config, required StreamFunction streamFunction, required ToolExecutor toolExecutor, CancelToken? cancelToken}) AgentEventStream
Continues an agent loop from context without adding a new message.
aiinGenerateState() String
One-time CSRF state for the AIIN sign-in flow (32 random bytes, base64url without padding).
aiinJwtEmail(String token) String?
The email claim of an AIIN JWT payload, or null when the token carries none or is not a JWT. Used to name provider entries after the account.
applicationNote(String section) String
Whether/when a change to section applies at runtime.
applyHashlineEdits(String text, List<HashlineEdit> edits) HashlineApplyResult
Applies edits to text and returns the post-edit result. Throws HashlineFormatException if an anchor is out of bounds.
applyPayloadHook(Map<String, dynamic> params, Model model, FutureOr<Map<String, dynamic>?> onPayload(Map<String, dynamic>, Model)?) Future<Map<String, dynamic>>
Runs an adapter's onPayload hook, returning the replacement payload or params unchanged when the hook is absent or returns null.
applyTextEditsToString(String content, List<LspTextEdit> edits) String
Applies edits to content in-memory, bottom-to-top (omp's applyTextEditsToString). Call sortAndValidateTextEdits first (this function re-sorts defensively).
applyWorkspaceEdit(ExecutionEnv env, LspWorkspaceEdit edit, {Map<String, int> openFileVersions = const {}}) Future<List<LspAppliedChange>>
Applies edit through env and returns the per-file changes.
approvalModeFromLabel(String? value) ApprovalMode?
Parses a CLI/config label into an ApprovalMode; null when unknown.
architectMode(String cwd, {PromptOverrides? overrides}) AgentMode
High-level design and planning mode.
archiveFormatFromPath(String filePath) ArchiveFormat?
Infers the archive format from a filesystem path's extension (omp's archiveFormatFromPath).
askTool({AskCallback? callback}) AgentTool
Creates the ask tool bound to callback.
assistantDisplayText(List<ContentBlock> content) String
Row label for a message with no visible text or reasoning.
attachApproval(Agent agent, ApprovalManager manager) → void
Composes the approval gate for manager onto agent, preserving any BeforeToolCallHook already registered (approval runs first).
attachedRowFromMessage(Message message) AttachedMessage?
Renders one conversation Message as an attached-view row, or null for content the view skips (tool results, empty rows).
attachRedactionPipeline(Agent agent, RedactionPipeline pipeline, {RedactionToolPolicy policy = const _ConstPolicy()}) → void
Composes the pipeline hooks onto agent, preserving hooks already registered. beforeToolCall: existing hooks run first; if any of them blocks, that verdict stands. afterToolCall/transformContext: existing hooks run first, redaction runs last so content they produce is masked too.
attachSecretRedactor(Agent agent, SecretRedactor redactor) → void
Composes the redaction hooks for redactor onto agent, preserving any hooks already registered (existing hooks run first, redaction runs last so content they produce is masked too).
attachSpillHooks(Agent agent, {required ExecutionEnv env, required String? sessionId(), required SpillsConfig config}) → void
Composes the spill hook onto agent, preserving hooks already registered (the redactor runs FIRST — spill sees redacted content, issue #678 AC5; secrets never touch disk raw). Oversized results are written to the store and replaced by the symmetric preview; a failed write keeps the full body inline with spillFailureMarker. Content the redactor or an earlier hook overrode stays overridden.
authExpiredProvider(String formattedError) String?
Returns the provider id for an auth-expired formatted message, or null if there is no marker.
bashJobTool(ShellJobRegistry jobs) AgentTool
Creates the bash_job tool: inspect and stop the session's background shell jobs (see ShellJobRegistry).
bridgeBackoff(int attempt) Duration
Reconnect backoff for bridge clients: 1s doubling, capped at 30s.
browserTools({required BrowserController controller, required Future<String> saveScreenshot(Uint8List png)}) List<AgentTool>
Builds the browser tool family over controller. Every tool is exec-tier (the AgentTool default) and throws BrowserToolException on failure.
buildAiinLoginUrl({required String redirectUri, required String state, String clientType = 'desktop', String environment = 'prod', String authBaseUrl = aiinAuthBaseUrl}) Uri
The hosted AIIN sign-in page — the recommended entry point for clients. The page lists every enabled provider (Apple included once enabled), runs the whole OAuth round-trip on AIIN's side (including silent pass-through for an existing AIIN session) and redirects back to redirectUri with code + our state. The state is generated by the CLIENT (not the server) and validated on the caught redirect.
buildCatalogModel(String provider, String modelId, {String? baseUrl, int? contextWindow, int? maxTokens, List<String>? input, String? thinkingLevel}) Model
Builds a Model for provider/modelId with catalog defaults, overrid- able per reference (see ModelRef).
buildChatGptAuthorizeUrl({required String redirectUri, required String codeChallenge, required String state}) Uri
buildCliDefaultModel(String providerKind, {String? modelId, String? baseUrl, List<String>? input, String? thinkingLevel}) Model
Providers carry NO default model: a model is always an explicit choice (--model, a saved switch, a roles chain, or a picker's live /models list). Silent defaults chose paid flagships over free tiers behind the user's back (zai's glm-5.3 vs glm-5.3-flash — real spend nobody ordered), so the mechanism was removed, not re-seeded. Builds the legacy single Model the fah executable runs when no roles are configured (--provider/--model/--base-url flags).
buildCodeMieSsoUrl(String codeMieUrl, int port) String
The SSO login URL embedding the local callback port — the organization redirects to http://localhost:<port>/?token=... after the browser login.
buildOpenRouterAuthUrl({required String codeChallenge, String? callbackUrl, String? keyLabel, String? state}) Uri
Builds the OpenRouter authorization URL.
buildPreview(String body, {required String spillPath, required SpillsConfig config}) String
Builds the symmetric preview for body — exactly what the session stores and the model sees (issue #678 Decision). Pinned sectioning (blank-line separated): header lines / head / omitted marker / tail + read hint:
buildProviderQueueChain(List<ProviderQueueEntry> entries, {required Map<String, String> secrets, StreamFunction streamFactory(String kind, String apiKey)?, List<String>? skipped}) List<ChainEntry>
Builds the ChainEntry list for a resolved queue: one model per entry (catalog defaults + the entry's overrides), a single key stack per entry from its apiKeyEnv (the _2/_3 stack convention rides along free), and the catalog stream factory bound per key.
buildProvidersSync(Iterable<CustomProviderEntry> entries, {required ProvidersSyncMode mode, required String hostname, Map<String, String> keys = const {}}) ProvidersSyncPayload
Builds the sync payload from the CLI's saved custom providers.
buildSqliteAsciiTable(List<String> columns, List<Map<String, Object?>> rows) String
Renders rows as a width-capped ASCII table (omp's buildAsciiTable).
builtInAgentModes(String cwd, {PromptOverrides? overrides}) Map<String, AgentMode>
All built-in modes keyed by name.
builtinTools(ExecutionEnv env, {HashlineSnapshotStore? snapshots, WebSearchConfig? webSearch, CubeNetworkGate? networkGate, ConfigService? config, Model? model()?, SqliteEngine? sqlite, LspToolConfig? lsp, McpManager? mcp, ShellJobRegistry? shellJobs, PasswordPromptCallback? onPasswordPrompt}) List<AgentTool>
Creates the four built-in tools (readFileTool, writeFileTool, listDirTool, shellTool) bound to env.
caffeinateArguments(PowerAssertionOptions options, {required int pid}) List<String>
The caffeinate(8) argument vector for options, ending in the -w <pid> lifecycle bind: caffeinate watches the fa pid and self-exits when it goes away, so a crashed fa can never leak the assertion.
calculateContextTokens(Usage usage) int
Calculate total context tokens from provider usage.
calculateCost(Usage usage, Model model) Usage
Fills in Usage.cost from the model's ModelCost rates.
cancelSubagentWithoutJob({required String id, required SubagentManager? manager, TaskExecutor? executor, String source = 'task_cancel'}) Future<String>
Cancels the subagent named id when its id names no live background TaskJob (issue #332) — the ONE helper both cancel surfaces (the task_cancel tool and /tasks cancel) route through, so their wording can never diverge. Three honest outcomes:
canonicalProviderName(String name) String
The canonical provider identity of name: alias spellings fold onto their canonical id (case-insensitive); unknown names map to themselves (lowercased). One auth domain — one identity, across the registry, the picker rows, and the current marker.
canonicalTaskAgentName(String name) String
Canonicalizes a task-agent type name: lowercase, with the Claude Code / omp naming aliases folded onto the built-in type they alias (general-purposetask, scoutexplore, reviewerreview, plannerplan).
canonicalToolCallId(String id) String
Canonical wire form of a tool-call id: the projection every provider adapter applies before putting an id on the wire — characters outside [a-zA-Z0-9_-] become _ (Anthropic/Google/OpenAI _normalizeToolCallId) and the result truncates to 40 chars (the strictest limit, OpenAI). Pairing checks and the uniqueness stamp compare canonical forms, so two raw ids that collapse into one provider-side id count as duplicates even when their raw forms differ.
catalogProvider(String name) ProviderSpec?
Resolves name against the providerCatalog, honoring the build-time provider filter (FA_PROVIDERS — filtered names resolve to null and the error paths list only the enabled providers).
clampThinkingBudgetToAnswerRoom(int thinkingBudget, int ceiling) int
pi's clampThinkingBudgetToAnswerRoom: the budget may never exceed the output ceiling minus minAnswerTokens.
clampThinkingLevel(String? level) String?
pi's clampThinkingLevel: the ladder has no xhigh/max rung, so they fold to high, the ladder's top. Everything else passes through unchanged, including null (no thinking requested).
clampWebSearchCount(int? count) int
Clamps a requested result count to 1..[maxWebSearchCount], defaulting to defaultWebSearchCount (omp's clampNumResults).
classifyCopilotPollResponse(Response response, {required String clientId}) CopilotPollOutcome
Classifies one device-flow poll response. Pure: 404 → endpointDisabled, a non-JSON body → transport, an access_token → success, otherwise the OAuth error field decides.
classifyFinishReason(String reason) FinishReasonClass
Classifies a raw wire finish_reason (AssistantMessage.rawStopReason). Anything outside both sets is FinishReasonClass.unknown.
classifyQueueDeath(ErrorEvent event) QueueDeath?
Classifies an error event into a queue death (issue #418 AC3/UT-13 kind strings). Returns null when the chain must NOT advance — the content_filter finish_reason family, a user abort, and unknown errors all surface verbatim (the roles precedent).
cliHelpText(String version) String
The full --help output printed by the fa executable. version is threaded through from the executable (_version in bin/fah.dart) — the single source of truth shared with --version — and rendered in the header line.
codeMieApiBase(String rawUrl) String
Normalizes an organization URL to the API base: https://hosthttps://host/code-assistant-api (idempotent).
codeMieCookieExpired(String cookie) bool
Parses a CodeMie cookie string (k=v; k=v) and checks whether the access-token JWT is past its exp claim. If parsing fails, treats the cookie as expired so the caller can force a fresh SSO login.
codeMieJwtExpired(String token) bool
Whether a CodeMie JWT Bearer token is past its exp claim. Tokens without an exp claim are treated as non-expired.
codeMieJwtExpiresAtMs(String token) int?
The expiry (ms epoch) of a CodeMie JWT Bearer token's exp claim, or null when the token is malformed or has no exp.
codeMieOrgUrl(String baseUrl) String
The inverse of the stored provider base URL: <org>/code-assistant-api/v1<org> — the bare organization URL the SSO flow needs (re-login from the provider editor).
codexRequestHeaders({required String accessToken, String? accountId, required String sessionId, required String threadId, String originator = codexOriginator, String? subagent}) Map<String, String>
Headers Codex clients attach to ChatGPT backend requests.
collectEntriesForBranchSummary(Session session, String? oldLeafId, String targetId) Future<CollectBranchEntries>
Collect the entries to summarize when navigating from oldLeafId to targetId: walks from the old leaf back to the common ancestor, returning entries in chronological order (omp's collectEntriesForBranchSummary). Compaction boundaries do NOT stop the walk — their summaries become context for the branch summary.
collectKeyStack(Map<String, String> secrets, String baseName) List<ApiKeyCredential>
Collects a key stack for baseName from secrets: the bare name first, then _2, _3, ... in numeric order. Returns an empty list when the base name is absent.
compareSessionActivity(SessionMetadata a, SessionMetadata b) int
Sorts by latest activity (file mtime), falling back to creation time so stable ordering is guaranteed even when mtimes are equal.
computeFileHash(String text) String
Computes the content-derived hash tag carried by a hashline section header: the low 16 bits of xxHash32 (seed 0) over the UTF-8 bytes of the normalized text, as 4 uppercase hex characters.
computeFileLists(FileOperations fileOps) → ({List<String> modifiedFiles, List<String> readFiles})
Compute sorted read-only and modified file lists from accumulated operations. Ported from pi's computeFileLists.
configLeafLines(String value, {required int depth}) List<String>
The leaf value lines for a config value: a JSON array/object renders as a yaml block under the key (list-valued keys — customProviders, the roles: chains, redact: lists); anything else stays the single scalar line renderYamlScalar always wrote. Shared by config set and the settings flows' surgical upsert.
configTool(ConfigService service) AgentTool
The worst-case op (set) mutates a config file, so the tool declares ApprovalTier.write. A failed op (unknown key, invalid value, refused write) surfaces as an error: … text result — never an exception — so the model always gets an actionable answer.
containsRecognizableHashlineOperations(String input) bool
Returns true when the input contains at least one line that the tokenizer recognizes as a hashline op.
copilotApiBaseUrlFromToken(String token) String?
The Copilot API base URL carried INSIDE the token, if any (pi getBaseUrlFromToken parity): Copilot tokens embed proxy-ep=proxy.<tenant>.githubcopilot.com (individual/business/ enterprise tenants, incl. dedicated enterprise endpoints); the API host is the proxy host with the proxy. prefix swapped for api.. Null when the token carries no proxy-ep (older/individual tokens — the caller keeps the configured base URL).
copilotApiHeaders({required String copilotToken}) Map<String, String>
The mandatory Copilot API headers, per request (goal: copilot-proxy-go internal/api/config.go: BuildCopilotHeaders). A fresh x-request-id UUID is minted per call.
copilotInitiatorFor(List<Message> messages) String
The X-Initiator value for messages: agent when the LAST message is an assistant or tool result (a continuation of the model's own turn), user otherwise (goal: copilot-proxy-go requestHeaders).
createAiinApiKey({required String accessToken, Client? client, String apiBaseUrl = aiinApiBaseUrl}) Future<AiinApiKey>
Registers a new AIIN API key for the authenticated user.
createAssistantMessageEventStream() AssistantMessageEventStream
Creates an AssistantMessageEventStream.
createFileOps() FileOperations
Create an empty file-operation accumulator. Ported from pi's createFileOps.
createSessionId() String
Creates a new session id (time-ordered uuidv7).
createSseIterator(StreamedResponse response, CancelToken? cancelToken, {Duration? idleTimeout}) StreamIterator<ServerSentEvent>
Wires an SSE StreamIterator over response's body, cancelling the subscription when cancelToken fires so the connection closes promptly.
credentialPathOf(ToolCall call) String?
Extracts the credential path a tool call is about to touch, if any.
cubeBackendForPlatform(String os, {CubeSpec spec = const CubeSpec(name: 'host'), String workspaceRoot = '/workspace', String tmpdir = '/tmp', Map<String, String> envVars = const {}}) CubeSandboxBackend
Picks the backend for host platform os, bound to a run's context.
cubeEnvPrefix({required String workspaceRoot, required String tmpdir, Map<String, String> envVars = const {}}) String
The env -i VAR=value argument words for a kernel-wrapped run: the fixed PATH trio, HOME at workspaceRoot and TMPDIR under it (the only guaranteed-writable area), then the cube's injected envVars on top (a same-named var overrides the default). Values are single-quoted so paths with spaces survive the outer shell.
cubeSpecCacheKey(CubeSpec spec) String
The content-addressed spec key: 10 hex chars of the md5 over the spec's CubeSpec.toCanonicalMap JSON. Shared by the cache root (cube-cache/<key>) and the kernel profile staging path (cube-profiles/<key>.sb).
currentYieldToken() CancelToken?
The soft-yield token of the enclosing tool-call phase, or null.
decodeCodeMieSsoToken(String raw) Map<String, String>
Decodes the callback token parameter: base64 JSON with a cookies object. Throws FormatException on any malformed shape.
decodeHtmlEntities(String text) String
Decodes the small set of HTML entities seen in search results and page content (named, decimal, and hexadecimal forms).
decodeSessionCwd(String slug) String?
Reverses encodeSessionCwd: --Users-Uladzimir_Klyshevich-git-dm.ai--/Users/Uladzimir_Klyshevich/git/dm.ai.
decodeUtf8Text(Uint8List bytes) String?
Decodes bytes as strict UTF-8 text, or returns null for binary content (omp's decodeUtf8Text: NUL bytes or malformed UTF-8 mark binary).
dedupeUploadName(String name, int n) String
name.extname-1.ext for n = 1; names without an extension get the suffix appended whole.
defaultAgentCliSystemPrompt(String cwd) String
The default system prompt for the CLI agent.
defaultAgentMode(String cwd, {PromptOverrides? overrides}) AgentMode
The default coding-agent mode.
defaultHubBackoff(int attempt) Duration
Exponential reconnect backoff: 1 s doubling, capped at 30 s (spec "Client reconnect"). The cap also guards the attempt counter: a hub down for days must not shift a timer by years.
defaultSessionIoDelay(Duration delay) Future<void>
The wall-clock sleep between retries. Injectable so tests observe the backoff schedule without waiting for it.
defaultSkillRoots({required String cwd, String? homeDir}) → ({List<SkillRoot> projectRoots, List<SkillRoot> userRoots})
The default skill roots for a host.
defaultWebSiteHandlers() List<WebSiteHandler>
The site handlers tried, in order, before the generic HTML→markdown converter.
deliveryStage(String childId, String stage, {DateTime? since}) → void
One delivery stage line for childId: elapsed anchored at since (the send) when given; stage names where the message is. A stage past the SLO is marked as a breach so the diagnostic names the stalled stage.
deriveCodeMieExpiresAt(Map<String, String> cookies) int
The expiry (ms epoch) of the first JWT cookie's exp claim.
deriveMailboxId(String agentId) String
Fabric mailbox id for a paired extension: browser-ext/<agentId>, the agent id sanitized by the same rules every mailbox directory uses.
deriveTrajectoryLayout(TrajectorySnapshot snapshot) List<TrajectoryTurnModel>
Folds a snapshot into turns of Message/Step groups.
deriveTrajectoryTimeline(List<TrajectoryTurnModel> turns, [TrajectoryTimelineMode mode = TrajectoryTimelineMode.sequence]) TrajectoryTimelineModel?
Projects every visible record into a stable three-lane timeline.
describeAnchorExamples([String linePrefix = '']) String
Formats a comma-separated list of example anchors with an optional line-number prefix, quoted for inclusion in error messages: "160", "42", "7".
detailTextOf(Iterable<ContentBlock> content) String
Detail text of the text blocks, newline separated (TS detailContent).
detectLineEnding(String content) LineEnding
Detects the first line ending style in content. Defaults to LineEnding.lf when neither is present.
dialCompletionsUri(String baseUrl, String deployment, {String? apiVersion}) Uri
Builds the DIAL chat-completions URL: {baseUrl}/openai/deployments/{deployment}/chat/completions, with the api-version query parameter appended when apiVersion is non-empty.
discoverSkills(ExecutionEnv env, {List<SkillRoot> projectRoots = const [], List<SkillRoot> userRoots = const [], Set<SkillSource>? allowedSources}) Future<List<Skill>>
Discovers skills under projectRoots then userRoots (project wins on a name clash, first-name-wins case-insensitively). Roots whose source is not in allowedSources (defaults: everything) are skipped — hosts pass the first-party set when the user has not granted third-party skills access. Missing roots are silently skipped.
discoverToolsTool({required Map<String, String> discoverableDocs(), required String onMount(List<String> requested)}) AgentTool
Builds the discover_tools tool.
downgradeAllImages(List<Message> messages) List<Message>
Replaces EVERY image block with the non-vision placeholders, regardless of the model's declared modalities. Used when a text-only backend rejected the request's image parts (issue #42: z.ai glm-5.3 400 messages.content.type is invalid, allowed values: ['text']): the adapter retries once with the images downgraded, so the turn survives and the model can explain the swap instead of dying with a raw API error.
downgradeUndecodableImages(List<Message> messages) List<Message>
Replaces EVERY image block with undecodableUserImagePlaceholder / undecodableToolImagePlaceholder, regardless of the model's declared modalities. Used when a vision-capable backend rejected the request as undecodable (Gemini's 400 Unable to process input image): the adapter retries once with the images downgraded, so the turn survives and the model can tell the user the image was unreadable.
downgradeUnsupportedImages(List<Message> messages, Model model) List<Message>
Replaces image blocks with explicit placeholder text when model has no image input, so nothing is dropped silently at request time.
dynamicMessageTool({DynamicMessageCallback? callback}) AgentTool
Creates the dynamic_message tool bound to callback.
editFileTool(ExecutionEnv env, {HashlineSnapshotStore? snapshots}) AgentTool
Creates the edit tool: edits a file in one of two modes.
effectiveContextWindow(int contextWindow, int? cap) int
The effective context window: contextWindow clamped to cap when an owner cap is configured (agent.contextWindowCap, issue #273) and positive; a null/non-positive cap leaves the window untouched, so uncapped runs behave byte-identically to before. Every consumer of the EFFECTIVE window — the compaction thresholds, the ctx meter/footer, the loop's over-window guard — computes through this (one clamp point, not one per consumer).
enabledProviderNames() List<String>
The build-enabled provider names (enabledProviders in name form).
enabledProviders() List<ProviderSpec>
The build-enabled subset of the catalog (insertion order preserved). Without FA_PROVIDERS this is the whole table; visible: false entries are excluded regardless of the filter.
encodeSessionCwd(String cwd) String
The per-project directory slug used under the sessions root (/work--work--). Public so sibling stores (e.g. the messaging fabric root) colocate with the project's sessions.
estimateContextTokens(List<Message> messages) ContextUsageEstimate
Estimate context tokens for messages using provider usage when available.
estimateProjectedBranchTokens(List<SessionRecord> branch) int
Projection-aware variant of estimateSessionBranchTokens (issue #503 round 3b): counts what Session.buildContextMessages would ACTUALLY project, not the raw branch. Three adjustments over the raw tally:
estimateRequestOverheadTokens(String? systemPrompt, List<Tool> tools) int
Estimated token cost of the request parts that are NOT transcript messages: the system prompt and the tool schemas (name + description + JSON-encoded parameters), at pi's 4-chars-per-token heuristic.
estimateRequestTokens(List<Message> messages, {String? systemPrompt, List<Tool> tools = const []}) int
Full next-request estimate — the ONE basis the ctx meter, the loop's over-window guard, and the compaction threshold all enforce.
estimateSessionBranchTokens(List<SessionRecord> branch) int
Estimated context tokens for a walked session branch (root-first records), counting ONLY what Session.buildContextMessages would project into the model context: messages, custom messages, compaction and branch summaries. Ledger-only records (custom payloads like model_request_summary, model/label markers, …) never reach the context and count zero — a marathon tail full of giant model_request_summary snapshots does not inflate the estimate.
estimateStringTokens(String text) int
estimateTokens for a bare string — the same chars/4 heuristic, no per-block structure. The ONE estimator for a system prompt: the boot banner's pi-mode initial-context line and the parity gate (pi_hello_parity_test.dart) both price a prompt with it, so the printed and gated numbers agree by construction.
estimateTokens(Message message) int
Estimate token count for one message using pi's character heuristic.
estimationImageKey(ImageContent image) String
The content key estimation dedups against — a public seam pinned to imageContentKey so the estimator and the registry never drift.
exchangeAiinOAuthCode({required String code, required String state, Client? client, String authBaseUrl = aiinAuthBaseUrl}) Future<AiinOAuthTokens>
Exchanges the redirect's temporary code + state for AIIN JWTs.
exchangeChatGptAuthorizationCode({required String code, required String redirectUri, required String codeVerifier, Client? client}) Future<ChatGptOAuthCredentials>
exchangeOpenRouterCode(String code, {required String codeVerifier, Client? client, String? label}) Future<OpenRouterOAuthKey>
Exchanges an authorization code for an OpenRouter API key.
executeSqliteReadQuery(SqliteDatabase db, String sql) SqliteRows
Runs a raw read-only query (omp's executeReadQuery): rejects bound parameters and caps row collection at maxSqliteRawQueryRows.
expandPromptTemplate(String text, List<PromptTemplate> templates) String
Expands a /name args... template invocation if it matches a known template. Returns text unchanged when it is not a template command.
exportTrajectoryJson(TrajectorySnapshot snapshot) String
Serializes snapshot to a pretty-printed JSON string with full fidelity: every record keeps its kind, turn/step, timestamps, full texts, raw tool arguments, results, error fields, request summaries, and usage.
exportTrajectoryMarkdown(TrajectorySnapshot snapshot) String
Renders snapshot as readable Markdown: one ## section per model turn, one ### row per record, full texts and tool payloads in fenced blocks.
extractDefaultValue(String question) String?
Parses a (empty = X): or (empty keeps 'X'): hint from question, returning X so the TUI prompt can show it as the default value, or null when no default hint is present.
extractFileOpsFromMessage(Message message, FileOperations fileOps) → void
Add file operations from assistant read/write/edit tool calls to fileOps. Ported from pi's extractFileOpsFromMessage.
extractHtmlTitle(String html) String?
Extracts and decodes the <title> of an HTML document, or null when absent or empty.
fenceScreenContent({required String source, required String packageName, required String content}) String
Wraps screen-derived content in the untrusted fence (the browser-extension quarantine shape): provenance header, neutered inner fences, and the treat-as-data trailer.
fetchAiinOAuthProviders({Client? client, String authBaseUrl = aiinAuthBaseUrl}) Future<List<String>>
The identity providers AIIN currently accepts for sign-in.
fetchCodeMieModels(String apiBase, String cookie, {Client? client}) Future<List<String>>
Fetches the model ids from <apiBase>/llm_models?include_all=true (apiBase is <org>/code-assistant-api/v1), authenticating with the full cookie string as a Cookie: header. The response is a list of descriptors whose id lives in id, base_name, or deployment_name (first non-empty wins).
fetchCodeMieModelsWithJwt(String apiBase, String jwtToken, {Client? client}) Future<List<String>>
Fetches the model ids from <apiBase>/llm_models?include_all=true using JWT Bearer authorization (Authorization: Bearer <jwtToken>).
fetchCodeMieProjects(String apiBase, String cookie, {Client? client}) Future<List<String>>
Fetches the user's accessible projects from <apiBase>/v1/user — the applications + applications_admin arrays merged and deduplicated. Authentication uses the full cookie string as a Cookie: header.
fetchCopilotApiToken({required String githubToken, Client? client}) Future<CopilotApiToken>
Exchanges a GitHub token for a Copilot API token (goal: copilot-proxy-go internal/auth/github_client.go).
fetchDialModels(String baseUrl, String apiKey, {Client? client}) Future<List<String>>
Fetches the deployment ids from {baseUrl}/openai/models (OpenAI-shaped {"data": [{"id": …}]} response), authenticating with the Api-Key header. Any failure answers an empty list — callers keep their hardcoded fallback model list.
fetchDialModelsInfo(String baseUrl, String apiKey, {Client? client}) Future<DialModelsInfo>
fetchDialModels plus the DIAL-specific deployment features: the second component carries the ids whose features.cache flag is on (manual cache_breakpoint markers are honored). features.auto_caching models cache on their own and need no markers; they are NOT in the set.
fetchGitHubLogin({required String githubToken, Client? client}) Future<String>
The GitHub login behind a token (GET https://api.github.com/user, goal: the account name is the default Copilot entry name copilot-<login>). Throws CopilotAuthException on a non-200.
fetchModelsForEndpoint(String baseUrl, {required String apiKey, String? provider, Client? client}) Future<ModelsEndpointInfo>
Fetches the model list of baseUrl, picking the wire dialect by registration order. Any failure answers an empty info — callers always keep their manual-entry fallback.
fetchRemoteModelsCatalog({Uri? url, Client? client}) Future<RemoteModelsCatalog?>
Fetches the remote catalog. Honours a 10-second connect/idle budget (matches the other lightweight endpoint reads in models_endpoint) and never throws — every error returns null, the host falls back to bundledRemoteModelsCatalog + the endpoint's own /v1/models.
fileToUri(String path) String
Converts an absolute file path to a file:// URI (omp's fileToUri).
findCutPoint(List<SessionRecord> entries, int startIndex, int endIndex, int keepRecentTokens) CutPointResult
Find the compaction cut point that keeps approximately keepRecentTokens recent tokens.
findTurnStartIndex(List<SessionRecord> entries, int entryIndex, int startIndex) int
Find the user-visible message that starts the turn containing an entry.
finishReasonRetryClass(AssistantMessage message) FinishReasonClass?
The structured retry verdict the wire finish_reason carries, or null when the failure has no finish_reason (HTTP-level errors, socket cuts, truncation) and the message-text nets decide instead. TERMINAL vetoes every retry.
firstResponsesGrammarViolation(List<Map<String, dynamic>> input) String?
Describes the first Responses item/content-grammar violation in a converted input list, or null when the payload is valid (issue #705).
folderModelStateApplies({required bool modelExplicit, required bool providerExplicit, required bool baseUrlExplicit, required bool hasProviderPreconfig}) bool
Whether the saved per-folder state may override the global config for this launch: only when the user pinned nothing explicitly (flags or the FA_PROVIDER_* env preconfig are per-launch declarations and always win).
folderModelStatePath({required String sessionsRoot, required String cwd}) String
Path of the per-folder model state file for cwd.
formatAnchoredContext(List<int> anchorLines, List<String> fileLines) List<String>
Numbered LINE:TEXT rows around anchorLinesmismatchContextLines), *-marking anchors, ... between non-adjacent runs. Out-of-range anchors contribute no rows.
formatCompactionReport(AutoCompactorPass pass, {required bool auto}) List<String>
Auto/manual compaction run methods (moved from agent_cli.dart under the repo's 2800-line size gate). Same library, so private state is in scope. Formats the in-chat compaction report block (issue #276): tokens before → after, freed count/percent, WHICH ENGINE did the summarizing (the smol/main role — review major 3: a report that doesn't name the engine can't be judged), how many records were hidden vs summarized, and — when the pass actually wrote summary text — the summary in a fenced block so the user can eyeball — and copy — what the transcript was condensed to. A pass with no summary text (all evictions went to hide, or the model returned blank — issue #578) omits the block: an empty ```-fence says nothing and reads as a bug. Pure; _AgentCliCompactionReportPrinter.print renders it.
formatDurationMillis(int? milliseconds) String
Formats a duration in milliseconds with thousands separators.
formatElapsedSeconds(double? seconds) String
Formats an elapsed duration given in seconds as a millisecond label.
formatFileOperations(List<String> readFiles, List<String> modifiedFiles) String
Format file lists as summary metadata tags. Ported from pi's formatFileOperations.
formatHashlineHeader(String filePath, String fileHash) String
Formats a hashline section header for a file path and snapshot tag.
formatLineRanges(List<int> lines) String
Compresses a line list into a sorted 1-4, 7, 10-12 range string.
formatMemoryStatsLines(List<MemoryEntry> entries, DateTime? lastMaintenance, bool maintenanceDue) List<String>
Formats the /memory stats block (pure, testable): counts per type, last maintenance, and the due hint.
formatNumberedLine(int lineNumber, String line) String
Formats a single numbered line as LINE:TEXT.
formatNumberedLines(String text, [int startLine = 1]) String
Formats file text with hashline-mode line-number prefixes for display.
formatPathRelativeToCwd(String path, String cwd) String
Renders path relative to cwd when it sits underneath it (omp's formatPathRelativeToCwd, reduced to the common case).
formatProjectContext(List<ProjectContextFile> files) String
Renders the context files as a system-prompt section (kimi's wrapper, reduced): each file annotated with its source path, precedence note for deeper-vs-shallower rules. Empty when nothing was discovered.
formatProviderError(Object error) String
Composes the display string for an ErrorEvent.errorMessage.
formatSkillsForPrompt(List<Skill> skills, {bool forModel = true, Iterable<String> touchedPaths = const [], String? cwd}) String
Renders the progressive-disclosure block for the system prompt: metadata only — the agent loads a skill's file with the read tool when the task matches its description. Empty when there are no skills.
formatTimelineOffset(double milliseconds) String
Format a timeline duration as an integer-millisecond label.
formatTokenPreset(int tokens) String
Formats a token count as a compact preset label (4K, 16K, 1M).
formatTokens(int? tokens) String
Formats a token count compactly (999, 12.3k, 1.2M).
formatToolSize(int bytes) String
Formats a byte count as a human-readable size (pi's formatSize).
formatWebSearchResults(WebSearchResponse response) String
Formats a response for the model (omp's formatForLLM, reduced to the fields the ported providers produce): the answer first when present, then [n] title / url / snippet sources.
generateBranchSummary(List<SessionRecord> entries, {required SummarizeFn summarize, int tokenBudget = 0, String? customInstructions, CancelToken? cancelToken}) Future<BranchSummaryResult>
Generate a summary of abandoned-branch entries (omp's generateBranchSummary): serializes them into <conversation> tags, ends with the fixed branch-summary prompt (or customInstructions), and prepends the branch preamble plus the file-operation tags. Never throws: failures surface as BranchSummaryResult.error.
generateChatGptPkceChallenge(String verifier) String
generateChatGptPkceVerifier() String
generateChatGptState() String
generateOpenRouterCodeChallenge(String verifier) String
Generates the S256 code challenge for a verifier.
generateOpenRouterCodeVerifier() String
Generates a PKCE code verifier.
generateSessionEntryId(Map<String, SessionRecord> byId) String
generateSummary(List<Message> messages, {required SummarizeFn summarize, String? customInstructions, String? previousSummary, CancelToken? cancelToken, CompactionPrompts prompts = defaultCompactionPrompts, String? userRequestCandidates}) Future<String>
Generate (or update) a conversation summary for compaction.
getSqliteRow(SqliteDatabase db, String table, SqliteRowLookup lookup, String key) Map<String, Object?>?
Looks a row up by primary key or rowid (omp's getRowByKey / getRowByRowId). Returns null when no row matches.
getSqliteTableSchema(SqliteDatabase db, String table) String
The CREATE TABLE statement for table (omp's getTableSchema).
groupSessionsByParent(List<SessionMetadata> sessions) List<SessionGroup>
Groups sessions into SessionGroups: every subagent session whose parent is present in the list nests under it; orphans stay top-level.
handleRedactCommand(RedactionPipeline? pipeline, List<String> args) RedactCommandOutcome
Handles a /redact command line against pipeline (null = redaction disabled by config).
hasHeader(Map<String, String?>? headers, String name) bool
Whether headers contains a non-empty value for name (case-insensitive).
headerToSessionMetadata(SessionHeader header, String path, {DateTime? lastUpdatedAt, int? sizeBytes}) SessionMetadata
hepAgentStartFrame({required int turnId}) String
Builds agent_start for turnId.
hepArgsSummary(Map<String, dynamic> args, HepToolArgs mode) String
Renders tool-call arguments for a tool_start frame.
hepCancelledFrame({required int turnId}) String
Builds cancelled for turnId.
hepCompactionEndFrame(int turnId, int tokensFreed) String
Builds compaction_end for turnId.
hepCompactionStartFrame(int turnId) String
Builds compaction_start for turnId.
hepHeaderFrame({required String fahVersion, required String sessionId}) String
Builds the header frame: protocol version, fah version, session id.
hepMessageDeltaFrame({required int turnId, required String delta}) String
Builds message_delta for turnId.
hepMessageStartFrame({required int turnId, required String role}) String
Builds message_start for turnId.
hepMessageText(AssistantMessage message) String
Joins an assistant message's text blocks into the turn_done message.
hepToolDeltaFrame({required int turnId, required String id, required String update}) String
Builds tool_delta for turnId.
hepToolResultEntry(ToolResultMessage result) Map<String, Object>
Builds a tool_results entry from a tool result message.
hepToolStartFrame({required int turnId, required String id, required String name, required String argsSummary}) String
Builds tool_start for turnId.
hepTurnDoneFrame({required int turnId, required String message, required List<Map<String, Object>> toolResults, required Usage usage, required String stopReason}) String
Builds turn_done for turnId.
hepTurnErrorFrame({required int turnId, required String error, required bool fatal}) String
Builds turn_error for turnId.
htmlToMarkdown(String html, {Uri? baseUrl}) String
Converts an HTML document to structured Markdown. baseUrl resolves relative link/image targets; when null they are emitted verbatim.
httpMcpTransport(McpHttpServerConfig server, {Client? client}) Future<McpTransport>
Opens the transport for a remote server (both HTTP kinds are pure Dart, so hosts without process support still get remote servers).
hubHex(List<int> bytes) String
The hex-encoding shared by id derivation and signing payloads.
hubRandomHex(int nChars) String
Random lowercase hex string of nChars characters (hello nonces).
imageContentKey(ImageContent image) String
Content key of an image: SHA-256 over the canonical payload string (data:<mime>;base64,<data>). Same bytes under a different mime are distinct entries (re-encoded occurrences dedup-miss — correct but suboptimal, learn.ai's resilient-lookup semantics).
imageKeyPreview(String key) String
A short, stable preview of a content key for drop notices.
imageRefLabel(int index) String
Renders the reference label for index.
initiateAiinOAuth({required String provider, required String redirectUri, String clientType = 'desktop', String environment = 'prod', Client? client, String authBaseUrl = aiinAuthBaseUrl}) Future<AiinOAuthInitiate>
Starts the AIIN OAuth proxy flow: returns the sign-in AiinOAuthInitiate.authUrl for the browser and the AiinOAuthInitiate.state to exchange later.
inputModalitiesFor(String modelId) List<String>
The input modalities for modelId per the heuristic — used when switching to a model the endpoint reported no metadata for.
inspectImageTool(ExecutionEnv env, InspectImageConfig config) AgentTool
Creates the inspect_image tool.
interactiveKeySet({required String? name, required SecureKeyCache keys, required void onSecretStored(String name, String value)?, required Future<TuiPromptAnswer?> prompt(TuiPromptSpec), required void onResult(String message), required void onSaved(String name, String value)}) Future<void>
Testable core of the TUI key-set flow: prompts for name (when name is null) and a masked value through prompt, validates, saves to keys, and reports the outcome through onResult. The freshly saved key is handed to onSaved for immediate provider pickup.
interactiveModelEdit({required Model current, required Future<TuiPromptAnswer?> prompt(TuiPromptSpec), required void onResult(String message), required void onApply({required bool isContext, required int value})}) Future<void>
Testable core of the TUI model-edit flow. Prompts for field (context window vs max tokens), then a preset or custom value, and calls onApply with the result. Reports messages through onResult.
isAiinBaseUrl(String baseUrl) bool
True when baseUrl points at an AIIN endpoint (api.aiin.by or auth.aiin.by, host-exact — path/query text does not count).
isAllowedChatgptHost(String host) bool
Whether requests to host may carry ChatGPT backend credentials.
isAllowedCloudflareCookieName(String name) bool
Whether a cookie name may be stored for ChatGPT backend traffic.
isClassicGitHubPat(String token) bool
Whether token is a GitHub classic PAT (ghp_…). Official Copilot CLI docs (2026-09): classic PATs are NOT a supported Copilot credential type — the connect flow warns at paste time and re-asks.
isClassifiedYamlKey(String key) bool
Whether key is classified: owned by a SharedSetting or documented as file-only. The completeness gate (test/parity/ settings_completeness_test.dart) fails on any parsed key where this is false.
isCodeMieBaseUrl(String baseUrl) bool
True when baseUrl points at a CodeMie API endpoint (<org>/code-assistant-api[/v1]).
isCodeMieJwtToken(String token) bool
True when token looks like a JWT (header.payload.signature). This is a shallow format check; codeMieJwtExpired validates the payload too. Cookie strings (k=v; k=v) are rejected because they can also contain dots and split into three parts. JWT padding (=) is allowed and normalized during decoding.
isContextOverflow(AssistantMessage message, {int? contextWindow}) bool
Whether message represents a context overflow.
isContextWindowExhaustedError(String? errorMessage) bool
Whether an assistant AssistantMessage.errorMessage was produced by the loop's mid-turn over-window guard (as opposed to a provider error, a tool failure, or an abort).
isCopilotBaseUrl(String baseUrl) bool
Whether baseUrl points at a Copilot API endpoint (any account type). The one detection shared by model listing and by surface code that must recognize a connected Copilot entry (e.g. key cleanup on delete).
isCredentialFilePath(String path) bool
True when path points at a credential file: its basename is one of _credentialBasenames (with config.json only counting under a .docker directory), or it is a .env.* variant.
isCredentialPath(String path) bool
Whether path names a credential file.
isDuckDuckGoAnomalyPage(String html) bool
true when DDG returned its bot-challenge page instead of results. DDG mixes 200/202 statuses on these, so the body marker is the reliable signal (omp's isAnomalyResponse).
isFineGrainedGitHubPat(String token) bool
Whether token is a GitHub fine-grained PAT (v2, github_pat_…). Per the official Copilot CLI docs this IS a supported Copilot credential — but only with the "Copilot Requests" permission, so the connect flow uses this to print an informational hint at paste time (the exchange itself decides).
isKnownHtmlTag(String tagName) bool
Whether tagName parses as a markup tag (vs. literal text).
isOldFormatJobLogName(String name) bool
sh-7.log — the pre-unique-id job-log name scheme. Every fa build older than the collision fix starts its background-job counter at 1 per process, so a file with this shape freshly modified in OUR bash_jobs directory means a stale fa process is also writing here.
isRateLimitOrQuota(AssistantMessage message, {Duration? retryAfter}) bool
Whether message is a rate-limit/quota failure the chain may retry.
isRawSelector(ReadSelector parsed) bool
Whether the selector requested verbatim/raw output (alone or combined with a range) — omp's isRawSelector.
isRedactionExemptTool(String name) bool
True when name's output must never be redacted: the built-in model-authored tools, or an MCP tool whose name contains a write-ish segment (mcp__server__write_file).
isReservedCustomProviderName(String name) bool
Whether name is reserved for a built-in catalog provider (case-insensitive): an entry named openai/anthropic/… shadows /provider <name> routing — issue #221's ghost "openai". Reserved names are rejected at CustomProviderRegistry.add, dropped at config load, and filtered out of every merged write.
isSubagentSession(SessionMetadata session) bool
Whether session's header classifies it as a subagent session (metadata: {agent: 'subagent', parent: <mainSessionId>}). Sessions without header metadata (pre-feature files) are mains.
isSyntheticUserText(String text) bool
Whether a user-role text is synthetic harness content (system-notice envelope, agent mail, or a projected branch summary) rather than the user's own words. Shared by the summarizer's request-candidate scan and the structured compaction ledger (which must never hide a real user turn).
isToolPairingProviderError(String? errorMessage) bool
Whether a provider errorMessage belongs to the tool-pairing error family (the loop uses this to trigger the one-shot repair-and-retry).
isTransientNetworkError(AssistantMessage message) bool
Whether message is a transient failure worth replaying: socket-level drops and gateway 5xx. Rate limits stay with the roles layer (the FallbackStreamFunction rotation policy — checked FIRST, a 429 may quote "please try again later"), auth failures stand, context overflow belongs to compaction, and the idle watchdog's own TimeoutException wording deliberately does NOT match (that error means "the endpoint went silent", which a retry re-arms anyway).
isTransientTransportError(AssistantMessage message) bool
Whether message is a transient transport failure the chain may retry in place: the endpoint (or the network path to it) dropped, so rotating credentials is pointless — the same entry is retried with backoff, then the chain fails over to the next model. Context overflow and rate limits are excluded (their own policies own them).
isUsableCustomProviderName(String name) bool
Whether name is a usable saved-provider name; the name prompts re-prompt otherwise. Empty answers never reach this — they take the flow's default name.
isWebSearchProviderAvailable(WebSearchProvider provider, Map<String, String> secrets) bool
Whether provider can serve searches given secrets: keyless providers are always available, keyed ones need their non-empty key.
layerAsn1(String text, RedactionConfig cfg, {List<RedactionMatch> prior = const []}) List<RedactionMatch>
Finds standalone DER base64 runs in text.
layerConnection(String text, RedactionConfig cfg) List<RedactionMatch>
Finds connection-string password spans in text.
layerContext(String text, RedactionConfig cfg) List<RedactionMatch>
Finds context-anchored value spans in text.
layerCredential(String text, RedactionConfig config) List<RedactionMatch>
Finds DOM credential value spans in text.
layerEntropy(String text, RedactionConfig cfg, {List<RedactionMatch> prior = const []}) List<RedactionMatch>
Finds high-entropy ASCII token spans in text.
layerPath(String text, RedactionConfig cfg, {String? pathHint}) List<RedactionMatch>
Scans text for credential path content.
layerPem(String text, RedactionConfig cfg) List<RedactionMatch>
Finds PEM/X.509/PGP blocks in text.
layerPii(String text, RedactionConfig cfg) List<RedactionMatch>
Finds PII spans in text; non-overlapping, left-to-right.
layerPrefix(String text, RedactionConfig cfg) List<RedactionMatch>
Thin pre-pass over the vendor token shapes; see the library docs.
layerRegistered(String text, List<String> secrets) List<RedactionMatch>
Finds every occurrence of every value in secrets inside text.
layerVendor(String text, RedactionConfig cfg) List<RedactionMatch>
Finds known vendor token shapes in text.
leafIdAfterSessionRecord(SessionRecord record) String?
leaseOwnerLabel(String host) String
Human label for a lease host in banners: clifa CLI, app surfaces → Fa.app, else the raw kind.
listDirTool(ExecutionEnv env) AgentTool
Creates the ls tool: lists directory entries sorted alphabetically (case-insensitive), directories suffixed with /, capped at limit entries (default defaultLsEntryLimit) and defaultToolMaxBytes bytes.
listSqliteTables(SqliteDatabase db, {int probeCap = rowCountProbeCap}) List<SqliteTableSummary>
Lists non-sqlite_% tables with bounded row counts (omp's listTables).
loadCliConfig(String homeDir) CliConfig
Loads CliConfig from ~/.fah/config.yaml.
loadFolderModelState(ExecutionEnv env, {required String sessionsRoot, required String cwd}) Future<FolderModelState?>
Loads the model/provider triple saved for the folder cwd lives in, or null when absent/corrupt (the global config stays in charge).
loadJsonlSessionMetadata(FileSystem fs, String filePath, {DateTime? lastUpdatedAt, int? sizeBytes}) Future<SessionMetadata>
Reads just the header of a session file and returns its metadata.
loadPackagesConfig(ExecutionEnv env) Future<Map<String, dynamic>>
Loads plugin configuration from the environment cwd's .fah/packages.yaml. Returns a map of plugin name -> config.
loadProjectCompactionEngine(String projectDir) CompactionEngine?
Loads the PROJECT-level compaction: section from <projectDir>/.fah/config.yaml — the engine choice travels with the repo (issue #148). Project wins over the user-level compaction: section; the runtime flag wins over both. Null when the file or the section is absent/unreadable; a present-but-invalid section throws ConfigException (strict, like the user config).
loadProjectContextFiles(ExecutionEnv env, {String? userFile}) Future<List<ProjectContextFile>>
Loads every projectContextFileNames file walking from cwd up to the git root (or the filesystem root). Returns files farthest-first, closest (most specific) last. A userFile (e.g. ~/.fah/AGENTS.md) is merged first when present (pi's global layer).
loadProjectCubeSettings(String projectDir) CubeSettings?
Loads the PROJECT-level cube: section from <projectDir>/.fah/config.yaml — the git-backed sandbox default travels with the repo. Project wins over the user-level cube: section. Null when the file or the section is absent/unreadable; a present-but-invalid section throws ConfigException (strict, like the user config).
loadProjectMemoryConfig(String projectDir) MemoryConfig?
Loads the PROJECT-level memory: section from <projectDir>/.fah/config.yaml — the git-backed memory path travels with the repo (anyone cloning gets the pointer AND the memory). Project wins over the user-level memory: section. Null when the file or the section is absent/unreadable; a present-but-invalid section throws ConfigException (strict, like the user config).
loadPromptTemplates(ExecutionEnv env, List<String> dirs) Future<List<PromptTemplate>>
Loads prompt templates from a list of directories.
loadWebPage(Client client, Uri uri, {required Duration timeout, required int maxBytes, Map<String, String>? headers}) Future<WebPage>
Fetches uri with a browser profile, following redirects and capping the body at maxBytes (omp's loadPage, reduced: no user-agent rotation or 429 retry — the tool surfaces failures directly).
lspTool(ExecutionEnv env, {required LspToolConfig config}) AgentTool
Creates the lsp tool bound to env. Registered from builtinTools only when the host supplies an LspToolConfig — process-capable envs (CLI/desktop) do; web/stub construction leaves the tool out.
luhnValid(String digits) bool
Whether the digit string passes the Luhn checksum.
mailboxMisrouteNote(List<MailboxEntry> entries, String targetId) String
The cross-root misroute diagnostic for a send resolved to targetId (issue #516). Returns '' when the id maps to fewer than two mailboxes — the normal case; an asleep target stays silent because offline queueing is the contract (#402). When the same id owns mailboxes under SEVERAL project roots, the sender learns where delivery landed instead of silently queueing: the live registration's root is named and stale corpses are called out, or — when no root holds a live registration — the named misroute warning fires.
mailboxWakeCommand({String? wakeExecutable, required String sessionId, String? sessionName}) String
Builds the detached wake command for an asleep mailbox: nohup <exe> --session <name> "<prompt>" >/dev/null 2>&1 &. Single quotes every shell word; falls back to fa on PATH when wakeExecutable is null/empty and to sessionId when sessionName is.
markdownToPlainText(String source) String
Strips common GFM presentation markup, preserving content text.
matchCriticalBashCommand(String command) String?
Returns the label of the first criticalBashPatterns entry matching command, or null when the command matches nothing critical.
mcpAgentTool({required String server, required McpToolInfo tool, required McpToolCaller caller}) AgentTool
Builds the AgentTool for one advertised MCP tool.
mcpContentBlocks(Object? content) List<ContentBlock>
Maps MCP content blocks onto ContentBlocks: text as-is, images as ImageContent, everything else as a readable text placeholder.
mcpResultToToolResult(Map<String, dynamic> result) ToolExecutionResult
Converts a raw tools/call result map into a ToolExecutionResult. Throws StateError when the result carries isError: true (the loop turns the throw into an error tool result).
mcpToolName(String server, String tool) String
The registered name of tool from server: mcp__<server>__<tool> with provider-hostile characters flattened to _ and the result clamped to 64 characters (the common provider tool-name limit).
memoryTools(MemoryController? controller, {void onChanged()?}) List<AgentTool>
Returns the three memory tools backed by controller. memory_add is write-tier; memory_search and memory_list are read-tier. onChanged fires after every successful memory_add — hosts use it to refresh the prompt's cached <memory> section.
mergeCustomProviderEntries(List<CustomProviderEntry> caller, List<CustomProviderEntry> onDisk) List<CustomProviderEntry>
The merge-before-write union for the customProviders: section (issue #221): caller is the saving process's intended list, onDisk the freshly re-read list. Caller's entries win per name (case-insensitive) — an in-flight edit lands — while on-disk entries the caller never loaded survive (no stale-snapshot clobber). Reserved (catalog-named) entries are dropped from the result so a ghost can never persist.
mergeProviderHeaders(Map<String, String> defaults, Map<String, String>? modelHeaders, Map<String, String?>? optionsHeaders) Map<String, String>
Merges request headers: defaults first, then modelHeaders, then optionsHeaders. An option header with a null value suppresses the header with the same name (pi's ProviderHeaders semantics).
mergeWithRemoteCatalog({required ModelsEndpointInfo endpointInfo, required String? providerKind, required RemoteModelsCatalog? catalog, List<String> mediaSlot = const []}) ModelsEndpointInfo
Folds a remote catalog into the per-endpoint fetch result.
messageFromJson(Map<String, dynamic> json) Message
Deserializes a Message from its JSON map, dispatching on role.
messagesContainImages(List<Message> messages) bool
Whether messages contains any ImageContent (user messages and tool results) — guards the undecodable-image retry so image-shaped backend errors on image-free requests don't trigger a pointless second call.
mobileCapabilityFloor({required MobileTier tier}) Map<String, ToolCapability>
The capability floor the tier flavor implies, for the three mobile availability ids (mobile, mobile_automation, mobile_shell).
mobileObserveStep(MobileAutomationBackend automation, {Duration budget = defaultMobileObserveBudget, Duration clock()?}) Future<MobileObserveResult>
One observation step: both captures are dispatched before either is awaited (the concurrency contract), and the step fails with the named observe-budget-exceeded state when the wall clock passes budget.
mobileTools({required MobileLaunchBackend launch, required MobileLogsBackend logs, MobileAutomationBackend? automation, MobileShellBackend? shell, RedactionPipeline? redactor}) List<AgentTool>
Builds the tier's mobile.* tools over the wired backends.
modelIdSuggestsVision(String modelId) bool
Whether modelId looks like a vision-capable hosted model.
Navigate session to targetId (omp's tree navigation with branch summarization): the branch being left is summarized via summarize into a branch_summary record prepended to the context of the branch being entered, and the active leaf moves. Returns the new branch_summary record id, or null when no summary was written (no-op navigation, nothing to summarize, or summarization failed/aborted).
newHubFrameId() String
Opaque unique frame id, uuid-v4 shaped.
newMessageId() String
Time-ordered, collision-resistant message id: <microsSinceEpoch:16>_<counter:4>_<rand> — fixed-width components, so string order == arrival order (inbox file names sort correctly).
newShellJobId(int n) String
Globally-unique background job id: several fa processes share one workspace, so per-process counters alone (sh-1, sh-2) would make them append to the SAME .fah/bash_jobs/<id>.log and interleave each other's captured output. The microsecond stamp plus a random tail makes cross-process collisions practically impossible.
nextCopilotPollDelay(Duration current, {required bool slowDown}) Duration
The next poll wait: current, plus the 5s slow_down penalty when the server said slow_down (the penalty is cumulative — every slow_down grows the wait by another 5s).
nextFrameId() String
Frame correlation id: <epochMs>-<8 hex rand> — sortable by time, collision-safe across peers.
nextShrinkStep(int width, int height) → (int, int)
One 0.75 shrink step of the inline-image shrink loop (a dimension already at 1 stays there).
nextWakeDelay({required DateTime now, required DateTime deadline, required int heartbeatMin, required DateTime lastHeartbeat, required Iterable<int> timerDueMs}) Duration
Nearest wake delay for the --wait-for-jobs loop (issue #450): the minimum of the ceiling deadline, each armed timer's due moment, and the heartbeat cadence. Pure — unit-tested directly.
noChangeDiagnostic(String path) String
The patch parsed and applied cleanly but produced no change — the +literal body rows matched the file content at the targeted lines byte-for-byte (omp's noChangeDiagnostic).
normalizeArchiveLookupPath(String? rawPath) String?
Normalizes a member lookup path: / separators, . segments dropped. Returns null when the path escapes via .. (omp's normalizeArchiveLookupPath).
normalizeConcurrencyLimit(num max) int
Normalizes a configured concurrency cap (omp's normalizeConcurrencyLimit): max <= 0 (or any non-finite input) means unbounded — every Semaphore.acquire resolves immediately, matching task.maxConcurrency = 0's "Unlimited" semantics in omp's settings UI.
normalizeConfigThinkingLevel(String level) String?
Normalizes a config-declared level to its ladder rung: known rungs pass through clampThinkingLevel (xhigh/max fold to high), anything else returns null for the caller to reject with its own named error.
normalizeLocationResult(Object? result) List<LspLocation>
Normalizes a textDocument/definition-family result: accepts null, Location, Location[], LocationLink, or LocationLink[] and returns a flat location list (omp's normalizeLocationResult, reduced).
normalizeToLF(String text) String
Normalizes every line ending to LF.
pairingToken() String
One-time pairing token: 32 secure random bytes as 64 lowercase hex chars. Minted fresh by every /browser connect — an old token stops working.
parseArchivePathCandidates(String filePath) List<ArchivePathCandidate>
Splits an archive.ext:inner/path reference into every plausible {archivePath, subPath} pair, longest archive prefix first. A path may contain more than one archive extension, so each candidate is a guess at where the archive ends and the member portion begins (omp's parseArchivePathCandidates).
parseCliArgs(List<String> args) CliArgsResult
parseCodexRateLimits(Map<String, String> headers) CodexRateLimits?
Parses the x-codex-* rate limit headers of a ChatGPT backend response.
parseCommandArgs(String input) List<String>
Parses bash-style quoted arguments from the text after a /command.
parseDelay(String spec) Duration?
Parses 90s / 25m / 2h / 1d (and combinations like 1h30m).
parseDuckDuckGoResults(String html, {int? limit}) List<WebSearchSource>
Walks the DDG results page and pulls out result blocks in document order (omp's parseHtmlResults, rebuilt on the forgiving scanHtml tokenizer so minor markup rot — attribute order, quote style, extra classes, snippet element variants — does not break parsing).
parseDurationSpec(String raw) Duration
Parses a single-unit duration string — '3600s', '5m', '24h' — into a Duration. Compounds ('1h30m') and unknown units are rejected with FormatException.
parseEnvProviderPreconfig({required String? providerType, required String? providerName, required String? providerConfig, required String? providerConfigBase64, required String? envVarValue(String name), required Iterable<String> takenNames}) EnvProviderPreconfig?
Parses the FA_PROVIDER_* preconfig, or returns null when the feature is off (providerType null/blank).
parseFrontmatter(String content) → ({String body, Map<String, dynamic> frontmatter})
Splits markdown content into YAML frontmatter and body.
parseHashlinePatch(String diff) HashlineParseResult
Parses one section body (diff) into edits plus warnings. The input must NOT contain the [path#tag] section header — section splitting happens in input.dart (omp's parsePatch).
parseLineRangeChunk(String sel) LineRange?
Parses a single N, N-M, N-, N+K, or ..-aliased (N..M, N..) chunk. Returns null when sel is not range-shaped; throws StateError on invalid bounds (omp's ToolError messages, verbatim).
parseLineRanges(String sel) List<LineRange>?
Parses a comma-separated list of line ranges (e.g. 5-16,960-973). Returns the ranges in ascending order with overlapping/adjacent ranges merged so downstream consumers can stream the file in a single forward pass per range. Returns null when any chunk is not range-shaped.
parseMobileHierarchy(String xml, {String packageHint = 'unknown', int cap = defaultMobileElementCap}) MobileElementIndex
Extracts the filtered MobileElementIndex from a hierarchy XML dump.
parseModelsResponse(String body) ModelsEndpointInfo
Parses body (the raw /models JSON) into ModelsEndpointInfo.
parsePowerSection(Object? node) PowerSection
Parses the power: yaml section (sleepPrevention level + hold lifecycle). A null node means the section is absent — the CALLER applies the defaults (level idle, hold per-run; "not configured" and "explicitly off" stay distinct). Any present-but-invalid shape, value or key throws ConfigException, consistent with the other strict config sections.
parsePromptOverrideMap(Object? node) Map<String, String>
Validates the raw prompts: yaml section into a prompt name → raw source map (values stay raw: a file path or inline text — classified later, at file-resolution time).
parseProviderQueueEntries(Object? node, {required String source, ({String? baseUrl, String? keyName, String kind, String model})? resolveRef(String name)?}) ParsedProviderQueue
Parses the queue entries from an already-decoded JSON/YAML list.
parseProviderQueueEnv(String raw, {String source = 'FA_PROVIDERS_QUEUE', String? readText(String path) = _unreadable}) ParsedProviderQueue
Parses the FA_PROVIDERS_QUEUE env value: a JSON array, or @path to load a JSON file (readText is injected — this library never touches IO). Whitespace tolerance, BOM stripping, and line/col in JSON errors (UT-parse-env-happy, UT-parse-file-form, E9).
parseProviderQueueJsonText(String text, {String source = 'FA_PROVIDERS_QUEUE'}) ParsedProviderQueue
Parses a queue JSON text: strict decoding with line/column in every syntax error (UT-parse-strict).
parseProviderQueueYaml(Object? node, {required String source, ({String? baseUrl, String? keyName, String kind, String model})? resolveRef(String name)?}) ParsedProviderQueue
Parses a providersQueue: yaml node (the project/user config form). The yaml syntax itself was already checked by the host's loadYaml; this validates the section shape.
parseRemoteAddress(String address) → (String, String)
Splits a name@machine remote address at the @. Both halves must be non-empty; throws StateError otherwise.
parseRetryAfter(String? value, {DateTime? now}) Duration?
Parses a Retry-After header value into a Duration.
parseRoleChains(Object? node, {String? source}) Map<String, List<ModelRef>>
Parses a roles: map (role name → chain). Shared by the top-level section and PathRoleOverride; source labels errors.
parseSel(String? sel) ReadSelector
Parses a selector string (as returned by SplitReadPath.sel) into a ReadSelector. Unrecognized selectors fall through to ReadSelectorNone — archive/SQLite readers consume their own colon syntax — but compounds that LOOK read-like yet are malformed throw (omp's invalidSelector), so a mistyped selector never silently widens into a whole-file read.
parseSessionEntryLine(String line, String filePath, int lineNumber) SessionRecord
Parses one JSONL entry line into its SessionRecord.
parseSessionEntryLinesSync(SessionParseBatch batch) SessionParseResult
Parses one batch right here — the inline executor's body and the isolate worker's entry point share it, so both paths run the exact same parse code (issue #199 AC4 parity).
parseSessionHeaderLine(String line, String filePath) SessionHeader
Parses the header line of a session file into its SessionHeader.
parseSessionLines(List<String> lines, {required String filePath, required int firstLineNumber, SessionParseExecutor? executor, bool shallowGiantCustoms = false}) Future<List<SessionRecord?>>
Parses lines through executor — or inline, batch by batch, when it is null — and returns one slot per line in file order (null where a line was torn/foreign).
parseShallowCustomRecord(String line) SessionRecord?
Header-only decode for giant custom records (issue #503 round 3b).
parseSizeBytes(String raw) int
Parses a size string to bytes: a plain integer ('1024') is bytes; binary suffixes K/KiB, M/Mi/MiB, G/GiB are 1024-based and decimal B, KB, MB, GB are 1000-based (case-insensitive).
parseSqlitePathCandidates(String filePath) List<SqlitePathCandidate>
Splits a db.sqlite:table?query reference into every plausible candidate, longest database prefix first (omp's parseSqlitePathCandidates). Database detection is by extension only; existence and readability are checked by the caller.
parseSqliteSelector(String subPath, String queryString) SqliteSelector
Parses the table/query selector tail of a SQLite path (omp's parseSqliteSelector). Throws StateError with omp's messages on unsupported combinations.
parseTokenPreset(String label) int
Parses a compact preset label (4K, 16K, 1M) back to tokens.
parseToolsSpec(String csv) ToolsConfig
Parses the --tools flag / FA_TOOLS env CSV spec: 'web_search=off,dap=off,mcp:my-server=on'.
parseTuiMouseMode(String? value) TuiMouseMode
Parses a user-supplied string into a TuiMouseMode.
pathPatternMatches(String pattern, String cwd, {String? homeDir}) bool
Whether pattern matches the working directory cwd.
pickModelEditField(Future<TuiPromptAnswer?> prompt(TuiPromptSpec), Model current) Future<bool?>
Step 1: picks which field to edit (null on cancel).
pickModelEditValue(Future<TuiPromptAnswer?> prompt(TuiPromptSpec), bool isContext, void onResult(String message)) Future<int?>
Step 2: picks a preset value or enters a custom one (null on cancel).
piToolsOverride() ToolsConfig
pi's runtime availability scope: every known tool id off except piToolIds. Applied as the DEEPEST scope in rebuildToolAvailability, so it pins the surface exactly — --tools and FA_TOOLS cannot widen a benchmark run.
pollCopilotDeviceGrant({required CopilotDeviceGrant grant, required String clientId, required Future<void> delay(Duration delay), void onStatus(String status)?, Client? client}) Future<String>
Polls for the GitHub token until the user authorizes (goal: device_flow.go pollAccessToken).
powerAssertionOptions(PowerAssertionLevel level) PowerAssertionOptions?
Translates a level into request options, or null when the level asks for no assertion at all (off). Cumulative levels, exactly oh-my-pi's powerAssertionOptions().
prepareBranchEntries(List<SessionRecord> entries, {int tokenBudget = 0}) BranchPreparation
Prepare entries for summarization within tokenBudget (omp's prepareBranchEntries): walks NEWEST to OLDEST, keeping the most recent context when the branch is too long. File operations accumulate from ALL entries — including nested branch-summary details — even past the budget. tokenBudget: 0 means no limit.
projectAssistantRecord({required MessageRecord record, required AssistantMessage message, required int index, required String recordId, required int turn, required int step, DateTime? previousTime, TrajectoryRequestDetail? requestDetail}) TrajectoryAssistantRecord
Projects an assistant message record into a fully-populated message row.
projectCompactedRecord({required SessionRecord record, required int index, required String recordId, required String summary, String? firstKeptEntryId, DateTime? previousTime, List<String>? hiddenRecordIds}) TrajectoryCompactedRecord
Projects a compaction or branch-summary record into a compacted row.
projectHiddenRecordPreviews({required List<String> recordIds, required Map<String, SessionRecord> resolved}) List<TrajectoryHiddenRecordPreview>
Builds the bounded drill-in previews for the records a hidden range covers, in the order the caller supplies (chain order when the caller read the file). Records that resolved to nothing render as explicit [hidden: not captured for this session] placeholders (E6) — never fake content.
projectToolResult({required ToolResultMessage result, DateTime? callTime}) → ({bool isError, String result, Duration? timeSeconds})
Projects a tool result into the settled fields of its tool row.
projectUserRecord({required MessageRecord record, required int index, required String recordId, required bool opensTurn}) TrajectoryUserRecord
Projects a user message record into a fully-populated user row.
promptTextTui(Future<TuiPromptAnswer?> prompt(TuiPromptSpec), String? initial, {required String header, required String question, bool secret = false}) Future<String?>
Opens a TextPromptSpec through prompt and returns the trimmed text answer. Returns initial as-is when provided (no prompt needed), or null on cancel/unexpected result.
promptToolInstructions(List<Tool> tools, {bool slim = false}) String
Renders the tool-instruction section promptToolStreamFunction appends to the system prompt when tools is non-empty (the prompts/tools/tool_calling.md template with the numbered name/description/schema list).
promptToolStreamFunction(StreamFunction inner, {PromptToolOptions? options}) StreamFunction
Wraps inner with prompt-based tool calling.
providerEnabledInBuild(String name) bool
Whether name survives the provider filter (see providerCatalog). true for every name without a filter.
providerQueueAdd(List<ProviderQueueEntry> entries, ProviderQueueEntry entry) List<ProviderQueueEntry>
Appends one entry to entries after the same strict validation the parsers apply (the editor's add — UT-editor-api). Returns the new list; throws ConfigException/ArgumentError on invalid input.
providerQueueMove(List<ProviderQueueEntry> entries, int index, int newIndex) List<ProviderQueueEntry>
Moves the entry at index to newIndex (reorder/move-to-head).
providerQueueRemoveAt(List<ProviderQueueEntry> entries, int index) List<ProviderQueueEntry>
Removes the entry at index; throws RangeError on a bad index.
providersQueueYamlBody(List<ProviderQueueEntry> entries) String
Serializes entries to the yaml body of a providersQueue: block (2-space indented list items, no trailing newline) — the surgical write's payload (UT-yaml-roundtrip). Secrets cannot leak: the shape only carries apiKeyEnv names.
providersSyncProvenance(String hostname) String
Provenance marker stamped on every synced entry: synced-from-cli@<host>.
providerStreamFunction(String kind, String apiKey, {String? sessionId()?, String? cacheRetention, String? dialApiVersion, bool? dialCacheMarkersSupported, ChatGptCredentialsPersist? onChatGptCredentialsRefreshed}) StreamFunction
Builds the StreamFunction for a provider adapter kind (openai-completions, minimax, zai, anthropic, google, dial, chatgpt-codex, copilot) with a static apiKey. Throws ConfigException for unknown kinds.
pushBlockEndEvent(AssistantMessageEventStream eventStream, List<StreamingBlock> blocks, StreamingBlock block, AssistantMessage snapshot()) → void
Pushes the end event for block (text, thinking, or tool call) at its position in blocks.
pushStreamErrorEvent(AssistantMessageEventStream eventStream, ProviderStreamState state, Object error, CancelToken? cancelToken) → void
Converts a caught error into the terminal ErrorEvent (errors-as-events invariant): aborts get StopReason.aborted, everything else StopReason.error.
querySqliteRows(SqliteDatabase db, String table, {required int limit, required int offset, String? order, String? where}) SqliteTablePage
Runs a paged table query (omp's queryRows).
queueKindCatalogName(String kind, String? baseUrl) String
Maps a queue adapter kind to the catalog provider NAME the model builder keys off. openai-completions keeps the historical CLI rule: a custom baseUrl reports provider openai, the default reports openrouter.
quickScreen(String text) bool
Cheap pre-screen: true when at least one vendor prefix occurs in text. A false result guarantees layerVendor finds nothing.
randomMailboxSuffix() String
8 secure random hex chars — the fallback <agentId> when the extension did not persist one (contract: browser-ext/<agentId or random8>).
readFileTool(ExecutionEnv env, {HashlineSnapshotStore? snapshots, Model? model()?, SqliteEngine? sqlite}) AgentTool
Creates the read tool: reads a text file or image with optional offset (1-indexed) and limit, truncating text output to defaultToolMaxLines lines or defaultToolMaxBytes bytes with an actionable continuation notice. Images are decoded, optionally resized to the inline dimension/byte limits, and returned as base64 content.
readPersistedTtsrInjections(Session session) Future<List<String>>
Reads the persisted injected-rule names along the session's active branch (omp's getInjectedTtsrRules), for TtsrManager.restoreInjected on session resume.
readToolsScopeFile(ExecutionEnv env, String path) Future<(ToolsConfig?, String?)>
Reads the tools: section of the yaml file at path through env. Returns (null, null) when the file or the section is absent, (null, message) when the file/section is broken, else the parsed config.
reapOrphanJobGroups({required ExecutionEnv env, required Iterable<int> candidatePids, void onWarn(String message)?}) Future<({int groups, int processes})>
Boot sweep (issue #517): reap the process groups of previous-run jobs — entries whose leader pid is dead but whose group members (the toolchain grandchildren: dartvm, flutter_tester) survived for hours. Only jobs that ran as their own group leader (posix setsid) can be recognized — a live group keyed by a DEAD pid can only be a leftover job group, never this process's own. Best-effort: any shell/platform failure yields a zero sweep, and onWarn fires at most once. Returns the counts.
reclaimOrphanMailboxMail({required ExecutionEnv env, required String root, required String agentId}) Future<int>
Moves pending mail out of orphan mailboxes into agentId's real inbox, returning the number of messages moved. An orphan mailbox appears when a sender addressed this agent with a truncated id (the short form agent_directory displays, or an older binary without prefix resolution): the send then created a fresh directory no watcher ever polls (01a060f2_main for 01a060f2-7d4b-…_main) — silent mail loss. An orphan is a <head>_main directory whose head is a strict prefix of agentId's own id. Best-effort: a failing move leaves the orphan in place; an emptied orphan directory is removed.
redactionHooks(SecretRedactor redactor) RedactionHooks
Builds the agent hooks that redact redactor's values:
redactionPipelineHooks(RedactionPipeline pipeline, {RedactionToolPolicy policy = const _ConstPolicy()}) RedactionPipelineHooks
Builds the agent hooks for the layered pipeline:
redactPrompt(RedactionPipeline pipeline, String prompt) String
Masks secrets in prompt before it reaches the provider/session (issue #24 AC8). Counted under the user_input tool name.
redactScreenText(String text, RedactionPipeline? redactor) String
Redacts screen-derived text. Defaults to a fresh pipeline so the entropy/context layers still mask token-shaped secrets even when the host passes nothing — redaction has no exceptions (#622 threat model).
refreshChatGptCredentials(ChatGptOAuthCredentials credentials, {Client? client}) Future<ChatGptOAuthCredentials>
relayOpenAiCompletion(LlmRelayRequest request, void onDelta(String delta), {Client? client, Duration? idleTimeout}) Future<void>
The real relay transport: one OpenAI-completions-dialect streaming call — POST {baseUrl}/chat/completions with the injected key, SSE deltas forwarded per chunk.
remoteChatModelsFor({required String? providerKind, required RemoteModelsCatalog? catalog}) List<String>
Chat model ids the catalog knows about for providerKind — used only as a LAST-RESORT picker fallback when the live /v1/models fetch returns an empty list (e.g. token failure, 5xx, endpoint down). The endpoint is ALWAYS the source of truth; this list just keeps the picker from collapsing to the saved entry's single modelId when the endpoint can't answer. The catalog ships these ids explicitly in contextWindows so the data is data-driven, not hardcoded.
remoteMediaModelsFor({required String? providerKind, required String slot, required RemoteModelsCatalog? catalog}) List<String>
The media-model list the picker shows for the slot when no override is configured. Empty when the catalog doesn't list the slot — the picker falls through to manual entry, the existing behaviour.
renderAppStoreBlockHtml(LinksConfig links) String
Renders the fa1.dev homepage App Store block (the whole <section> element, WITHOUT the markers) for links.
renderConfigCheckReport(ConfigCheckReport report) String
Renders a ConfigCheckReport as the canonical multi-line text both surfaces print: fa config check (exit code 1 on failure) and the config agent tool's check op — one rendering, never two.
renderProviderQueueRows({required List<ProviderQueueEntry> entries, required ProviderQueueState state, required DateTime now}) List<String>
The queue editor's per-entry health rows — pure so tests pin the byte layout across the four health states (current / healthy / recovering / cooldown) and any terminal width (issue #418, GOLDEN-tui-rows).
renderSqliteRow(Map<String, Object?> row) String
Renders a single row as column: value lines (omp's renderRow).
renderSqliteSchema(String createSql, SqliteRows sampleRows) String
Renders a table schema plus sample rows (omp's renderSchema).
renderSqliteTable(List<String> columns, List<Map<String, Object?>> rows, {required int totalCount, required int offset, required int limit, required String table}) String
Renders a paged table plus the continuation note when more rows remain (omp's renderTable).
renderSqliteTableList(List<SqliteTableSummary> tables) String
Renders the table list (omp's renderTableList).
renderYamlScalar(String raw) String
Renders raw as a YAML scalar: booleans/numbers verbatim, plain-safe strings unquoted, everything else JSON-quoted (a JSON string is a valid YAML double-quoted scalar — the same convention the prompts: section uses).
repairToolPairing(List<Message> messages) → ({List<Message> messages, ToolPairingRepairReport report})
Symmetric pairing repair at the request boundary. Returns messages untouched (same instance, empty report) when the context already satisfies validateToolPairing; otherwise returns a rebuilt payload whose wire view is valid — the transcript itself is never modified.
reportDeliveryStage(String line) → void
Emits one stage line when a host sink is wired; drops it otherwise.
repr(String text) String
Renders text with JSON-style quoting for diagnostics.
requestCopilotDeviceGrant({String clientId = copilotDeviceClientId, String scope = copilotDeviceScope, Client? client}) Future<CopilotDeviceGrant>
Requests a device code (goal: device_flow.go requestDeviceCode).
requestSecretTool({RequestSecretCallback? callback}) AgentTool
Creates the request_secret tool bound to callback.
resetLoadedUsageAnchors(List<Message> messages) List<Message>
Drops generation-time AssistantMessage.usage anchors from messages loaded off disk.
resolveAgentLoadMode({bool flagOmp = false, String? envMode, String? configMode}) AgentLoadMode
Resolves the load mode for this boot: flag > env > config (issue #680 AC3 precedence). flagOmp is --omp; envMode the raw FA_AGENT_MODE value; configMode the raw agent.mode yaml value.
resolveAgentUrl(String url, AgentOutputStore store) AgentUrlResolution
Resolves an agent:// URL against store (port of omp's AgentProtocolHandler.resolve, reduced to the dot-path query subset).
resolveCompactionEngine({CompactionEngine? global, CompactionEngine? project, CompactionEngine? session}) CompactionEngine
Resolves the effective engine: global < project < session, deepest non-null wins, default CompactionEngine.structured (issue #287 — classic stays selectable as the supported rollback).
resolveEndpointKey({required List<String> envNames, required String defaultBaseUrl, required String baseUrl, required String? envRead(String name), required String? storeRead(String name)?, String? activeCustomKeyName}) String?
Resolves the API key for baseUrl given the catalog env envNames and the spec's defaultBaseUrl. envRead reads genuine environment values; storeRead reads the secure store (null store = env-only resolution, e.g. tests or the web build). activeCustomKeyName is the active custom registry entry's own key name, when known (wins over the host-scoped entry for non-default endpoints).
resolveHarnessMode({bool? flag, Map<String, String> env = const {}, String? configMode}) String?
Resolves the active harness mode: --pi flag > FA_PI_MODE env > config agent.mode (issue #679 AC3).
resolveModelMaxOutputTokens(String modelId, {required String api}) int?
The ceiling-table step of max-output-token resolution for modelId: per-model config override (caller-side) > this table > provider default (caller-side). Null is the table MISS — non-claude ids (glm, kimi, ...) ride the caller's provider default unchanged, and so does any claude id whose api is outside the table's family (anthropicMessagesApi, issue #302: Claude-specific ceilings never leak onto other provider families).
resolveProviderQueueScopes(List<ProviderQueueScopeInput> inputs) ProviderQueueResolution
Resolves the queue across scopes: env > project > user > legacy.
resolveSqliteRowLookup(SqliteDatabase db, String table) SqliteRowLookup
Resolves the row-lookup strategy for table (omp's resolveTableRowLookup).
resolveStartupCubeSource({String? flagConfigPath, String? flagName, CubeSettings? project, CubeSettings? user}) String?
The startup cube source (fa_cube): explicit flags win, then the project cube: section, then the user cube: section — each config section applies only when enabled. Null = start unsandboxed.
resolveToolAvailability({required Map<String, ToolCapability> capabilities, required List<(ToolScope, ToolsConfig)> scopes, Set<String>? essentialToolIds, Iterable<String> mcpServerIds = const []}) ToolAvailabilityResolution
Resolves the scope stack against the host's capabilities.
resolveWebSearchChain(List<String> providerIds, {required Map<String, String> secrets}) List<WebSearchProvider>
Resolves providerIds (auto expands to the default chain) into an ordered, deduplicated list of available providers (omp's resolveProviderCandidates, reduced). Keyed providers without a key in secrets are skipped; unknown ids throw.
responsesInputItems(List<Message> messages) List<Map<String, dynamic>>
Converts harness history into Responses API input items (issue #705).
restoreLineEndings(String text, LineEnding ending) String
Re-encodes LF text with the requested line ending.
retryTransientSessionFileIo<T>(Future<Result<T, FileError>> operation(), {required String op, required String path, SessionIoRetryConfig config = const SessionIoRetryConfig()}) Future<Result<T, FileError>>
Runs operation — one FileSystem-shaped call returning a Result — retrying while it fails with a not-found-shaped FileError (the transient-ENOENT shape; every other error code is returned immediately). The last Err is returned as-is on exhaustion, so the caller's _fsOrThrow names it (SessionErrorCode.notFound via the existing mapping). Success and non-retryable failures are indistinguishable from an un-wrapped call.
reviewMode(String cwd, {PromptOverrides? overrides}) AgentMode
Code-review mode.
rewriteHistoryImages(List<Message> messages, {int? maxPerRequest, void onDrop(int index, String keyPreview)?}) List<Message>
Rewrites the OUTGOING request payload (never the transcript): image blocks become [Image N] refs, unique originals ride once as carriers, the current user message rides in place, and the per-request cap drops by priority (current > newest > older) reporting every drop.
runAgentLoop({required List<Message> prompts, required Context context, required AgentLoopConfig config, required StreamFunction streamFunction, required ToolExecutor toolExecutor, required AgentEventSink emit, CancelToken? cancelToken}) Future<List<Message>>
Starts an agent loop with new prompt messages, delivering events to emit and resolving with the messages produced by the run.
runAgentLoopContinue({required Context context, required AgentLoopConfig config, required StreamFunction streamFunction, required ToolExecutor toolExecutor, required AgentEventSink emit, CancelToken? cancelToken}) Future<List<Message>>
Continues an agent loop from context, delivering events to emit.
runBrowserCommand(BrowserBridgeHandle? handle, String rest) Future<List<String>>
Runs the /browser command and returns the lines to print.
runConfigServiceCommand(ConfigCliCommand cmd, {required CliIO io, required ExecutionEnv env, required String? homeDir}) Future<int>
Runs one fa config <verb> command and returns the process exit code.
runProviderStream(AssistantMessageEventStream eventStream, ProviderStreamState state, CancelToken? cancelToken, Client httpClient, {required bool ownsClient, required Future<void> body()}) Future<void>
Runs a provider adapter's streaming body under the shared terminal protocol: any caught error becomes an ErrorEvent via pushStreamErrorEvent (errors-as-events invariant), the stream is always ended, and the owned HTTP client is closed.
sandboxExecOptions(CubeSpec spec, ShellExecOptions? options) ShellExecOptions
A Shell whose commands are gated by a cube's policies. Builds the forwarded options for a permitted command under spec: the timeout clamped to the cube's CubeResourceLimits.timeout (the smaller of caller and cube wins; a null caller inherits the cube's), plus the cube's injected env vars.
sanitizeUploadName(String name) String
Strips path separators and ./.. segments from a picked file name (some browsers send a webkitRelativePath), so the upload stays inside the target directory. Returns the cleaned relative path — possibly with subdirectories — or an empty string when nothing usable is left.
saveBrowserScreenshot(ExecutionEnv env, Uint8List png) Future<String>
Saves a screenshot PNG under generated/browser-<epochMs>.png in the env root — the media tools' generated/ convention. Hosts with different persistence pass their own browserTools saver instead.
saveFolderModelState(ExecutionEnv env, {required String sessionsRoot, required String cwd, required String providerKind, required String modelId, required String? baseUrl}) Future<void>
Saves the model/provider triple for the folder cwd lives in.
scanHtml(String html) Iterable<Object>
Scans html sequentially, yielding HtmlTag and HtmlText tokens in document order. Comments, doctypes, and processing instructions are skipped. Malformed input degrades to text instead of throwing.
scheduleMessageTool(ScheduledMessageQueue queue) AgentTool
sendProviderRequest(Client httpClient, Request request, CancelToken? cancelToken) Future<StreamedResponse>
Sends request, racing cancelToken (abort wins), and validates the response status.
serializeConversation(List<Message> messages) String
Serialize messages to plain text for summarization prompts.
sessionPowerAssertions(AgentCliConfig config, void onWarn(String message)) PowerAssertionController?
Builds the session's sleep-prevention controller (issues #325/#326) from the host-injected runner + configured level + hold lifecycle; a null runner (tests, web) means no assertions — power is host-best-effort.
setRemoteCatalogEnrichmentForTesting(RemoteCatalogEnrichment fake) → void
Test seam — swap in a fake enrichment so unit tests don't need a real HTTP client. Not part of the public API.
settingForYamlKey(String key) SharedSetting?
The SharedSetting that owns the yaml top-level key, or null when no shared setting covers it (the key must then be in fileOnlyConfigKeys or it is unclassified — the completeness gate fails).
sha256Hex(String value) Future<String>
Computes the lowercase hex SHA-256 digest of value.
shallowCustomHeader(String line) String?
Extracts the JSON header (everything up to ,"data":) of a giant custom record line as a parseable JSON object with data omitted — or null when the line does not match the canonical writer order (customType must precede data). Pre-truncating with this BEFORE the batch parse keeps the ~0.75 MB payloads out of the isolate transfer entirely (issue #503 round 3b): the truncated header decodes as a CustomRecord with data: null through the normal path.
shannonEntropy(String token) double
Shannon entropy of token in bits per character.
sharedProviderHttpClient() → Client
The shared keep-alive HTTP client for provider streams.
shellQuote(String value) String
Quotes value as a single POSIX shell word: wrapped in single quotes with embedded quotes escaped the standard '\'' way. An empty value becomes ''.
shellTool(ExecutionEnv env, {ShellJobRegistry? jobs, Duration retryBackoff = _bashRetryBackoff, PasswordPromptCallback? onPasswordPrompt, Duration passwordQuiet = _bashPasswordQuiet}) AgentTool
Creates the bash tool: executes a shell command via ExecutionEnv.exec and returns stdout followed by stderr, truncated to the last defaultToolMaxLines lines / defaultToolMaxBytes bytes. A non-zero exit code, timeout, or abort throws (the loop turns it into an error tool result, pi semantics).
shouldCompact(int contextTokens, int contextWindow, CompactionSettings settings) bool
Whether context usage exceeds the compaction threshold.
shouldSpill(String text, SpillsConfig config) bool
True when text spills: longer than the threshold and not empty/whitespace (issue #678 AC1 boundary both sides, AC2 empty never spills). Pure function.
shrinkStepStalls(int currentWidth, int currentHeight, int nextWidth, int nextHeight) bool
The shrink loop's safety valves: the step stalls at 1x1 or when the 0.75 shrink stops making progress. Unreachable via the public API with default limits — even a maximal source clamps to _defaultImageMaxDimension and fits the byte budget long before the step stalls.
sigintAction({required bool headless}) SigintAction
Resolve the action for one Ctrl+C press.
skillsAccessAllowsDiscovery(SkillsAccess access, {required bool interactive}) bool
Whether third-party skill/agent discovery may read from disk.
skillsAccessFromLabel(String? label) SkillsAccess
Parses a persisted label (ask/granted/denied); null/unknown → SkillsAccess.granted (discovery is opt-out, not opt-in).
skillsAccessLabel(SkillsAccess access) String
The persisted label of access.
skillSourceIsThirdParty(SkillSource source) bool
Whether source is a third-party directory that requires the user's skills-access consent before reading.
skipHtmlSubtree(List<Object> tokens, int openIndex) int
Returns the index of the token closing the subtree rooted at the open tag openIndex within tokens (depth-counted on the same tag name). Returns openIndex itself for self-closing tags, or the last token index when the close tag is missing (malformed input).
sortAndValidateTextEdits(List<LspTextEdit> edits) List<LspTextEdit>
Sorts edits bottom-to-top for in-place application and rejects overlaps (omp's sortAndValidateTextEdits).
sortSessionsCurrentFolderFirst(List<SessionMetadata> sessions, String? currentCwd) List<SessionMetadata>
Orders sessions for display (issue #83): sessions from the currentCwd folder first, then sessions from every other folder; each group newest-activity first. JsonlSessionRepo.list stays plain activity order so /resume keeps its most-recent-anywhere semantics.
spillFailureMarker(String reason) String
The named inline-fallback marker appended when a spill write fails (issue #678 AC6): the output is never lost and never a silent crash.
splitPathAndSel(String rawPath) SplitReadPath
Splits a trailing :sel off rawPath when the tail matches the selector grammar (a range list or raw, optionally one of each in either order — path:1-50:raw / path:raw:1-50). Anything else stays part of the path so archive and SQLite targets keep their colon syntax.
splitPathAndSelPreferringLiteral(String rawPath, FileSystem env) Future<SplitReadPath>
Async sibling of splitPathAndSel that prefers a literal filesystem path over selector interpretation (omp's splitPathAndSelPreferringLiteral, issue #4618): filenames whose tail matches the selector grammar (e.g. test:1-2, log:raw) are legal on POSIX; without this the strict splitter peels the tail and read refuses to open the real file. The literal wins whenever env reports the raw path exists — and also when the existence check itself fails — so an unreachable literal is never silently reinterpreted as path + selector.
splitSessionParseBatches(List<String> lines, {required String filePath, required int firstLineNumber, bool shallowGiantCustoms = false}) List<SessionParseBatch>
Splits lines into bounded transfer batches. Issue #199 E5: an oversize line becomes its own batch, so one huge record can never stall a batch beyond its own parse.
stageUpload(ExecutionEnv env, {required String name, required Uint8List bytes}) Future<String>
Stages one chat attachment into uploadsDirName inside env, creating the directory and de-duplicating the file name on collision (report.pdfreport-1.pdf → …). Returns the env-relative path (uploads/report.pdf) the outgoing message should reference.
stageUploadTooLargeError(int bytes) String
The named refusal both sides surface for an oversized upload — one wording for the SW op and the panel pre-check, so a user sees the same message no matter which hop rejects the paste.
startProviderResponse(AssistantMessageEventStream eventStream, ProviderStreamState state, Client httpClient, Request request, CancelToken? cancelToken, FutureOr<void> onResponse(int statusCode, Map<String, String> headers, Model)?) Future<StreamedResponse>
Sends request (via sendProviderRequest), runs the adapter's onResponse hook, and pushes the StartEvent with the initial snapshot.
streamAnthropic(Model model, Context context, [AnthropicOptions? options, Client? client]) AssistantMessageEventStream
Streams an assistant message from an Anthropic messages endpoint.
streamChatGptCodex(Model model, Context context, {required String credentials, ChatGptCredentialsPersist? onCredentialsRefreshed, CancelToken? cancelToken, Client? client}) AssistantMessageEventStream
streamCopilot(Model model, Context context, [CopilotOptions? options, Client? client]) AssistantMessageEventStream
Streams an assistant message from GitHub Copilot.
streamDial(Model model, Context context, [DialOptions? options, Client? client]) AssistantMessageEventStream
Streams an assistant message from a DIAL Core deployment.
streamFunctionSummarizer(StreamFunction streamFunction, Model model, {CompactionPrompts prompts = defaultCompactionPrompts, void onDelta(String delta)?}) SummarizeFn
Adapts a provider StreamFunction into a SummarizeFn.
streamGoogle(Model model, Context context, [GoogleOptions? options, Client? client]) AssistantMessageEventStream
Streams an assistant message from a Google Generative AI endpoint.
streamJsonEventLine(AgentEvent event) String?
Maps one AgentEvent to its stream-json line, or null when the event is filtered out of the stream (fa-native events).
streamJsonSessionHeaderLine({required String sessionId, required String cwd, DateTime? timestamp}) String
Builds the session header line (always the first stdout line).
streamOpenAICompletions(Model model, Context context, [OpenAICompletionsOptions? options, Client? client]) AssistantMessageEventStream
Streams an assistant message from an OpenAI-compatible chat-completions endpoint.
stringifySqliteValue(Object? value) String
Renders a SQLite value for a table cell (omp's stringifySqliteValue).
stripAuthExpiredMarker(String formattedError) String
Removes the auth-expired marker (and surrounding whitespace) from the formatted error, leaving the human-readable part for display.
stripBom(String content) BomStripResult
Strips a UTF-8 BOM if present and returns both the BOM and the trailing text.
stripHtmlTags(String html) String
Strips all tags, decodes entities, and collapses whitespace — the text content of an HTML fragment (omp's decodeHtmlText).
subagentMonitoringTools({required SubagentManager? manager, ChildMessageReader? readMessages, ChildResumeRunner? resumeChild, CurrentSubagentIdProvider? currentSubagentId, TaskJobManager? jobs, TaskExecutor? executor, Duration taskSendWaitCap = const Duration(milliseconds: 1500)}) List<AgentTool>
Returns the subagent monitoring tools backed by manager. Register alongside the task tool when a manager is available. jobs enables task_cancel over the session's background job registry. executor lets task_cancel reach children that run inline on the session executor (blocking batches, resumes) — no TaskJob exists for those, so without it the cancel fallback cannot tell a LIVE inline child from an orphaned registry row (issue #332).
subagentParentId(SessionMetadata session) String?
The parent session id a subagent session nests under, or null for a main session (including malformed headers without a parent field).
substituteArgs(String content, List<String> args) String
Substitutes positional arguments into a template body.
systemdInhibitArguments(PowerAssertionOptions options, {required int pid}) List<String>
The systemd-inhibit(1) argument vector for options: systemd-inhibit holds its --what capabilities while the COMMAND it runs stays alive, so the argument vector ends in a watchdog shell loop that exits when the fa pid disappears — the Linux counterpart of caffeinate -w.
taskItemAgentName(TaskItem item) String
The agent type item runs as: its agent, or defaultTaskAgentName when omitted (omp's spawn-policy default).
taskItemNameBase(TaskItem item) String
The requested id base for item (omp's sanitizeAgentId): its name scrubbed to A-Za-z0-9_- (≤48 chars), defaulting to the capitalized agent type name (omp's AdjectiveNoun name-generator is not ported).
taskTool({required TaskToolConfig config}) AgentTool
Creates the task tool bound to config (omp's TaskTool).
textOfBlocks(List<ContentBlock> content) String
Text of the text blocks, blank-line separated (TS expandAssistant).
textPayloadOf(Object content) String
Plain-text payload of a String or content-block message body.
thinkingBudgetForLevel(String? level, [Map<String, int>? customBudgets]) int
pi's thinkingBudgetForLevel: merged-map lookup on the clamped level.
thinkingOfBlocks(List<ContentBlock> content) String
Thinking text of the reasoning blocks, blank-line separated.
toolAvailabilityIdOf(String toolName) String?
The availability id gating toolName, or null when the name is outside every host-agnostic family (unknown names, host-specific tools, dynamic MCP tools).
trajectoryBuildWireDump(String rawPayload, {String redact(String)?}) TrajectoryWireDump
Builds a wire dump record payload from the raw request JSON: redacts through redact (the host's active pipeline — E1: each dump is redacted under the config active at capture time), then caps. Returns the finished TrajectoryWireDump.
trajectoryCapWireDump(String payload, {int maxChars = wireDumpMaxChars}) → (String, bool)
Applies the wire-dump cap: payloads beyond maxChars are cut and carry wireDumpTruncationMarker (F5 cap enforcement). Returns the capped payload plus whether it was cut.
trajectoryContentHash(String text) String
Stable content hash of text: two independent 32-bit FNV-1a lanes (different basis/primes) over the UTF-8 bytes, hex-encoded as 16 characters. Not a security primitive — a dedup key for blob tables. Two lanes instead of one 64-bit hash because 64-bit literals cannot be represented exactly under dart2js (web builds).
trajectoryDurationSeconds(DateTime? later, DateTime? earlier) Duration?
Own-duration seconds from two stamps; null when either side is unknown.
trajectoryPreviewText(String text) String
Builds a bounded one-line preview without parsing the full document.
trajectoryPromptDiff(String before, String after) List<TrajectoryDiffLine>
Minimal unified-style line diff between two prompt versions (AC2): the common prefix/suffix is trimmed, the middle renders as one changed block, up to 3 context lines flank it, and collapsed ranges show an ellipsis line. Pure — the UI tab and the CLI mirror share it.
trajectoryRecordId({required String kind, String? recordId, String? callId, int? sourceSeq, required int index}) String
Resolves the identity that survives prepending older projected records.
trajectoryRequestBlocks(List<ContentBlock> content) List<TrajectoryRequestMessageBlock>
trajectorySourceBlock(ContentBlock block) TrajectorySourceBlock
Projects one content block into a details-panel source block.
trajectoryTimelineFocusIndexes(List<TrajectoryTurnModel> turns, TrajectoryTimeRange range, [TrajectoryTimelineMode mode = TrajectoryTimelineMode.sequence]) Set<int>
Identifies records active at any point inside an inclusive selected interval in the active projection.
trajectoryToolManifestDiff(TrajectoryToolManifestBlob? before, TrajectoryToolManifestBlob? after) → ({List<String> added, List<String> modified, List<String> removed})
The tool-set diff between two manifest versions (F2): names only — renderers pull descriptions/schemas from the blobs.
trajectoryWireDumpPayload(Context context) String
Builds the raw wire-dump payload for a request (F5): the outbound context as JSON with base64 image bytes replaced by [dump: image omitted] markers (E5). RAW — the host redacts through its RedactionPipeline and caps through trajectoryCapWireDump before persisting.
transcribeAudioTool(ExecutionEnv env, TranscribeAudioConfig config) AgentTool
Creates the transcribe_audio tool.
transientRetryStreamFunction(StreamFunction inner, {int maxAttempts = 3, Duration delay = const Duration(seconds: 5)}) StreamFunction
Wraps inner with the transient-network retry policy: up to maxAttempts total attempts (1 = no retry), delay between them.
truncateSqliteWidth(String value, int width) String
Truncates value to width characters, ending with an ellipsis when cut (omp's truncateToWidth, measured in code units).
unwrapDuckDuckGoUrl(String href) String?
Resolves a DDG result href back to the underlying target URL (omp's unwrapResultUrl): DDG routes outbound clicks through //duckduckgo.com/l/?uddg=<encoded>; also handles protocol-relative and plain absolute URLs.
updateSessionLabelCache(Map<String, String> labelsById, SessionRecord record) → void
upsertYamlPath(String text, List<String> segments, List<String> leafLines) String
Edits text so the dotted segments path carries leafLines (one scalar line, or a multi-line yaml block), keeping every unrelated line (including comments) byte-identical:
uriToFile(String uri) String
Converts a file:// URI back to a file path (omp's uriToFile).
userRequestCandidateLines(List<Message> messages, {List<String?>? recordIds}) List<String>
Extracts open-user-request candidate lines from messages: EVERY user-role text, oldest first — the summarizer LLM itself judges which are open asks, so no message is lost to a detection gate (issue #86). Only structural non-user content is skipped: <system-notice> envelopes, agent mail, and projected branch summaries. recordIds, when given, runs parallel to messages and lands in the line pointer; null/empty entries fall back to a date-only pointer.
userRequestCandidatesBlock(List<Message> messages, {List<String?>? recordIds}) String?
Renders the USER REQUEST CANDIDATES block appended to the summarizer input (after the conversation, before <previous-checkpoint>), or null when there are no candidates — the section is then the LLM's to fill with "(none)".
validateAgentSection(Object? node) → void
The strict agent: section validator, shared by check, set and the settings flow (issues #394/#680). Mirrors the private boot parser in cli_config.dart (pinned by test): the section takes exactly contextWindowCap (a positive integer at or above the compaction reserve — a cap below 16384 must never soften that floor) and mode (the load preset default|pi|omp, validated by the shared agentLoadModeValidationError rule).
validateJsonValue({required Object? value, required Map<String, dynamic> schema}) List<String>
Validates an arbitrary value against the same JSON-schema subset validateToolArguments enforces and returns every violation as a path.with.dots: message string ((root) for the top level). An empty result means valid.
validateProviderTimeoutsSection(Object? node) → void
The strict providerTimeouts: section validator (mirrors the public parser parseProviderTimeouts in cli_config.dart; pinned by test). Shared by check, set and the settings flow (issue #393).
validateRedactSection(Object? value) → void
The strict redact: section validator, shared by check, set and the settings flow (issue #391). RedactionConfig.fromYaml is tolerant for booleans and numbers, but an invalid allowlist regex throws a bare FormatException mid-parse — wrapped here so every caller surfaces the parser's verbatim message as a ConfigException instead of crashing (a config set redact.allowlist used to escape the diagnostics pass uncaught).
validateToolArguments({required Map<String, dynamic> arguments, required Map<String, dynamic> schema, required String toolName}) Map<String, dynamic>
Validates arguments against the tool's JSON-schema schema and returns a new map with coerced values and injected defaults. Undeclared keys pass through unchanged. The input map is never mutated.
validateToolPairing(List<Message> messages) List<ToolPairingViolation>
Validates the pairing invariant on the wire-equivalent sequence of messages. An empty result means the context is safe to send.
viewerBacklogSlice(List<AttachedMessage> rows, bool sawBacklog) → (List<AttachedMessage>, String?)
Caps the pre-open backlog to the last _viewerBacklogCap rows and returns an optional caption naming the hidden remainder. Live rows pass through untouched.
viewerBannerText(SessionLease lease, {required bool stale}) String
The viewer banner (AC3/AC9). Live: Driven by fa CLI (pid 85634) since 14:32 — you are viewing. Your messages are delivered to the live agent. Stale (owner's heartbeat expired while we watch): the same provenance plus the reopen hint — a viewer still never drives; the reopen is a fresh drive-open of a free lease.
viewerRowText(AttachedMessage row) String
Plain text of one transcript row as a viewer renders it (styles are applied by the caller; dimming and bolding are presentation).
viewerStaleNotice(SessionLease lease) String
The once-only notice a viewer prints when the owner's lease flips live → stale under it.
visionMarker(String modelId) String
The short picker marker for modelId's vision support — shown next to model ids in the CLI model pickers.
waitingBeatDue({required DateTime now, required DateTime lastHeartbeat, required int heartbeatMin}) bool
Whether a still waiting heartbeat beat is due now (issue #450): cadence must be enabled and lastHeartbeat plus heartbeatMin must have passed. Pure — unit-tested directly.
waitingDescribe(WaiterSnapshot snap) String
One-line human description of a snapshot (issue #450): "1 background job (…), 2 timers armed". Pure — unit-tested directly.
waitingDetachSummary(WaiterSnapshot snap) String
The headless detach summary line (issue #450 AC7): "N background jobs detached (logs: .fah/bash_jobs/) · M timers armed". Pure.
waitingMinutesElapsed(DateTime? since, DateTime now) int
Whole minutes elapsed since the current waiting stretch began (issue #450): 0 while unknown, otherwise floor of the difference. Pure.
webFetchTool({required WebSearchConfig config}) AgentTool
Creates the web_fetch tool, sharing WebSearchConfig's HTTP plumbing.
webSearchTool({required WebSearchConfig config}) AgentTool
Creates the web_search tool.
withSessionFileLock<T>(String filePath, Future<T> op()) Future<T>
Runs op after every previously queued operation on filePath completes. Never lets one failure poison the chain for later callers.
writeFileTool(ExecutionEnv env) AgentTool
Creates the write tool: creates or overwrites a file, creating parent directories as needed.
xxHash32(Uint8List data, [int seed = 0]) int
Computes xxHash32 of data with seed (both treated as unsigned 32-bit).

Typedefs

A2aAgentRunner = Future<String> Function(String userMessage)
Injected agent runner: processes a user message and returns the response.
A2aMailSink = Future<String> Function(A2aMailEnvelope envelope)
Processes envelopes deposited by a remote sender. Returns the ack text that becomes the A2A task artifact; a throw fails the task.
AfterToolCallHook = FutureOr<AfterToolCallResult?> Function(AfterToolCallContext context, CancelToken? cancelToken)
Called after a tool finishes executing, before tool_execution_end and the tool-result message events are emitted (pi's afterToolCall).
AgentEventSink = FutureOr<void> Function(AgentEvent event)
Sink receiving every event the loop emits (pi's AgentEventSink).
AgentListener = FutureOr<void> Function(AgentEvent event, CancelToken cancelToken)
Listener for agent lifecycle events (pi's Agent.subscribe callback).
AgentToolExecute = Future<ToolExecutionResult> Function(Map<String, dynamic> arguments, CancelToken? cancelToken, ToolUpdateCallback? onUpdate)
Runs one invocation of an AgentTool.
ApprovalPrompt = FutureOr<ApprovalDecision> Function(ApprovalRequest request)
Renders an approval prompt and resolves with the user's ApprovalDecision.
AskCallback = Future<List<AskAnswer>?> Function(List<AskQuestion> questions)
Answers questions on behalf of the user — the host UI surface (CLI menu, Flutter sheet). Returns one AskAnswer per question, or null when the user cancels (dismiss/escape): the tool then resolves with an "ask cancelled by user" result so the model continues gracefully.
BeforeToolCallHook = FutureOr<BeforeToolCallResult?> Function(BeforeToolCallContext context, CancelToken? cancelToken)
Called before a tool is executed (pi's beforeToolCall).
BomStripResult = ({String bom, String text})
Result of stripping a leading UTF-8 BOM from a text body.
BrowserDom = ({String dom, int nodeCount, bool truncated})
The outcome of BrowserController.readDom.
BrowserNavigation = ({int tabId, String title, String url})
The outcome of BrowserController.navigate.
BrowserTab = ({bool active, int? groupId, int id, String title, String url})
One tab as reported by BrowserController.listTabs.
BrowserWaitResult = ({bool found, int waitedMs})
The outcome of BrowserController.waitFor.
ChatGptCredentialsPersist = FutureOr<void> Function(String encoded)
ChildMessageReader = Future<List<(String, String)>> Function(String sessionId, {int tail})
Callback to read the last N messages from a child's session.
ChildResumeRunner = Future<void> Function(String id, String message)
Callback to resume a child IN ITS OWN SESSION with a follow-up message (issue #222): the run appends to the same JSONL transcript, keeping the same mailbox id and display name. Backs task_resume (failed children) and task_send (idle/completed children). Null on hosts that cannot reopen child sessions — the tool descriptors then advertise the missing child-resume capability up front.
ChildSessionFactory = Future<String> Function(String parentSessionId, String childId)
CollectBranchEntries = ({String? commonAncestorId, List<SessionRecord> entries})
Entries collected for a branch summary plus the common ancestor between the old and the new position.
CurrentSubagentIdProvider = String? Function()
Callback resolving the CURRENT subagent id, or null outside a child run. The executor sets this per-spawn so the child-only reply/agent_message tools know whose handle to use.
DialModelsInfo = (List<String>, Set<String>, Map<String, int>, Map<String, int>)
The ids from a DIAL /openai/models response whose features.cache flag is on (manual cache_breakpoint markers are honored for them), plus the per-deployment reported limits (context window / max output — from limits.max_total_tokens/max_prompt_tokens and limits.max_completion_tokens).
DynamicMessageCallback = Future<String?> Function(DynamicMessageRequest request)
Presents request inline in the chat — the host UI surface (Flutter session view). Returns the host-assigned widget id once presented, or null when declined (per-run presentation cap reached / no chat session): the tool then resolves with a plain decline result so the model continues gracefully.
HarnessLlmSlot = ({Model model, StreamFunction stream})
One resolved LLM slot: the stream function and the model for a call.
ImageDropNotice = void Function(int index, String keyPreview)
Host-visible drop notice: every image dropped by the per-request cap is reported with its index and a key preview — never silent.
LlmKeyResolver = String? Function(String baseUrl, String? providerName)
Resolves the stored key for an endpoint (env-first, then the secure store — mirroring the CLI's envVarValue order). Null = no key.
LlmRelayStream = Future<void> Function(LlmRelayRequest request, void onDelta(String delta))
Streams one relayed completion, calling onDelta per text chunk. A throw fails the relay with an llmRes error — error messages MUST NOT embed the key.
LogTeeSink = void Function(String text)
Writes one teed chunk — exactly the text the CLI produced, writeln chunks already carrying their trailing newline. The executable wires this to an unbuffered file sink (bin/fah.dart owns dart:io), so every chunk reaches the OS as it is produced and a tail -f on the log streams the trace live.
LspTransportFactory = Future<LspTransport> Function(LspServerConfig config, String cwd)
Spawns a language server for config rooted at cwd.
MailboxWakeLauncher = Future<String?> Function({required String cwd, required String sessionId, String? sessionName})
Session-scoped subagent manager. Launches a detached, non-interactive run of a session so a SLEEPING agent processes its pending inbox mail right away (issue: "if the target is asleep it will never read the message"). Hosts wire the launcher (the CLI spawns its own binary with --session <name>); the run appends to the same session JSONL, so a later interactive fa --session <name> resumes that exact transcript. Null disables the wake path — callers then get a "how to start it" hint instead.
McpToolCaller = Future<Map<String, dynamic>> Function(String server, String tool, Map<String, dynamic> arguments)
Calls tool on server with arguments, returning the raw MCP result map. Provided by the manager so the wrapper never holds a client.
McpTransportFactory = Future<McpTransport> Function(McpServerConfig server, String cwd)
Spawns/connects the transport for server, running stdio processes in cwd. Implementations must throw McpServerUnavailableException (not return null) when the server cannot be started.
ModelsEndpointFetcher = Future<ModelsEndpointInfo> Function(String baseUrl, {required String apiKey})
Fetches and parses the /models payload of baseUrl (hosts inject fakes in tests; production defaults do the HTTP GET + parseModelsResponse).
ModelsEndpointInfo = (List<String>, Map<String, int>, Map<String, int>)
The parsed /models payload: ids, per-id context windows, per-id output caps.
OverWindowRelief = Future<List<Message>?> Function(List<Message> overWindowMessages)
Emergency over-window relief (issue #387): called by the loop's over-window guard when a request is about to be refused (gross mid-turn overflow). The host runs ONE synchronous compaction and returns the relieved transcript to retry with — or null when nothing hideable remains (the loop then surfaces the verbatim guard error). The argument is the loop's live transcript; the returned list REPLACES it for the rest of the run.
PasswordPromptCallback = FutureOr<String?> Function(String promptLine)
Answers a detected password ask on behalf of the host UI (the TUI's masked prompt zone, the Flutter sheet). promptLine is the actual prompt as it appeared in the output ([sudo] password for user:).
PluginAskLine = Future<String?> Function(String question, {bool secret})
A free-form question rendered by the host (masked input when secret). Resolves to the entered text, or null on cancel.
PluginMenuOption = (String, String, String)
One multiple-choice option for PluginPickOption: stable key + display label + dim description.
PluginPickOption = Future<String?> Function(String title, List<PluginMenuOption> options, {String? initialKey})
A multiple-choice question rendered by the host (a TUI menu, or a numbered list in line mode). Resolves to the chosen option key, or null on cancel.
PrepareNextTurnHook = FutureOr<AgentLoopTurnUpdate?> Function(NextTurnContext context)
Called after turn_end and before the loop decides whether another provider request should start (pi's prepareNextTurn).
QueueDeathClassifier = QueueDeath? Function(ErrorEvent event)
Classifies an error event into a queue death, or null when the chain must NOT advance (content_filter family, user abort) and the error surfaces verbatim (issue #418: advance on ANY provider death, never on safety stops).
QueuedMessagesSource = FutureOr<List<Message>> Function()
Returns queued messages to inject into the conversation.
RedactionHooks = ({AfterToolCallHook afterToolCall, TransformContextHook transformContext})
Agent hooks that mask registered secrets, see redactionHooks.
RedactionPipelineHooks = ({AfterToolCallHook afterToolCall, BeforeToolCallHook beforeToolCall, TransformContextHook transformContext})
The hook set the redaction pipeline installs on an Agent; see redactionPipelineHooks and attachRedactionPipeline.
RemoteCatalogUrlResolver = Uri? Function()
The host-injected accessor. The CLI passes its yaml override; the app passes its in-memory config.
RequestSecretCallback = Future<RequestSecretResult?> Function(String name, String reason)
Answers the agent's credential request on behalf of the user — the host UI surface (Flutter bottom sheet). Returns the granted RequestSecretResult, or null when the user declines: the tool then resolves with a "user declined" result so the model continues gracefully.
SessionIoRetryLogger = void Function(String message)
Host diagnostic sink for retry lines. Hosts wire their existing diagnostic log (the CLI's _logDiagnostic~/.fah/logs/fa.log); null keeps retries silent.
SessionTimingLogger = void Function(String message)
Host diagnostic sink for resume-open timing lines (resume_timing …). Hosts wire their existing diagnostic log (the CLI's _logDiagnostic~/.fah/logs/fa.log); null keeps timing silent. One line per opened session storage, naming every phase's milliseconds.
SlashCommand = Future<void> Function(List<String> args)
A slash-command handler registered by a plugin.
SseEvent = ({String data, String event})
One parsed SSE event: the event name (message when absent) and the joined data: payload.
StreamFunction = AssistantMessageEventStream Function(Model model, Context context, {CancelToken? cancelToken})
Provider adapter contract consumed by the agent loop.
SubagentRegistrySink = Future<void> Function(List<Map<String, dynamic>> registry)
Callback to record the subagent registry into the parent session.
SubagentRegistrySource = Future<List<Map<String, dynamic>>> Function()
Callback to rehydrate the registry from the parent session.
SummarizeFn = Future<SummarizationResult> Function(SummarizationRequest request)
The injectable summary LLM call.
TaskSpawnProgressCallback = void Function(int index, String id, TaskSpawnPhase phase)
Progress sink for spawn lifecycle transitions. Items without a report are still waiting on the session semaphore.
TextOnlyImageDropNotice = void Function(int droppedCount)
Host-set hook for the text-only strip (downgradeUnsupportedImages): reports how many image blocks the model's declared modalities dropped, so the run shows a VISIBLE notice instead of silence (issue #638). Null (the default) keeps the strip silent.
ToolExecutor = Future<ToolExecutionResult> Function(ToolCall toolCall, CancelToken? cancelToken, ToolUpdateCallback? onUpdate)
Executes a single tool call and returns its result.
ToolUpdateCallback = void Function(ToolExecutionResult partialResult)
Callback used by a tool executor to stream partial execution updates.
TransformContextHook = FutureOr<List<Message>> Function(List<Message> messages, CancelToken? cancelToken)
Rewrites the message list sent to the provider before each call (pi's transformContext). The transcript itself is never modified.
TransientRetryNotice = void Function(int attempt, int maxAttempts, Duration delay, String reason)
The no-silent-retry note: fired before each retry sleep so the user sees "connection lost — retrying in 5s (attempt 2/3)" instead of a mysterious pause. attempt is the 1-based attempt that just failed; maxAttempts the total budget; reason the truncated provider error.

Exceptions / Errors

A2aException
Thrown on A2A protocol errors.
AbortedError
Thrown internally when a CancelToken fires; caught and converted into an aborted ErrorEvent. Never escapes an adapter.
AgentHarnessException
Base class for all harness exceptions. Sealed so consumers can exhaustively switch on the exception type.
AgentUrlException
Thrown when an agent:// URL cannot be resolved (port of omp's model-visible protocol errors).
AiinAuthException
A setup-flow failure talking to the AIIN auth or API service.
BridgeProtocolException
A protocol violation found while decoding a frame. The transport answers with an error frame (and closes for BridgeErrorCode.proto).
BrowserToolException
A browser-op failure carrying the contract's wire error code (no_target, node_vanished, restricted_page, timeout, …). The code rides the thrown message so the model can read and react to it.
CancelledException
Thrown by CancelToken.throwIfCancelled and by operations that abort early due to cancellation.
CliArgsException
Invalid command line: the executable prints message plus a usage hint to stderr and exits with code 64 (EX_USAGE).
CompactionException
Thrown when the compaction pipeline cannot produce a summary.
ConfigException
Thrown when harness configuration is invalid (e.g. malformed config files or missing required settings).
CopilotAuthException
The GitHub credential was rejected by the token exchange (HTTP 401/403): the GitHub token is dead and must be re-issued (/provider copilot), NOT refreshed like a short-lived Copilot token would be.
CopilotDeviceFlowError
A typed device-flow failure; the CLI prints message verbatim.
CubeNetworkDeniedException
Thrown by GatedHttpClient when a request — or a redirect hop — targets a destination the active cube's network policy denies. The web tools catch it and answer with the note as a normal tool result.
ExecutionError
Error returned by Shell.exec.
FileError
Error returned by FileSystem operations.
HashlineFormatException
Error thrown for malformed hashline patch input (parse-time), distinct from HashlineMismatchError-style apply-time rejections.
HashlineMismatchError
Raised when a hashline section's snapshot tag doesn't match the live file's content. The formatted message tells the model exactly which tag the file currently hashes to and shows the live content around the anchored lines, so the recovery path is "re-read / re-anchor", never a blind retry.
LspNoServerException
Thrown when no configured server handles a file's extension.
LspRequestException
Thrown when an LSP request fails: server error response, timeout, or a dead connection.
LspServerUnavailableException
Thrown by an LspTransportFactory when the server process cannot be started (e.g. the command is not on PATH). The lsp tool converts this into a clean error result — never a crash.
McpRequestException
Thrown when an MCP request fails: server error response, timeout, or a dead connection.
McpServerUnavailableException
Thrown when an MCP server cannot be reached or spawned. The manager converts this into the server's failed status — never a crash.
MobileAutomationException
A named mobile automation failure. The tools catch these and return the message as a plain (non-throwing) result the model can react to.
ProviderHttpError
A non-200 HTTP response, carrying the status and raw body for error reporting (the Dart counterpart of the SDK error objects pi normalizes).
SessionException
Thrown when a session storage operation fails (read, write, or corrupt JSONL records).
ToolNotFoundException
Thrown when a tool referenced by the model is not registered.
ToolValidationException
Thrown when tool call arguments fail validation against the tool's declared parameter schema.
WebSearchException
A provider failure carrying the originating provider id and, for HTTP failures, the status code (omp's SearchProviderError).