@cognipeer/agent-sdk 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -103
- package/dist/index.cjs +2014 -421
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +529 -111
- package/dist/index.d.ts +529 -111
- package/dist/index.mjs +2822 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +42 -26
- package/dist/index.js +0 -1212
- package/dist/index.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,41 +1,79 @@
|
|
|
1
1
|
# @cognipeer/agent-sdk
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
-
|
|
10
|
-
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
-
|
|
3
|
+
[](https://npmjs.com/package/@cognipeer/agent-sdk) [Docs Website](https://cognipeer.github.io/agent-sdk/)
|
|
4
|
+
|
|
5
|
+
Lightweight, message-first agent runtime that keeps tool calls transparent, automatically summarizes long histories, and ships with planning, multi-agent handoffs, and structured tracing.
|
|
6
|
+
|
|
7
|
+
- SDK source: `src/`
|
|
8
|
+
- Examples: `examples/`
|
|
9
|
+
- Docs (VitePress): `docs/`
|
|
10
|
+
- Requires Node.js **18.17+**
|
|
11
|
+
|
|
12
|
+
## Table of contents
|
|
13
|
+
- [Overview](#overview)
|
|
14
|
+
- [What’s inside](#whats-inside)
|
|
15
|
+
- [Install](#install)
|
|
16
|
+
- [Quick start](#quick-start)
|
|
17
|
+
- [Smart agent (planning + summarization)](#smart-agent-planning--summarization)
|
|
18
|
+
- [Base agent (minimal loop)](#base-agent-minimal-loop)
|
|
19
|
+
- [Key capabilities](#key-capabilities)
|
|
20
|
+
- [Examples](#examples)
|
|
21
|
+
- [Architecture snapshot](#architecture-snapshot)
|
|
22
|
+
- [API surface](#api-surface)
|
|
23
|
+
- [Tracing & observability](#tracing--observability)
|
|
24
|
+
- [Development](#development)
|
|
25
|
+
- [Troubleshooting](#troubleshooting)
|
|
26
|
+
- [Documentation](#documentation)
|
|
27
|
+
|
|
28
|
+
## Overview
|
|
29
|
+
|
|
30
|
+
`@cognipeer/agent-sdk` is a zero-graph, TypeScript-first agent loop. Tool calls are persisted as messages, token pressure triggers automatic summarization, and optional planning mode enforces TODO hygiene with the bundled `manage_todo_list` tool. Multi-agent composition, structured output, and batched tracing are built-in.
|
|
31
|
+
|
|
32
|
+
Highlights:
|
|
33
|
+
- **Message-first design** – assistant tool calls and tool responses stay in the transcript.
|
|
34
|
+
- **Token-aware summarization** – chunked rewriting archives oversized tool outputs while exposing `get_tool_response` for lossless retrieval.
|
|
35
|
+
- **Planning mode** – strict system prompt + TODO tool keeps one task in progress and emits plan events.
|
|
36
|
+
- **Structured output** – provide a Zod schema and the agent injects a finalize tool to capture JSON deterministically.
|
|
37
|
+
- **Multi-agent and handoffs** – wrap agents as tools or transfer control mid-run with `asTool` / `asHandoff`.
|
|
38
|
+
- **Usage + events** – normalize provider usage, surface `tool_call`, `plan`, `summarization`, `metadata`, and `handoff` events.
|
|
39
|
+
- **Structured tracing** – optional per-invoke JSON traces with metadata, payload capture, and pluggable sinks (file, HTTP, Cognipeer, custom).
|
|
40
|
+
|
|
41
|
+
## What’s inside
|
|
42
|
+
|
|
43
|
+
| Path | Description |
|
|
44
|
+
|------|-------------|
|
|
45
|
+
| `src/` | Source for the published package (TypeScript, bundled via tsup). |
|
|
46
|
+
| `examples/` | End-to-end scripts demonstrating tools, planning, summarization, multi-agent, MCP, structured output, and vision input. |
|
|
47
|
+
| `docs/` | VitePress documentation site served at [cognipeer.github.io/agent-sdk](https://cognipeer.github.io/agent-sdk/). |
|
|
48
|
+
| `dist/` | Build output (generated). Contains ESM, CommonJS, and TypeScript definitions. |
|
|
49
|
+
| `logs/` | Generated trace sessions when `tracing.enabled: true`. Safe to delete. |
|
|
14
50
|
|
|
15
51
|
## Install
|
|
16
52
|
|
|
53
|
+
Install the SDK and its (optional) LangChain peer dependency:
|
|
54
|
+
|
|
17
55
|
```sh
|
|
18
|
-
npm install @cognipeer/agent-sdk zod
|
|
19
|
-
#
|
|
20
|
-
npm install @langchain/
|
|
56
|
+
npm install @cognipeer/agent-sdk @langchain/core zod
|
|
57
|
+
# Optional: LangChain OpenAI bindings for quick starts
|
|
58
|
+
npm install @langchain/openai
|
|
21
59
|
```
|
|
22
60
|
|
|
23
|
-
|
|
61
|
+
You can also bring your own model adapter as long as it exposes `invoke(messages[])` and (optionally) `bindTools()`.
|
|
24
62
|
|
|
25
|
-
##
|
|
63
|
+
## Quick start
|
|
26
64
|
|
|
27
|
-
###
|
|
65
|
+
### Smart agent (planning + summarization)
|
|
28
66
|
|
|
29
67
|
```ts
|
|
30
|
-
import { createSmartAgent,
|
|
68
|
+
import { createSmartAgent, createTool, fromLangchainModel } from "@cognipeer/agent-sdk";
|
|
31
69
|
import { ChatOpenAI } from "@langchain/openai";
|
|
32
70
|
import { z } from "zod";
|
|
33
71
|
|
|
34
|
-
const echo =
|
|
72
|
+
const echo = createTool({
|
|
35
73
|
name: "echo",
|
|
36
|
-
description: "Echo back
|
|
74
|
+
description: "Echo back user text",
|
|
37
75
|
schema: z.object({ text: z.string().min(1) }),
|
|
38
|
-
func: async ({ text }) => ({ echoed: text })
|
|
76
|
+
func: async ({ text }) => ({ echoed: text })
|
|
39
77
|
});
|
|
40
78
|
|
|
41
79
|
const model = fromLangchainModel(new ChatOpenAI({
|
|
@@ -44,136 +82,172 @@ const model = fromLangchainModel(new ChatOpenAI({
|
|
|
44
82
|
}));
|
|
45
83
|
|
|
46
84
|
const agent = createSmartAgent({
|
|
85
|
+
name: "ResearchHelper",
|
|
47
86
|
model,
|
|
48
87
|
tools: [echo],
|
|
49
|
-
limits: { maxToolCalls: 5, maxToken: 6000 },
|
|
50
88
|
useTodoList: true,
|
|
89
|
+
limits: { maxToolCalls: 5, maxToken: 8000 },
|
|
90
|
+
tracing: { enabled: true },
|
|
51
91
|
});
|
|
52
92
|
|
|
53
93
|
const result = await agent.invoke({
|
|
54
|
-
messages: [{ role: "user", content: "
|
|
94
|
+
messages: [{ role: "user", content: "plan a greeting and send it via the echo tool" }],
|
|
95
|
+
toolHistory: [],
|
|
55
96
|
});
|
|
56
97
|
|
|
57
98
|
console.log(result.content);
|
|
58
99
|
```
|
|
59
100
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
The runtime only requires `invoke(messages[]) => assistantMessage` and (optionally) `bindTools()`. To use a bespoke SDK, wrap it:
|
|
63
|
-
|
|
64
|
-
```ts
|
|
65
|
-
const model = {
|
|
66
|
-
async invoke(messages) {
|
|
67
|
-
const payload = messages.map(m => ({ role: m.role, content: m.content }));
|
|
68
|
-
const response = await myClient.chat({ messages: payload });
|
|
69
|
-
return { role: "assistant", content: response.output, tool_calls: response.tool_calls };
|
|
70
|
-
},
|
|
71
|
-
bindTools(tools) {
|
|
72
|
-
this._tools = tools;
|
|
73
|
-
return this;
|
|
74
|
-
}
|
|
75
|
-
};
|
|
76
|
-
|
|
77
|
-
const agent = createAgent({ model, tools: [...], limits: { maxToolCalls: 3 } });
|
|
78
|
-
```
|
|
101
|
+
The smart wrapper injects a system prompt, manages TODO tooling, and runs summarization passes whenever `limits.maxToken` would be exceeded.
|
|
79
102
|
|
|
80
|
-
###
|
|
103
|
+
### Base agent (minimal loop)
|
|
81
104
|
|
|
82
|
-
|
|
105
|
+
Prefer a tiny core without system prompt or summarization? Use `createAgent`:
|
|
83
106
|
|
|
84
107
|
```ts
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
content: [
|
|
89
|
-
{ type: "text", text: "Describe this image" },
|
|
90
|
-
{ type: "image_url", image_url: { url: "https://example.com/cat.jpg", detail: "low" } },
|
|
91
|
-
],
|
|
92
|
-
}],
|
|
93
|
-
});
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
### CommonJS
|
|
97
|
-
|
|
98
|
-
```js
|
|
99
|
-
const { createSmartAgent, createTool, fromLangchainModel } = require("@cognipeer/agent-sdk");
|
|
100
|
-
const { ChatOpenAI } = require("@langchain/openai");
|
|
101
|
-
const { z } = require("zod");
|
|
108
|
+
import { createAgent, createTool, fromLangchainModel } from "@cognipeer/agent-sdk";
|
|
109
|
+
import { ChatOpenAI } from "@langchain/openai";
|
|
110
|
+
import { z } from "zod";
|
|
102
111
|
|
|
103
112
|
const echo = createTool({
|
|
104
113
|
name: "echo",
|
|
114
|
+
description: "Echo back",
|
|
105
115
|
schema: z.object({ text: z.string().min(1) }),
|
|
106
116
|
func: async ({ text }) => ({ echoed: text }),
|
|
107
117
|
});
|
|
108
118
|
|
|
109
119
|
const model = fromLangchainModel(new ChatOpenAI({ model: "gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY }));
|
|
110
|
-
const agent = createSmartAgent({ model, tools: [echo] });
|
|
111
120
|
|
|
112
|
-
agent
|
|
113
|
-
|
|
121
|
+
const agent = createAgent({
|
|
122
|
+
model,
|
|
123
|
+
tools: [echo],
|
|
124
|
+
limits: { maxToolCalls: 3, maxParallelTools: 2 },
|
|
114
125
|
});
|
|
126
|
+
|
|
127
|
+
const res = await agent.invoke({ messages: [{ role: "user", content: "say hi via echo" }] });
|
|
128
|
+
console.log(res.content);
|
|
115
129
|
```
|
|
116
130
|
|
|
117
|
-
##
|
|
131
|
+
## Key capabilities
|
|
132
|
+
|
|
133
|
+
- **Summarization pipeline** – automatic chunking keeps tool call history within `contextTokenLimit` / `summaryTokenLimit`, archiving originals so `get_tool_response` can fetch them later.
|
|
134
|
+
- **Planning discipline** – when `useTodoList` is true the system prompt enforces a plan-first workflow and emits `plan` events as todos change.
|
|
135
|
+
- **Structured output** – supply `outputSchema` and the framework adds a hidden `response` finalize tool; parsed JSON is returned as `result.output`.
|
|
136
|
+
- **Usage normalization** – provider `usage` blobs are normalized into `{ prompt_tokens, completion_tokens, total_tokens }` with cached token tracking and totals grouped by model.
|
|
137
|
+
- **Multi-agent orchestration** – reuse agents via `agent.asTool({ toolName })` or perform handoffs that swap runtimes mid-execution.
|
|
138
|
+
- **MCP + LangChain tools** – any object satisfying the minimal tool interface works; LangChain’s `Tool` implementations plug in directly.
|
|
139
|
+
- **Vision input** – message parts accept OpenAI-style `image_url` entries (see `examples/vision`).
|
|
140
|
+
- **Observability hooks** – `config.onEvent` surfaces tool lifecycle, summarization, metadata, and final answer events for streaming UIs or CLIs.
|
|
141
|
+
|
|
142
|
+
## Examples
|
|
143
|
+
|
|
144
|
+
Examples live under `examples/` with per-folder READMEs. Build the package first (`npm run build` or `npm run preexample:<name>`).
|
|
145
|
+
|
|
146
|
+
| Folder | Focus |
|
|
147
|
+
|--------|-------|
|
|
148
|
+
| `basic/` | Minimal tool call run with real model. |
|
|
149
|
+
| `tools/` | Multiple tools, Tavily search integration, `onEvent` usage. |
|
|
150
|
+
| `tool-limit/` | Hitting the global tool-call cap and finalize behavior. |
|
|
151
|
+
| `todo-planning/` | Smart planning workflow with enforced TODO updates. |
|
|
152
|
+
| `summarization/` | Token-threshold summarization walkthrough. |
|
|
153
|
+
| `summarize-context/` | Summaries + `get_tool_response` raw retrieval. |
|
|
154
|
+
| `structured-output/` | Zod schema finalize tool and parsed outputs. |
|
|
155
|
+
| `rewrite-summary/` | Continue conversations after summaries are injected. |
|
|
156
|
+
| `multi-agent/` | Delegating between agents via `asTool`. |
|
|
157
|
+
| `handoff/` | Explicit runtime handoffs. |
|
|
158
|
+
| `mcp-tavily/` | MCP remote tool discovery. |
|
|
159
|
+
| `vision/` | Text + image input using LangChain’s OpenAI bindings. |
|
|
160
|
+
|
|
161
|
+
Run directly with `tsx`, for example:
|
|
162
|
+
|
|
163
|
+
```sh
|
|
164
|
+
# from repo root
|
|
165
|
+
npm run build
|
|
166
|
+
OPENAI_API_KEY=... npx tsx examples/tools/tools.ts
|
|
167
|
+
```
|
|
118
168
|
|
|
119
|
-
|
|
169
|
+
## Architecture snapshot
|
|
120
170
|
|
|
121
|
-
-
|
|
122
|
-
- `createAgent(options)` – minimal loop without system prompt or summarization.
|
|
123
|
-
- `createSmartTool({ name, description?, schema, func })` – helper for Zod-backed tools.
|
|
124
|
-
- `createTool(...)` – alias kept for migration.
|
|
125
|
-
- `fromLangchainModel(model)` – duck-type adapter for LangChain `ChatModel` / `Runnable` objects.
|
|
126
|
-
- `withTools(model, tools)` – best-effort tool binding helper.
|
|
127
|
-
- `buildSystemPrompt(extra?, planning?, name?)` – construct the internal system prompt.
|
|
128
|
-
- Node factories (`nodes/*`), context helpers, token utilities, and full TypeScript types (`SmartAgentOptions`, `SmartState`, `AgentInvokeResult`, etc.).
|
|
171
|
+
The agent is a deterministic while-loop – no external graph runtime. Each turn flows through:
|
|
129
172
|
|
|
130
|
-
|
|
173
|
+
1. **resolver** – normalize state (messages, counters, limits).
|
|
174
|
+
2. **contextSummarize** (optional) – when token estimates exceed `limits.maxToken`, archive heavy tool outputs.
|
|
175
|
+
3. **agent** – invoke the model (binding tools when supported).
|
|
176
|
+
4. **tools** – execute proposed tool calls with configurable parallelism.
|
|
177
|
+
5. **toolLimitFinalize** – if tool-call cap is hit, inject a system notice so the next assistant turn must answer directly.
|
|
131
178
|
|
|
132
|
-
|
|
133
|
-
- `tools`: array of tool implementations (LangChain `Tool`, MCP adapters, or plain objects implementing `invoke`/`call`).
|
|
134
|
-
- `limits`: `{ maxToolCalls?, maxParallelTools?, maxToken?, contextTokenLimit?, summaryTokenLimit? }`.
|
|
135
|
-
- `useTodoList`: enable planning rules and `manage_todo_list` tool.
|
|
136
|
-
- `summarization`: set to `false` to disable summarization entirely.
|
|
137
|
-
- `outputSchema`: Zod schema for structured output parse + finalize tool.
|
|
138
|
-
- `usageConverter`: hook to normalize provider-specific usage shapes.
|
|
139
|
-
- `debug`: `{ enabled: boolean, path?, callback? }` for Markdown logs.
|
|
140
|
-
- `onEvent`: receive `tool_call`, `plan`, `summarization`, `metadata`, `handoff`, and `finalAnswer` events per invoke.
|
|
179
|
+
The loop stops when the assistant produces a message without tool calls, a structured output finalize signal is observed, or a handoff transfers control. See `docs/architecture/README.md` for diagrams and heuristics.
|
|
141
180
|
|
|
142
|
-
|
|
181
|
+
## API surface
|
|
143
182
|
|
|
144
|
-
|
|
183
|
+
Exported helpers (`agent-sdk/src/index.ts`):
|
|
145
184
|
|
|
146
|
-
|
|
185
|
+
- `createSmartAgent(options)`
|
|
186
|
+
- `createAgent(options)`
|
|
187
|
+
- `createTool({ name, description?, schema, func })`
|
|
188
|
+
- `fromLangchainModel(model)`
|
|
189
|
+
- `withTools(model, tools)`
|
|
190
|
+
- `buildSystemPrompt(extra?, planning?, name?)`
|
|
191
|
+
- Node factories (`nodes/*`), context helpers, token utilities, and full TypeScript types (`SmartAgentOptions`, `SmartState`, `AgentInvokeResult`, etc.).
|
|
147
192
|
|
|
148
|
-
|
|
149
|
-
- When the next model turn would exceed `limits.maxToken`, the contextSummarize node chunk-summarizes tool responses into concise briefs while archiving originals in `state.toolHistoryArchived`.
|
|
150
|
-
- `get_tool_response` lets the model request the raw payload later using `executionId`.
|
|
193
|
+
`SmartAgentOptions` accepts the usual suspects (`model`, `tools`, `limits`, `useTodoList`, `summarization`, `usageConverter`, `tracing`). See `docs/api/` for detailed type references.
|
|
151
194
|
|
|
152
|
-
##
|
|
195
|
+
## Tracing & observability
|
|
153
196
|
|
|
154
|
-
Enable
|
|
197
|
+
Enable tracing by passing `tracing: { enabled: true }`. Each invocation writes `trace.session.json` into `logs/<SESSION_ID>/` detailing:
|
|
155
198
|
|
|
156
|
-
- Model name,
|
|
157
|
-
-
|
|
158
|
-
-
|
|
199
|
+
- Model/provider, agent name/version, limits, and timing metadata
|
|
200
|
+
- Structured events for model calls, tool executions, summaries, and errors
|
|
201
|
+
- Optional payload captures (request/response/tool bodies) when `logData` is `true`
|
|
202
|
+
- Aggregated token usage, byte counts, and error summaries for dashboards
|
|
159
203
|
|
|
160
|
-
|
|
204
|
+
You can disable payload capture with `logData: false` to keep only metrics, or configure sinks such as `httpSink(url, headers?)`, `cognipeerSink(apiKey, url?)`, or `customSink({ onEvent, onSession })` to forward traces after each run. Sensitive headers/callbacks remain in-memory and are never written alongside the trace.
|
|
161
205
|
|
|
162
|
-
##
|
|
206
|
+
## Development
|
|
163
207
|
|
|
164
|
-
|
|
208
|
+
Install dependencies and build the package:
|
|
165
209
|
|
|
166
210
|
```sh
|
|
211
|
+
cd agent-sdk
|
|
167
212
|
npm install
|
|
168
213
|
npm run build
|
|
169
214
|
```
|
|
170
215
|
|
|
171
|
-
|
|
216
|
+
From the repo root you can run `npm run build` (delegates to the package) or use `npm run example:<name>` scripts defined in `package.json`.
|
|
217
|
+
|
|
218
|
+
### Publishing
|
|
219
|
+
|
|
220
|
+
Only publish `agent-sdk/`:
|
|
221
|
+
|
|
222
|
+
```sh
|
|
223
|
+
cd agent-sdk
|
|
224
|
+
npm version <patch|minor|major>
|
|
225
|
+
npm publish --access public
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
`prepublishOnly` ensures a fresh build before publishing.
|
|
229
|
+
|
|
230
|
+
## Troubleshooting
|
|
231
|
+
|
|
232
|
+
- **Missing tool calls** – ensure your model supports `bindTools`. If not, wrap with `withTools(model, tools)` to provide best-effort behavior.
|
|
233
|
+
- **Summaries too aggressive** – adjust `limits.maxToken`, `contextTokenLimit`, and `summaryTokenLimit`, or disable with `summarization: false`.
|
|
234
|
+
- **Large tool responses** – return structured payloads and rely on `get_tool_response` for raw data instead of dumping megabytes inline.
|
|
235
|
+
- **Usage missing** – some providers do not report usage; customize `usageConverter` to normalize proprietary shapes.
|
|
172
236
|
|
|
173
|
-
##
|
|
237
|
+
## Documentation
|
|
174
238
|
|
|
175
|
-
|
|
239
|
+
- Live site: https://cognipeer.github.io/agent-sdk/
|
|
240
|
+
- Key guides within this repo:
|
|
241
|
+
- `docs/getting-started/`
|
|
242
|
+
- `docs/core-concepts/`
|
|
243
|
+
- `docs/architecture/`
|
|
244
|
+
- `docs/api/`
|
|
245
|
+
- `docs/tools/`
|
|
246
|
+
- `docs/examples/`
|
|
247
|
+
- `docs/debugging/`
|
|
248
|
+
- `docs/limits-tokens/`
|
|
249
|
+
- `docs/tool-development/`
|
|
250
|
+
- `docs/faq/`
|
|
176
251
|
|
|
177
|
-
|
|
252
|
+
Contributions welcome! Open issues or PRs against `main` with reproduction details when reporting bugs.
|
|
178
253
|
|
|
179
|
-
LangChain remains an optional peer – install it only if you need its tools or models. The core runtime has no hard dependency on LangChain message classes or graph libraries.
|