Cogitator Runtime
The main runtime that orchestrates agent execution, LLM routing, memory, and observability.
Overview
The Cogitator class is the central runtime for executing AI agents. It manages LLM backend connections, memory persistence, the global tool registry, approvals and observability. You create one instance and use it to run any number of agents.
import { Cogitator, Agent } from '@cogitator-ai/core';
const cog = new Cogitator({
llm: {
defaultProvider: 'openai',
providers: {
openai: { apiKey: process.env.OPENAI_API_KEY! },
},
},
});
const agent = new Agent({
name: 'assistant',
model: 'openai/gpt-6.1-sol',
instructions: 'You are a helpful assistant.',
});
const result = await cog.run(agent, { input: 'Hello!' });
console.log(result.output);
await cog.close();Constructor
const cog = new Cogitator(config?: CogitatorConfig);The config object is entirely optional. Without it, Cogitator talks to Ollama at localhost:11434, and every agent must name its own model. Nothing connects in the constructor: backends, memory and other services start on first use.
Configuration
interface CogitatorConfig {
llm?: {
defaultProvider?: LLMProvider; // for model strings without a known provider prefix (default 'ollama')
defaultModel?: string; // for agents that set no model
providers?: LLMProvidersConfig; // API keys and URLs per provider
backends?: Record<string, LLMBackend>; // your own backends, by name
plugins?: Record<string, unknown>; // config for registerLLMBackend() plugins
retry?: LLMRetryConfig | false; // default: 2 retries with backoff
promptCache?: PromptCacheConfig | false; // default: on
toolOutputSchemas?: 'native' | 'description'; // where a tool's outputSchema reaches the model
modelCircuitBreaker?: ModelCircuitBreakerConfig; // when a failing fallbackModels model is skipped
pricing?: Record<string, ModelPriceConfig>; // prices of your own, USD per million tokens, over the registry
};
limits?: {
maxConcurrentRuns?: number; // runs over the limit wait in order
defaultTimeout?: number; // ms, for agents and runs that set no timeout (default 120000)
maxTokensPerRun?: number; // checked before each model call
maxToolResultLength?: number; // characters of a tool result the model reads (default 100000)
};
memory?: MemoryConfig; // adapters, contextBuilder, extraction of memory items, compaction after a run, memory files and upkeep between runs
runCheckpoints?: RunCheckpointStore; // where paused runs wait
prompts?: PromptsConfig; // instruction versions and A/B tests
sandbox?: SandboxManagerConfig;
reflection?: ReflectionConfig;
guardrails?: Partial<GuardrailConfig>;
costRouting?: CostRoutingConfig;
security?: { promptInjection?: Partial<PromptInjectionConfig>; pii?: PiiConfig };
context?: ContextManagerConfig;
logging?: LoggingConfig; // level, format and destination of the process-wide logger
observers?: RunObserver[]; // watch every run (see Run Observers), flushed by close()
middleware?: RunMiddleware[]; // hooks around every run's model and tool calls (see Run Middleware)
deploy?: DeployConfig; // read by `cogitator deploy`
}The same object can come from cogitator.yml and the environment via loadConfig(). Retries and prompt caching are described in LLM Backends; security in Security.
Defaults and Limits
llm.defaultModelis the model of every agent that sets nomodelof its own.cog.resolveModel(agent)returns the model a run would use and throwsCONFIGURATION_ERRORwhen there is none.limits.maxConcurrentRunscaps how manyrun()calls execute at once on this instance. The rest wait in arrival order; their timeout and abort signal also cover the wait.limits.defaultTimeoutapplies to runs whose options and agent set notimeout. Without it, runs time out after 2 minutes. A run that times out throws aCogitatorErrorwith codeRUN_TIMEOUT(HTTP 504 in the server adapters).limits.maxTokensPerRunis checked before every model call: once the run has used that many input and output tokens, the next call fails withRUN_TOKEN_LIMIT_EXCEEDED. The answer of the call that crosses the limit is still returned.limits.maxToolResultLengthcaps how many characters of each tool result the model reads (default 100 000, about 25 000 tokens), so one huge output cannot fill the context. A longer result is cut in the middle, see Result Size. A tool's ownmaxResultLengthoverrides it, andonToolResultstill gets the whole result, whileRunResult.messagesand the thread history keep what the model read.loggingreplaces the process-wide logger (getLogger()) when the runtime is created, so with several runtimes the last one created withloggingwins.level: 'silent'turns logging off;destination: 'file'appends JSON lines tofilePath. See Configuration.
Multi-Provider Setup
Configure multiple LLM providers and let agents route to whichever they need:
const cog = new Cogitator({
llm: {
defaultProvider: 'ollama',
providers: {
ollama: { baseUrl: 'http://localhost:11434' },
openai: { apiKey: process.env.OPENAI_API_KEY! },
anthropic: { apiKey: process.env.ANTHROPIC_API_KEY! },
google: { apiKey: process.env.GOOGLE_API_KEY! },
},
},
});Backends are created lazily -- Cogitator only instantiates a provider's client the first time an agent requests it. The provider is determined by the model string prefix (openai/gpt-6.1-sol routes to OpenAI, anthropic/claude-sonnet-5-5 routes to Anthropic). cog.route(model) returns the backend and model name a run would use, and cog.getLLMBackend(model) just the backend, already wrapped with retries and PII masking.
Running Agents
The run() method executes an agent and returns a RunResult:
const result = await cog.run(agent, {
input: 'Search for TypeScript tutorials',
threadId: 'session-123',
stream: true,
onToken: (token) => process.stdout.write(token),
onToolCall: (call) => console.log('Tool:', call.name),
onToolResult: (result) => console.log('Result:', result),
});RunOptions
| Option | Type | Description |
|---|---|---|
input | string | User prompt (required) |
images | ImageInput[] | Images to include with the input (Vision & Audio) |
audio | AudioInput[] | Audio files to transcribe and include |
threadId | string | Conversation to continue, a new one is created when omitted |
userId | string | The user the run acts for: owns new threads, scopes memory, reaches tools as context.userId |
threadAccess | 'owner' | 'shared' | 'owner' (default): only the thread's creator may continue it (Multi-User) |
context | Record<string, unknown> | Data for the model, one JSON block sent with the input (Memory Context), adapters accept client keys via acceptContext |
deps | TDeps | Values for the tools as context.deps, never shown to the model (Dependencies) |
stream | boolean | Enable token streaming |
signal | AbortSignal | Cancel the run and linked provider/tool work |
timeout | number | Milliseconds the whole run may take, over the agent's timeout (RUN_TIMEOUT) |
timeouts | RunTimeouts | Deadlines of the stages: totalMs, stepMs (one model call), chunkMs (a streamed chunk), toolMs (a tool call), over the agent's field by field (Stage Timeouts) |
reasoning | ReasoningConfig | Override the agent's reasoning for this run |
parallelToolCalls | boolean | Run the concurrency-safe calls of a step at the same time, a call that is not safe alone (default: one after another, Concurrency) |
maxParallelToolCalls | number | Most calls of a step that run at once with parallelToolCalls (default 10) |
multitaskStrategy | 'enqueue' | 'reject' | 'interrupt' | 'rollback' | What the run does when its thread has a run going on (Double-Texting), side by side when unset |
saveInterruptedReply | boolean | An aborted run keeps the text it streamed as an interrupted assistant message (default true), off when your code keeps what the user got (Cancellation) |
middleware | RunMiddleware[] | Hooks around this run's model and tool calls, after the Cogitator's and the agent's (Run Middleware) |
toolChoice | ToolChoice | 'none' on every turn, or force 'required' or a named function until the model makes a call, then 'auto' |
useMemory | boolean | Enable/disable memory for this run (default: on when an adapter is configured) |
loadHistory | boolean | Load prior memory history for this run (default: true) |
history | Message[] | The conversation before input, as you hold it: read instead of the thread history in memory. No system messages, saveHistory saves only the new turn |
saveHistory | boolean | Persist run messages to memory (default: true) |
branch | { fromEntryId: string | null; activate?: boolean } | Run on a branch of the thread's memory (Runs on Branches) |
brief | string | Notes for this turn only, such as the current time, sent with the input and not saved (Memory Context) |
asOf | Date | The moment the turn is read at, the clock by default: relative times in the input resolve from it, and memory items are read as of it |
onApproval | (request) => decision | 'pause' | Decide calls of tools with requiresApproval (Approvals) |
onToken | (token: string) => void | Streaming callback |
onReasoning | (delta: string) => void | Streamed reasoning summary (needs reasoning.summary) |
onToolCall | (call: ToolCall) => void | Called when the agent invokes a tool |
onToolResult | (result: ToolResult) => void | Called when a tool returns, with its details and presentation (Results) |
onToolUpdate | (update: ToolUpdate) => void | What a running tool reported with context.update() |
onToolInputStart | (event: ToolInputStart) => void | The model began a tool call, { toolCallId, toolName } (needs stream: true, Streaming Tool Input) |
onToolInputDelta | (event: ToolInputDelta) => void | The next piece of the JSON arguments of the call the model writes |
onToolInputAvailable | (event: ToolInputAvailable) => void | A call the model wrote is complete, with its arguments read |
onToolInputAbandoned | (event: ToolInputAbandoned) => void | A call the model began will not run, reason: 'incomplete' | 'discarded' |
onHandoff | (handoff: HandoffEvent) => void | Called when an agent hands the conversation over (Handoffs) |
onModelFallback | (event: ModelFallbackEvent) => void | A turn moved to the next of fallbackModels (Fallback Models) |
onModelTurn | (turn: KeptModelTurn) => void | Each model turn the run keeps, { content, toolCalls, model }, as every afterModel middleware left it |
onRunStart | ({ runId, agentId, input, threadId }) => void | Called when the run starts |
onRunComplete | (result: RunResult) => void | Called with the result |
onRunError | (error: Error, runId: string, usage?: RunUsage) => void | Called when the run fails, with what its finished model calls used and cost (a run cut short by its timeout spent them too) |
onMemoryError | (error: Error, operation: 'save' | 'load') => void | Called when loading or saving history fails (the run goes on) |
onMemoryEntry | (entry: MemoryEntry) => void | Promise<void> | Each entry the run saved, also of a run that is aborted or fails, before it rejects (a failing callback is only logged) |
onSpan | (span: Span) => void | Observability callback for tracing |
channelType, channelId, topicId, conversationId | string | Where the message came from, passed on to tools in their context |
RunResult
interface RunResult {
output: string; // final answer text
structured?: unknown; // parsed JSON for json / json_schema agents
runId: string;
agentId: string;
threadId: string;
modelUsed?: string; // the model of the final answer, under cost routing or after a fallback
usage: {
inputTokens: number;
outputTokens: number;
totalTokens: number;
cost: number; // USD, reported by the provider or priced by llm.pricing and the model registry
duration: number; // ms
reasoningTokens?: number;
cachedInputTokens?: number;
cacheWriteTokens?: number;
};
reasoning?: string; // reasoning summary, when asked for
prompt?: RunPrompt; // instruction version / A/B variant used
handoffs?: HandoffEvent[];
finalAgent?: string; // the agent that answered after handoffs
status?: 'completed' | 'paused';
pendingApprovals?: ToolApprovalRequest[]; // when paused
interrupts?: RunInterrupt[]; // when paused: approvals and questions of tools
undelivered?: QueuedRunMessage[]; // messages queued on a run handle it did not take
checkpoint?: RunCheckpoint; // when paused, for cog.resume()
toolCalls: ToolCall[];
messages: Message[];
trace: { traceId: string; spans: Span[] };
reflections?: Reflection[];
reflectionSummary?: ReflectionSummary;
memory?: { threadId: string; branchPoint: string | null; leafId?: string }; // where the run wrote in memory
}All fields are readonly.
Pausing and Resuming
A run that reaches a tool call with requiresApproval and no onApproval decision pauses: it returns with status: 'paused', the waiting calls in pendingApprovals and a JSON checkpoint. Continue it later by thread id (the checkpoint is kept in runCheckpoints, by default in the memory adapter's threads or in process memory) or from the checkpoint itself:
const paused = await cog.run(agent, { input: 'Refund order 42', threadId, userId });
if (paused.status === 'paused') {
const result = await cog.resume(agent, threadId, {
userId,
decisions: { [paused.pendingApprovals![0].toolCallId]: { approved: true } },
});
}See Approvals for decisions, stores and servers. A tool can pause a run the same way to ask a person a question (context.interrupt()), and cog.start() returns a handle to steer or abort a run going on, see Steering, Interrupts and Cancellation.
Runs on Branches
A thread's memory is a tree of entries (see Threads as Trees), and a run goes on after the thread's active leaf by default. branch runs it from another point instead: it reads history along the branch that ends at fromEntryId and chains its own entries after it. fromEntryId: null starts a new root with no history. With activate: false the thread's active leaf stays where it was, so the run writes a branch of its own while the conversation goes on, true (the default) makes the run's last entry the leaf.
const first = await cog.run(agent, { input: 'Plan a day in Rome', threadId: 'trip' });
await cog.run(agent, { input: 'Make it cheaper', threadId: 'trip' });
const other = await cog.run(agent, {
input: 'Make it a museum day instead',
threadId: 'trip',
branch: { fromEntryId: first.memory!.leafId!, activate: false },
});
other.memory; // { threadId: 'trip', branchPoint: first.memory.leafId, leafId: '...' }The second branch sees the first question and answer, not the request for a cheaper plan, and the next run on trip without branch goes on after the cheaper plan. Read a branch back with memory.getPath({ threadId, leafId: other.memory.leafId }).
result.memorysays where every run that saved something wrote:threadId,branchPoint(the entry its first entry went after,nullat the root) andleafId(its last entry). It is absent when the run saved nothing, such as withsaveHistory: false.- A run on a branch needs a memory adapter with
getPath(every built-in one has it), andfromEntryIdmust be an entry of the thread. Otherwise the run fails withVALIDATION_ERRORbefore it calls the model. - The run records events of the session as entries next to its messages:
model_changewhen a turn falls back to another offallbackModels({ from, to, reason }),approvalwhen it pauses for approvals ({ pending: [{ toolCallId, toolName }] }) andinterruptwhen itssignalaborts it or its timeout cuts it short ({ reason }, the error message), or when it pauses on questions of its tools and resumes with their answers ({ status: 'paused' | 'resumed', interrupts }, see Interrupts). Reads return them only when asked withtypes, and they are never sent to a model. - A paused run keeps its place in the checkpoint (
RunCheckpoint.branch), soresume()goes on along the same branch and reports the samebranchPoint. A run withactivate: falsedoes not take the thread's place for a paused run, so it never replaces or abandons the pause of the conversation itself: resume it with its checkpoint (resume(agent, result.checkpoint, …)), not with the thread id.
Time travel runs live replays and forks this way, and the Studio shows every branch of a thread in its Tree panel.
Prompt Versions
cog.prompts deploys new instructions for an agent without changing code, rolls them back, and runs A/B tests on live traffic; every run records its outcome against the version it used:
await cog.prompts.deploy(agent, 'You write release notes. Lead with what changed for the user.');
const result = await cog.run(agent, { input });
result.prompt; // { key: 'assistant', versionId: '...', version: 2 }See Prompt Versions.
Cost Estimation
Estimate the cost before running an agent:
const estimate = await cog.estimateCost({
agent,
input: 'Analyze this document and summarize key points',
options: { assumeIterations: 3, assumeToolCalls: 5 },
});
console.log(`Expected cost: $${estimate.expectedCost.toFixed(4)}`);
console.log(`Confidence: ${(estimate.confidence * 100).toFixed(0)}%`);With costRouting enabled, cog.getCostSummary() returns what runs have spent and cog.getCostRouter() the router itself, both before the first run as well (Cost Routing). A run over budget throws a CogitatorError with code BUDGET_EXCEEDED (HTTP 429).
Run Observers
A run observer sees every run of a runtime, also the runs agent tools start on it, without touching the run options of each call:
interface RunObserver {
onRunStart?(event: {
runId: string;
agentId: string;
agentName: string;
input: string;
threadId: string;
model?: string;
}): void;
onSpan?(span: Span, run: { runId: string }): void; // each span as it finishes
onRunComplete?(result: RunResult): void;
onRunError?(error: Error, runId: string, usage?: RunUsage): void; // usage of the finished model calls
close?(): Promise<void> | void; // called by cogitator.close() to flush
}A run that fails still reports what it spent: onRunError gets the tokens and cost of every model call that finished, and a RUN_TIMEOUT error carries the same in details.usage. A call cut off by the timeout reports nothing, so it is not counted. Each llm.chat span carries its call's cost in llm.cost.
Pass them in the config, or attach one to a runtime that is already built with observe(), which returns the function that detaches it:
const otlp = createOTLPExporter({ endpoint: 'http://localhost:4318/v1/traces', enabled: true });
otlp.start();
const cog = new Cogitator({ observers: [otlp.observer()] });
const stop = cog.observe({
onRunComplete: (result) => console.log(`${result.runId} cost $${result.usage.cost}`),
});
// ...
stop();An observer sees the runs that start after it is attached. The run's own callbacks (onRunStart, onSpan and the rest in RunOptions) go first, and an observer that throws is logged without failing the run. cogitator.close() calls close() of every observer, so exporters send what they buffered. The OpenTelemetry and Langfuse exporters provide one with observer(), see Observability.
Observers watch and cannot change a run. To change what a run sends to models and tools, or to stop it, use Run Middleware.
Global Tool Registry
Cogitator exposes a shared tools registry. Tools registered here are available to every agent run on this instance, next to the agent's own tools (an agent tool with the same name wins, without a warning):
cog.tools.register(myGlobalTool);Registering a different tool under a name the registry already holds replaces it and logs a warning. Pass { replace: true } to register or registerMany when that is the intent.
Memory
The configured memory adapter connects on the first run. To read threads before any agent has run — an endpoint that lists a conversation, an export job — ask for it:
const memory = await cog.getMemory(); // undefined when memory is not configuredcog.memory is the same adapter once connected, and undefined before. Assigning cog.memory = adapter uses an adapter you connected yourself, for example one the config cannot create.
Compaction After a Run
With memory.compaction a run compacts its thread once it is done, when the conversation of its branch passed at (default 0.8) of the context window of the model it ended on:
const cog = new Cogitator({
memory: {
adapter: 'sqlite',
sqlite: { path: './memory.db' },
compaction: {
at: 0.8,
beforeCompact: async ({ threadId }) => {
await notes.flush(threadId);
},
},
},
});The compaction is hierarchical: the newest keepRecentTokens (by default the less of 20000 and a quarter of the window) stay verbatim and the rest becomes a handoff of grounded atoms that the next run reads in their place. run() returns once the compaction is done, a compaction that fails is logged and the run keeps its result, and a run on another branch than the thread's active one is left alone. See Compaction After a Run for beforeCompact, afterCompact and the guard against compacting again right away.
Memory Items After a Run
With memory.extraction a run's conversation is read once the run is done, and what it established about the user becomes memory items, which later runs of the user read as facts with contextBuilder.includeFacts:
const cog = new Cogitator({
memory: {
adapter: 'sqlite',
sqlite: { path: './memory.db' },
contextBuilder: { strategy: 'recent', includeFacts: true },
extraction: { timeZone: 'Europe/Lisbon' },
},
});
await cog.run(agent, { input: 'I moved to Lisbon last month.', threadId: 't1', userId: 'ana' });
await cog.run(agent, { input: 'Where do I live now?', threadId: 't2', userId: 'ana' }); // LisbonEach window of the entries new since the last extraction is one call of extraction.model (by default the model the run ended on), and every item is checked against the quotes it gives: only what the user said, with quotes that hold and at activationConfidence (default 0.7) or above, becomes active, and what the assistant or a tool said stays a suggestion. Items are kept under the agent's configured id, else its name (memoryAgentId(agent)), so a new instance of the agent finds them, and belong to the run's own user by default, or to the thread for a run without a user (scope: 'agent' or 'thread' for others), and relative dates are resolved from the date of the message that says them, in the thread's metadata.timeZone when it is a valid IANA zone, else extraction.timeZone, else UTC. The thread keeps its place after every window, runs of one thread extract one after another, the calls are counted in the run's costs and usage, run() returns once the extraction is done, and one that fails is logged while the run keeps its result. See Extraction After a Run.
Memory Tools and Memory Files
memory.files gives every agent this instance runs the memory tool, notes under /memories it keeps across conversations, and lists the files a run sees in its memory context. Claude 4 and later get it as Anthropic's native memory_20250818 tool, every other model as a tool with the same commands:
const cog = new Cogitator({
memory: {
adapter: 'sqlite',
sqlite: { path: './memory.db' },
files: { scope: 'user', readOnly: false, indexChars: 2000 }, // the defaults
},
});scope decides who the files belong to (user, the thread for a run without a user, agent or thread), readOnly lets the agent view them and nothing more, and indexChars caps the list in the context. Every change is kept as a version, a run in a thread sees the versions of its own branch, and an edit of a file another writer changed since the run viewed it fails. See Memory Files.
await cog.memorySearchTools(memoryAgentId) returns the tools an agent searches memory with, search_memory, open_turns and list_entities, over this runtime's store, memory items, embedding service and message index, for the agent whose memory id is memoryAgentId (memoryAgentId(agent): its configured id, else its name). It throws VALIDATION_ERROR when no memory is configured. The memoryCitations() middleware then keeps the references an answer makes to what the run opened:
import { Agent, Cogitator, memoryCitations } from '@cogitator-ai/core';
const cog = new Cogitator({ memory, middleware: [memoryCitations()] });
const agent = new Agent({
name: 'concierge',
instructions: 'Answer from memory and cite what you rely on as [turn:<id>] or [item:<id>].',
tools: await cog.memorySearchTools('concierge'),
});See Agent Memory Tools.
Memory Between Runs
memory.brief gives a turn cards of what memory holds for it before its first model call, each quoting its source and checked against it, as a hint in the turn's memory context. memory.observations keeps what memory makes of each entity as a memory file, written again in the background once its facts change, and shows it to a turn that names the entity, with memory.contextBuilder set. memory.consolidation runs a pass in the background every everyRuns runs of a thread (20) and after a compaction that changed the thread: items a model finds to repeat or contradict a newer one are marked stale, and new lessons are folded into the playbook, /memories/playbook.md, in at most three edits, which every run then sees as a hint while showPlaybook is on (playbook: false only stops new lessons):
const cog = new Cogitator({
memory: {
adapter: 'sqlite',
sqlite: { path: './memory.db' },
contextBuilder: { strategy: 'recent', maxTokens: 8000 },
extraction: {},
brief: { model: 'google/gemini-3.5-flash-lite', timeoutMs: 4000 },
observations: { minItems: 3 },
consolidation: { everyRuns: 20, playbook: 'apply' },
},
});No run waits for upkeep, its model calls count in the cost router but not in a run's usage, and close() stops the passes under way. await cog.consolidateMemory(agent, { userId?, threadId?, since? }) runs a pass now, such as from a worker while the agent is idle, and returns a MemoryConsolidationReport (scope, stale, playbook, observations, observationsDeleted, dedupe). When report.dedupe.complete is false a cap stopped the look for repeats, and calling again with since: report.dedupe.through goes on from there. With the user extraction scope (the default) it needs a userId, or a threadId for the memory of runs without a user, with thread a threadId (even with a userId), and with agent nothing. It throws VALIDATION_ERROR when neither memory.consolidation nor memory.observations is set, or when memory keeps no memory items. A pass on demand asks consolidation.model for repeats and lessons and observations.model for observations, each falling back to the agent's model (llm.defaultModel when the agent has none), while a pass after a run falls back to the model the run ended on. See Between Runs.
Forgetting, Redacting and Rewinding
Three methods take a conversation out of memory together with everything memory derived from it: compaction summaries, memory items, facts (when the memory adapter is a fact store), graph nodes and edges (with graph), vectors, memory file versions, observations and playbook rules, and the copies of the entries in forks.
await cog.forget({ entryIds: [entry.id] }); // entries, a user message with its replies
await cog.forget({ threadId: 'chat' }); // a thread
await cog.forget({ userId: 'ana' }, { agents: [assistant] }); // every thread and everything kept for the user
await cog.redactEntries([entry.id], { reason: 'the user asked' }); // '[redacted]' in place
await cog.rewind('chat', earlier.id); // the turns after it stay on their branch, their items go stale
await cog.rewind('chat', earlier.id, { files: true, agents: [coder] }); // and the files, from the checkpoint there| Method | What it does |
|---|---|
forget(target, options?) | { entryIds } deletes those entries (a user message with the entries that answer it, unless keepReplies), { threadId } the thread, { userId } every thread whose metadata.userId is the user whole, the user's messages in threads of others with their replies, and every item, entity, memory file, fact, graph node and edge and embedding kept for the user |
redactEntries(entryIds, options?) | Replaces what the entries said with [redacted] while they keep their place (MemoryAdapter.redactEntry), and takes away what was derived from them as forget does. An event entry among them or their replies is deleted instead. reason goes into metadata.redacted |
rewind(threadId, toEntryId, options?) | Moves the thread's active leaf back to toEntryId, an entry of its active branch, marks as stale the memory items that stood only on the entries after it (staleBecause: { reason: 'rewound' }) and drops the paused and durable runs of the thread. With files: true it restores the workspace from the file checkpoint at that point first |
Each returns a MemoryCascadeReport (entries, threads, threadsChanged, summaries, items, entities, facts, graph, fileVersions, playbookRules). forget and redactEntries take MemoryCascadeCall (agents, graph, keepReplies), plus reason for redactEntries. rewind takes RewindOptions (agents, memory, files, workspace, dryRun, force) and returns a RewindReport, the cascade report with what happened to the conversation, the files and the runs, and refuses with THREAD_BUSY while a run goes on in the thread unless force, see Rewinding. All three drop the paused runs of the threads they touch, also from a runCheckpoints store of your own, and their durable runs, as their messages would bring back on resume what went. forkThread(threadId, atEntryId, options?) copies a branch into a new thread, with files: true with the files of that point, see Forking With Files.
Items, files, facts and the graph are kept by the memory id of an agent, its configured id, else its name. Every run notes in the thread's metadata the memory id of its agent and of every agent it hands over to (metadata.memoryAgentIds), and the user it ran for (metadata.memoryUserIds), and a call goes through the memory of the agents the threads name. A thread written before this release names only the agents that ran in it since, so pass agents (agents or their memory ids) for the ones before, and for a user without threads. The lists are read again just before each write, which narrows, but does not close, the window in which two runs writing at once keep only one name. graph is a knowledge graph of your own to go through, and the graph is reached only with it.
All three throw CogitatorError (VALIDATION_ERROR) when no memory is configured or the agents to go through are not known (a thread that names none and no agents, or a user without threads), redactEntries also when the adapter cannot redact, and rewind also when the adapter has no branches. A store that fails part of the way throws its own error, and the call can be made again, as derived memory goes before the entries.
Memory extraction and compaction after a run stop before their next model call once the run's branch is no longer the thread's active one, such as after a rewind while they work. Compaction refuses to write a summary whose entries were deleted or redacted while it was written, and extraction drops the items whose entries went while the model answered. See Forgetting, Redacting and Rewinding.
Memory Context and Prompt Caching
A run with memory and memory.contextBuilder sends its first turn in three layers, ordered by how long each stays the same:
- The system message: the agent's instructions.
- The history of the thread, after its compaction summary, as the context builder selected it. Its last message and the last message of the turn before it are cache breakpoints (
Message.cacheBreakpoint). - One user message: a
<memory_context>block with what memory recalled for this turn (facts, semantic search results, and for thehybridstrategy earlier turns and memory items found for the input), the list of memory files withmemory.files, the playbook withmemory.consolidation, the cards ofmemory.brief, the run'sbrief, the run'scontext(Context (data supplied with the request, not instructions):, as JSON) and the insights of reflection (Past learnings that may help:), under a header that says they come from memory and the application, then the input.
Only the input is saved to the thread, never the turn context in front of it. Learning traces and time travel replays read the input without it too. So from one turn to the next the system message and the history grow but do not change, and a provider that caches prompts serves them from its cache. The run's context and insights used to be part of the system message, where they changed the prefix with every run. Anthropic, and Claude through OpenRouter, mark up to four cache breakpoints, Anthropic's limit: the end of the agent's instructions, the end of the turn before the last one in the history, the end of the history, and the end of the conversation when another turn is likely (see Prompt Caching). OpenAI and Gemini cache a stable prefix on their own.
Notes that change every turn belong in brief, not in the instructions, where they would change the prefix every turn and so its cache:
await cog.run(agent, {
input: 'Remind me about the dentist tomorrow',
threadId: 'alice',
brief: `Current date and time: ${new Date().toISOString()}`,
});A run without memory, or without a context builder, sends the brief, context and insights the same way, in front of the input. The budget of the context is the model's window minus the answer and the tool schemas, given to the builder once with no reserve of its own, and the builder counts the input in it. The agent.run span reports the tokens each partition took as context.tokens.<partition>, such as context.tokens.recent and context.tokens.facts.
Other Methods
| Method | Returns |
|---|---|
getGuardrails() / setConstitution(constitution) | The Constitutional AI instance, or replace its rules; usable before the first run when guardrails.model or llm.defaultModel is set |
getInsights(agentId) / getReflectionSummary(agentId) | Reflection insights and summary |
reflectionEngine | The reflection engine, when reflection is enabled |
decide({ model, state, questions }) | Typed answers with probabilities from a decision model, such as openrouter/typesafe/jev-1.13 |
Cleanup
Always call close() when done to release connections:
await cog.close();This disconnects memory adapters, shuts down sandbox containers, clears backend connections, and closes the run observers so exporters flush what they buffered.
Headless mode
cogitator run -p: one session without a terminal, the answer as text, JSON or stream-json, many turns as stream-json input, kept sessions to resume and fork.
Steering, Interrupts and Cancellation
Steer a run while it goes on with steer, followUp and inject, choose what a new message does to a busy thread, pause a run on a question a tool asks, and cancel a run without losing what it showed or did.