Skip to content
AgentsKit

@agentskit/core β€” Functions

API functions for @agentskit/core.

#Function: activateSkills()

activateSkills(skills, prompt?): Promise<ActivateSkillsResult>

Defined in: packages/core/src/agent-loop.ts:45

Add skill prompts and activation-provided tools to a chat configuration.

#Parameters

#skills

SkillDefinition[]

Skills whose prompts and activation hooks should be applied.

#prompt?

string

Optional base system prompt.

#Returns

Promise<ActivateSkillsResult>

The combined system prompt and tools returned by activation hooks.


#Function: audioPart()

audioPart(source, opts?): AudioPart

Defined in: packages/core/src/types/content.ts:72

Build an audio part from a URL, data URI, or hosted reference.

#Parameters

#source

string

Audio source reference.

#opts?

Omit<AudioPart, "type" | "source"> = \{\}

Optional MIME type and duration metadata.

#Returns

AudioPart

An audio content part.


#Function: buildMessage()

buildMessage(params): Message

Defined in: packages/core/src/primitives.ts:88

Create a message with a generated ID and creation timestamp.

#Parameters

#params

Role, content, and optional message status and metadata.

#content

string

#metadata?

Record<string, unknown>

#role

MessageRole

#status?

MessageStatus

#toolCallId?

string

#Returns

Message

A message with a generated ID and current creation date.


#Function: buildToolMap()

buildToolMap(...sources): Map<string, ToolDefinition<Record<string, unknown>>>

Defined in: packages/core/src/agent-loop.ts:21

Combine tool lists into a name-keyed map; later definitions replace earlier ones.

#Parameters

#sources

...(ToolDefinition<Record<string, unknown>>[] | undefined)[]

Tool lists in replacement precedence order.

#Returns

Map<string, ToolDefinition<Record<string, unknown>>>

A map containing the last definition for each name.


#Function: compileBudget()

compileBudget(input): Promise<CompileBudgetResult>

Defined in: packages/core/src/budget.ts:90

Count and trim request content according to the selected budget strategy.

#Parameters

#input

CompileBudgetInput

Messages, prompt, tools, budget, and trimming strategy.

#Returns

Promise<CompileBudgetResult>

The retained request content with token counts and dropped messages.

#Throws

Error when the system prompt and tools exceed the effective budget or summarization is requested without a summarizer.


#Function: consumeStream()

consumeStream(source, handlers): Promise<void>

Defined in: packages/core/src/primitives.ts:335

Dispatch stream events to handlers and report accumulated text on completion.

#Parameters

#source

StreamSource

Abortable source of response chunks.

#handlers

ConsumeStreamHandlers

Callbacks for text, reasoning, tools, usage, errors, and completion.

#Returns

Promise<void>

A promise fulfilled when the stream ends or reports an error.


#Function: createChatController()

createChatController(initial): ChatController

Defined in: packages/core/src/controller.ts:27

Create a chat controller from adapter, conversation, and optional integrations.

#Parameters

#initial

ChatConfig

Adapter, prompt, tool, memory, and observer settings.

#Returns

ChatController

Controller methods for managing the session and reading its state.

#Example

`const chat = createChatController({ adapter }); await chat.send('Hello')`.

#Function: createEventEmitter()

createEventEmitter(): object

Defined in: packages/core/src/primitives.ts:61

Create an observer emitter that isolates observer failures from callers.

#Returns

object

Methods to register observers and emit events to them.

#addObserver()

addObserver(observer): () => void

#Parameters

observer

Observer

#Returns

() => void

#emit()

emit(event): void

#Parameters

event

AgentEvent

#Returns

void


#Function: createId()

createId(prefix): string

Defined in: packages/core/src/primitives.ts:40

Create a unique ID with a caller-provided prefix and a cryptographically random UUID.

#Parameters

#prefix

string

Namespace or kind to include at the start of the ID.

#Returns

string

The prefix followed by a UUID.

#Example

const messageId = createId('msg')

#Since

1.13.0


#Function: createInMemoryMemory()

createInMemoryMemory(initialMessages?): ChatMemory

Defined in: packages/core/src/memory.ts:31

Create a message-memory backend that stores data in the current process.

#Parameters

#initialMessages?

Message[] = []

Optional messages to seed the store.

#Returns

ChatMemory

A ChatMemory implementation backed by an in-memory array.


#Function: createLocalStorageMemory()

createLocalStorageMemory(key): ChatMemory

Defined in: packages/core/src/memory.ts:52

Create a browser-local-storage backend using the supplied storage key.

#Parameters

#key

string

Local storage key for the serialized message record.

#Returns

ChatMemory

A ChatMemory implementation backed by browser local storage.

#Throws

MemoryError from load, save, or clear when storage access fails.


#Function: createProgressiveArgParser()

createProgressiveArgParser(): ProgressiveArgParser

Defined in: packages/core/src/progressive.ts:42

Stream-parse a JSON object where top-level field values arrive incrementally. Fires an event as soon as each top-level field has a syntactically complete value, enabling "progressive" tool execution β€” the tool can begin work on the first field before the LLM has finished emitting the rest.

Only works at the top level of a JSON object β€” nested structures are parsed atomically when their enclosing top-level field closes. That matches the common tool-args shape: a flat \{ query, limit, ...\} object where the expensive operation depends on one key.

#Returns

ProgressiveArgParser


#Function: createStaticRetriever()

createStaticRetriever(config): Retriever

Defined in: packages/core/src/rag.ts:22

Create a retriever that returns configured documents for each query.

#Parameters

#config

StaticRetrieverConfig

Documents to expose through the retriever.

#Returns

Retriever

A retriever that returns the configured documents.


#Function: createToolLifecycle()

createToolLifecycle(tools): object

Defined in: packages/core/src/primitives.ts:252

Track tool initialization and defer disposal until active calls finish.

#Parameters

#tools

Map<string, ToolDefinition<Record<string, unknown>>>

Name-keyed tool definitions used by this lifecycle.

#Returns

object

Idempotent initialization and disposal methods for a tool set.

#disposeAll()

disposeAll(): Promise<void>

#Returns

Promise<void>

#init()

init(tool): Promise<void>

#Parameters

tool

ToolDefinition

#Returns

Promise<void>


#Function: createVirtualizedMemory()

createVirtualizedMemory(backing, options?): ChatMemory & object

Defined in: packages/core/src/virtualized-memory.ts:34

Wrap any ChatMemory implementation with a fixed active window. Older messages (cold) are preserved on disk / in the backing store but omitted from load() unless a retriever surfaces them.

Key guarantees:

  • Backing store always holds the full conversation. No data loss.
  • load() returns at most maxActive + maxRetrieved messages.
  • save() merges the caller's messages with any cold tail the caller did not see, so callers that load -> mutate -> save do not accidentally truncate history.

#Parameters

#backing

ChatMemory

#options?

VirtualizedMemoryOptions = \{\}

#Returns

ChatMemory & object


#Function: defineTool()

defineTool<TSchema>(config): ToolDefinition<InferSchemaType<TSchema>>

Defined in: packages/core/src/types/tool.ts:147

Create a ToolDefinition with automatic type inference from the JSON schema.

#Type Parameters

#TSchema

TSchema extends JSONSchema7

#Parameters

#config

DefineToolConfig<TSchema>

#Returns

ToolDefinition<InferSchemaType<TSchema>>


#Function: deserializeMessages()

deserializeMessages(record): Message[]

Defined in: packages/core/src/memory.ts:19

Restore messages from a memory record, including createdAt dates.

#Parameters

#record

MemoryRecord | null | undefined

Serialized record, or null / undefined for no messages.

#Returns

Message[]

Restored messages; an absent record produces an empty array.


#Function: executeSafeTool()

executeSafeTool(options): Promise<ToolExecResult>

Defined in: packages/core/src/agent-loop.ts:103

Validate, authorize, and execute a tool while reporting its lifecycle.

#Parameters

#options

ExecuteSafeToolOptions

Tool call and lifecycle dependencies, validators, and callbacks.

#Returns

Promise<ToolExecResult>

The execution status, result or error text, and elapsed time.


#Function: executeToolCall()

executeToolCall(tool, args, context, onPartialResult?): Promise<string>

Defined in: packages/core/src/primitives.ts:128

Execute a tool and return its result as text, reporting streamed partial output.

#Parameters

#tool

ToolDefinition

Tool whose execute function is called.

#args

Record<string, unknown>

Parsed arguments passed to the tool.

#context

ToolExecutionContext

Conversation and tool-call context.

#onPartialResult?

(accumulated) => void

Called with accumulated text after each streamed item.

#Returns

Promise<string>

The tool result serialized as text.


#Function: executeToolProgressively()

executeToolProgressively<TArgs>(tool, chunks, context, options?): ProgressiveExecResult

Defined in: packages/core/src/progressive.ts:232

Run a tool "progressively": feed argument-text chunks as they stream, and kick off tool.execute as soon as the trigger fields have arrived. Additional field events keep landing in the same onField callback so the tool can adapt.

The tool's args parameter reflects whichever fields had arrived by the trigger point β€” callers that need the complete object should wait for finalArgs.

#Type Parameters

#TArgs

TArgs extends Record<string, unknown>

#Parameters

#tool

ToolDefinition<TArgs>

#chunks

AsyncIterable<string>

#context

Omit<ToolExecutionContext, "call"> & object

#options?

ProgressiveExecOptions = \{\}

#Returns

ProgressiveExecResult


#Function: filePart()

filePart(source, opts?): FilePart

Defined in: packages/core/src/types/content.ts:90

Build a file part from a URL, data URI, or hosted reference.

#Parameters

#source

string

File source reference.

#opts?

Omit<FilePart, "type" | "source"> = \{\}

Optional MIME type and original filename.

#Returns

FilePart

A file content part.


#Function: filterParts()

filterParts<T>(parts, kind): (Extract<TextPart, { type: T; }> | Extract<ImagePart, { type: T; }> | Extract<AudioPart, { type: T; }> | Extract<VideoPart, { type: T; }> | Extract<FilePart, { type: T; }>)[]

Defined in: packages/core/src/types/content.ts:140

Filter parts by kind.

#Type Parameters

#T

T extends "text" | "image" | "audio" | "video" | "file"

#Parameters

#parts

ContentPart[]

#kind

T

#Returns

(Extract<TextPart, { type: T; }> | Extract<ImagePart, { type: T; }> | Extract<AudioPart, { type: T; }> | Extract<VideoPart, { type: T; }> | Extract<FilePart, { type: T; }>)[]


#Function: formatRetrievedDocuments()

formatRetrievedDocuments(documents): string

Defined in: packages/core/src/rag.ts:43

Format retrieved documents into text suitable for a model prompt.

#Parameters

#documents

RetrievedDocument[]

Retrieved content and metadata to format.

#Returns

string

A labeled text block containing the document contents.


#Function: generateId()

generateId(prefix): string

Defined in: packages/core/src/primitives.ts:54

Generate a prefixed UUID for an entity such as a message or run.

#Parameters

#prefix

string

Namespace or entity kind included before the UUID.

#Returns

string

The prefix and a cryptographically random UUID separated by -.


#Function: imagePart()

imagePart(source, opts?): ImagePart

Defined in: packages/core/src/types/content.ts:63

Build an image part from a URL / data URI / hosted id.

#Parameters

#source

string

#opts?

Omit<ImagePart, "type" | "source"> = \{\}

#Returns

ImagePart


#Function: isRecord()

isRecord(value): value is Record&lt;string, unknown>

Defined in: packages/core/src/primitives.ts:27

Check whether a value is a non-null object other than an array. Instances such as Date, Map, and class instances satisfy this guard; use a schema validator when a plain JSON object is required.

#Parameters

#value

unknown

Value to check.

#Returns

value is Record&lt;string, unknown>

true for non-null, non-array objects; otherwise false.

#Example

isRecord({ name: 'Ada' }) // true
isRecord([]) // false

#Since

1.14.0


#Function: normalizeContent()

normalizeContent(content, parts): object

Defined in: packages/core/src/types/content.ts:128

Normalize any of (string | ContentPart[] | undefined) into \{ text, parts \}. Callers that have both the legacy content string and the new parts array use this to pick the right one.

#Parameters

#content

string | undefined

#parts

ContentPart[] | undefined

#Returns

object

#parts

parts: ContentPart[]

#text

text: string


#Function: parseToolArgs()

parseToolArgs(args): ParsedToolArgs

Defined in: packages/core/src/primitives.ts:178

Parse a bounded JSON object of tool arguments; invalid input returns an empty object.

#Parameters

#args

string

JSON text emitted for a tool call.

#Returns

ParsedToolArgs

Parsed arguments and a validity flag.


#Function: partsToText()

partsToText(parts): string

Defined in: packages/core/src/types/content.ts:99

Collapse a parts array into a text-only projection. Non-text parts are rendered as [image: url] / [audio: url] etc. so plain-text adapters see something meaningful.

#Parameters

#parts

ContentPart[]

#Returns

string


#Function: safeParseArgs()

safeParseArgs(args): Record<string, unknown>

Defined in: packages/core/src/primitives.ts:197

Return parsed tool arguments, or an empty object when parsing fails.

#Parameters

#args

string

JSON text emitted for a tool call.

#Returns

Record<string, unknown>

Parsed arguments or an empty object when invalid.


#Function: serializeMessages()

serializeMessages(messages): MemoryRecord

Defined in: packages/core/src/memory.ts:8

Convert messages into the versioned JSON-safe memory record format.

#Parameters

#messages

Message[]

Messages to serialize.

#Returns

MemoryRecord

A version 1 record with ISO timestamp strings.


#Function: textPart()

textPart(text): TextPart

Defined in: packages/core/src/types/content.ts:58

Build a text part.

#Parameters

#text

string

#Returns

TextPart


#Function: videoPart()

videoPart(source, opts?): VideoPart

Defined in: packages/core/src/types/content.ts:81

Build a video part from a URL, data URI, or hosted reference.

#Parameters

#source

string

Video source reference.

#opts?

Omit<VideoPart, "type" | "source"> = \{\}

Optional MIME type and duration metadata.

#Returns

VideoPart

A video content part.

Explore nearby

On this page

Function: activateSkills()Parametersskillsprompt?ReturnsFunction: audioPart()Parameterssourceopts?ReturnsFunction: buildMessage()Parametersparamscontentmetadata?rolestatus?toolCallId?ReturnsFunction: buildToolMap()ParameterssourcesReturnsFunction: compileBudget()ParametersinputReturnsThrowsFunction: consumeStream()ParameterssourcehandlersReturnsFunction: createChatController()ParametersinitialReturnsExampleFunction: createEventEmitter()ReturnsaddObserver()ParametersobserverReturnsemit()ParameterseventReturnsFunction: createId()ParametersprefixReturnsExampleSinceFunction: createInMemoryMemory()ParametersinitialMessages?ReturnsFunction: createLocalStorageMemory()ParameterskeyReturnsThrowsFunction: createProgressiveArgParser()ReturnsFunction: createStaticRetriever()ParametersconfigReturnsFunction: createToolLifecycle()ParameterstoolsReturnsdisposeAll()Returnsinit()ParameterstoolReturnsFunction: createVirtualizedMemory()Parametersbackingoptions?ReturnsFunction: defineTool()Type ParametersTSchemaParametersconfigReturnsFunction: deserializeMessages()ParametersrecordReturnsFunction: executeSafeTool()ParametersoptionsReturnsFunction: executeToolCall()ParameterstoolargscontextonPartialResult?ReturnsFunction: executeToolProgressively()Type ParametersTArgsParameterstoolchunkscontextoptions?ReturnsFunction: filePart()Parameterssourceopts?ReturnsFunction: filterParts()Type ParametersTParameterspartskindReturnsFunction: formatRetrievedDocuments()ParametersdocumentsReturnsFunction: generateId()ParametersprefixReturnsFunction: imagePart()Parameterssourceopts?ReturnsFunction: isRecord()ParametersvalueReturnsExampleSinceFunction: normalizeContent()ParameterscontentpartsReturnspartstextFunction: parseToolArgs()ParametersargsReturnsFunction: partsToText()ParameterspartsReturnsFunction: safeParseArgs()ParametersargsReturnsFunction: serializeMessages()ParametersmessagesReturnsFunction: textPart()ParameterstextReturnsFunction: videoPart()Parameterssourceopts?Returns