Skip to main content

Crate swink_agent

Crate swink_agent 

Source
Expand description

§Encapsulation regression

The credential module is private; consumers must use the canonical re-exports at the crate root rather than reaching into submodule paths.

use swink_agent::credential::ResolvedCredential;

Modules§

atomic_fs
Atomic file-write helpers shared across workspace crates.
prelude
Convenience re-exports for common Swink-Agent types.
stream_assembly
Narrow public module for shared stream-assembly helpers.

Structs§

Agent
Stateful wrapper over the agent loop.
AgentConfig
A fully serializable snapshot of agent configuration.
AgentContext
The immutable snapshot passed into each loop turn.
AgentHandle
A handle to a spawned agent task.
AgentId
Unique identifier assigned to every crate::Agent on construction.
AgentLoopConfig
Configuration for the agent loop.
AgentMailbox
A per-agent inbox for receiving messages.
AgentOptions
Configuration options for constructing an Agent.
AgentOrchestrator
Manages a set of named agents with parent/child hierarchies and supervision.
AgentRegistry
Thread-safe registry that maps string names to AgentRef handles.
AgentRequest
A message sent to a running agent via its request channel.
AgentResult
The value returned by non-streaming invocations.
AgentState
Observable state of the agent.
AgentToolResult
The result of a tool execution.
AssistantMessage
A message from the assistant (LLM response).
AuthConfig
Per-tool declaration of authentication requirements.
BashTool
Built-in tool that executes a shell command.
CacheConfig
Configuration for provider-side context caching.
CacheConfigData
Serializable representation of CacheConfig.
CacheState
Tracks the cache lifecycle across turns.
CatalogPreset
ChannelMessageProvider
A MessageProvider backed by tokio unbounded mpsc channels.
Checkpoint
A serializable snapshot of agent conversation state.
CompactionReport
Result of a context transformation pass.
ComposedMessageProvider
A MessageProvider that combines two providers, draining both on each poll.
ContextVersion
A snapshot of messages captured at a point in time.
ContextVersionMeta
Metadata for a stored context version (returned by list_versions).
CoreDisplayMessage
A message converted to a frontend-friendly format.
Cost
Per-category and total cost breakdown (floating-point currency values).
CustomMessageRegistry
Registry for deserializing CustomMessage types from JSON.
DefaultRetryStrategy
Exponential back-off retry strategy with optional jitter.
DefaultSupervisor
A supervisor that restarts on retryable errors and stops otherwise.
DefaultTokenCounter
Default token counter using the chars / 4 heuristic.
DowncastError
Error returned when downcasting an AgentMessage to a concrete custom message type fails.
EditFileTool
Built-in tool for making precise, surgical edits to a file.
Emission
A structured event emitted by an agent, tool, or callback.
FnTool
A tool built entirely from closures and configuration, implementing AgentTool without requiring a custom struct.
InMemoryVersionStore
In-memory implementation of ContextVersionStore.
LoopCheckpoint
A serializable snapshot of the agent loop’s in-flight state.
MessageSender
A clonable handle for pushing messages into a ChannelMessageProvider.
ModelCapabilities
Per-model capability flags and limits.
ModelCatalog
ModelConnection
ModelConnections
ModelConnectionsBuilder
Incrementally builds a ModelConnections value.
ModelFallback
An ordered sequence of fallback models to attempt when the primary model (and its retries) are exhausted.
ModelSpec
Identifies the target model for a request.
NoopTool
A placeholder tool that returns an error message when invoked.
OrchestratedHandle
Handle to a spawned orchestrated agent.
PolicyContext
Shared read-only context available to every policy evaluation.
PresetCatalog
ProviderCatalog
ReadFileTool
Built-in tool that reads a file and returns its contents.
RetryConfig
Serializable representation of DefaultRetryStrategy parameters.
SerializedCustomMessage
A lightweight CustomMessage stand-in that holds pre-serialized data.
SerializedMessages
The result of splitting an AgentMessage slice into LLM and custom vectors, plus ordering metadata.
SessionState
Key-value store with change tracking for session-attached structured data.
SlidingWindowTransformer
Built-in sliding window context transformer with compaction reporting.
StateDelta
Record of mutations since the last flush.
StreamMiddleware
Intercepts the output stream from a wrapped StreamFn.
StreamOptions
Per-call configuration passed through to the LLM provider.
StreamOptionsConfig
Serializable representation of StreamOptions.
SubAgent
A tool that wraps an agent, enabling multi-agent composition.
SubscriptionId
Unique identifier for an event subscription.
ThinkingBudgets
Optional per-level token budget overrides for providers that support token-based reasoning control.
ToolApprovalRequest
Information about a tool call pending approval.
ToolCallSummary
Lightweight view of a pending tool call, exposed to policy callbacks.
ToolDispatchContext
Combined context for PreDispatch policies.
ToolExecMetrics
Timing and outcome data for a single tool execution within a turn.
ToolFilter
Filters tools at registration time using pattern-based allow/reject lists.
ToolMetadata
Optional organizational metadata for an AgentTool.
ToolMiddleware
Intercepts execute() on a wrapped AgentTool.
ToolResultMessage
The result of a tool execution, sent back to the LLM.
ToolSchema
Common tool metadata extracted from AgentTool instances.
TransferChain
Safety mechanism tracking the ordered sequence of agents in a transfer chain.
TransferSignal
Data structure carrying all information needed for a target agent to continue a conversation after a handoff.
TransferToAgentTool
Tool that signals the agent loop to transfer conversation to another agent.
TurnMetrics
Metrics snapshot emitted at the end of each agent loop turn.
TurnPolicyContext
Per-turn context for PostTurn policies.
TurnSnapshot
A point-in-time snapshot of agent state at a turn boundary.
Usage
Token usage counters for an LLM response.
UserMessage
A message from the user.
VersioningTransformer
A context transformer that captures dropped messages as versioned snapshots.
WriteFileTool
Built-in tool that writes content to a file, creating parent directories as needed.

Enums§

AgentError
The top-level error type for the swink agent.
AgentEvent
Fine-grained lifecycle event emitted by the agent loop.
AgentMessage
The top-level message type that wraps either an LLM message or a custom application-defined message.
AgentStatus
The lifecycle status of a spawned agent task.
ApiVersion
ApprovalMode
Controls whether the approval gate is active.
ApprovalModeConfig
Serializable mirror of ApprovalMode.
AssistantMessageDelta
A typed incremental update during streaming, used in MessageUpdate events.
AssistantMessageEvent
An incremental event emitted by a StreamFn implementation.
AuthMode
AuthScheme
How a resolved credential is attached to the outbound request.
CacheHint
Hint attached to messages indicating the desired cache action.
CacheStrategy
Provider-agnostic caching configuration.
ContentBlock
The atomic unit of all message content.
Credential
A secret value with type information for tool authentication.
CredentialError
Errors from credential resolution.
CredentialType
Credential type discriminant for mismatch checking (FR-018).
DisplayRole
Role of a message for display styling.
FollowUpMode
Controls how follow-up messages are drained from the queue.
FollowUpModeConfig
Serializable mirror of FollowUpMode.
ImageSource
Source for image data.
LlmMessage
A discriminated union of the three LLM message roles.
MessageSlot
Tracks the original position of each message in the sequence.
PolicyVerdict
Outcome of a policy evaluation for PreTurn, PostTurn, and PostLoop slots.
PreDispatchVerdict
Outcome of a PreDispatch policy evaluation.
PresetCapability
PresetStatus
ProviderKind
ResolvedCredential
Minimal secret value delivered to a tool after credential resolution.
SteeringMode
Controls how steering messages are drained from the queue.
SteeringModeConfig
Serializable mirror of SteeringMode.
StopReason
Indicates why assistant generation ended.
StreamErrorKind
Structured classification of stream errors.
StreamTransport
Transport protocol for streaming responses.
SupervisorAction
What the supervisor decides after an agent error.
ThinkingLevel
Reasoning depth for models that support configurable thinking.
ToolApproval
Result of the approval gate for a tool call.
ToolExecutionPolicy
Controls how tool calls within a single turn are dispatched.
ToolPattern
A pattern for matching tool names.
TransferError
Error type for transfer chain safety violations.
TurnEndReason
Why a turn ended.

Constants§

DEFAULT_PLAN_MODE_ADDENDUM
Fallback addendum appended in plan mode when no custom addendum is set.

Traits§

AgentTool
A tool that can be invoked by the agent loop.
AsyncContextTransformer
Async context transformer for operations that require I/O (summary fetching, RAG retrieval, database lookups) before transforming the message context.
CheckpointStore
Async trait for persisting and loading agent checkpoints.
ContextSummarizer
Pre-computed summarization of dropped context messages.
ContextTransformer
ContextVersionStore
Pluggable storage for context version snapshots.
CredentialResolver
Orchestrator for credential resolution — checks validity, triggers refresh, deduplicates concurrent requests.
CredentialStore
Pluggable credential storage abstraction.
CustomMessage
Trait for application-defined custom message types.
IntoDisplayMessages
Convert message types into display-ready representations.
IntoTool
Convenience trait to convert a tool implementation into Arc<dyn AgentTool>.
JsonSchema
A type which can be described as a JSON Schema document.
MessageConverter
Callbacks for provider-specific message conversion.
MessageProvider
Provides steering and follow-up messages to the agent loop.
MetricsCollector
Async observer that receives structured metrics at the end of each turn.
PostLoopPolicy
Slot 4: Evaluated after the inner loop exits, before follow-up polling.
PostTurnPolicy
Slot 3: Evaluated after each completed turn.
PreDispatchPolicy
Slot 2: Evaluated per tool call, before approval and execution.
PreTurnPolicy
Slot 1: Evaluated before each LLM call.
RetryStrategy
Determines whether a failed model call should be retried and, if so, how long to wait before the next attempt.
StreamFn
The pluggable boundary between the harness and LLM providers.
SupervisorPolicy
Policy that determines how to handle agent failures.
TokenCounter
Pluggable token counting strategy.
ToolExecutionStrategy
Fully custom tool execution strategy.
ToolParameters
Trait for types that can produce a JSON Schema describing their fields.

Functions§

accumulate_message
Reconstruct a finalized AssistantMessage from a collected list of stream events.
agent_loop
Start a new agent loop with prompt messages.
agent_loop_continue
Resume an agent loop from existing messages.
builtin_tools
Returns all built-in tools (BashTool, ReadFileTool, WriteFileTool) wrapped in Arc, ready to pass to an Agent.
calculate_cost
Compute monetary cost from token usage using catalog pricing data.
clone_messages_for_send
Snapshot a slice of AgentMessage into fully Send + Clone-safe values.
convert_messages
Generic message conversion that iterates AgentMessage values, skips non-LLM variants, and delegates to the MessageConverter implementation for format-specific construction.
default_convert
Default message converter: pass LLM messages through, drop custom messages.
deserialize_custom_message
Deserialize a CustomMessage from a JSON envelope produced by serialize_custom_message.
estimate_tokens
Estimate token count using chars / 4 for LLM messages, 100 flat for custom.
extract_tool_schemas
Extract tool metadata from a slice of AgentTool trait objects.
from_fns
Create a MessageProvider from two closures.
is_context_overflow
Estimate whether the context exceeds the model’s maximum context window.
message_channel
Create a channel-backed MessageProvider and its paired MessageSender.
model_catalog
now_timestamp
Get the current Unix timestamp in seconds.
prefix_chars
Return the longest prefix containing at most max_chars Unicode scalar values.
redact_sensitive_values
Scan a serde_json::Value for common secret patterns and replace matching string values with "[REDACTED]".
restore_messages
Reconstruct an interleaved Vec<AgentMessage> from separate LLM and custom vectors, using MessageSlot ordering metadata.
restore_single_custom
Restore a single custom-message envelope via a registry.
run_policies
Evaluate PreTurn, PostTurn, or PostLoop policies in order.
run_post_loop_policies
Evaluate PostLoop policies in order.
run_post_turn_policies
Evaluate PostTurn policies in order.
run_pre_dispatch_policies
Evaluate PreDispatch policies for a single tool call.
sanitize_incomplete_tool_calls
Scrub incomplete ToolCall blocks in an assistant message so it can safely be replayed to a provider.
schema_for
Generate a JSON Schema as a serde_json::Value from a type implementing JsonSchema.
selective_approve
Wraps an approval callback so that only tools with requires_approval == true go through the inner callback. All other tools are auto-approved.
send_to
Send a message to a named agent via its steering queue.
serialize_custom_message
Serialize a CustomMessage into a portable JSON envelope.
serialize_messages
Split a slice of AgentMessage into separate LLM and custom vectors with ordering metadata.
sliding_windowDeprecated
Create a sliding-window context compaction function.
suffix_chars
Return the longest suffix containing at most max_chars Unicode scalar values.
unknown_tool_result
Build an error result for an unknown tool name.
validate_schema
Validate that a JSON value is a valid JSON Schema document.
validate_tool_arguments
Validate tool call arguments against a JSON Schema.
validation_error_result
Build an error result listing all validation errors.

Type Aliases§

AgentRef
A shareable, async-safe handle to an Agent.
AsyncTransformFuture
A boxed future returned by an AsyncContextTransformer.
CheckpointFuture
A boxed future returned by CheckpointStore methods.
CredentialFuture
Boxed async result used by credential traits.
EventForwarderFn
A function that receives forwarded agent events.
MetricsFuture
OnRawPayload
Callback for observing raw SSE data lines before event parsing.
PriorityFn
Callback that assigns an integer priority to a tool call.
ToolExecutionStrategyFuture
A boxed future returned by a ToolExecutionStrategy.
ToolFuture
A boxed future returned by AgentTool execution.

Derive Macros§

JsonSchema
Derive macro for JsonSchema trait.