Extensibility

Hooks

Run your own code at fixed points in a turn. Hooks let a plugin read or transform what flows through the Assistant without forking the core loop.

A hook is a function that the Assistant calls at a known boundary in their lifecycle. The harness owns the loop, and your Assistant's code runs at named points along the way. Each hook lives in its own file under hooks/<name>.ts, and the filename is the hook name.

The Agent Loop

The diagram below maps what we call the Agent Loop. The nodes are lifecycle events: the points in time turns of a conversation passes through. The connecting hooks are the places your code can run as the turn moves from one event to the next.

The Agent LoopA turn flows from the user prompt through a context check, model call, and model response to the assistant reply, with tool results and a compaction branch looping back. When the context check finds the conversation does not fit within the context window, control branches to compaction; a context error on the model response also branches to compaction. The hooks user-prompt-submit, pre-model-call, post-compact, post-model-call, post-tool-use, and stop fire on the transitions.user-prompt-submitpost-tool-usecontext too largepre-model-callpost-compactpost-model-callContext Errortool_usestopcontinueUser promptContext checkModel callModel responseAssistant replyCompactionTool result
Hook (fires on this transition)Control flow
NodeWhat it means
User promptThe incoming user message that kicks off a turn. The user-prompt-submit hook fires as the prompt enters the loop.
Context checkDecides whether the conversation fits within the model's context window. If it does not, control branches to Compaction before the model is called.
Model callThe inference request sent to the LLM. The pre-model-call hook fires immediately before the request is dispatched.
Model responseThe raw output returned by the model. The post-model-call hook fires here, and the loop branches based on what the model returned: a tool call, a continuation, a stop, or a context error.
Assistant replyThe final message delivered to the user. The stop hook fires just before the reply is sent, marking the end of the turn.
CompactionSummarizes or truncates older conversation history so the context fits within the model's window. The post-compact hook fires after compaction, and control returns to the Model call node.
Tool resultThe output of a tool execution. The post-tool-use hook fires here, and the result loops back to the merge junction for another model call.

The loop can iterate several times within a single user turn: every tool result returns to a fresh model call, and a post-model-call hook can choose to continue rather than end the turn. Because of this, pre-model-call, post-model-call, and post-tool-use can each fire more than once per turn.

The Assistant Lifecycle

The Assistant can also hook into Lifecycle Events that sit outside the Agent Loop. The diagram below shows where these hooks sit and how they interplay with the Server that manages the Agent Loop.

The Assistant LifecycleA plugin wakes, runs while the Run Server is up, then sleeps. The init and shutdown hooks fire once each on those boundaries. The Run Server exchanges conversations with the Agent Loop, which persists to the Workspace.initshutdownConversationspersistenceWakeRun ServerSleepAgent LoopWorkspace
Hook (fires on this transition)

Hooks reference

These are the lifecycle hooks this guide covers. The full set of wired hook names lives in the HOOKS constant. Expand a hook to see its Context API contract.

initInitContext

When: Once, when the plugin is first registered (on boot or install).

Use it to: Validate config and open resources. Throwing aborts the plugin's load.

FieldTypeAccessDescription
configunknownRead-onlyParsed config for this plugin, read from <pluginDir>/config.json.
pluginStorageDirstringRead-onlyAbsolute path to <pluginDir>/data/, the plugin's writable data directory (created during bootstrap).
assistantVersionstringRead-onlyAssistant semver, for defensive runtime checks.
loggerPluginLoggerRead-onlyPino-compatible logger scoped to the plugin.
user-prompt-submitUserPromptSubmitContext

When: Once per user turn, after messages are assembled and before the agent loop runs.

Use it to: Read or rewrite the message list the model is about to see.

Example: advisor

FieldTypeAccessDescription
conversationIdstringRead-onlyConversation the prompt was submitted on.
userMessageIdstringRead-onlyPersisted id of the user message that triggered the turn.
requestIdstringRead-onlyStable id for the request driving this turn.
modelProfileKeystringRead-onlyEffective inference profile identity for the model this turn will use. Profileless configs receive the resolved model id.
isNonInteractivebooleanRead-onlyTrue when no human is present to answer clarifications (scheduled or headless runs).
promptstringRead-onlyResolved text of the user prompt, after slash-command expansion.
originalMessagesReadonlyArray<Message>Read-onlyThe user's original message list. Snapshot only, never mutate.
latestMessagesMessage[]MutableThe working list that flows into the agent loop. Mutate in place or replace via the return value.
loggerPluginLoggerRead-onlyLogger scoped to the current turn.
post-compactPostCompactContext

When: After the loop compacts a conversation mid-turn, before the turn resumes. It fires on a compaction event rather than a fixed turn boundary, so it branches off the loop rather than sitting on a turn edge.

Use it to: Re-apply context that compaction dropped (for example memory injections) onto the compacted history before the next model call.

Example: memory-v3-shadow

FieldTypeAccessDescription
historyMessage[]MutableThe compacted message history to re-inject onto. The loop resumes the turn from the settled value.
requestIdstringRead-onlyStable id of the request driving this turn. Forward it onto the injector so re-applied blocks are attributed to the originating request.
conversationIdstringRead-onlyConversation the turn being compacted is scoped to.
isNonInteractivebooleanRead-onlyTrue when no human is present to answer clarifications (scheduled, background, or headless runs).
modelProfileKeystringRead-onlyEffective inference profile identity for the model the compacted turn will keep using. Profileless configs receive the resolved model id.
injectionMode"full" | "minimal"Read-onlyVolume of runtime injection to re-apply. 'full' restores the complete context, 'minimal' is the reduced volume overflow recovery selects. Defaults to 'full'.
pre-model-callPreModelCallContext

When: Immediately before every provider call within a turn, including tool-result follow-ups.

Use it to: Edit the outbound request (for example the system prompt), route the call to a chosen inference profile, or defer this turn's live output stream.

Example: advisor

FieldTypeAccessDescription
conversationIdstringRead-onlyConversation the call belongs to.
callSiteLLMCallSite | nullRead-onlyWhich call site this serves (mainAgent for the user-facing reply), or null when not tied to a known site. Self-gate on it before acting.
systemPromptstring | nullMutableThe system prompt about to be sent. Replace it to edit the request; guard the null case.
modelProfilestring | nullMutableThe inference profile this call routes to. Set it to a profile key to send the call there (the lever a model-router hook uses to pick a profile per call), or leave it as is for the default resolution. Seeded from the call's resolved override, and null when none applies. Gate on callSite first, and discover the routable keys with getModelProfiles().
deferAssistantOutputbooleanMutableSet true to suppress the live token stream so a post-model-call hook can emit the final text instead.
loggerPluginLoggerRead-onlyLogger scoped to the current turn.
post-model-callPostModelCallContext

When: At every model-call outcome: a finalized assistant message, or a provider rejection. Fires once per model call, before a finalized reply is persisted and streamed.

Use it to: Transform the reply's text blocks (leave tool_use intact), and own the continue decision. On a degenerate no-tool reply or a recoverable rejection, repair the history and set decision to continue to re-query the model.

Example: advisor

FieldTypeAccessDescription
conversationIdstringRead-onlyConversation the message belongs to.
callSiteLLMCallSite | nullRead-onlyWhich call site this message serves, or null when not tied to a known site. Self-gate before acting.
contentContentBlock[]MutableThe finalized message content; empty on a provider rejection. Transform text blocks and leave tool_use intact.
messagesMessage[]MutableFull conversation history. When continuing, leave this as the history the next iteration should send (append a follow-up turn, or replace it with a repaired one).
errorError | undefinedRead-onlyThe provider rejection that ended the call, on a rejection outcome; absent on a finalized reply. Hooks that only act on a real reply should guard on it and return early.
stopReasonstring | nullRead-onlyProvider-reported stop reason, or null when none was reported (also null on a rejection).
decisionPostModelCallDecisionMutableSeeded to 'stop'. Set it to 'continue' to re-query the model. Honored only at actionable outcomes (a no-tool reply or a provider rejection); the loop does not gate it on call site, so self-gate via callSite to avoid re-querying background or subagent calls.
loggerPluginLoggerRead-onlyLogger scoped to the current turn.
post-tool-usePostToolUseContext

When: After each tool returns, before the result rejoins the history sent to the provider.

Use it to: Transform the tool result, for example truncating oversized output to fit the context window.

Example: tool-result-truncate

FieldTypeAccessDescription
conversationIdstringRead-onlyConversation the tool ran on.
toolResponseToolResultContentMutableThe tool result block. Mutate its content in place or replace the block.
messagesReadonlyArray<Message>Read-onlyHistory up to and including the assistant turn that issued the call. The result is not in it yet.
additionalContextstring | nullMutableExtra model-only guidance appended after the tool result, for example retry coaching. Defaults to null; set a string to append guidance.
maxInputTokensnumberRead-onlyThe model's context-window size in tokens, for deriving a character budget.
loggerPluginLoggerRead-onlyLogger scoped to the current turn.
stopStopContext

When: Once per run, when the loop has committed to ending the turn. Fires on every terminal exit (a no-tool reply, max tokens, a yield to the user, exhausted overflow recovery, an abort, or an error) and on a checkpoint handoff.

Use it to: Run teardown: release per-turn resources or clear per-turn state, knowing nothing will re-enter the loop this run. It cannot continue the loop; the retry decision lives in post-model-call.

Example: max-tokens-continue

FieldTypeAccessDescription
conversationIdstringRead-onlyConversation the run belongs to.
messagesReadonlyArray<Message>Read-onlyFull conversation history at the terminal stop. Provided for inspection; mutating it has no effect, since the loop will not run again this turn.
exitReasonAgentLoopExitReasonRead-onlyWhich terminal state the turn reached (for example no_tool_calls, max_tokens_reached, error, checkpoint_handoff). A hook that should act only on a particular ending guards on it.
errorError | undefinedRead-onlyThe rejection that ended the turn, when it ended on one; absent on a clean stop.
loggerPluginLoggerRead-onlyLogger scoped to the current turn.
shutdownShutdownContext

When: Once, when the Assistant tears down the plugin (process exit, unload).

Use it to: Best-effort cleanup. Do not rely on it for critical writes; persist durably during normal operation instead.

FieldTypeAccessDescription
assistantVersionstringRead-onlyAssistant semver, for version-conditional cleanup.

When several plugins register hooks for the same boundary, they chain: each hook sees the previous hook's changes, and the merged result flows into the next. The order is deterministic.

Resolution order

When multiple plugins define the same hook, they execute in a fixed order so the chain is predictable:

  1. Built-in default plugins. Registered explicitly at startup. They always run first, so their context transformations are visible to every user plugin after them.
  2. User plugins. Ordered by the plugin's original install date, the installedAt timestamp from the install-meta.json sidecar written at install time. Plugins installed earlier run first. Plugins without a sidecar fall back to the directory creation time and sort after dated ones.

Within a single plugin, hooks for the same name are not duplicated: each plugin contributes at most one hook per boundary. The chain is linear: the output of hook N is the input of hook N+1, and the final output is what the Assistant acts on.

Anatomy of a hook

Every hook has the same shape: it receives a typed context and either mutates it in place and returns nothing, or returns a partialcontext. A returned partial is merged onto the threaded context — only the keys it includes are overwritten, every other field is preserved — so a hook can edit just the subset of fields it cares about without re-specifying the rest. The runtime threads the merged context to the next plugin and then to the Assistant.

type PluginHookFn<TCtx> = (ctx: TCtx) => Promise<Partial<TCtx> | void>;

Because an omitted key means “keep the existing value”, every context field is required and uses | null rather than ? or | undefined: a present key always carries a concrete value, so a field absent from a returned partial is never ambiguous with one a hook meant to clear.

One hook per file, default-exported. The filename becomes the hook key, so a pre-model-call hook is hooks/pre-model-call.ts:

// hooks/pre-model-call.ts
import type { PreModelCallContext } from "@vellumai/plugin-api";

export default async function preModelCall(
  ctx: PreModelCallContext,
): Promise<void> {
  // Only touch the user-facing reply, not background or subagent calls.
  if (ctx.callSite !== "mainAgent") {
    return;
  }
  ctx.systemPrompt = (ctx.systemPrompt ?? "") + "\nBe concise.";
}

Context types and constants come from @vellumai/plugin-api, the only supported contract.

When should my assistant write a Hook?

Reach for a hook when you need to read or transform what flows through a turn at a fixed point in the loop, regardless of what the model decides. Hooks are unconditional: rewrite the prompt before the model sees it, route a call to a different model, truncate an oversized tool result, re-inject context after compaction. If the behavior has to happen every time the loop reaches that boundary, it is a hook.

The Personal AI you were promised

GET STARTED