Skip to content

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.

FileReferenceResources
context.tsCONTEXTExplicit Context, Redis or ContextStateStore
memory.tsMEMORYMemoryResources; filters/cursors/orderBy belong to the adapter
infer.tsINFER · ProvidersInferClient/ModelConfig or configuration loaded by setupInfer
interaction.tsINTERACTIONWorkspace access; connected MCP client and allowed absolute paths
retrieval.tsRETRIEVAL · ProvidersSearch/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 / objectBehavior
setupMemoryLoad configuration and create a MEMORY Worker/Runtime and direct SDK using application-owned store/search resources.
getMemoryRead exact IDs/keys, deduplicate repeated IDs and check NodeResult success.
queryMemoryRead up to two pages ordered by id, pass nextCursor and merge items; the adapter must support this order field.
searchMemoryUse the storage plugin's default search strategy; return full memories and optional scores.
writeMemoryWrite a language preference and return its database ID; repeated-key behavior belongs to the adapter.
updateMemoryReplace content and clear metadata by an existing id, demonstrating partial-update semantics.
deleteMemoryDelete IDs and inspect actual deletions; repeated IDs are not reported twice.
executeMemoryCall MEMORY.QUERY through the common execute entry point.
adaptDatabaseWrap a compatible application adapter as store/search while preserving method this binding.
memoryErrorsShow structured failures for invalid limits and application MemoryError.
memoryGraphRun MEMORY.GET through a Graph and close Runtime.
customGetDefine a node descriptor returning NOT_CONFIGURED without accessing a database.

infer.ts ​

Function / objectBehavior
setupInferLoad YAML/environment configuration and create a Worker, Runtime and direct SDK with a shared cache.
sampleSample once and inspect Message, finishReason and usage.
sampleActionsDeclare read_text to the model; generate a request without executing a file read.
trajectoryRun a CoT trajectory and check both outer success and inner completed status.
strategyRequestsConstruct CoT, Long CoT, ToT, GoT and self-consistency requests without model calls.
reflectModesEvaluate or revise a candidate using critique/verify/revise mode.
deliberateModesProcess candidates using select/merge/consensus/debate; selectCount applies only to select.
cacheApisWrite and read cache entries, then invalidate by key/tag/namespace.
executeInferSample through execute with a per-call timeoutMs.
streamApisConsume all four reasoning streams and terminal outputs; this makes multiple model calls.
cancelInferPass an already-aborted signal and observe cancelled without issuing a model request.
cacheProviderApiCall cache write/lookup/invalidate directly; return raw outputs without NodeResult.
refineStrategyDefine a strategy that drafts, revises, deliberates and records public decision steps; inject before use.
providerRegistryApisRegister, resolve, invoke and unregister a model provider.
providerStreamConsume provider streaming, falling back to invoke when streaming is unsupported.
httpModelProviderConstruct an HTTP provider from supplied configuration; construction does not send requests.
sampleDescriptorWrap SDK sample as a NodeDefinition without automatic registration/execution.

interaction.ts ​

Function / objectBehavior
readTextToolDefine a workspace reader with argument validation, capability metadata and Sandbox access.
consoleSinkDefine a console sink that prints messages and returns an accepted receipt.
setupInteractionRegister a file tool, connected MCP client and output sink with a Worker/Runtime.
interactionNodesCompose registries, createInteractionNodes and defineWorker.
interactionHandlersCompose the four Interaction nodes using handler factories.
toolRegistryApisRegister, list allowed tools, invoke and unregister inside a real WorkerContext.
invokeToolRead README.md through Runtime; ExternalResult has no output wrapper.
mcpRegistryApisDiscover and invoke read_text_file with McpRegistry, then unregister the client.
invokeMcpDiscover and read through Runtime while distinguishing both response shapes.
observeApisCompare pure normalization with OBSERVE using supplied outcomes, without external requests.
outputApiSend structured messages and artifact references to the console sink; this does not create artifact files.
missingRecordToolDefine a NOT_FOUND tool outcome to illustrate business failure.
rejectedSinkDefine a sink returning a rejected delivery receipt.
interactionGraphRead README.md and package.json through Graph + Loop and output two observations.
observationDefinitionDefine an OBSERVE node descriptor without registration/execution.
mcpClientAdapterWrap a neutral MCP client, preserving this binding and optional fields.

retrieval.ts ​

Function / objectBehavior
requestDefine request data: agent memory query, kb target, limit=5; no execution.
setupRetrievalRegister the optional Worker and logical target/strategy and create the direct SDK.
retrievalSearchSearch the same backend through SDK and Runtime and inspect candidates.
registryResolveResolve a target's default strategy provider and inspect raw results.
cancelRetrievalPass AbortSignal as search's third argument and fallback defaults as the second.
embeddingApisCompare embed with batched embedContents and validate vector dimensions.
httpEmbeddingCreate a real HTTP embedding provider from environment and use YAML batch configuration.
externalVectorEmbed externally before passing the vector to database search.
nativeVectorSend the raw query to a backend with built-in embedding.
precomputedVectorSearch using an existing vector after dimension validation.
textSearchWrap native database text search without embedding.
hybridSearchRun vector and keyword branches concurrently and combine with weighted RRF.
rerankApisCreate a cosine reranker from embeddings and compare indexes/scores with mapped candidates.
rerankSearchExpand the recall pool, rerank with an injected provider and return the requested count.
sqlSearchCreate a PostgreSQL full-text adapter with injected query and bound text/tenant parameters.
milvusSearchAdapt Milvus requests/responses with injected SDK search, namespaces and complete MemoryItem records.
nativeMemoryInRetrievalConvert a native MemorySearchProvider into a retrieval provider and back into Memory results.
nativeMemoryWithNamespaceMap Retrieval namespace to the adapter's tenant filter; this does not replace authentication.
localMemoryPipelineReuse a retrieval pipeline inside MEMORY without starting a RETRIEVAL Worker.
delegatedMemoryDelegate MEMORY.SEARCH to Runtime RETRIEVAL.SEARCH using same-process routing.
mapTextCandidatesMap complete candidate business data to MemoryItem; ID/snippet indexes need batch hydration.
retrievalDescriptorWrap the retrieval SDK as a NodeDefinition while retaining SDK validation and NodeResult.

context.ts ​

Function / objectBehavior
setupContextCreate the direct SDK and Worker; see CONTEXT for configuration.
loadContextLoad messages, items and references.
selectContextSelect context for inference or memory.
updateContextApply incremental changes and preserve provenance.
compressContextCompress against a budget.
executeContextUse the common execute entry point.
cachedContextInvoke all four Context nodes in cache mode.
redisStoreConfigure Redis storage and explicit versions.
contextServicesInject custom Context services.
ragContextConfigure a RAG selection strategy.
contextRetrievalReuse a RETRIEVAL provider for Context.
contextToInferConvert selected Context for INFER.
memoryToContextCompose Memory and Context in a Graph.
contextFlowsRun predefined RAG and Skill flows.
contextErrorsDemonstrate Context failure paths.
directStrategiesReuse built-in strategies directly.
customContextLoadDefine a custom load node descriptor.
contextToMemoryWrite selected content into long-term MEMORY.
toolToCachedContextWrite tool observations into cached Context.
remoteContextRetrievalDelegate search to a separate RETRIEVAL Worker.

Suggested order ​

  1. Start with the complete examples without optional services.
  2. Choose a function for a Worker and inject resources matching its signature. Close Runtime returned by setupMemory/setupInfer/setupInteraction/setupRetrieval.
  3. Run npm run typecheck after changes. Running node docs/worker-api/examples/memory.ts alone 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.

Ditto · @codesoul-co/ditto · Node.js 24+