@dudko.dev/agent 0.0.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/LICENSE +21 -0
- package/README.md +173 -0
- package/dist/cli.js +1447 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +1056 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +172 -0
- package/dist/index.d.ts +172 -0
- package/dist/index.js +1052 -0
- package/dist/index.js.map +1 -0
- package/package.json +78 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Siarhei Dudko
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# @dudko.dev/agent
|
|
2
|
+
|
|
3
|
+
A small, opinionated planning agent that uses tools exposed via [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers, built on top of the [Vercel AI SDK](https://sdk.vercel.ai/).
|
|
4
|
+
|
|
5
|
+
The agent runs a plan → execute → replan → synthesize loop:
|
|
6
|
+
|
|
7
|
+
1. **Plan** — the planner LLM produces a structured plan (a thought + ordered steps with optional suggested tools).
|
|
8
|
+
2. **Execute** — the executor LLM runs each step, calling MCP tools through the Vercel AI SDK.
|
|
9
|
+
3. **Replan** — after each step the replanner decides whether to continue, revise the plan, or finish.
|
|
10
|
+
4. **Synthesize** — once finished, the synthesizer LLM writes the final answer for the user.
|
|
11
|
+
|
|
12
|
+
Multi-provider out of the box: OpenAI, Anthropic, Google, and any OpenAI-compatible endpoint. Streaming events, per-run cancellation via `AbortSignal`, token budgets, retry/timeout, and concurrent runs on a single agent instance.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @dudko.dev/agent
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Requires Node.js **22.6+**.
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { createAgent } from '@dudko.dev/agent'
|
|
26
|
+
|
|
27
|
+
const agent = await createAgent({
|
|
28
|
+
clientName: 'my-app',
|
|
29
|
+
providerType: 'openai',
|
|
30
|
+
apiKey: process.env.OPENAI_API_KEY!,
|
|
31
|
+
model: 'gpt-4.1-mini',
|
|
32
|
+
mcpServers: {
|
|
33
|
+
docs: { url: 'https://mcp.example.com/sse' },
|
|
34
|
+
},
|
|
35
|
+
maxIterations: 6,
|
|
36
|
+
maxStepsPerTask: 8,
|
|
37
|
+
logLevel: 'info',
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
const result = await agent.run({
|
|
41
|
+
input: 'Find the latest pricing page and summarize the tiers.',
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
console.log(result.text)
|
|
45
|
+
console.log(`tokens: ${result.usage.totalTokens}`)
|
|
46
|
+
|
|
47
|
+
await agent.close()
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Streaming events
|
|
51
|
+
|
|
52
|
+
Pass an event handler as the second argument to `createAgent`, or per run via `onEvent`. Events include plan deltas, step starts and tool calls, replanner decisions, retries, budget breaches, the streamed final answer, and errors. See [`AgentEvent`](./src/types.ts) for the full union.
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
const agent = await createAgent(config, (event) => {
|
|
56
|
+
if (event.type === 'final.text-delta') process.stdout.write(event.delta)
|
|
57
|
+
})
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Cancellation
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
const ac = new AbortController()
|
|
64
|
+
setTimeout(() => ac.abort(), 30_000)
|
|
65
|
+
|
|
66
|
+
await agent.run({ input: '...', signal: ac.signal })
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Conversation history
|
|
70
|
+
|
|
71
|
+
Pass prior turns as `history` on each run; the agent treats them as context but does not mutate the array.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
const history = [
|
|
75
|
+
{ role: 'user', content: 'Who maintains the docs server?' },
|
|
76
|
+
{ role: 'assistant', content: 'The platform team owns it.' },
|
|
77
|
+
]
|
|
78
|
+
await agent.run({ input: 'Got a contact?', history })
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Reconnecting MCP
|
|
82
|
+
|
|
83
|
+
Use `getHeaders` on a server config to inject fresh credentials at connect time, then call `agent.reconnect()` after a token rotation. Reconnect refuses while runs are in flight.
|
|
84
|
+
|
|
85
|
+
## Configuration
|
|
86
|
+
|
|
87
|
+
`createAgent(config)` accepts an [`IAgentConfig`](./src/types.ts). Highlights:
|
|
88
|
+
|
|
89
|
+
| Field | Notes |
|
|
90
|
+
| --- | --- |
|
|
91
|
+
| `providerType` | `'openai' \| 'anthropic' \| 'google' \| 'openai-compatible'` |
|
|
92
|
+
| `baseURL` | Required for `openai-compatible`; optional for the rest. |
|
|
93
|
+
| `model` / `plannerModel` / `synthesizerModel` | The latter two default to `model`. |
|
|
94
|
+
| `mcpServers` | `Record<name, { url, headers?, getHeaders? }>` |
|
|
95
|
+
| `availableTools` / `excludedTools` | Whitelist / blacklist applied to MCP-discovered tools. |
|
|
96
|
+
| `maxIterations` | Cap on **executed steps** across the run (every step counts, including those run after a `revise`). |
|
|
97
|
+
| `maxStepsPerTask` | Cap on LLM steps inside a single executor call (multi-step tool calling). |
|
|
98
|
+
| `maxRevisions` | Cap on `revise` decisions the replanner can make per run. Default `2`. |
|
|
99
|
+
| `maxTotalTokens` | Soft cap on cumulative input + output tokens; checked between steps and triggers an early jump to synthesis when crossed. |
|
|
100
|
+
| `llmTimeoutMs` / `llmMaxRetries` | Per-LLM-call timeout and retry budget. |
|
|
101
|
+
| `toolSelectionStrategy` | `'all'` (default) gives the executor every tool each step; `'plan-narrowed'` exposes only `step.suggestedTools`. |
|
|
102
|
+
| `outputSanitizer` | Optional `(toolName, output) => unknown` hook to redact tool results before they reach the LLM. |
|
|
103
|
+
| `systemPrompt` | Appended to the executor system prompt. |
|
|
104
|
+
| `failOnNoTools` | When `true`, `createAgent` throws if every configured MCP server failed to connect (otherwise the agent starts with zero tools and emits an `error`-level log). Default `false`. |
|
|
105
|
+
| `logLevel` | `'none' \| 'error' \| 'warn' \| 'info' \| 'debug'` |
|
|
106
|
+
|
|
107
|
+
## API
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
interface IAgent {
|
|
111
|
+
run(options: IAgentRunOptions): Promise<IAgentRunResult>
|
|
112
|
+
listTools(): { name: string; description: string }[]
|
|
113
|
+
reconnect(): Promise<void>
|
|
114
|
+
close(options?: { waitForRuns?: boolean; timeoutMs?: number }): Promise<void>
|
|
115
|
+
activeRuns(): number
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
A single agent instance supports concurrent `run()` calls — each gets its own `runId` (via `AsyncLocalStorage`), usage accumulator, abort signal, and `onEvent`. Tools and models are shared.
|
|
120
|
+
|
|
121
|
+
Top-level exports beyond `createAgent`:
|
|
122
|
+
|
|
123
|
+
- `getCurrentRunId(): string | undefined` — read the active run's id from any code reachable from `agent.run()` (planner, executor, MCP `execute`, retry sleeps, …). Useful for correlating logs/metrics across concurrent runs on a single agent instance.
|
|
124
|
+
- `redactHeaders(headers)` — small helper for masking `Authorization`, `X-Api-Key`, `Cookie`, etc. when logging request headers (e.g. inside an `outputSanitizer` or your own MCP transport wrapper).
|
|
125
|
+
|
|
126
|
+
### Closing the agent
|
|
127
|
+
|
|
128
|
+
`close()` defaults to **immediate** teardown; in-flight runs that touch MCP after that point will fail. Pass `{ waitForRuns: true, timeoutMs }` to drain first:
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
await agent.close({ waitForRuns: true, timeoutMs: 60_000 })
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## CLI
|
|
135
|
+
|
|
136
|
+
The package ships a REPL CLI as `dd-agent`. After install, npm makes it available on `node_modules/.bin/dd-agent`:
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
dd-agent --env-file=.env
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`--env-file=<path>` is loaded via Node's built-in `process.loadEnvFile`, so no `dotenv` dependency is needed. Without the flag the CLI reads the ambient process env. `-h` / `--help` prints the supported flags and the in-REPL slash commands (`/status`, `/tools`, `/history`, `/reset`, `/reconnect`, `/exit`).
|
|
143
|
+
|
|
144
|
+
For local development against the source tree:
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
npm start # node --experimental-strip-types src/cli/start.ts --env-file=.env
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
The CLI source lives in [`src/cli`](./src/cli) — see [`env.example`](./env.example) for the full list of recognized env vars.
|
|
151
|
+
|
|
152
|
+
## Build & test
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
npm run build # tsup -> dist/ (ESM + CJS + .d.ts + cli.js with shebang)
|
|
156
|
+
npm run typecheck # tsc --noEmit
|
|
157
|
+
npm test # node --test against tests/
|
|
158
|
+
npm run format # prettier --write
|
|
159
|
+
npm run format:check # prettier --check
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
## Behavior notes & limitations
|
|
163
|
+
|
|
164
|
+
- **Module formats.** ESM is the primary target; the CJS build (`dist/index.cjs`) is best-effort and depends on upstream deps (`ai`, `@ai-sdk/*`, `@modelcontextprotocol/sdk`) keeping their CJS fallbacks. If they go pure-ESM, CJS will break — the dual-format guard in [`tests/dist-loadable.test.ts`](./tests/dist-loadable.test.ts) catches the regression on the next build.
|
|
165
|
+
- **MCP connect failures.** By default `createAgent` is fail-tolerant: a server that can't connect is logged at `error` level and skipped. The agent still starts with whatever tools did mount. Set `failOnNoTools: true` to throw when **every** configured server failed.
|
|
166
|
+
- **Blocker detection.** When the executor cannot complete a step it ends its reply with the literal `[BLOCKER]` token; the agent strips the token from the surfaced summary and sets `IStepResult.blocked = true`, which triggers the replanner. The detection is structural and language-independent — works regardless of the language the executor wrote in.
|
|
167
|
+
- **Retry duplicates in events.** Executor LLM retries (5xx / 429 / network) restart `streamText`, so consumers may observe `step.text-delta` / `step.tool-call` / `step.tool-result` events repeated for the same step. The `retry` event with `phase: 'execute'` precedes each repeat — UIs should clear any per-step buffers on it.
|
|
168
|
+
- **Mid-stream thought rewrites.** Some providers (notably Gemini structured outputs) rewrite `partialObjectStream.thought` from scratch instead of appending. The agent emits a single `log`-level warning and stops streaming `plan.thought-delta` for that run; the canonical thought still arrives in `plan.created`.
|
|
169
|
+
- **`.npmignore` is mostly inert.** `package.json#files` is an explicit allowlist (`["dist", "README.md"]`), so `.npmignore` only affects what npm strips **inside** that allowlist. The file is kept as a backstop in case `files` is ever broadened.
|
|
170
|
+
|
|
171
|
+
## License
|
|
172
|
+
|
|
173
|
+
MIT
|