@cognipeer/agent-sdk 0.1.1

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 ADDED
@@ -0,0 +1,179 @@
1
+ # @cognipeer/agent-sdk
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`.
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ npm install @cognipeer/agent-sdk zod
19
+ # optional peers for quick starts
20
+ npm install @langchain/core @langchain/openai
21
+ ```
22
+
23
+ `@langchain/core` is marked as an optional peer dependency – install it if you plan to use LangChain tools or models.
24
+
25
+ ## Usage
26
+
27
+ ### ESM quick start
28
+
29
+ ```ts
30
+ import { createSmartAgent, createSmartTool, fromLangchainModel } from "@cognipeer/agent-sdk";
31
+ import { ChatOpenAI } from "@langchain/openai";
32
+ import { z } from "zod";
33
+
34
+ const echo = createSmartTool({
35
+ name: "echo",
36
+ description: "Echo back the input text",
37
+ schema: z.object({ text: z.string().min(1) }),
38
+ func: async ({ text }) => ({ echoed: text }),
39
+ });
40
+
41
+ const model = fromLangchainModel(new ChatOpenAI({
42
+ model: "gpt-4o-mini",
43
+ apiKey: process.env.OPENAI_API_KEY,
44
+ }));
45
+
46
+ const agent = createSmartAgent({
47
+ model,
48
+ tools: [echo],
49
+ limits: { maxToolCalls: 5, maxToken: 6000 },
50
+ useTodoList: true,
51
+ });
52
+
53
+ const result = await agent.invoke({
54
+ messages: [{ role: "user", content: "Plan a greeting and deliver it via the echo tool" }],
55
+ });
56
+
57
+ console.log(result.content);
58
+ ```
59
+
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
+ ```
79
+
80
+ ### Vision / multimodal input
81
+
82
+ Messages can contain OpenAI-style content parts:
83
+
84
+ ```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");
102
+
103
+ const echo = createTool({
104
+ name: "echo",
105
+ schema: z.object({ text: z.string().min(1) }),
106
+ func: async ({ text }) => ({ echoed: text }),
107
+ });
108
+
109
+ const model = fromLangchainModel(new ChatOpenAI({ model: "gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY }));
110
+ const agent = createSmartAgent({ model, tools: [echo] });
111
+
112
+ agent.invoke({ messages: [{ role: "user", content: "say hi via echo" }] }).then(res => {
113
+ console.log(res.content);
114
+ });
115
+ ```
116
+
117
+ ## API overview
118
+
119
+ Exports from `dist/index.*`:
120
+
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.).
129
+
130
+ ### SmartAgentOptions highlights
131
+
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.
141
+
142
+ ### Structured output finalize
143
+
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.
145
+
146
+ ### Summarization internals
147
+
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`.
151
+
152
+ ## Debugging
153
+
154
+ Enable logging with `debug.enabled: true`. By default Markdown files are written to `logs/<ISO_TIMESTAMP>/` containing:
155
+
156
+ - Model name, invocation limits, and raw usage (if reported).
157
+ - Serialized tool schemas.
158
+ - Message timeline with assistant/tool turns.
159
+
160
+ Provide `debug.callback` to receive the same payload programmatically (no files written).
161
+
162
+ ## Build
163
+
164
+ `tsup` bundles to `dist/index.js` (ESM) and `dist/index.cjs` (CJS) with declarations. Run:
165
+
166
+ ```sh
167
+ npm install
168
+ npm run build
169
+ ```
170
+
171
+ `prepublishOnly` also performs a build to keep the published artifact fresh.
172
+
173
+ ## License
174
+
175
+ MIT
176
+
177
+ ---
178
+
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.