Type-checked Worker API examples
The learning catalog is in examples. See the setup guide, Runtime examples and database integrations.
graph-loop-worker.ts, runtime/graph-loop.ts and runtime/placement.ts execute at module load. The per-API function files below only export functions; importing them does not issue requests. Supply configured application model/database/MCP adapters, then call the function you need. Model calls can consume provider credits, and write/update/delete examples perform those operations.
| File | Reference | Resources |
|---|---|---|
| context.ts | CONTEXT | Explicit Context, Redis or ContextStateStore |
| memory.ts | MEMORY | MemoryResources; filters/cursors/orderBy belong to the adapter |
| infer.ts | INFER · Providers | InferClient/ModelConfig or configuration loaded by setupInfer |
| interaction.ts | INTERACTION | Workspace access; connected MCP client and allowed absolute paths |
| retrieval.ts | RETRIEVAL · Providers | Search/embedding/rerank backends; complete MemoryItem candidates or mapOutput |
Run npm run typecheck at the repository root. tsconfig includes these files, while emitted package builds exclude them. These are usage examples, not alternative SDKs or automatic live integration tests. Keep each // example: region and the matching API reference aligned when changing signatures.
For an executable local flow, use npm run example:agent or npm run example:tools. MCP commands are in the setup guide. Load .env explicitly with Node --env-file=.env or your application loader. loadRuntimeConfigFile reads YAML and uses the supplied environment; it does not read .env.
Function guide
Objects and constructors below do not automatically execute Graphs. Model/database/MCP parameters are configured application-owned resources.
memory.ts
| Function / object | Behavior |
|---|---|
setupMemory | Load configuration and create a MEMORY Worker/Runtime and direct SDK using application-owned store/search resources. |
getMemory | Read exact IDs/keys, deduplicate repeated IDs and check NodeResult success. |
queryMemory | Read up to two pages ordered by id, pass nextCursor and merge items; the adapter must support this order field. |
searchMemory | Use the storage plugin's default search strategy; return full memories and optional scores. |
writeMemory | Write a language preference and return its database ID; repeated-key behavior belongs to the adapter. |
updateMemory | Replace content and clear metadata by an existing id, demonstrating partial-update semantics. |
deleteMemory | Delete IDs and inspect actual deletions; repeated IDs are not reported twice. |
executeMemory | Call MEMORY.QUERY through the common execute entry point. |
adaptDatabase | Wrap a compatible application adapter as store/search while preserving method this binding. |
memoryErrors | Show structured failures for invalid limits and application MemoryError. |
memoryGraph | Run MEMORY.GET through a Graph and close Runtime. |
customGet | Define a node descriptor returning NOT_CONFIGURED without accessing a database. |
infer.ts
| Function / object | Behavior |
|---|---|
setupInfer | Load YAML/environment configuration and create a Worker, Runtime and direct SDK with a shared cache. |
sample | Sample once and inspect Message, finishReason and usage. |
sampleActions | Declare read_text to the model; generate a request without executing a file read. |
trajectory | Run a CoT trajectory and check both outer success and inner completed status. |
strategyRequests | Construct CoT, Long CoT, ToT, GoT and self-consistency requests without model calls. |
reflectModes | Evaluate or revise a candidate using critique/verify/revise mode. |
deliberateModes | Process candidates using select/merge/consensus/debate; selectCount applies only to select. |
cacheApis | Write and read cache entries, then invalidate by key/tag/namespace. |
executeInfer | Sample through execute with a per-call timeoutMs. |
streamApis | Consume all four reasoning streams and terminal outputs; this makes multiple model calls. |
cancelInfer | Pass an already-aborted signal and observe cancelled without issuing a model request. |
cacheProviderApi | Call cache write/lookup/invalidate directly; return raw outputs without NodeResult. |
refineStrategy | Define a strategy that drafts, revises, deliberates and records public decision steps; inject before use. |
providerRegistryApis | Register, resolve, invoke and unregister a model provider. |
providerStream | Consume provider streaming, falling back to invoke when streaming is unsupported. |
httpModelProvider | Construct an HTTP provider from supplied configuration; construction does not send requests. |
sampleDescriptor | Wrap SDK sample as a NodeDefinition without automatic registration/execution. |
interaction.ts
| Function / object | Behavior |
|---|---|
readTextTool | Define a workspace reader with argument validation, capability metadata and Sandbox access. |
consoleSink | Define a console sink that prints messages and returns an accepted receipt. |
setupInteraction | Register a file tool, connected MCP client and output sink with a Worker/Runtime. |
interactionNodes | Compose registries, createInteractionNodes and defineWorker. |
interactionHandlers | Compose the four Interaction nodes using handler factories. |
toolRegistryApis | Register, list allowed tools, invoke and unregister inside a real WorkerContext. |
invokeTool | Read README.md through Runtime; ExternalResult has no output wrapper. |
mcpRegistryApis | Discover and invoke read_text_file with McpRegistry, then unregister the client. |
invokeMcp | Discover and read through Runtime while distinguishing both response shapes. |
observeApis | Compare pure normalization with OBSERVE using supplied outcomes, without external requests. |
outputApi | Send structured messages and artifact references to the console sink; this does not create artifact files. |
missingRecordTool | Define a NOT_FOUND tool outcome to illustrate business failure. |
rejectedSink | Define a sink returning a rejected delivery receipt. |
interactionGraph | Read README.md and package.json through Graph + Loop and output two observations. |
observationDefinition | Define an OBSERVE node descriptor without registration/execution. |
mcpClientAdapter | Wrap a neutral MCP client, preserving this binding and optional fields. |
retrieval.ts
| Function / object | Behavior |
|---|---|
request | Define request data: agent memory query, kb target, limit=5; no execution. |
setupRetrieval | Register the optional Worker and logical target/strategy and create the direct SDK. |
retrievalSearch | Search the same backend through SDK and Runtime and inspect candidates. |
registryResolve | Resolve a target's default strategy provider and inspect raw results. |
cancelRetrieval | Pass AbortSignal as search's third argument and fallback defaults as the second. |
embeddingApis | Compare embed with batched embedContents and validate vector dimensions. |
httpEmbedding | Create a real HTTP embedding provider from environment and use YAML batch configuration. |
externalVector | Embed externally before passing the vector to database search. |
nativeVector | Send the raw query to a backend with built-in embedding. |
precomputedVector | Search using an existing vector after dimension validation. |
textSearch | Wrap native database text search without embedding. |
hybridSearch | Run vector and keyword branches concurrently and combine with weighted RRF. |
rerankApis | Create a cosine reranker from embeddings and compare indexes/scores with mapped candidates. |
rerankSearch | Expand the recall pool, rerank with an injected provider and return the requested count. |
sqlSearch | Create a PostgreSQL full-text adapter with injected query and bound text/tenant parameters. |
milvusSearch | Adapt Milvus requests/responses with injected SDK search, namespaces and complete MemoryItem records. |
nativeMemoryInRetrieval | Convert a native MemorySearchProvider into a retrieval provider and back into Memory results. |
nativeMemoryWithNamespace | Map Retrieval namespace to the adapter's tenant filter; this does not replace authentication. |
localMemoryPipeline | Reuse a retrieval pipeline inside MEMORY without starting a RETRIEVAL Worker. |
delegatedMemory | Delegate MEMORY.SEARCH to Runtime RETRIEVAL.SEARCH using same-process routing. |
mapTextCandidates | Map complete candidate business data to MemoryItem; ID/snippet indexes need batch hydration. |
retrievalDescriptor | Wrap the retrieval SDK as a NodeDefinition while retaining SDK validation and NodeResult. |
context.ts
| Function / object | Behavior |
|---|---|
setupContext | Create the direct SDK and Worker; see CONTEXT for configuration. |
loadContext | Load messages, items and references. |
selectContext | Select context for inference or memory. |
updateContext | Apply incremental changes and preserve provenance. |
compressContext | Compress against a budget. |
executeContext | Use the common execute entry point. |
cachedContext | Invoke all four Context nodes in cache mode. |
redisStore | Configure Redis storage and explicit versions. |
contextServices | Inject custom Context services. |
ragContext | Configure a RAG selection strategy. |
contextRetrieval | Reuse a RETRIEVAL provider for Context. |
contextToInfer | Convert selected Context for INFER. |
memoryToContext | Compose Memory and Context in a Graph. |
contextFlows | Run predefined RAG and Skill flows. |
contextErrors | Demonstrate Context failure paths. |
directStrategies | Reuse built-in strategies directly. |
customContextLoad | Define a custom load node descriptor. |
contextToMemory | Write selected content into long-term MEMORY. |
toolToCachedContext | Write tool observations into cached Context. |
remoteContextRetrieval | Delegate search to a separate RETRIEVAL Worker. |
Suggested order
- Start with the complete examples without optional services.
- Choose a function for a Worker and inject resources matching its signature. Close Runtime returned by setupMemory/setupInfer/setupInteraction/setupRetrieval.
- Run
npm run typecheckafter changes. Runningnode docs/worker-api/examples/memory.tsalone does not call its exported functions.
Database integrations cover Redis Context and SQL/Milvus Memory. Runtime examples cover a first Graph, custom Workers, events, artifacts, cleanup and RAG/Skill/Tool/MCP/ReAct flows. The per-function modules are safe to import without issuing requests; consult each directory for executable entry points.
