@cognipeer/agent-sdk 0.1.1 → 0.2.0

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 CHANGED
@@ -1,41 +1,79 @@
1
1
  # @cognipeer/agent-sdk
2
2
 
3
- Composable, message-first agent runtime with token-aware summarization, optional planning, and tool debugging baked in. Ships both ESM and CJS builds with full TypeScript types. LangChain is fully optional via a duck-typed adapter.
4
-
5
- ## Features
6
-
7
- - **Transparent tool turns** – assistant tool calls and tool responses live in `state.messages` so transcripts stay debuggable.
8
- - **Summarization pipeline** – large tool outputs are archived with reversible execution IDs; summaries keep context under token budgets.
9
- - **Planning mode** – enable `useTodoList` to expose the `manage_todo_list` tool and strict system prompt rules.
10
- - **Structured output** – pass a Zod schema to add a hidden `response` finalize tool and receive parsed JSON on `result.output`.
11
- - **Multi-agent composition** – reuse agents via `asTool` or transfer control mid-run via `asHandoff`.
12
- - **Usage normalization** – provider usage blobs are normalized and aggregated per model turn.
13
- - **Rich logging** – enable `debug.enabled` to emit Markdown snapshots under `logs/` or intercept them via `debug.callback`.
3
+ [![npm](https://img.shields.io/npm/v/@cognipeer/agent-sdk?color=success)](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
- # optional peers for quick starts
20
- npm install @langchain/core @langchain/openai
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
- `@langchain/core` is marked as an optional peer dependency – install it if you plan to use LangChain tools or models.
61
+ You can also bring your own model adapter as long as it exposes `invoke(messages[])` and (optionally) `bindTools()`.
24
62
 
25
- ## Usage
63
+ ## Quick start
26
64
 
27
- ### ESM quick start
65
+ ### Smart agent (planning + summarization)
28
66
 
29
67
  ```ts
30
- import { createSmartAgent, createSmartTool, fromLangchainModel } from "@cognipeer/agent-sdk";
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 = createSmartTool({
72
+ const echo = createTool({
35
73
  name: "echo",
36
- description: "Echo back the input text",
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,187 @@ 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: "Plan a greeting and deliver it via the echo tool" }],
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
- ### Custom adapters
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
- ### Vision / multimodal input
103
+ ### Base agent (minimal loop)
81
104
 
82
- Messages can contain OpenAI-style content parts:
105
+ Prefer a tiny core without system prompt or summarization? Use `createAgent`:
83
106
 
84
107
  ```ts
85
- await agent.invoke({
86
- messages: [{
87
- role: "user",
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.invoke({ messages: [{ role: "user", content: "say hi via echo" }] }).then(res => {
113
- console.log(res.content);
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
- ## API overview
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
+ To run examples:
162
+
163
+ ```bash
164
+ # Install root dependencies
165
+ npm install
118
166
 
119
- Exports from `dist/index.*`:
167
+ # Install example dependencies
168
+ cd examples
169
+ npm install
120
170
 
121
- - `createSmartAgent(options)` – smart wrapper with system prompt, planning tools, summarization.
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
+ # Run an example from the examples directory
172
+ npm run example:basic
173
+ npm run example:tools
174
+ npm run example:multi-agent
175
+ ```
176
+
177
+ Or run directly with tsx:
178
+
179
+ ```bash
180
+ # From examples directory
181
+ OPENAI_API_KEY=... npx tsx basic/basic.ts
182
+ ```
183
+
184
+ ## Architecture snapshot
185
+
186
+ The agent is a deterministic while-loop – no external graph runtime. Each turn flows through:
129
187
 
130
- ### SmartAgentOptions highlights
188
+ 1. **resolver** – normalize state (messages, counters, limits).
189
+ 2. **contextSummarize** (optional) – when token estimates exceed `limits.maxToken`, archive heavy tool outputs.
190
+ 3. **agent** – invoke the model (binding tools when supported).
191
+ 4. **tools** – execute proposed tool calls with configurable parallelism.
192
+ 5. **toolLimitFinalize** – if tool-call cap is hit, inject a system notice so the next assistant turn must answer directly.
131
193
 
132
- - `model`: required chat model adapter (must expose `invoke`).
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.
194
+ 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
195
 
142
- ### Structured output finalize
196
+ ## API surface
143
197
 
144
- When `outputSchema` is provided, the framework injects a hidden `response` tool. The model is instructed (via system prompt) to call it exactly once with the final JSON object. Parsed output appears on `result.output` and the loop stops automatically.
198
+ Exported helpers (`agent-sdk/src/index.ts`):
145
199
 
146
- ### Summarization internals
200
+ - `createSmartAgent(options)`
201
+ - `createAgent(options)`
202
+ - `createTool({ name, description?, schema, func })`
203
+ - `fromLangchainModel(model)`
204
+ - `withTools(model, tools)`
205
+ - `buildSystemPrompt(extra?, planning?, name?)`
206
+ - Node factories (`nodes/*`), context helpers, token utilities, and full TypeScript types (`SmartAgentOptions`, `SmartState`, `AgentInvokeResult`, etc.).
147
207
 
148
- - Token estimates use a lightweight `countApproxTokens` heuristic (~4 chars per token).
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`.
208
+ `SmartAgentOptions` accepts the usual suspects (`model`, `tools`, `limits`, `useTodoList`, `summarization`, `usageConverter`, `tracing`). See `docs/api/` for detailed type references.
151
209
 
152
- ## Debugging
210
+ ## Tracing & observability
153
211
 
154
- Enable logging with `debug.enabled: true`. By default Markdown files are written to `logs/<ISO_TIMESTAMP>/` containing:
212
+ Enable tracing by passing `tracing: { enabled: true }`. Each invocation writes `trace.session.json` into `logs/<SESSION_ID>/` detailing:
155
213
 
156
- - Model name, invocation limits, and raw usage (if reported).
157
- - Serialized tool schemas.
158
- - Message timeline with assistant/tool turns.
214
+ - Model/provider, agent name/version, limits, and timing metadata
215
+ - Structured events for model calls, tool executions, summaries, and errors
216
+ - Optional payload captures (request/response/tool bodies) when `logData` is `true`
217
+ - Aggregated token usage, byte counts, and error summaries for dashboards
159
218
 
160
- Provide `debug.callback` to receive the same payload programmatically (no files written).
219
+ 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
220
 
162
- ## Build
221
+ ## Development
163
222
 
164
- `tsup` bundles to `dist/index.js` (ESM) and `dist/index.cjs` (CJS) with declarations. Run:
223
+ Install dependencies and build the package:
165
224
 
166
225
  ```sh
226
+ cd agent-sdk
167
227
  npm install
168
228
  npm run build
169
229
  ```
170
230
 
171
- `prepublishOnly` also performs a build to keep the published artifact fresh.
231
+ 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`.
232
+
233
+ ### Publishing
234
+
235
+ Only publish `agent-sdk/`:
236
+
237
+ ```sh
238
+ cd agent-sdk
239
+ npm version <patch|minor|major>
240
+ npm publish --access public
241
+ ```
242
+
243
+ `prepublishOnly` ensures a fresh build before publishing.
244
+
245
+ ## Troubleshooting
246
+
247
+ - **Missing tool calls** – ensure your model supports `bindTools`. If not, wrap with `withTools(model, tools)` to provide best-effort behavior.
248
+ - **Summaries too aggressive** – adjust `limits.maxToken`, `contextTokenLimit`, and `summaryTokenLimit`, or disable with `summarization: false`.
249
+ - **Large tool responses** – return structured payloads and rely on `get_tool_response` for raw data instead of dumping megabytes inline.
250
+ - **Usage missing** – some providers do not report usage; customize `usageConverter` to normalize proprietary shapes.
172
251
 
173
- ## License
252
+ ## Documentation
174
253
 
175
- MIT
254
+ - Live site: https://cognipeer.github.io/agent-sdk/
255
+ - Key guides within this repo:
256
+ - `docs/getting-started/`
257
+ - `docs/core-concepts/`
258
+ - `docs/architecture/`
259
+ - `docs/api/`
260
+ - `docs/tools/`
261
+ - `docs/examples/`
262
+ - `docs/debugging/`
263
+ - `docs/limits-tokens/`
264
+ - `docs/tool-development/`
265
+ - `docs/faq/`
176
266
 
177
- ---
267
+ Contributions welcome! Open issues or PRs against `main` with reproduction details when reporting bugs.
178
268
 
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.