@gajae-code/agent-core

中文文档
0.21.0发布于 2026/11/16MITTypeScriptES Module构建来源已验证近 30 天下载 7490

General-purpose agent with transport abstraction, state management, and attachment support

原始使用文档
文档目录30 节
  1. Installation
  2. Quick Start
  3. Core Concepts
  4. AgentMessage vs LLM Message
  5. Message Flow
  6. Event Flow
  7. prompt() Event Sequence
  8. With Tool Calls
  9. continue() Event Sequence
  10. Event Types
  11. Agent Options
  12. Agent State
  13. Methods
  14. Prompting
  15. State Management
  16. Control
  17. Events
  18. Steering & Follow-up
  19. Custom Message Types
  20. Tools
  21. Error Handling
  22. Proxy Usage
  23. Low-Level API
  24. Run-level telemetry
  25. agent_end event (additive)
  26. onRunEnd hook (non-fatal)
  27. agentLoopDetailed (typed detailed() result)
  28. Multi-run aggregation
  29. Tool status reporting
  30. License

@gajae-code/agent-core

Stateful agent with tool execution and event streaming. Built on @gajae-code/ai.

Installation

npm install @gajae-code/agent-core

Quick Start

import { Agent } from "@gajae-code/agent-core";
import { getModel } from "@gajae-code/ai";

const agent = new Agent({
    initialState: {
        systemPrompt: ["You are a helpful assistant."],
        model: getModel("anthropic", "anthropic-model-sonnet-4-20250514"),
    },
});

agent.subscribe((event) => {
    if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
        // Stream just the new text chunk
        process.stdout.write(event.assistantMessageEvent.delta);
    }
});

await agent.prompt("Hello!");

Core Concepts

AgentMessage vs LLM Message

The agent works with AgentMessage, a flexible type that can include:

  • Standard LLM messages (user, assistant, toolResult)
  • Custom app-specific message types via declaration merging

LLMs only understand user, assistant, and toolResult. The convertToLlm function bridges this gap by filtering and transforming messages before each LLM call.

Message Flow

AgentMessage[] → transformContext() → AgentMessage[] → convertToLlm() → Message[] → LLM
                    (optional)                           (required)
  1. transformContext: Prune old messages, inject external context
  2. convertToLlm: Filter out UI-only messages, convert custom types to LLM format

Event Flow

The agent emits events for UI updates. Understanding the event sequence helps build responsive interfaces.

prompt() Event Sequence

When you call prompt("Hello"):

prompt("Hello")
├─ agent_start
├─ turn_start
├─ message_start   { message: userMessage }      // Your prompt
├─ message_end     { message: userMessage }
├─ message_start   { message: assistantMessage } // LLM starts responding
├─ message_update  { message: partial... }       // Streaming chunks
├─ message_update  { message: partial... }
├─ message_end     { message: assistantMessage } // Complete response
├─ turn_end           { message, toolResults: [] }
└─ agent_end       { messages: [...] }

When a provider or local run failure occurs, the agent emits agent_failed before the terminal agent_end:

{ type: "agent_failed", error, scope? }
// ...then
{ type: "agent_end", messages, stopReason: "error" }

agent_failed is diagnostic and correlated to the same attempt; consumers must not treat it as the terminal boundary or stop waiting for agent_end. The failure event is additive, so existing agent_end handling remains required.

agent_failed.error is always a sanitized { code, message } pair produced by the runtime's failure sanitizer before emission — never the raw provider error. Consumers must not depend on provider-specific detail, request bodies, or raw error objects in this payload; the code is a stable classifier and the message is a fixed human-readable description.

With Tool Calls

If the assistant calls tools, the loop continues:

prompt("Read config.json")
├─ agent_start
├─ turn_start
├─ message_start/end  { userMessage }
├─ message_start      { assistantMessage with toolCall }
├─ message_update...
├─ message_end        { assistantMessage }
├─ tool_execution_start  { toolCallId, toolName, args }
├─ tool_execution_update { partialResult }           // If tool streams
├─ tool_execution_end    { toolCallId, result }
├─ message_start/end  { toolResultMessage }
├─ turn_end           { message, toolResults: [toolResult] }
│
├─ turn_start                                        // Next turn
├─ message_start      { assistantMessage }           // LLM responds to tool result
├─ message_update...
├─ message_end
├─ turn_end
└─ agent_end

continue() Event Sequence

continue() resumes from existing context without adding a new message. Use it for retries after errors.

// After an error, retry from current state
await agent.continue();

The last message in context must be user or toolResult (not assistant).

Event Types

EventDescription
agent_startAgent begins processing
agent_failedProvider/local failure diagnostic; emitted before terminal agent_end
agent_endAgent completes with all new messages
turn_startNew turn begins (one LLM call + tool executions)
turn_endTurn completes with assistant message and tool results
message_startAny message begins (user, assistant, toolResult)
message_updateAssistant only. Includes assistantMessageEvent with delta
message_endMessage completes
tool_execution_startTool begins
tool_execution_updateTool streams progress
tool_execution_endTool completes

Agent Options

const agent = new Agent({
  // Initial state
  initialState: {
    systemPrompt: string[],
    model: Model,
    thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh",
    tools: AgentTool<any>[],
    messages: AgentMessage[],
  },

  // Convert AgentMessage[] to LLM Message[] (required for custom message types)
  convertToLlm: (messages) => messages.filter(...),

  // Transform context before convertToLlm (for pruning, compaction)
  transformContext: async (messages, signal) => pruneOldMessages(messages),

  // How to handle queued messages: "one-at-a-time" (default) or "all"
  queueMode: "one-at-a-time",

  // Custom stream function (for proxy backends)
  streamFn: streamProxy,

  // Dynamic API key resolution (for expiring OAuth tokens)
  getApiKey: async (provider) => refreshToken(),

  // Tool execution context (late-bound UI/session access)
  getToolContext: () => ({ /* app-defined */ }),
});

Agent State

interface AgentState {
    systemPrompt: string[];
    model: Model;
    thinkingLevel: ThinkingLevel;
    tools: AgentTool<any>[];
    messages: AgentMessage[];
    isStreaming: boolean;
    streamMessage: AgentMessage | null; // Current partial during streaming
    pendingToolCalls: Set<string>;
    error?: string;
}

Access via agent.state. During streaming, streamMessage contains the partial assistant message.

Methods

Prompting

// Text prompt
await agent.prompt("Hello");

// With images
await agent.prompt("What's in this image?", [{ type: "image", data: base64Data, mimeType: "image/jpeg" }]);

// AgentMessage directly
await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });

// Continue from current context (last message must be user or toolResult)
await agent.continue();

State Management

agent.setSystemPrompt("New prompt");
agent.setModel(getModel("openai", "gpt-4o"));
agent.setThinkingLevel("medium");
agent.setTools([myTool]);
agent.replaceMessages(newMessages);
agent.appendMessage(message);
agent.clearMessages();
agent.reset(); // Clear everything

Control

agent.abort(); // Cancel current operation
await agent.waitForIdle(); // Wait for completion

Events

const unsubscribe = agent.subscribe((event) => {
    console.log(event.type);
});
unsubscribe();

Steering & Follow-up

Queue messages to inject during tool execution (steering) or after the agent would otherwise stop (follow-up):

agent.setSteeringMode("one-at-a-time");
agent.setToolInterruptPolicy("abort_tools");

// A steer is admitted ONLY into a live, non-aborted run.
const admission = agent.steer({
    role: "user",
    content: "Stop! Do this instead.",
    timestamp: Date.now(),
});
if (!admission.admitted) {
    // admission.reason is "idle" (no run to steer) or "aborting" (the run is
    // winding down). Nothing was queued: the caller owns routing the message,
    // e.g. as a fresh prompt or a follow-up of the next turn.
}

// Queue a follow-up to run after the current turn completes
agent.followUp({
    role: "user",
    content: "After that, summarize the changes.",
    timestamp: Date.now(),
});

Steering messages are checked after each tool call by default. Set toolInterruptPolicy to "finish_tools" to let the running tool batch finish before the steering turn opens; the steer is still consumed at the next tool/turn boundary either way.

A run that ends (completed, aborted, or error) never keeps steering it did not consume: the Agent clears its queue and reports the messages on agent_end.disownedSteering, so the owner decides once whether to re-route or drop them.

Custom Message Types

Extend AgentMessage via declaration merging:

declare module "@gajae-code/agent-core" {
    interface CustomAgentMessages {
        notification: { role: "notification"; text: string; timestamp: number };
    }
}

// Now valid
const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };

Handle custom types in convertToLlm:

const agent = new Agent({
    convertToLlm: (messages) =>
        messages.flatMap((m) => {
            if (m.role === "notification") return []; // Filter out
            return [m];
        }),
});

Tools

Define tools using AgentTool with a Zod parameter schema (via z from @gajae-code/ai).

import { z } from "@gajae-code/ai";

const readFileTool: AgentTool = {
    name: "read_file",
    label: "Read File", // For UI display
    description: "Read a file's contents",
    parameters: z.object({
        path: z.string().describe("File path"),
    }),
    execute: async (toolCallId, params, signal, onUpdate, context) => {
        const content = await fs.readFile(params.path, "utf-8");

        // Optional: stream progress
        onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });

        return {
            content: [{ type: "text", text: content }],
            details: { path: params.path, size: content.length },
        };
    },
};

agent.setTools([readFileTool]);

Error Handling

Throw an error when a tool fails. Do not return error messages as content.

execute: async (toolCallId, params, signal, onUpdate) => {
    if (!fs.existsSync(params.path)) {
        throw new Error(`File not found: ${params.path}`);
    }
    // Return content only on success
    return { content: [{ type: "text", text: "..." }] };
};

Thrown errors are caught by the agent and reported to the LLM as tool errors with isError: true.

Proxy Usage

For browser apps that proxy through a backend:

import { Agent, streamProxy } from "@gajae-code/agent-core";

const agent = new Agent({
    streamFn: (model, context, options) =>
        streamProxy(model, context, {
            ...options,
            authToken: "...",
            proxyUrl: "https://your-server.com",
        }),
});

Low-Level API

For direct control without the Agent class:

import { agentLoop, agentLoopContinue } from "@gajae-code/agent-core";

const context: AgentContext = {
    systemPrompt: ["You are helpful."],
    messages: [],
    tools: [],
};

const config: AgentLoopConfig = {
    model: getModel("openai", "gpt-4o"),
    convertToLlm: (msgs) => msgs.filter((m) => ["user", "assistant", "toolResult"].includes(m.role)),
};

const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };

for await (const event of agentLoop([userMessage], context, config)) {
    console.log(event.type);
}

// Continue from existing context
for await (const event of agentLoopContinue(context, config)) {
    console.log(event.type);
}

Run-level telemetry

Every invoke_agent produces two values alongside the OTEL spans:

  • AgentRunSummary — chat / tool / usage / cost / error counters bucketed by status, with per-tool-name breakdowns. Pure aggregation, safe to persist, diff, or assert.
  • AgentRunCoverage — sorted+deduped toolsAvailable / toolsInvoked / toolsUnused / modelsUsed / providersUsed arrays. Stable for snapshot tests.

Three delivery channels (use whichever fits):

agent_end event (additive)

for await (const event of agentLoop([userMessage], context, {
    ...config,
    telemetry: {},
})) {
    if (event.type === "agent_end" && event.telemetry) {
        console.log("tokens:", event.telemetry.usage.totalTokens);
        console.log("unused tools:", event.coverage?.toolsUnused);
    }
}

The messages field is unchanged. Consumers that ignore telemetry/ coverage continue to work.

onRunEnd hook (non-fatal)

const stream = agentLoop([userMessage], context, {
    ...config,
    telemetry: {
        onRunEnd: (summary, coverage) => {
            await persistRunSummary(summary, coverage);
        },
    },
});

Exceptions thrown from onRunEnd are caught and logged via console.warn; a misbehaving telemetry consumer can never turn a successful agent run into a failed one.

agentLoopDetailed (typed detailed() result)

Convenience wrapper that preserves the existing stream API and exposes the rollup as a typed value:

const { stream, detailed } = agentLoopDetailed([userMessage], context, {
    ...config,
    telemetry: {}, // required to populate telemetry/coverage
});

for await (const event of stream) {
    // existing event handling
}

const { messages, telemetry, coverage } = await detailed();

stream.result() still resolves to AgentMessage[] — no breaking change.

Multi-run aggregation

Callers that drive the loop multiple times (verify pass, benchmark harness) fold N summaries with aggregateAgentRunSummaries / aggregateAgentRunCoverage:

import {
    aggregateAgentRunSummaries,
    aggregateAgentRunCoverage,
} from "@gajae-code/agent-core";

const summaries: AgentRunSummary[] = [];
const coverages: AgentRunCoverage[] = [];
for (const target of targets) {
    const { detailed } = agentLoopDetailed(/* ... */);
    const result = await detailed();
    if (result.telemetry) summaries.push(result.telemetry);
    if (result.coverage) coverages.push(result.coverage);
}
const runSummary = aggregateAgentRunSummaries(summaries);
const runCoverage = aggregateAgentRunCoverage(coverages);

Tool status reporting

execute_tool spans carry pi.gen_ai.tool.status ∈ "ok" | "error" | "skipped" | "blocked" | "timeout" | "aborted". beforeToolCall blocks throw a distinguishable ToolCallBlockedError internally; the catch path reports status: "blocked" instead of conflating with generic tool errors. Pre-run interrupts and tail-sweep skips are recorded as "skipped" even though they never start a span.

License

MIT

版本与发布记录

@gajae-code/agent-core 共发布 158 个版本,首次发布于 2026/05/28;过去 12 个月发布了 158 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.21.0latest2026/11/16今天
0.20.1-nightly.20261108030927.43711868338.gb4127889c4a8nightly2026/11/15今天
0.20.1-nightly.20261108030927.43590872198.gb4127889c4a82026/11/141 天前
0.20.1-nightly.20261108030927.43424588966.gb4127889c4a82026/11/132 天前
0.20.1-nightly.20261108030927.43222623203.gb4127889c4a82026/11/123 天前
0.20.1-nightly.20261108030927.43016219422.gb4127889c4a82026/11/114 天前

关于 @gajae-code/agent-core 的常见问题

@gajae-code/agent-core 是什么?

General-purpose agent with transport abstraction, state management, and attachment support

如何安装 @gajae-code/agent-core?

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

@gajae-code/agent-core 支持 TypeScript 吗?

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

@gajae-code/agent-core 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gajae-code/agent-core 可以商用吗?

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

@gajae-code/agent-core 的下载量有多少?

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

@gajae-code/agent-core 还在维护吗?

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