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
- 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.
- AgentCli
- The CLI harness: agent + built-in tools + session persistence + compaction, driven by a CliIO.
- AgentCliConfig
- Static configuration for an AgentCli session.
- 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(nothinkingLevel: reasoning levels are not ported yet). - 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.
- 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 anarchive.ext:inner/pathreference (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
streamcalls. - 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.
- CheckpointRecord
-
Marks a self-service context checkpoint created by the
checkpointtool so a laterrewindcan collapse the exploratory detour into a report. - CheckpointRewindController
-
Orchestrates the
checkpoint/rewindflow 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/-hwas passed: print usage and exit 0. - CliArgsResult
-
The outcome of parsing the
fahargument list. - CliArgsVersion
-
--versionwas passed: print the version and exit 0. - CliIO
- Terminal IO abstracted for testability.
- 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, seelib/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.
- CustomRecord
- An application-defined record that is omitted from model context by default.
- CutPointResult
- Cut point selected for compaction.
- 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
fahplugin / 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.
- FileOperations
- File paths touched by a compaction range.
- 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_imagetool. - 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-, or50+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
lsptool 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
lsptool; 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'sWorkspaceEdit, reduced to text edits). - ManagedSession
- One managed session: the Agent, its persistent Session, and the metadata that identifies it.
- 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.
- 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.
- 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). - 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.
- 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.
- ProviderSpec
- Static description of a supported provider.
- PubDevHandler
-
Renders pub.dev package pages (
/packages/<name>) from the pub.dev API instead of scraping the HTML page (ported from omp'sscrapers/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
-
:rawalone — verbatim whole-resource output. -
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.
- 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.
- SessionHeader
- The session header — always the first line of a JSONL session file.
- SessionInfoRecord
- Records session-level information such as a display name.
- SessionMetadata
- Metadata describing a stored session.
- SessionRecord
- One entry in the append-only session tree.
- SessionRepo
- The repository contract for sessions.
- SessionStorage
- The storage contract behind a Session tree.
- Shell
- Shell execution capability used by the harness.
- ShellExecOptions
- Options for Shell.exec.
- ShellExecResult
- Outcome of a completed Shell.exec invocation.
- Skill
-
One discovered skill (metadata only; the body stays on disk for
progressive disclosure via the
readtool). - 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
readtool. The FFI-backed implementation lives behindlib/io.dart; web hosts pass no engine. - SqliteListSelector
-
db.sqlite— list non-sqlite_%tables with row counts. - SqlitePathCandidate
-
One
{sqlitePath, subPath, queryString}split of adb.sqlite:table?queryreference (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
queryRowsreturn 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_stat1estimate variant). - SseDecoder
- Decodes a stream of text chunks into ServerSentEvents.
- StartEvent
- Emitted once before any content events.
- StructuredTaskOutput
-
Parsed structured completion plus its validation metadata (omp's
StructuredSubagentOutput, reduced: no source/mode — v1 schemas always come from the call item). - 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.
- TaskAgentDefinition
-
Definition of a subagent type spawnable through the
tasktool (omp'sAgentDefinition, reduced: nospawns,thinkingLevel, frontmatteroutput, or file source). - TaskAgentRegistry
-
Resolves agent types for
taskcalls: TaskAgentRegistry.resolve finds a type by name, TaskAgentRegistry.toolSurfaceFor computes a type's restricted child tool surface. - TaskExecutor
-
Runs
taskbatch items as child Agents under a session Semaphore. - TaskItem
-
One unit of work in a
taskbatch call (omp'sTaskItem, reduced: noisolated, noschemaMode). - 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 asagent://<id>. - TaskJobManager
-
Session-scoped registry of background
taskjobs (reduced port of omp'sAsyncJobManagerrole 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)
taskcalls share the concurrency bound and theagent://id space (omp's session-scopedTaskToolinstance). - 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.
- 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.
- 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.
- 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_audiotool. - 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.
- 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_searchtool 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
- 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.
- CompactionErrorCode
-
Stable error codes for CompactionException, ported from pi's
CompactionErrorkinds. - 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).
- 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
SessionErrorCodeunion. - SkillScope
- Where a skill was discovered (listing order in the prompt).
- StopReason
- Why the assistant message stream terminated.
- StructuredValidationStatus
-
Final validation state of a schema-bearing spawn (omp's
StructuredSubagentValidationStatus). - 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/abortedpair 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).
Extensions
- ApprovalModeLabel on ApprovalMode
-
The CLI/config spelling of an ApprovalMode (
always-ask,write,yolo).
Constants
- agentUrlScheme → const String
- The internal URL scheme addressing subagent outputs.
- architectModePromptName → const String
- Canonical prompt name for the CLI architect mode.
- 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
(
shellToolinbuiltin_tools.dartregisters 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). - checkpointToolName → const String
-
The
checkpointtool name. -
cliProviderKinds
→ const Set<
String> -
The provider kinds accepted by
--provider. - 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. - defaultArchiveListLimit → const int
-
Default entry cap for archive directory listings (omp's
#readArchiveDirectoryDEFAULT_LIMIT). - 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
diagnosticswaits for a fresh publish after opening a file (omp'sSINGLE_DIAGNOSTICS_WAIT_TIMEOUT_MS). - defaultLsEntryLimit → const int
-
Default entry cap for the
lstool (pi'sDEFAULT_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'sDEFAULT_SPAWN_AGENT). - defaultTaskMaxConcurrent → const int
-
Default session concurrency cap (omp's
task.maxConcurrencydefault;0means 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). - 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 DESTmoves 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:
REMdeletes 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 againstSELECT *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
#readSqlitelist 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). -
modelRoleIds
→ const List<
String> - The model roles supported by ModelRolesConfig, in declaration order.
-
overridablePromptNames
→ const Map<
String, String> -
The prompt names accepted in the CLI config
prompts:section, mapped to a short description. Names mirror theprompts/tree ids used byscripts/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.
- reviewModePromptName → const String
- Canonical prompt name for the CLI review mode.
- rewindReportCustomType → const String
-
The
custom_messagetype carrying the retained rewind report in the session tree (omp'srewind-reportcustom message). - rewindToolName → const String
-
The
rewindtool 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). - smolModelRole → const String
- The role compaction summarization resolves through when configured.
- sqliteBusyTimeoutMs → const int
-
PRAGMA busy_timeoutapplied on open (omp: 3000 ms). - 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
systemconfig 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'sfullOutputThreshold). - taskToolName → const String
-
The
tasktool name. - tavilySearchUrl → const String
-
Tavily search endpoint (omp's
TAVILY_SEARCH_URL). - ttsrInjectionCustomType → const String
-
The
custom_messagetype carrying the injected reminder in the session tree (omp'sttsr-injectioncustom message). - ttsrInjectionRecordType → const String
-
The
customrecord type persisting injected rule names (omp'sttsr_injectionentry). - turnPrefixSummarizationPrompt → const String
- Prompt for summarizing the prefix of a split turn during compaction. Ported verbatim from pi TURN_PREFIX_SUMMARIZATION_PROMPT.
- 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.
Properties
- builtinExploreAgent → TaskAgentDefinition
-
omp's
scoutported under the nameexplore: read-only research on thesmolrole.final - builtinReviewAgent → TaskAgentDefinition
-
omp's
reviewerported under the namereview: read-only code review on theslowrole.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
-
criticalBashPatterns
→ List<
CriticalBashPattern> -
Patterns that force an approval prompt for any matching
bashcommand.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
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
contextwithout adding a new message. -
applyHashlineEdits(
String text, List< HashlineEdit> edits) → HashlineApplyResult -
Applies
editstotextand returns the post-edit result. Throws HashlineFormatException if an anchor is out of bounds. -
applyTextEditsToString(
String content, List< LspTextEdit> edits) → String -
Applies
editstocontentin-memory, bottom-to-top (omp'sapplyTextEditsToString). Call sortAndValidateTextEdits first (this function re-sorts defensively). -
applyWorkspaceEdit(
ExecutionEnv env, LspWorkspaceEdit edit, {Map< String, int> openFileVersions = const {}}) → Future<List< LspAppliedChange> > -
Applies
editthroughenvand returns the per-file changes. -
approvalModeFromLabel(
String? value) → ApprovalMode? -
Parses a CLI/config label into an ApprovalMode;
nullwhen 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
asktool bound tocallback. -
attachApproval(
Agent agent, ApprovalManager manager) → void -
Composes the approval gate for
managerontoagent, preserving any BeforeToolCallHook already registered (approval runs first). -
attachSecretRedactor(
Agent agent, SecretRedactor redactor) → void -
Composes the redaction hooks for
redactorontoagent, preserving any hooks already registered (existing hooks run first, redaction runs last so content they produce is masked too). -
buildCatalogModel(
String provider, String modelId, {String? baseUrl, int? contextWindow, int? maxTokens}) → Model -
Builds a Model for
provider/modelIdwith catalog defaults, overrid- able per reference (seeModelRef). -
buildCliDefaultModel(
String providerKind, {String? modelId, String? baseUrl}) → Model -
Builds the legacy single Model the
fahexecutable runs when no roles are configured (--provider/--model/--base-urlflags). -
buildSqliteAsciiTable(
List< String> columns, List<Map< rows) → StringString, Object?> > -
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}) → 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.
-
catalogProvider(
String name) → ProviderSpec? -
Resolves
nameagainst the providerCatalog. -
clampWebSearchCount(
int? count) → int -
Clamps a requested result count to
1..[maxWebSearchCount], defaulting to defaultWebSearchCount (omp'sclampNumResults). -
cliHelpText(
String version) → String -
The full
--helpoutput printed by thefaexecutable.versionis threaded through from the executable (_versioninbin/fah.dart) — the single source of truth shared with--version— and rendered in the header line. -
collectEntriesForBranchSummary(
Session session, String? oldLeafId, String targetId) → Future< CollectBranchEntries> -
Collect the entries to summarize when navigating from
oldLeafIdtotargetId: walks from the old leaf back to the common ancestor, returning entries in chronological order (omp'scollectEntriesForBranchSummary). 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
baseNamefromsecrets: 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.rawupstream 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).
-
decodeHtmlEntities(
String text) → String - Decodes the small set of HTML entities seen in search results and page content (named, decimal, and hexadecimal forms).
-
decodeUtf8Text(
Uint8List bytes) → String? -
Decodes
bytesas strict UTF-8 text, or returns null for binary content (omp'sdecodeUtf8Text: 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< String> projectRoots, List<String> userRoots}) -
The default skill roots for a host:
<cwd>/.fah/skills+<cwd>/.agents/skills(project) and, when a home directory exists,~/.fah/skills+~/.agents/skills(user). Web/sandbox hosts pass their sandbox cwd and no home (the sandbox FS carries project skills). -
defaultWebSiteHandlers(
) → List< WebSiteHandler> - The site handlers tried, in order, before the generic HTML→markdown converter.
-
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. -
discoverSkills(
ExecutionEnv env, {List< String> projectRoots = const [], List<String> userRoots = const []}) → Future<List< Skill> > -
Discovers skills under
projectRootsthenuserRoots(kimi's precedence: project > user), first-name-wins case-insensitively. Missing roots are silently skipped. -
editFileTool(
ExecutionEnv env, {HashlineSnapshotStore? snapshots}) → AgentTool -
Creates the
edittool: edits a file in one of two modes. -
estimateContextTokens(
List< Message> messages) → ContextUsageEstimate -
Estimate context tokens for
messagesusing provider usage when available. -
estimateTokens(
Message message) → int - Estimate token count for one message using pi's character heuristic.
-
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. Returnstextunchanged when it is not a template command. -
extractFileOpsFromMessage(
Message message, FileOperations fileOps) → void -
Add file operations from assistant
read/write/edittool calls tofileOps. Ported from pi'sextractFileOpsFromMessage. -
extractHtmlTitle(
String html) → String? -
Extracts and decodes the
<title>of an HTML document, or null when absent or empty. -
fileToUri(
String path) → String -
Converts an absolute file path to a
file://URI (omp'sfileToUri). -
findCutPoint(
List< SessionRecord> entries, int startIndex, int endIndex, int keepRecentTokens) → CutPointResult -
Find the compaction cut point that keeps approximately
keepRecentTokensrecent 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:TEXTrows aroundanchorLines(±mismatchContextLines),*-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-12range string. -
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
pathrelative tocwdwhen it sits underneath it (omp'sformatPathRelativeToCwd, 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.
-
formatSkillsForPrompt(
List< Skill> skills) → String -
Renders the progressive-disclosure block for the system prompt (pi's
<available_skills>): metadata only — the agent loads a skill's file with thereadtool when the task matches its description. Empty when there are no skills. -
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 / snippetsources. -
generateBranchSummary(
List< SessionRecord> entries, {required SummarizeFn summarize, int tokenBudget = 0, String? customInstructions, CancelToken? cancelToken}) → Future<BranchSummaryResult> -
Generate a summary of abandoned-branch
entries(omp'sgenerateBranchSummary): serializes them into<conversation>tags, ends with the fixed branch-summary prompt (orcustomInstructions), and prepends the branch preamble plus the file-operation tags. Never throws: failures surface as BranchSummaryResult.error. -
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 TABLEstatement fortable(omp'sgetTableSchema). -
htmlToMarkdown(
String html, {Uri? baseUrl}) → String -
Converts an HTML document to structured Markdown.
baseUrlresolves relative link/image targets; when null they are emitted verbatim. -
inspectImageTool(
ExecutionEnv env, InspectImageConfig config) → AgentTool -
Creates the
inspect_imagetool. -
isContextOverflow(
AssistantMessage message, {int? contextWindow}) → bool -
Whether
messagerepresents a context overflow. -
isDuckDuckGoAnomalyPage(
String html) → bool -
truewhen 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'sisAnomalyResponse). -
isKnownHtmlTag(
String tagName) → bool -
Whether
tagNameparses as a markup tag (vs. literal text). -
isRateLimitOrQuota(
AssistantMessage message, {Duration? retryAfter}) → bool -
Whether
messageis 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
providercan serve searches givensecrets: keyless providers are always available, keyed ones need their non-empty key. -
listDirTool(
ExecutionEnv env) → AgentTool -
Creates the
lstool: lists directory entries sorted alphabetically (case-insensitive), directories suffixed with/, capped atlimitentries (default defaultLsEntryLimit) and defaultToolMaxBytes bytes. -
listSqliteTables(
SqliteDatabase db, {int probeCap = rowCountProbeCap}) → List< SqliteTableSummary> -
Lists non-
sqlite_%tables with bounded row counts (omp'slistTables). -
loadJsonlSessionMetadata(
FileSystem fs, String filePath) → 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
cwdup to the git root (or the filesystem root). Returns files farthest-first, closest (most specific) last. AuserFile(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
uriwith a browser profile, following redirects and capping the body atmaxBytes(omp'sloadPage, reduced: no user-agent rotation or 429 retry — the tool surfaces failures directly). -
lspTool(
ExecutionEnv env, {required LspToolConfig config}) → AgentTool -
Creates the
lsptool bound toenv. Registered frombuiltinToolsonly 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, ornullwhen the command matches nothing critical. -
messageFromJson(
Map< String, dynamic> json) → Message -
Deserializes a Message from its JSON map, dispatching on
role. -
Navigate
sessiontotargetId(omp's tree navigation with branch summarization): the branch being left is summarized viasummarizeinto abranch_summaryrecord prepended to the context of the branch being entered, and the active leaf moves. Returns the newbranch_summaryrecord id, ornullwhen no summary was written (no-op navigation, nothing to summarize, or summarization failed/aborted). -
noChangeDiagnostic(
String path) → String -
The patch parsed and applied cleanly but produced no change — the
+literalbody rows matched the file content at the targeted lines byte-for-byte (omp'snoChangeDiagnostic). -
normalizeArchiveLookupPath(
String? rawPath) → String? -
Normalizes a member lookup path:
/separators,.segments dropped. Returns null when the path escapes via..(omp'snormalizeArchiveLookupPath). -
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, matchingtask.maxConcurrency = 0's "Unlimited" semantics in omp's settings UI. -
normalizeLocationResult(
Object? result) → List< LspLocation> -
Normalizes a
textDocument/definition-family result: acceptsnull,Location,Location[],LocationLink, orLocationLink[]and returns a flat location list (omp'snormalizeLocationResult, reduced). -
normalizeToLF(
String text) → String - Normalizes every line ending to LF.
-
parseArchivePathCandidates(
String filePath) → List< ArchivePathCandidate> -
Splits an
archive.ext:inner/pathreference 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'sparseArchivePathCandidates). -
parseCliArgs(
List< String> args) → CliArgsResult -
Parses the
fahargument 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 ininput.dart(omp'sparsePatch). -
parseLineRangeChunk(
String sel) → LineRange? -
Parses a single
N,N-M,N-,N+K, or..-aliased (N..M,N..) chunk. Returns null whenselis 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. -
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). -
parseRoleChains(
Object? node, {String? source}) → Map< String, List< ModelRef> > -
Parses a
roles:map (role name → chain). Shared by the top-level section and PathRoleOverride;sourcelabels 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?queryreference into every plausible candidate, longest database prefix first (omp'sparseSqlitePathCandidates). 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. -
pathPatternMatches(
String pattern, String cwd, {String? homeDir}) → bool -
Whether
patternmatches the working directorycwd. -
prepareBranchEntries(
List< SessionRecord> entries, {int tokenBudget = 0}) → BranchPreparation -
Prepare entries for summarization within
tokenBudget(omp'sprepareBranchEntries): 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: 0means no limit. -
promptToolInstructions(
List< Tool> tools, {bool slim = false}) → String -
Renders the tool-instruction section promptToolStreamFunction appends
to the system prompt when
toolsis non-empty (theprompts/tools/tool_calling.mdtemplate with the numbered name/description/schema list). -
promptToolStreamFunction(
StreamFunction inner, {PromptToolOptions? options}) → StreamFunction -
Wraps
innerwith prompt-based tool calling. -
providerStreamFunction(
String kind, String apiKey) → StreamFunction -
Builds the StreamFunction for a provider adapter
kind(openai-completions,anthropic,google) with a staticapiKey. Throws ConfigException for unknown kinds. -
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
readtool: reads a text file or image with optionaloffset(1-indexed) andlimit, 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: -
renderSqliteRow(
Map< String, Object?> row) → String -
Renders a single row as
column: valuelines (omp'srenderRow). -
renderSqliteSchema(
String createSql, SqliteRows sampleRows) → String -
Renders a table schema plus sample rows (omp's
renderSchema). -
renderSqliteTable(
List< String> columns, List<Map< rows, {required int totalCount, required int offset, required int limit, required String table}) → StringString, Object?> > -
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). -
repr(
String text) → String -
Renders
textwith JSON-style quoting for diagnostics. -
resolveAgentUrl(
String url, AgentOutputStore store) → AgentUrlResolution -
Resolves an
agent://URL againststore(port of omp'sAgentProtocolHandler.resolve, reduced to the dot-path query subset). -
resolveSqliteRowLookup(
SqliteDatabase db, String table) → SqliteRowLookup -
Resolves the row-lookup strategy for
table(omp'sresolveTableRowLookup). -
resolveWebSearchChain(
List< String> providerIds, {required Map<String, String> secrets}) → List<WebSearchProvider> -
Resolves
providerIds(autoexpands to the default chain) into an ordered, deduplicated list of available providers (omp'sresolveProviderCandidates, reduced). Keyed providers without a key insecretsare 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
emitand 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 toemit. -
scanHtml(
String html) → Iterable< Object> -
Scans
htmlsequentially, yielding HtmlTag and HtmlText tokens in document order. Comments, doctypes, and processing instructions are skipped. Malformed input degrades to text instead of throwing. -
serializeConversation(
List< Message> messages) → String - Serialize messages to plain text for summarization prompts.
-
shellTool(
ExecutionEnv env) → AgentTool -
Creates the
bashtool: 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.
-
skipHtmlSubtree(
List< Object> tokens, int openIndex) → int -
Returns the index of the token closing the subtree rooted at the open tag
openIndexwithintokens(depth-counted on the same tag name). ReturnsopenIndexitself for self-closing tags, or the last token index when the close tag is missing (malformed input). -
sortAndValidateTextEdits(
List< LspTextEdit> edits) → List<LspTextEdit> -
Sorts
editsbottom-to-top for in-place application and rejects overlaps (omp'ssortAndValidateTextEdits). -
splitPathAndSel(
String rawPath) → SplitReadPath -
Splits a trailing
:seloffrawPathwhen the tail matches the selector grammar (a range list orraw, 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 andreadrefuses to open the real file. The literal wins wheneverenvreports the raw path exists — and also when the existence check itself fails — so an unreachable literal is never silently reinterpreted aspath + selector. -
streamAnthropic(
Model model, Context context, [AnthropicOptions? options, Client? client]) → AssistantMessageEventStream - Streams an assistant message from an Anthropic messages endpoint.
-
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). -
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). -
substituteArgs(
String content, List< String> args) → String - Substitutes positional arguments into a template body.
-
taskItemAgentName(
TaskItem item) → String -
The agent type
itemruns as: itsagent, or defaultTaskAgentName when omitted (omp's spawn-policy default). -
taskItemNameBase(
TaskItem item) → String -
The requested id base for
item(omp'ssanitizeAgentId): itsnamescrubbed toA-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
tasktool bound toconfig(omp'sTaskTool). -
transcribeAudioTool(
ExecutionEnv env, TranscribeAudioConfig config) → AgentTool -
Creates the
transcribe_audiotool. -
truncateSqliteWidth(
String value, int width) → String -
Truncates
valuetowidthcharacters, ending with an ellipsis when cut (omp'struncateToWidth, 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'suriToFile). -
validateJsonValue(
{required Object? value, required Map< String, dynamic> schema}) → List<String> -
Validates an arbitrary
valueagainst the same JSON-schema subset validateToolArguments enforces and returns every violation as apath.with.dots: messagestring ((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
argumentsagainst the tool's JSON-schemaschemaand returns a new map with coerced values and injected defaults. Undeclared keys pass through unchanged. The input map is never mutated. -
webFetchTool(
{required WebSearchConfig config}) → AgentTool -
Creates the
web_fetchtool, sharing WebSearchConfig's HTTP plumbing. -
webSearchTool(
{required WebSearchConfig config}) → AgentTool -
Creates the
web_searchtool. -
writeFileTool(
ExecutionEnv env) → AgentTool -
Creates the
writetool: creates or overwrites a file, creating parent directories as needed. -
xxHash32(
Uint8List data, [int seed = 0]) → int -
Computes xxHash32 of
datawithseed(both treated as unsigned 32-bit).
Typedefs
-
AfterToolCallHook
= FutureOr<
AfterToolCallResult?> Function(AfterToolCallContext context, CancelToken? cancelToken) -
Called after a tool finishes executing, before
tool_execution_endand the tool-result message events are emitted (pi'safterToolCall). -
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.subscribecallback). -
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< Function(List<AskAnswer> ?>AskQuestion> questions) -
Answers
questionson behalf of the user — the host UI surface (CLI menu, Flutter sheet). Returns one AskAnswer per question, ornullwhen 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.
-
CollectBranchEntries
= ({String? commonAncestorId, List<
SessionRecord> entries}) - Entries collected for a branch summary plus the common ancestor between the old and the new position.
-
LspTransportFactory
= Future<
LspTransport> Function(LspServerConfig config, String cwd) -
Spawns a language server for
configrooted atcwd. -
PrepareNextTurnHook
= FutureOr<
AgentLoopTurnUpdate?> Function(NextTurnContext context) -
Called after
turn_endand before the loop decides whether another provider request should start (pi'sprepareNextTurn). -
QueuedMessagesSource
= FutureOr<
List< Function()Message> > - Returns queued messages to inject into the conversation.
- RedactionHooks = ({AfterToolCallHook afterToolCall, TransformContextHook transformContext})
- Agent hooks that mask registered secrets, see redactionHooks.
-
SlashCommand
= Future<
void> Function(List<String> args) - A slash-command handler registered by a plugin.
- StreamFunction = AssistantMessageEventStream Function(Model model, Context context, {CancelToken? cancelToken})
- Provider adapter contract consumed by the agent loop.
-
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< Function(List<Message> >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
- 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.
-
Thrown by an LspTransportFactory when the server process cannot be
started (e.g. the command is not on
PATH). Thelsptool converts this into a clean error result — never a crash. - 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).