Build it up · Step 3 of 8

Control what it sees

Every model call is built from three things: the system prompt, the saved history, and whatever is true right now. Glove keeps the first two stable and delivers the third fresh before every call, so the agent always sees current state and the provider can still cache everything before it.

Surfacechat · voice · APIContextprompt · history · live stateModelany providerStatestore · memory · inboxToolsvalidated · gatedTeamsubagents · meshWorkspacefiles · code · webloopuntil the model answersprompttool callsresultshistorymessageanswerdisplay stack: show · ask · waita subagent is a toolacts on
One request through a Glove harness. The message is saved to state; context is assembled from state before every model call; the model asks for tools; results are saved; the cycle repeats until the model answers. Tools can render UI on the surface and wait for a reply, act on a workspace, or hand work to a subagent.

The shape of every call

what the model receives, every iterationtext
system prompt            stable: who the agent is, its rules
saved history            stable: the conversation (after the last compaction)
                         + "history" context, saved once per change
"request" context        frozen for this request, just before its message
the request's message
tool calls and results   this request so far, plus events that arrived mid-loop
─────────────────────────────────────────────────── cache boundary
"iteration" context      fresh: current state from your providers
                         (never saved, never rewrites the prompt)

The tempting mistake is to rebuild the system prompt on every turn with the current state pasted in. It works until it doesn't: the prompt cache misses on every call, old states linger in history when you echo them into messages, and between two tool calls in the same request the state the model sees is already stale. Runtime context fixes all three.

Live state: context providers

release.tstypescript
// Called before every model iteration, including between tool steps.
const stop = agent.addContextProvider(async () => {
  const release = await releases.current(); // your data
  if (!release) return null;                 // nothing to add this time
  return [
    `Release in progress: ${release.version} (${release.status}).`,
    `Merged since last tag: ${release.changes.length} pull requests.`,
    `Blocking: ${release.blockers.join(", ") || "nothing"}.`,
  ].join("\n");
});

// Later, when the release ships:
stop();

A provider returns a string, content parts (an image of a dashboard, say) or null. The text arrives as a transient user-role message at the tail. Subscribers get a runtime_context event with what was sent (the text exactly, media as a placeholder), so you can trace it. glove-memory's pinned context, forms and goals all use this same seam; so does mountBrowser to show the model its latest screenshot.

When it arrives: delivery

A provider's delivery decides when it is read and whether it stays:

delivery.tstypescript
// Default: re-read before every model call, tool steps included. For state a
// tool can change mid-request — a browser screenshot, a build that is running.
agent.addContextProvider(renderBuild);

// Read once per request and frozen just before the request's message. The input
// is identical on every tool step, so each step reuses the cache.
agent.addContextProvider(renderAccount, { delivery: "request" });

// Saved to history before the request's message, only when it changed. It ages
// into the background like any message; the model reasons over it without a
// tool call. Saved again after compaction hides it. Text only.
agent.addContextProvider(renderPlan, { delivery: "history", key: "plan" });

A history provider's text is saved wrapped in <context key="plan">, which is how Glove finds its last value again with any store, after a restart too. When it returns nothing after having saved something, a status="cleared" marker is saved once. Goals, forms and pinned context take the same option: useGoalRunner(agent, adapter, { scope, delivery: "history" }).

Prompt caching follows: the Anthropic and Bedrock adapters put their conversation breakpoint on the last saved block, never on a transient one, plus one just before request-frozen context, because that prefix is what the next request starts with.

Things that happen on their own: events

Tool results and user messages have a place in the loop. A reply from another agent, a webhook or a calendar change arrives on its own schedule. Hand it to emitEvent:

events.tstypescript
await agent.emitEvent({
  id: delivery.id,                 // emitting the same id twice is a no-op
  source: "webhook:ci",
  kind: "build.finished",
  content: `Build ${build.id} is ${build.status}.`,
  whenIdle: "auto",                // "wake" | "defer" | "auto"
});

// From your client: the user is typing, or a voice session is live.
agent.notifyUserActivity();
  • While the loop runs, the event joins at the next tool-step boundary, saved once right after the tool results.
  • While idle, the policy decides. By default an event wakes the agent, starting a turn with the event as its message, unless the user has been active recently: then it waits and is saved just before their next message. A deferred event wakes the agent after deferTimeoutMs (60 s by default) if no message comes.

Events reach the model as escaped XML, <event id source kind received_at> inside an <events> wrapper that says they came from outside and are information, not instructions. Replace the policy, the formatter or the in-memory queue (for a durable one) through the events option on new Glove. Turns run one at a time, so a woken turn and a user's message never interleave. Subscribers get event_received, event_injected, event_dropped and event_wake_failed.

Work before each turn: turn preparers

Some state has to be brought up to date before the agent takes a turn, not just shown to it. Examples are resuming an interrupted goal transition, preparing a form's next step, or re-applying a configuration. Register that work with addTurnPreparer. Don't wrap processRequest for it: a realtime session never calls processRequest, so a wrapper would never run there.

prepare.tstypescript
const stop = agent.addTurnPreparer(async (signal) => {
  await approvals.syncPending(signal);   // throws to stop the turn before the model runs
});

await agent.processRequest("Where are we?");   // runs preparers first, then hooks and the model (event wakes too)
await agent.prepareTurn();                      // what a runtime without processRequest calls

Preparers run in registration order. A throw stops the turn. glove-memory's goals and forms register here, which is why they work unchanged on a realtime session. A runtime that drives the agent itself can also hand its activity to the agent's subscribers with agent.notifySubscribers(type, data), so UIs and modules listening on the agent see it as they would see a text turn. To take over the agent's turns for a while, such as for a call, it holds the turn queue with agent.holdTurns(). Requests and event wakes then wait, and emitted events queue for the holder (hold.takeEvents()) instead of waking the model. hold.historyContext() returns the "history" context a request would save.

Guidance on demand: skills

Long procedures don't belong in the system prompt. Give the agent a listing and let it read what it needs:

release.tstypescript
import { useReadSkill } from "glove-core";

useReadSkill(agent, [
  {
    name: "release-checklist",
    description: "The team's release procedure. Read before tagging anything.",
    content: "# Release checklist\n1. All CI green on main\n2. Changelog drafted ...",
    sections: {
      hotfix: "# Hotfix releases\nBranch from the last tag, cherry-pick, ...",
    },
  },
]);

The agent gets one glove_read_skill tool whose description lists the skills; reading one returns its content, or a named section. Users can also type /release-checklist to load it into the next turn. Keep skills as files with loadContentSkillsFromFs from glove-core/content-skills-fs, the same shape as a coding agent's SKILL.md folders.

For commands that change the agent rather than add text, use hooks. glove.defineHook("compact", …) runs when a user types /compact, with full control: force compaction, swap the model, or answer without calling the model at all. See hooks, skills and subagents.

A plan the agent keeps: the task list

If the store implements tasks (MemoryStore does), every agent gets glove_update_tasks. The model writes its plan as tasks with a status and updates them as it works; your UI reads store.getTasks() to show progress. There is nothing to wire up.

Long sessions: compaction and summaries

  • Compaction summarises the conversation when it nears compaction_context_limit, using your compaction_instructions. The model continues from the summary; the store still has every message, so your UI shows the whole thread. Pending inbox items are carried into the summary, and tasks live in the store, so neither is lost.
  • Tool result summaries: turn on enableToolResultSummary, give the tool generateToolSummary, and return generateSummaryArgs from its do(). A large result is then replaced by its summary in later requests.
  • Keep big data out entirely. A 5,000-row result belongs in a file or a REPL variable, not in context. That is step 5.

Already built for you

PrimitiveWhat you getInstead of building
Runtime context providersglove-coreLive state for the model without rewriting the system prompt: re-read before every model call (default), frozen once per request, or saved to history only when it changes.glove.addContextProvider(() => renderCurrentState(), { delivery? })rebuilding the system prompt every turn (and losing the prompt cache)
Spontaneous eventsglove-coreReplies, webhooks and app changes join a running loop at the next tool step, or wake or wait for an idle agent. Saved once, as escaped XML marked as outside information.await glove.emitEvent({ id, source, content, whenIdle? })pushing webhooks into processRequest as fake user messages
Compactionglove-coreLong sessions summarised automatically; the store keeps the full history for your UI.compaction_config: { compaction_instructions, compaction_context_limit }a summariser and history-trimming logic
Content skillsglove-coreA listing of guides the agent can read in full, by section, when it needs them.useReadSkill(glove, skills) · loadContentSkillsFromFs(dir)pasting every playbook into the system prompt
Hooks and slash skillsglove-core/commands that change agent state or inject context before the user's message.glove.defineHook("compact", handler) · glove.defineSkill({ name, handler })parsing slash commands in your request handler
Task listglove-coreA built-in plan the agent keeps up to date and your UI can show.store with getTasks/addTasks → glove_update_tasksa todo or planning tool
Pinned contextglove-memoryStanding facts every turn should see, editable by the agent, delivered as runtime context.useContext(glove, contextAdapter)a user-preferences block in the system prompt

Next

The agent sees the right things now, but forgets the team the moment the process restarts. In step 4 it gets a durable store, an inbox for answers that arrive later, and memory.

The whole path

  1. 01A loop and a toolLoop · Tools
  2. 02Show your workSurface
  3. 03Control what it seesContext
  4. 04Make it rememberState
  5. 05Give it a workspaceWorkspace
  6. 06Split the workTeam
  7. 07Make it a systemIdentity · Time · Arrival · Oversight · Access
  8. 08Put it in productionRun · Keep · Reach · Watch