glove-core

Complete API reference for the core runtime package. Contains the agent loop, tool execution engine, display manager, context management, model adapters, and all foundational types.

Glove

The top-level builder and runtime entry point. Use the builder pattern to register tools and subscribers, then call build() to produce a runnable agent.

typescript
import { Glove } from "glove-core";
import { z } from "zod";

const agent = new Glove({
  store,
  model,
  displayManager,
  systemPrompt: "You are a helpful assistant.",
  compaction_config: {
    compaction_instructions: "Summarize the conversation.",
    max_turns: 30,
  },
})
  .fold({
    name: "get_weather",
    description: "Get weather for a city.",
    inputSchema: z.object({ city: z.string() }),
    async do(input) {
      const res = await fetch(`https://api.weather.example/v1?city=${input.city}`);
      return res.json();
    },
  })
  .build();

const result = await agent.processRequest("What is the weather in Tokyo?");

Constructor

new Glove(config: GloveConfig)

GloveConfig

PropertyTypeDescription
storeStoreAdapterThe store adapter for conversation persistence. Required.
modelModelAdapterThe model adapter for language model communication. Required.
displayManagerDisplayManagerAdapterThe display manager adapter for UI slot management. Required.
systemPromptstringThe system prompt sent with every model request. Required.
maxRetries?numberMaximum number of retries for failed tool executions. Passed to the Executor.
compaction_configCompactionConfigConfiguration for automatic context window compaction. Required.

Methods

MethodReturnsDescription
fold<I>(args: GloveFoldArgs<I>)IGloveBuilderRegister a tool with the agent. Returns the builder for chaining.
addSubscriber(subscriber: SubscriberAdapter)IGloveBuilderAdd a subscriber that receives streaming events. Returns the builder for chaining.
build()IGloveRunnableFinalize configuration and return a runnable agent instance.
processRequest(request, signal?)Promise<ModelPromptResult | Message>Send a request string or ContentPart[] to the agent and receive the result. Available after build().
setModel(model: ModelAdapter)voidReplace the model adapter at runtime. Useful for model switching mid-session.

Properties

PropertyTypeDescription
displayManagerDisplayManagerAdapterRead-only access to the display manager instance.

GloveFoldArgs

PropertyTypeDescription
namestringUnique name for the tool.
descriptionstringDescription of what the tool does. The model reads this to decide when to invoke it.
inputSchemaz.ZodType<I>Zod schema defining the tool's input shape.
requiresPermission?booleanWhen true, checks the store for permission before execution. Defaults to false.
do(input: I, display: DisplayManagerAdapter) => Promise<unknown>The tool's implementation. Receives validated input and the display manager. Return value becomes the tool result.

IGloveRunnable

The interface returned by build(). Represents a fully configured, ready-to-run agent.

MemberTypeDescription
processRequest(request, signal?)(request: string | ContentPart[], signal?: AbortSignal) => Promise<ModelPromptResult | Message>Send a user request to the agent and get the response.
setModel(model)(model: ModelAdapter) => voidSwap the model adapter at runtime.
displayManagerDisplayManagerAdapterRead-only reference to the display manager.

DisplayManager

Manages the display stack: a ordered collection of UI slots that tools push and users resolve. Implements DisplayManagerAdapter.

typescript
import { DisplayManager } from "glove-core";

const dm = new DisplayManager();

dm.subscribe((stack) => {
  console.log("Display stack changed:", stack);
});

Methods

MethodReturnsDescription
registerRenderer<I,O>(renderer: Renderer<I,O>)voidRegister a named renderer with input/output schemas.
pushAndForget<I>(slot: { renderer?: string; input: I })Promise<string>Push a slot onto the stack without blocking. Returns the slot ID.
pushAndWait<I,O>(slot: { renderer?: string; input: I })Promise<O>Push a slot and block until resolved or rejected. Returns the resolved value.
subscribe(listener: ListenerFn)UnsubscribeFnSubscribe to stack changes. The listener is called with the current stack whenever it changes. Returns an unsubscribe function.
notify()Promise<void>Manually trigger all subscribed listeners with the current stack state.
resolve<O>(slot_id: string, value: O)voidResolve a pushAndWait slot by ID, unblocking the waiting tool.
reject(slot_id: string, error: string)voidReject a pushAndWait slot by ID, causing the pushAndWait promise to throw.
removeSlot(id: string)voidRemove a slot from the stack by ID.
clearStack()Promise<void>Remove all slots from the display stack and notify listeners.

DisplayManagerAdapter Interface

The interface that DisplayManager implements. Any custom display manager must conform to this shape.

MemberTypeDescription
renderersMap<string, Renderer<unknown, unknown>>Registry of named renderers.
stackSlot<unknown>[]The current display stack, ordered from bottom to top.
listenersSet<ListenerFn>Set of subscribed listener functions.
resolverStoreMap<string, { resolve: ResolverFn<unknown>; reject: RejectFn }>Internal map of pending pushAndWait resolvers keyed by slot ID.
registerRenderer(renderer)voidRegister a renderer.
pushAndForget(slot)Promise<string>Push without blocking.
pushAndWait(slot)Promise<unknown>Push and block until resolved.
notify()Promise<void>Trigger listeners.
subscribe(listener)UnsubscribeFnSubscribe to changes.
resolve(slot_id, value)voidResolve a pending slot.
reject(slot_id, error)voidReject a pending slot.
removeSlot(id)voidRemove a slot by ID.
clearStack()Promise<void>Clear all slots.

Slot

Represents a single entry on the display stack. Pushed by tools, rendered by the UI layer.

PropertyTypeDescription
idstringUnique identifier for this slot instance.
rendererstringName of the renderer to use for displaying this slot.
inputIInput data passed to the renderer. Shape depends on the tool that created the slot.

Renderer

A named renderer definition registered with the display manager.

PropertyTypeDescription
namestringUnique name identifying this renderer.
inputSchemaz.ZodType<I>Zod schema for validating the input data.
outputSchema?z.ZodType<O>Optional Zod schema for validating the resolved output.

Context

Wraps a StoreAdapter and provides a simplified interface for reading and writing conversation data, messages, and tasks.

typescript
import { Context } from "glove-core";

const ctx = new Context(store);
const messages = await ctx.getMessages();
await ctx.appendMessages([{ sender: "user", text: "Hello" }]);

Constructor

new Context(store: StoreAdapter)

Methods

MethodReturnsDescription
getMessages()Promise<Message[]>Retrieve all messages from the store.
appendMessages(msgs: Message[])Promise<void>Append messages to the conversation history.
getTasks()Promise<Task[]>Retrieve all tasks from the store. Requires store to implement getTasks.
addTasks(tasks: Task[])Promise<void>Add tasks to the store. Requires store to implement addTasks.
updateTask(taskId: string, updates: Partial<Task>)Promise<void>Update a task by ID. Requires store to implement updateTask.

PromptMachine

Manages model prompting: sends messages and tool definitions to the model adapter and collects the response. Notifies subscribers of streaming events.

typescript
import { PromptMachine } from "glove-core";

const pm = new PromptMachine(model, ctx, "You are a helpful assistant.");
pm.addSubscriber(subscriber);
const result = await pm.run(messages, tools);

Constructor

new PromptMachine(model: ModelAdapter, ctx: Context, systemPrompt: string)

Methods

MethodReturnsDescription
addSubscriber(subscriber: SubscriberAdapter)voidAdd a subscriber to receive model events (text_delta, tool_use, model_response_complete).
run(messages: Message[], tools?: Tool<unknown>[], signal?: AbortSignal)Promise<ModelPromptResult>Prompt the model with messages and optional tools. Returns the model's response including token counts.

Executor

The tool execution engine. Maintains a registry of tools and a call stack. Executes tool calls from the model, validates inputs, handles errors, and returns results.

typescript
import { Executor } from "glove-core";

const executor = new Executor(3, store);
executor.registerTool(myTool);
executor.addSubscriber(subscriber);

executor.addToolCallToStack({ tool_name: "get_weather", input_args: { city: "Tokyo" } });
const results = await executor.executeToolStack();

Constructor

new Executor(MAX_RETRIES?: number, store?: StoreAdapter)

Properties

PropertyTypeDescription
toolsTool[]Array of registered tools.
MAX_RETRIESnumberMaximum retry attempts for failed tool calls.

Methods

MethodReturnsDescription
registerTool(tool: Tool<unknown>)voidAdd a tool to the executor's registry.
addSubscriber(subscriber: SubscriberAdapter)voidAdd a subscriber to receive tool execution events (tool_use, tool_use_result).
addToolCallToStack(call: ToolCall)voidQueue a tool call for execution.
executeToolStack(handOver?: HandOverFunction, signal?: AbortSignal)Promise<ToolResult[]>Execute all queued tool calls and return their results. Clears the stack after execution.

Observer

Monitors the context window size and triggers compaction when limits are exceeded. Tracks turn counts and token consumption.

typescript
import { Observer } from "glove-core";

const observer = new Observer(
  store,
  ctx,
  promptMachine,
  "Summarize the conversation so far.",
  30,   // max turns
  100000 // context compaction token limit
);

await observer.turnComplete();
await observer.tryCompaction();

Constructor

new Observer(store: StoreAdapter, ctx: Context, prompt: PromptMachine, compaction_instructions: string, max_turns?: number, context_compaction_limit?: number)

Properties

PropertyTypeDescription
MAX_TURNSnumberMaximum turns before compaction is considered.
CONTEXT_COMPACTION_LIMITnumberMaximum token count before compaction is triggered.

Methods

MethodReturnsDescription
setCompactionInstructions(instruction: string)voidUpdate the compaction instructions at runtime.
setMaxTurns(new_max: number)voidUpdate the maximum turn threshold.
setContextCompactionLimit(new_limit: number)voidUpdate the token consumption threshold.
turnComplete()Promise<void>Notify the observer that a turn has completed. Increments the turn counter in the store.
getCurrentTurns()Promise<number>Get the current turn count from the store.
addTokensConsumed(count: number)Promise<void>Add to the cumulative token count in the store.
getCurrentTokenConsumption()Promise<number>Get the current total token consumption from the store.
tryCompaction()Promise<void>Check if compaction is needed (turns or tokens exceeded) and perform it if so. Summarizes the conversation, resets the history, and replaces it with the summary.

Agent

Orchestrates the core agent loop: prompt the model, check for tool calls, execute tools, feed results back, repeat until the model responds with text only.

typescript
import { Agent } from "glove-core";

const agent = new Agent(store, executor, context, observer, promptMachine);
const result = await agent.ask(userMessage);

Constructor

new Agent(store: StoreAdapter, executor: Executor, context: Context, observer: Observer, prompt_machine: PromptMachine)

Methods

MethodReturnsDescription
ask(message: Message, handOver?: HandOverFunction, signal?: AbortSignal)Promise<ModelPromptResult>Run the full agent loop for a user message. Prompts the model, executes any tool calls, loops until the model produces a final text response. Returns the final result with token counts.

AbortError

Custom error class thrown when an agent request is aborted via an AbortSignal. Has name set to "AbortError".

typescript
import { AbortError } from "glove-core";

try {
  await agent.processRequest("Hello", signal);
} catch (err) {
  if (err instanceof AbortError) {
    console.log("Request was aborted.");
  }
}

Constructor

new AbortError(message?: string)

ModelAdapter

Interface for language model providers. Implement this to connect any LLM to Glove.

typescript
interface ModelAdapter {
  name: string;
  prompt(
    request: PromptRequest,
    notify: NotifySubscribersFunction,
    signal?: AbortSignal
  ): Promise<ModelPromptResult>;
  setSystemPrompt(systemPrompt: string): void;
}
MemberTypeDescription
namestringDisplay name of the model or provider.
prompt(request, notify, signal?)Promise<ModelPromptResult>Send messages and tools to the model. Call notify() to emit streaming events. Returns the complete response with token counts.
setSystemPrompt(systemPrompt)voidUpdate the system prompt used for subsequent requests.

PromptRequest

PropertyTypeDescription
messagesMessage[]The conversation messages to send to the model.
tools?Tool<unknown>[]Optional array of tools the model can invoke.

ModelPromptResult

PropertyTypeDescription
messagesMessage[]Response messages from the model (typically one agent message).
tokens_innumberInput tokens consumed by this prompt.
tokens_outnumberOutput tokens generated by this prompt.

StoreAdapter

Interface for conversation persistence. Implement this to store messages, token counts, tasks, and permissions in any backend.

typescript
interface StoreAdapter {
  identifier: string;
  getMessages(): Promise<Message[]>;
  appendMessages(msgs: Message[]): Promise<void>;
  getTokenCount(): Promise<number>;
  addTokens(count: number): Promise<void>;
  getTurnCount(): Promise<number>;
  incrementTurn(): Promise<void>;
  resetHistory(): Promise<void>;
  // Optional:
  getTasks?(): Promise<Task[]>;
  addTasks?(tasks: Task[]): Promise<void>;
  updateTask?(taskId: string, updates: Partial<Task>): Promise<void>;
  getPermission?(toolName: string): Promise<PermissionStatus>;
  setPermission?(toolName: string, status: PermissionStatus): Promise<void>;
}
MemberTypeDescription
identifierstringUnique identifier for the store instance (typically a session ID).
getMessages()Promise<Message[]>Retrieve all conversation messages.
appendMessages(msgs)Promise<void>Append messages to the history.
getTokenCount()Promise<number>Get the cumulative token count.
addTokens(count)Promise<void>Add to the cumulative token count.
getTurnCount()Promise<number>Get the current turn count.
incrementTurn()Promise<void>Increment the turn counter.
resetHistory()Promise<void>Clear the conversation history. Used during compaction.
getTasks?()Promise<Task[]>Retrieve all tasks. Optional. Enables the built-in task tool when present.
addTasks?(tasks)Promise<void>Add tasks. Optional.
updateTask?(taskId, updates)Promise<void>Update a task by ID. Optional.
getPermission?(toolName)Promise<PermissionStatus>Check permission status for a tool. Optional.
setPermission?(toolName, status)Promise<void>Set permission status for a tool. Optional.

SubscriberAdapter

Interface for observing agent events. Subscribers receive streaming text deltas, tool invocations, tool results, and model response completions.

typescript
interface SubscriberAdapter {
  record(event_type: string, data: any): Promise<void>;
}
MemberTypeDescription
record(event_type, data)Promise<void>Called whenever an event occurs. The event_type string identifies the event, and data carries the payload.

Subscriber Events

The following events are emitted by the system and received by subscribers via the record method.

EventData ShapeDescription
text_delta{ text: string }A chunk of streaming text from the model. Emitted as the model generates tokens.
tool_use{ id: string; name: string; input: unknown }A tool invocation has started. Contains the tool call ID, name, and input arguments.
tool_use_result{ tool_name: string; call_id?: string; result: ToolResult['result'] }A tool has finished executing. Contains the tool name, call ID, and execution result.
model_response{ text: string; tool_calls: ToolCall[] }A model turn is complete (non-streaming adapters).
model_response_complete{ text: string; tool_calls: ToolCall[] }A model turn is complete (streaming adapters). Contains the full response text and any tool calls.

Message

Represents a single message in the conversation history.

typescript
interface Message {
  sender: "user" | "agent";
  id?: string;
  text: string;
  content?: ContentPart[];
  tool_results?: ToolResult[];
  tool_calls?: ToolCall[];
}
PropertyTypeDescription
sender"user" | "agent"Who sent the message.
id?stringOptional unique identifier for the message.
textstringThe text content of the message.
content?ContentPart[]Optional multimodal content parts (images, documents, etc.).
tool_results?ToolResult[]Tool execution results attached to this message (agent messages responding to tool calls).
tool_calls?ToolCall[]Tool calls the model wants to execute (present in agent messages).

ContentPart

Represents a multimodal content element within a message.

typescript
interface ContentPart {
  type: "text" | "image" | "video" | "document";
  text?: string;
  source?: {
    type: string;
    media_type: string;
    data?: string;
    url?: string;
  };
}
PropertyTypeDescription
type"text" | "image" | "video" | "document"The type of content.
text?stringText content. Used when type is "text".
source?objectSource information for binary content. Contains type, media_type, and either data (base64) or url.
source.typestringSource type (e.g., "base64", "url").
source.media_typestringMIME type (e.g., "image/png", "application/pdf").
source.data?stringBase64-encoded content data.
source.url?stringURL pointing to the content.

Tool

The core tool interface used by the Executor. This is the runtime representation, distinct from ToolConfig in glove-react which adds the render property.

PropertyTypeDescription
namestringUnique tool name.
descriptionstringDescription for the model.
input_schemaz.ZodType<I>Zod schema for input validation and JSON Schema generation.
requiresPermission?booleanWhether the tool requires explicit permission before execution.
run(input: I, handOver?: HandOverFunction)Promise<unknown>Execute the tool with validated input. Optional handOver function for delegation patterns.

ToolCall

PropertyTypeDescription
tool_namestringName of the tool to invoke.
input_argsunknownArguments to pass to the tool (validated against the tool's input schema at runtime).
id?stringOptional call identifier for correlating calls with results.

ToolResult

PropertyTypeDescription
tool_namestringName of the tool that produced this result.
call_id?stringIdentifier correlating this result with its ToolCall.
result{ data: unknown; status: "error" | "success"; message?: string }The execution result. Contains the return data, a status indicator, and an optional message.

Task

Represents a tracked task in the agent's task list.

PropertyTypeDescription
idstringUnique identifier for the task.
contentstringDescription of the task in imperative form (e.g., "Fix the login bug").
activeFormstringPresent-continuous form shown during execution (e.g., "Fixing the login bug").
statusTaskStatusCurrent status: "pending", "in_progress", or "completed".

TaskStatus

typescript
type TaskStatus = "pending" | "in_progress" | "completed";

PermissionStatus

typescript
type PermissionStatus = "granted" | "denied" | "unset";

Function Types

TypeSignatureDescription
NotifySubscribersFunction(event_name: string, event_data: unknown) => Promise<void>Callback passed to ModelAdapter.prompt for emitting events to subscribers.
HandOverFunction(input: unknown) => Promise<unknown>Delegation callback passed to tool execution for handing control to another tool or system.
ListenerFn(stack: Slot<unknown>[]) => voidDisplay stack change listener. Called whenever the stack is modified.
UnsubscribeFn() => voidReturned by subscribe() to remove a listener.
ResolverFn<RI>(value: RI) => voidInternal resolver for pushAndWait promises.
RejectFn(error: string) => voidInternal rejector for pushAndWait promises.

CompactionConfig

PropertyTypeDescription
compaction_instructionsstringInstructions given to the model when summarizing the conversation. Required.
max_turns?numberMaximum turns before compaction is triggered.
compaction_context_limit?numberMaximum token count before compaction is triggered.

Built-in Task Tool

The framework provides a built-in tool for task management. It is automatically registered when the store supports tasks (implements getTasks, addTasks, updateTask).

typescript
import { createTaskTool } from "glove-core";

const taskTool = createTaskTool(context);
// taskTool.name === "glove_update_tasks"

Signature

typescript
function createTaskTool(context: Context): Tool<TaskToolInput>

TaskToolInput

PropertyTypeDescription
todosArray<{ content: string; activeForm: string; status: TaskStatus }>The complete task list. Each call replaces the entire list.

The tool name is glove_update_tasks. The model calls it to create, update, or complete tasks. Each invocation sends the full current task list, enabling additions, status changes, and removals in a single call.

Providers

The glove-core/models/providers module exports factory functions for creating model adapters from supported providers.

typescript
import { createAdapter, getAvailableProviders } from "glove-core/models/providers";

const model = createAdapter({
  provider: "anthropic",
  model: "claude-sonnet-4-20250514",
  maxTokens: 4096,
  stream: true,
});

const available = getAvailableProviders();
// [{ id: "openai", name: "OpenAI", ... }, ...]

createAdapter

typescript
function createAdapter(opts: CreateAdapterOptions): ModelAdapter

CreateAdapterOptions

PropertyTypeDescription
providerstringProvider ID. One of: openai, anthropic, openrouter, gemini, minimax, kimi, glm.
model?stringModel name to use. Defaults to the provider's default model.
apiKey?stringAPI key. Defaults to the provider's environment variable.
maxTokens?numberMaximum output tokens. Defaults to the provider's default.
stream?booleanWhether to use streaming. Defaults to false.

getAvailableProviders

Returns an array of provider configurations that have API keys available in the current environment.

typescript
function getAvailableProviders(): ProviderConfig[]

Supported Providers

IDEnv VariableDefault Model
openaiOPENAI_API_KEYgpt-4o
anthropicANTHROPIC_API_KEYclaude-sonnet-4-20250514
openrouterOPENROUTER_API_KEYopenai/gpt-4o
geminiGEMINI_API_KEYgemini-2.0-flash
minimaxMINIMAX_API_KEYMiniMax-Text-01
kimiMOONSHOT_API_KEYmoonshot-v1-auto
glmZHIPUAI_API_KEYglm-4-plus

Each provider has properties: id, name, baseURL, envVar, defaultModel, models[], format (either "openai" or "anthropic"), and defaultMaxTokens.