@agentskit/core

中文文档
1.15.0发布于 2026/10/10MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 3.8万

Portable AgentsKit runtime for chat orchestration, tools, memory, and retrieval.

原始使用文档
文档目录16 节
  1. Verified proof
  2. How this fits the ecosystem
  3. Why core
  4. Install
  5. Quick example
  6. Durable confirmations and content parts
  7. Features
  8. Error handling
  9. Type-safe tools with defineTool
  10. Subpath exports (tree-shaken, zero main-bundle weight)
  11. Ecosystem
  12. Contributors
  13. License
  14. Docs
  15. Maturity and compatibility
  16. Contributing

@agentskit/core

Profile: major-package

AgentsKit

The zero-dependency foundation that every AgentsKit package builds on — under the 10 KB gzip budget, edge-ready, works everywhere JavaScript runs.

npm version npm downloads bundle size license stability GitHub stars

Tags: ai · agents · llm · agentskit · typescript · orchestration · streaming · chat

Verified proof

How this fits the ecosystem

@agentskit/core is the contract layer: the tiny, stable foundation that makes adapters, tools, skills, memory, retrievers, and runtimes interchangeable.

  • AgentsKit: compose it with the other packages in this repo to build agents from small, swappable parts.
  • Registry: look for ready agents and templates that already use this layer at registry.agentskit.io.
  • Playbook: learn the production patterns behind this layer at playbook.agentskit.io.

Docs: package guide · agent handoff

Why core

  • Zero external dependencies — no npm bloat, no audit surprises; installs in milliseconds and works in Node, Deno, edge runtimes, and the browser
  • Stable contracts that unlock the whole ecosystem — six ADR-pinned interfaces (Adapter, Tool, Skill, Memory, Retriever, Runtime) make every package interchangeable
  • Chat state machine included — createChatController handles streaming, abort, and message history so you never implement that loop yourself
  • Under 10 KB gzipped, always — budget enforced in CI; the foundation you can commit to for the long term

Install

npm install @agentskit/core

Quick example

import { createChatController, createInMemoryMemory } from '@agentskit/core'
import { anthropic } from '@agentskit/adapters'

const controller = createChatController({
  adapter: anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, model: 'claude-sonnet-4-6' }),
  memory: createInMemoryMemory(),
})

await controller.send('Hello!')
console.log(controller.getState().messages)

Durable confirmations and content parts

controller.send accepts a string or ContentPart[]; parts are retained on the user message and content is their text projection. The shared ChatReturn.send signature also accepts parts; existing string callers remain compatible. Structural ChatController implementations must provide the required decide method.

Configure ChatConfig.decisionStore with a conversation-scoped ToolDecisionStore, then call await controller.decide(toolCallId, 'approve') or await controller.decide(toolCallId, 'deny', reason). A controller uses its live conversation when present, including unsaved turns; otherwise it loads configured chat memory, preserving later turns; the claimed snapshot is a fallback only when no current conversation exists. It patches and persists the target tool outcome. The model resumes only for the latest completed assistant message when every confirmation in that target assistant message is decided; tool results follow their originating assistant message in call order. Pending confirmations are saved to configured chat memory and the decision store before proposal completion.

The store implements insert-if-absent putPending, get, atomic claim (pending → claimed, returning a snapshot only to the winner), and settle (persist the matching claim's terminal outcome). Store records must survive process restart, and methods must be linearizable per tool call. An asynchronous read followed by a write is not an atomic claim: use a database conditional update/transaction or an equivalent compare-and-swap, including across processes. Use an application-authorized conversation scope. A database claim can use UPDATE ... WHERE status = 'pending' RETURNING ...; core ships no database implementation.

Identical decisions are idempotent even while claimed: they return the recorded outcome, or the original call while execution is in flight, without invoking the tool or model again. Streamed confirmations are registered before onToolCall. After restart, streamed decisions require current ChatMemory: arrival snapshots are immutable and may omit later calls; without a current conversation, AK_CONFIG_INVALID rejects an incomplete streaming snapshot before claiming. A live controller does not require memory.

Idempotency compares the decision only; a repeated denial with a different reason retains the original reason and outcome. Same-decision terminal replay returns the recorded ToolCall without invoking the tool or model. Unknown IDs raise AK_ACTION_NOT_FOUND; a conflicting decision or a target that is no longer pending raises AK_ACTION_ALREADY_DECIDED. Tool failures are terminal and are fed to the model; retry requires a new proposal ID. A crash after claim leaves an indeterminate record for application reconciliation, never automatic side-effect retry. Serialize different calls in a conversation to protect transcript writes.

For a stuck claimed record, an operator must inspect get(id) and domain execution evidence, stop the original worker, and terminally settle the matching claim with a proven outcome or an explicit indeterminate failure. Never delete or reset the claim to pending. Reconcile the target call in current chat memory, then continue explicitly with a new user turn; any authorized retry needs a new proposal ID. See the operational recovery procedure in ADR 0042.

approve and deny are deprecated. With a decision store they delegate to decide and share its atomic claim and typed errors; without a store they retain generation-local behavior. See ADR 0042.

Features

  • createChatController — streaming-capable chat state machine with abort support; memory is saved after successful turns, never after failed or aborted turns. Background memory and skill activation failures are surfaced through onError.
  • createInMemoryMemory — zero-config in-process memory for prototyping
  • createLocalStorageMemory — browser/demo persistence; malformed stored data raises MemoryError instead of silently becoming an empty history
  • createStaticRetriever — deterministic token-overlap retrieval for demos and fallbacks; use @agentskit/rag for semantic production retrieval
  • parseToolArgs — typed JSON argument parsing for adapters that need fail-closed validation; safeParseArgs remains the compatibility helper
  • createId(prefix) — prefix plus a cryptographically random UUID; generateId(prefix) remains the compatibility helper used for messages and calls
  • TypeScript types for every contract: ToolDefinition, SkillDefinition, AgentEvent, Adapter, ChatMemory, Retriever, ChatController
  • Event emitter for AgentEvent streams — observability hooks attach here
  • AgentEvent.correlation is an optional, provider-neutral identity envelope: operationId is stable across boundaries while runId, sessionId, turnId, actionId, and traceId retain local meaning
  • Dual CJS/ESM output, strict TypeScript, no any
  • Static source guardrail rules are available from @agentskit/core/rules as CORE_RULES; they are intended for tooling and are not imported by the core runtime.

Error handling

AgentsKit ships a didactic error system inspired by the Rust compiler. Every error includes a code, a hint for the fix, and a docsUrl — no more vague "Something went wrong" messages.

import {
  AgentsKitError,
  AdapterError,
  ToolError,
  MemoryError,
  ConfigError,
  ErrorCodes,
} from '@agentskit/core'

try {
  await runtime.run(task)
} catch (err) {
  if (err instanceof ToolError) {
    // err.code     → 'AK_TOOL_EXEC_FAILED'
    // err.hint     → actionable suggestion
    // err.docsUrl  → https://www.agentskit.io/docs/agents/tools
    console.error(err.toString())
    // error[AK_TOOL_EXEC_FAILED]: ...
    //   --> Hint: ...
    //   --> Docs: https://www.agentskit.io/docs/agents/tools
  }
}

Available error codes (via ErrorCodes):

CodeThrown by
AK_ADAPTER_MISSINGadapter not provided to the controller
AK_ADAPTER_STREAM_FAILEDstreaming call to the provider fails
AK_TOOL_NOT_FOUNDrequested tool name is not registered
AK_TOOL_EXEC_FAILEDexecute() throws
AK_TOOL_PEER_MISSINGoptional tool peer dependency is not installed
AK_TOOL_INVALID_INPUTtool arguments or proposal are invalid
AK_TOOL_QUOTA_EXCEEDEDtool execution exceeds its configured quota
AK_TOOL_FORBIDDENtool execution is denied by policy
AK_MEMORY_LOAD_FAILEDmemory.load() fails
AK_MEMORY_SAVE_FAILEDmemory.save() fails
AK_MEMORY_CLEAR_FAILEDmemory.clear() fails
AK_MEMORY_DESERIALIZE_FAILEDpersisted state is corrupt
AK_MEMORY_PEER_MISSINGoptional memory backend is not installed
AK_MEMORY_REMOTE_HTTPremote memory request fails
AK_CONFIG_INVALIDrequired config is missing or wrong type
AK_RUNTIME_INVALID_INPUTruntime input is invalid
AK_RUNTIME_STEP_FAILEDa runtime step fails
AK_RUNTIME_DELEGATE_FAILEDdelegated agent execution fails
AK_SANDBOX_DENIEDsandbox policy denies execution
AK_SANDBOX_INVALID_TOOLtool is not valid for the sandbox
AK_SANDBOX_PEER_MISSINGoptional sandbox backend is not installed
AK_SANDBOX_BACKEND_FAILEDsandbox backend fails
AK_SKILL_INVALIDskill definition is invalid
AK_SKILL_DUPLICATEskill identity is duplicated

Type-safe tools with defineTool

defineTool infers the TypeScript type of execute's args parameter from the JSON Schema — no manual casting.

import { defineTool } from '@agentskit/core'

const greet = defineTool({
  name: 'greet',
  schema: {
    type: 'object',
    properties: { name: { type: 'string' } },
    required: ['name'],
  } as const,   // as const is required for inference
  execute(args) {
    // args.name → string  (inferred, not cast)
    return `Hello, ${args.name}!`
  },
})

Use InferSchemaType<typeof schema> to reference the inferred type elsewhere in your codebase.

Subpath exports (tree-shaken, zero main-bundle weight)

SubpathPurpose
@agentskit/core/agent-schemaDeclarative YAML/JSON agent definitions + validator
@agentskit/core/prompt-experimentsA/B prompts with PostHog / GrowthBook / custom flag providers
@agentskit/core/auto-summarizeChatMemory wrapper that folds old turns into a summary
@agentskit/core/hitlApproval gates + ApprovalStore
@agentskit/core/securityPII and secret redaction + injection detector + rate limiter
@agentskit/core/fuzzy-matchDeterministic Jaro-Winkler matching for KYC, sanctions, deduplication, and entity resolution
@agentskit/core/findingCanonical Finding / Severity shape for review and compliance results
@agentskit/core/compose-toolChain N tools into one macro tool
@agentskit/core/self-debugRetry failing tools with LLM-corrected arguments
@agentskit/core/generative-uiTyped UI element tree + code / markdown / html / chart artifacts
@agentskit/core/a2aAgent-to-Agent protocol spec (JSON-RPC over any transport)
@agentskit/core/manifestSkill + tool manifest format (MCP-compatible)
@agentskit/core/eval-formatPortable eval dataset + run-result JSON
@agentskit/core/memory-validationBounded validation for untrusted serialized memory records
@agentskit/core/tool-proposalPublic helper for routing a validated proposal through controller authorization
@agentskit/core/hashRFC 8785 canonical JSON and SHA-256 helpers

See the core guide for agents for the full contract.

Ecosystem

PackageRole
@agentskit/adaptersLLM chat + embedding providers, router, ensemble, fallback
@agentskit/runtimecreateRuntime, speculate, topologies, durable execution, background agents
@agentskit/reactuseChat, headless chat components
@agentskit/vue · svelte · solid · react-native · angularSame ChatReturn contract, one package per framework
@agentskit/toolsBuilt-in tools, 20+ integrations, MCP bridge
@agentskit/memoryChat + vector + hierarchical + encrypted + graph stores
@agentskit/ragPlug-and-play RAG + reranker + loaders
@agentskit/skillsReady-made personas + marketplace
@agentskit/observabilityTraces, audit log, cost guard, devtools
@agentskit/sandboxSecure code execution + mandatory sandbox policy
@agentskit/evalEval suites, deterministic replay, snapshots, CI reporter
@agentskit/cliagentskit init / chat / run / ai / dev / doctor

Contributors

AgentsKit contributors

License

MIT — see LICENSE.

Docs

Full documentation · GitHub

Maturity and compatibility

  • Stability: stable — see docs/STABILITY.md
  • Node.js 20+ and TypeScript strict mode
  • Published as @agentskit/core

Contributing

See CONTRIBUTING.md and the monorepo LICENSE.

版本与发布记录

@agentskit/core 共发布 36 个版本,首次发布于 2026/04/06;过去 12 个月发布了 36 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.15.0latest2026/10/1026 天前
1.14.12026/10/031 个月前
1.14.02026/10/031 个月前
1.13.02026/09/291 个月前
1.12.102026/09/261 个月前
1.12.92026/09/032 个月前

关于 @agentskit/core 的常见问题

@agentskit/core 是什么?

Portable AgentsKit runtime for chat orchestration, tools, memory, and retrieval.

如何安装 @agentskit/core?

在项目目录运行 npm install @agentskit/core,或使用 pnpm add / yarn add / bun add。

@agentskit/core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@agentskit/core 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@agentskit/core 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.19。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@agentskit/core 可以商用吗?

@agentskit/core 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@agentskit/core 的下载量有多少?

根据 npm 官方下载统计,@agentskit/core 在 2026/10/05 – 2026/11/03 这 30 天内被下载 37,669 次,日均约 1,256 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@agentskit/core 还在维护吗?

最新版本 1.15.0 发布于 2026/10/10(26 天前);至今共发布 36 个版本,其中过去 12 个月发布了 36 个;首次发布于 2026/04/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。