oi-kit-agent
oi-kit's agent loop, unrolled into a state machine you assemble yourself.
Instead of a fixed "call the model, run the tools, repeat" loop, an agent here is an ordered list of steps. Each step gets a chance to look at the conversation and either decline or produce effects. The machine walks the list, applies the first step that applies, and starts over from the top — so the whole agent's behavior is a function of the persisted conversation, not of in-memory loop state.
The pieces
Operation<S, E>— one step. Implementrunto act on the conversation, plus any ofinference_tools,prompt_parts, andmoim_partsto contribute to the model request. ReturnsOperationResult::NotApplicableto pass, orapplied(..)/yielded(..)to take the step. Helpers:not_applicable(),applied(),yielded(),yielded_with().Inference<S, E>— the step that reaches the provider. Before calling it, the machine collects tools and prompt parts from every operation in the list into anInferenceInput. It runs whenever the conversation ends on a user or tool message, even if other tool calls from the same reply still have no response. A pipeline that keeps calls open, for example while waiting for the user to approve one, needs an operation before inference that yields while any call is open.ToolOperation<S>— adapts caller-definedrmcptools into one operation. RegisterSyncTool<S>andAsyncTool<S>implementations with the typed builder methods, or implementToolProvider<S>for tools discovered dynamically per session. Dynamic providers are queried before inference and again before execution, so their tool names and handlers must remain stable between those boundaries. Their schemas are sent to inference and matching calls are dispatched against the current session.StateMachine<'a, S, E>— holdsVec<Step<..>>and aCancellationToken.step()runs one pass and returns aStepResultwhoseapplied_stepnames the step that applied (Noneif none did) and whosestatussays whether the run isContinuing,Yieldedto the client, orCancelled;apply()writes effects back;run()loops whilestatusisContinuing.ConversationEffect— the default effect type:AppendMessage,ReplaceConversation,PatchToolRequestMeta,SetMessageVisibility. Bring your own by implementingMachineEffect.Emitter— streamsAgentEvents (Message,Usage,MessageUsage,McpNotification,HistoryReplaced) to the client while a step runs, and carries the cancellation token.SessionLoader/EffectHandler/MachineSession— the traits your runtime implements so the machine can load a session by id and persist effects. The machine reloads the session between passes; it never caches it.
Tool approval
Tool execution does not require approval. To add a policy, put
ToolApprovalOperation before the tool handlers and implement
ToolApproval<S>. Its check gets every new call from the model's reply at
once, so it can check them together, and returns one decision per call, in the
same order. Each decision is one of:
Allow— the call may run.Deny— the call doesn't run. The model getsreasonas the call's error result.Ask— the user is asked to confirm first. The confirmation request shows the tool and its arguments, pluspromptif you set one.- An error — the run ends with that error. The run also ends with an error if
checkreturns a different number of decisions than calls.
When the user chooses, on_confirmation gets the choice once, so approval can
remember "always allow" or "always deny". If the user declines, the call gets
the declined message as its error result; change that text with
with_declined_message. If the user allows, the call may run. Allowed calls
are recorded in a private message so the policy does not check them again.
Tool handlers do not read that record. An app without an approval policy can
omit ToolApprovalOperation entirely.
Good to know:
- The approval operation pauses the turn until all outstanding confirmations are answered, so tool handlers and inference do not run while it is waiting.
- Show the confirmation request to the user only after it is saved, so the user can't choose before it exists. The operation saves it but doesn't send it.
- When the user chooses, save
confirmation_response_message(call_id, permission). It is hidden, so it isn't mistaken for a new user message. - Calls with arguments that can't be read skip approval; the tool step responds to them with the error.
- A tool handler runs otherwise eligible calls that do not already have a response. A denial is an error tool response, so it needs no special handling in the executor.
ToolApprovalOperationtakes one approval. To run several, write one that calls the others.
Place UnhandledToolCallsOperation after all tool handlers and before inference
if your pipeline needs to answer unclaimed calls. It returns a parse error for
malformed calls and "Tool 'X' is not available." for other unanswered calls.
Reading the conversation
Because steps re-derive their decisions from history, the crate ships the
predicates they need: messages_since_kickoff, last_effective_role,
assistant_turn_count, ends_turn, and trailing_error. When a step must
remember that it already did something, it records that on the message itself via
Operation::set_message_meta / message_meta rather than in memory.
Error boundary
exit_on_error::ExitOnErrorOperation yields when the conversation ends in an
error. Its position divides operations that may inspect or recover from an error
from operations that should only run without one. Put error recovery before it;
operations after it will not see a trailing error. For example, put compaction
before the boundary if it should recover from context-length errors.
Compaction
compaction::CompactionOperation keeps the conversation inside the context
window. Give it a CompactionModel (a one-shot completion), a TokenEstimator
(sizes the context when the provider reports no usage), the context limit, and
the threshold fraction at which to compact. with_compact_command makes it
publish a compact command (alias summarize) through commands, which
SlashCommandOperation dispatches. Your effect type implements CompactionEffect; override
compact if replacing the conversation should update messages in place rather
than rewrite them.
By default compaction is in-band: once the threshold is crossed, the operation
hides the prompt the model has not answered yet, appends an agent-only request,
and the next inference writes the summary on the live prefix. The request
carries hide_response, so inference stores the reply without emitting it to
the user. On the following pass the operation harvests the reply into the
compacted layout: the originals leave the agent's context but stay visible to
the user, the summary and a continuation note become the agent's context, and
the hidden prompt is re-issued. When the reply is
unusable (a tool call, an empty reply, or a context-length error), it falls
back to a standalone summarization request, which is also how it recovers from
a context-length error during a turn (at most MAX_CONTEXT_ERROR_COMPACTIONS
per turn). CompactionMode::Standalone uses the separate request always.
Place it first among the operations: it must see the in-band reply before tool
execution or turn-end logic does, and the error boundary must come after it.
MachineSession::reported_context_tokens lets the host supply the provider's
reported context size; without it the estimator counts the conversation.
Turn limits
max_turns::MaxTurnsOperation::new(limit) limits autonomous turns using the persisted conversation. Place it after tool execution, pending approvals, and normal completion, before inference. It counts consecutive assistant-message blocks since the latest kickoff; provider retries and history transformations can affect how closely that approximates inference calls. A new user prompt resets the budget, and a zero limit yields immediately. A completed assistant answer is preserved even at the limit.
At exhaustion, the operation appends a user-visible ResourceExhausted error and yields. The operation also contributes a moim_parts budget reminder once half the limit is used. Hosts must render these parts in their request preparer; IdentityInferenceRequestPreparer does not include them.
Slash commands
Operations offer commands through Operation::commands. A command::Command
holds its name, aliases, description, input hint, host metadata and the action
that runs it, so listing a command and running it read the same object.
StateMachine::commands returns every command the steps offer, duplicates
included.
slash_command::SlashCommandOperation is one way to run them. On a fresh
kickoff that starts with /, it lowercases the name that follows, collects
commands from its operations and runs the first one whose name or alias matches,
so name commands in lowercase. Ordinary messages and
unknown commands pass through. with_resolver replaces the first-match rule.
Put it before the other operations so a command runs before they see the
kickoff.
Bang commands
bang_command::BangCommandOperation::new(tool_name, argument_name) turns a
user message starting with ! into a request for tool_name, with the text
after ! as argument_name. Put it before inference.
Cancellation
On Stop, the machine drops the running step's future, including inference
preparation. It then saves the interrupted step's finalize_cancellation
effects, responds to every tool request since kickoff that still has no response
with "Tool call was interrupted before completing", and finally calls
finalize_cancellation on the remaining operations in pipeline order. Every
operation's finalize_cancellation runs once, and the session is reloaded
after each save. Callers driving step and apply
themselves must call finalize on exit.
An operation implements finalize_cancellation only when it holds received
output across a later await, or owns work that must finish. Keep that output in
the operation, not in locals of the dropped future, and drain the same field on
normal completion. finalize_cancellation emits only what the client has not
seen yet.
InferenceRunner holds its streamed messages and usage; ToolOperation holds
its tool response message. Use one operation instance per active execution.
Emitter sends on an unbounded channel, so emitting never pauses and an
operation that only builds, emits, and returns holds nothing. Dropping a future
cannot undo external actions or stop blocking work that has already started.
Skills
skills provides argument substitution and loaded-skill formatting. On native
platforms, it also discovers skills from explicit, ordered roots. Configuration
paths, built-in skills, and tool registration remain host responsibilities;
these helpers do not automatically change the agent pipeline. Filesystem
discovery is not a secure file-open API.
Extension configuration and shared MCP types
On native targets, extension provides stdio/HTTP transport configuration,
environment filtering, and secret resolution through ExtensionConfigResolver.
Goose composes these transport configs with its own builtin/platform variants,
keeping the persisted application schema unchanged.
action_required_manager, subprocess, and tool_visibility provide shared MCP
support without application persistence, builtin factories, or container policy.
The extension manager itself still lives in Goose; the next extraction moves it
behind an application adapter without adding Goose-only config variants to oi-kit.
WebAssembly
The crate builds for wasm32-unknown-unknown and runs without a tokio runtime,
so it can be embedded in a JavaScript host. There, the clock and randomness come
from JavaScript. Some things differ from native:
- The traits you implement (
Provider,Operation,ToolProvider,SessionLoader,EffectHandler, and the rest) do not requireSendorSync, and neither doesMessageStream. So you can await JavaScript promises and hold host handles directly. Implement the traits with#[async_trait(?Send)]. The bounds areMaybeSendandMaybeSyncfromoi_kit_provider_types::maybe_send, which are the realSendandSyncnatively. SyncTools run inline instead of on a blocking thread, so cancellation cannot interrupt one that has started.ProviderRetrywaits between attempts on the host'ssetTimeoutinstead of tokio's timer, so retries work without a tokio runtime.compactionis not available:oi-kit-context-managementdoes not build on wasm32 yet.
The reference assembly of these pieces is goose::agents::state_machine in the
goose crate.