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.
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.
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
Stateful wrapper around the low-level agent loop.
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
Static configuration for an AgentCli session.
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.
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.
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.
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.
CliIO
Terminal IO abstracted for testability.
CodeMieSsoCredentials
The result of a successful CodeMie SSO login: the session cookies plus the resolved API base URL.
CompactionManager
The compaction pipeline over a Session, mirroring pi's harness-level compact().
CompactionPreparation
Prepared inputs for a compaction run.
CompactionPrompts
The four summarization prompts used by the compaction pipeline, 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).
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.
CriticalBashPattern
A destructive shell pattern with a human-readable label, surfaced in the approval prompt's reason.
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.
DialOptions
Options for streamDial.
DoneEvent
Terminal event: the message completed successfully.
DuckDuckGoSearchProvider
DuckDuckGo search via the keyless no-JS HTML frontend.
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.
FahPlugin
Base interface for a fah plugin / package extension.
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.
FileSessionPresenceStore
FileSystem
Filesystem capability used by the harness.
GoogleOptions
Options for streamGoogle.
GoogleThinking
Thinking configuration for Gemini models.
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.
HtmlTag
One scanned HTML tag (open, close, or self-closing).
HtmlText
A plain-text chunk between tags.
ImageContent
An image supplied by the user or a tool result.
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.
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").
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).
MailboxEntry
One entry in the messaging-fabric directory.
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.
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.
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.
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.
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.
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.
PathRoleOverride
A path-scoped set of role chains, applied when the cwd matches pattern.
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.
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.
ProviderSpec
Static description of a supported provider.
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.
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.
RequestSecretResult
The credential the user granted through the host's secret prompt.
Result<T, E>
Result of a fallible operation. Expected failures are returned as Err instead of thrown — FileSystem operations must never throw.
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.
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.
SessionHeader
The session header — always the first line of a JSONL session file.
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.
SessionMetadata
Metadata describing a stored session.
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.
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.
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.
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.
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.
SubagentManager
Session-scoped subagent manager.
SubagentMessage
One inter-agent message (Phase 3b agent_message / reply payloads).
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.
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.
Tool
A tool the model may invoke, with a JSON Schema for its parameters.
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.
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.
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.
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.
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.

Enums

A2aTaskState
A2A Task states.
AgentMessageKind
The delivery intent of an AgentMessage.
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.
CompactionErrorCode
Stable error codes for CompactionException, ported from pi's CompactionError kinds.
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.
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.
ForkPosition
Where a fork cut point sits relative to JsonlSessionRepo.fork's entryId.
HashlineSectionOp
Per-section outcome of HashlinePatcher.commit.
KeyType
Kinds of keys recognized by the TUI input loop.
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.
PromptToolFormat
Which wire format the wrapper teaches the model and parses back.
QueueMode
Controls how many queued messages are injected when the loop reaches a queue drain point. Ported from pi's QueueMode.
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.
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.
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.
AgentCliMessagingFlow on AgentCli
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.
ApprovalModeLabel on ApprovalMode
The CLI/config spelling of an ApprovalMode (always-ask, write, yolo, unattended).
SettingsFlow on AgentCli
Implementation members of AgentCli for the settings-hub flows. Named (not anonymous) so hosts and tests can drive the flows directly.

Constants

agentUrlScheme → const String
The internal URL scheme addressing subagent outputs.
appOnlySettings → const Set<SharedSetting>
Settings that are currently app-only.
architectModePromptName → const String
Canonical prompt name for the CLI architect mode.
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.
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).
chatGptCodexBaseUrl → const String
chatGptIssuer → const String
chatGptOAuthClientId → const String
chatGptOAuthScope → const String
checkpointToolName → const String
The checkpoint tool name.
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).
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.
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.
defaultArchiveListLimit → const int
Default entry cap for archive directory listings (omp's #readArchiveDirectory DEFAULT_LIMIT).
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).
defaultModelRole → const String
The role used for ordinary agent runs.
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).
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).
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).
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).
estimatedImageChars → const int
Estimated character cost of an image block (pi's ESTIMATED_IMAGE_CHARS: 4800 chars ≈ 1200 tokens at 4 chars/token).
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
headTailDriftWarning → const String
INS.HEAD:/INS.TAIL: applied despite a stale snapshot tag.
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.
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.
lspConfigFileName → const String
Config file consulted in the workspace root (documented location; see LspConfig.load).
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).
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).
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).
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.
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.
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.
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).
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).
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.
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.
sqliteBusyTimeoutMs → const int
PRAGMA busy_timeout applied on open (omp: 3000 ms).
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.
summarizationPrompt → const String
Structured checkpoint prompt for a first-time compaction summary. Ported verbatim from pi SUMMARIZATION_PROMPT.
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).
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 summarizing the prefix of a split turn during compaction. Ported verbatim from pi TURN_PREFIX_SUMMARIZATION_PROMPT.
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 updating an existing compaction summary with new messages. Ported verbatim from pi UPDATE_SUMMARIZATION_PROMPT.
voidHtmlTags → const Set<String>
Tags that have no content model and never need a close tag.
webSearchUserAgent → const String
Shared browser-profiled user agent for the keyless scrape endpoints.
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
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
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
modelListDialects List<ModelListDialect>
The registered dialects, in precedence order. First match wins. Adding a new provider = one new class + one entry here.
final
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

Functions

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.
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.
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).
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).
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).
buildCatalogModel(String provider, String modelId, {String? baseUrl, int? contextWindow, int? maxTokens}) 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}) Model
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.
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, Model? model()?, SqliteEngine? sqlite, LspToolConfig? lsp, McpManager? mcp, ShellJobRegistry? shellJobs}) List<AgentTool>
Creates the four built-in tools (readFileTool, writeFileTool, listDirTool, shellTool) bound to env.
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.
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).
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).
clampWebSearchCount(int? count) int
Clamps a requested result count to 1..[maxWebSearchCount], defaulting to defaultWebSearchCount (omp's clampNumResults).
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).
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.
compactProviderError(String message) String
Reduces a provider error blob to something readable on one line: unwraps OpenRouter's metadata.raw upstream JSON recursively, prefers the most specific message, and caps the result at 300 chars.
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.
containsRecognizableHashlineOperations(String input) bool
Returns true when the input contains at least one line that the tokenizer recognizes as a hashline op.
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.
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).
defaultAgentCliSystemPrompt(String cwd) String
The default system prompt for the CLI agent.
defaultAgentMode(String cwd, {PromptOverrides? overrides}) AgentMode
The default coding-agent mode.
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.
deriveCodeMieExpiresAt(Map<String, String> cookies) int
The expiry (ms epoch) of the first JWT cookie's exp claim.
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".
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.
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.
editFileTool(ExecutionEnv env, {HashlineSnapshotStore? snapshots}) AgentTool
Creates the edit tool: edits a file in one of two modes.
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 (ChatGPT Codex until its WebSocket adapter ships) 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.
estimateTokens(Message message) int
Estimate token count for one message using pi's character heuristic.
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.
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.
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.
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.
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.
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.
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.
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.
formatTokenPreset(int tokens) String
Formats a token count as a compact preset label (4K, 16K, 1M).
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.
generateSummary(List<Message> messages, {required SummarizeFn summarize, String? customInstructions, String? previousSummary, CancelToken? cancelToken, CompactionPrompts prompts = defaultCompactionPrompts}) 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).
hasHeader(Map<String, String?>? headers, String name) bool
Whether headers contains a non-empty value for name (case-insensitive).
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).
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.
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.
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).
isKnownHtmlTag(String tagName) bool
Whether tagName parses as a markup tag (vs. literal text).
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.
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.
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).
loadJsonlSessionMetadata(FileSystem fs, String filePath, {DateTime? lastUpdatedAt}) Future<SessionMetadata>
Reads just the header of a session file and returns its metadata.
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).
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.
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.
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).
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.
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).
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).
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).
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.
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.
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
Parses the fah argument list.
parseCommandArgs(String input) List<String>
Parses bash-style quoted arguments from the text after a /command.
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).
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.
parseModelsResponse(String body) ModelsEndpointInfo
Parses body (the raw /models JSON) into ModelsEndpointInfo.
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).
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.
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.
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).
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.
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.
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, anthropic, google, dial, chatgpt-codex) 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).
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.
redactionHooks(SecretRedactor redactor) RedactionHooks
Builds the agent hooks that redact redactor's values:
refreshChatGptCredentials(ChatGptOAuthCredentials credentials, {Client? client}) Future<ChatGptOAuthCredentials>
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).
repairOrphanedToolCalls(List<Message> messages) List<Message>
Repairs orphaned tool calls in a request payload: every ToolCall in an assistant message must be answered by a ToolResultMessage, or providers hard-reject the whole context (OpenAI 400: "an assistant message with 'tool_calls' must be followed by tool messages..."). Aborted runs, restored sessions and compaction cuts can all leave calls without results. Rather than dropping them (which erases what the run was doing), a synthetic interrupted result is injected right after the assistant message. The transcript itself is never modified — the repair applies to the outbound request only. Returns messages untouched (same instance) when nothing is missing.
repr(String text) String
Renders text with JSON-style quoting for diagnostics.
requestSecretTool({RequestSecretCallback? callback}) AgentTool
Creates the request_secret tool bound to callback.
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).
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).
resolveSqliteRowLookup(SqliteDatabase db, String table) SqliteRowLookup
Resolves the row-lookup strategy for table (omp's resolveTableRowLookup).
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.
restoreLineEndings(String text, LineEnding ending) String
Re-encodes LF text with the requested line ending.
reviewMode(String cwd, {PromptOverrides? overrides}) AgentMode
Code-review mode.
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.
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.
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.
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.
sha256Hex(String value) Future<String>
Computes the lowercase hex SHA-256 digest of value.
sharedProviderHttpClient() → Client
The shared keep-alive HTTP client for provider streams.
shellTool(ExecutionEnv env, {ShellJobRegistry? jobs}) 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.
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.
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).
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.
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
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}) 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.
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, ChildMessageSender? sendToChild, CurrentSubagentIdProvider? currentSubagentId, TaskJobManager? jobs}) 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.
substituteArgs(String content, List<String> args) String
Substitutes positional arguments into a template body.
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).
transcribeAudioTool(ExecutionEnv env, TranscribeAudioConfig config) AgentTool
Creates the transcribe_audio tool.
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.
uriToFile(String uri) String
Converts a file:// URI back to a file path (omp's uriToFile).
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.
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.
visionMarker(String modelId) String
The short picker marker for modelId's vision support — shown next to model ids in the CLI model pickers.
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.
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.
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.
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.
ChildMessageSender = Future<void> Function(String sessionId, String message)
Callback to send a message to a child (resume/steer).
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).
LspTransportFactory = Future<LspTransport> Function(LspServerConfig config, String cwd)
Spawns a language server for config rooted at cwd.
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.
PrepareNextTurnHook = FutureOr<AgentLoopTurnUpdate?> Function(NextTurnContext context)
Called after turn_end and before the loop decides whether another provider request should start (pi's prepareNextTurn).
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.
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.
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.
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.

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).
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).
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.
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).