@dudko.dev/agent 0.0.1 → 0.0.3

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
@@ -2,6 +2,12 @@
2
2
 
3
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
4
 
5
+ [![npm](https://img.shields.io/npm/v/@dudko.dev/agent.svg)](https://www.npmjs.com/package/@dudko.dev/agent)
6
+ [![npm](https://img.shields.io/npm/dy/@dudko.dev/agent.svg)](https://www.npmjs.com/package/@dudko.dev/agent)
7
+ [![NpmLicense](https://img.shields.io/npm/l/@dudko.dev/agent.svg)](https://www.npmjs.com/package/@dudko.dev/agent)
8
+ ![GitHub last commit](https://img.shields.io/github/last-commit/dudko-dev/agent.svg)
9
+ ![GitHub release](https://img.shields.io/github/release/dudko-dev/agent.svg)
10
+
5
11
  The agent runs a plan → execute → replan → synthesize loop:
6
12
 
7
13
  1. **Plan** — the planner LLM produces a structured plan (a thought + ordered steps with optional suggested tools).
@@ -66,6 +72,54 @@ setTimeout(() => ac.abort(), 30_000)
66
72
  await agent.run({ input: '...', signal: ac.signal })
67
73
  ```
68
74
 
75
+ The run-level signal terminates everything. To cancel a single step (e.g. a long tool call) without aborting the whole run, use `onStepStart` — the cancelled step records as `blocked: true` and the replanner runs next:
76
+
77
+ ```ts
78
+ await agent.run({
79
+ input: '...',
80
+ onStepStart: ({ step, abort }) => {
81
+ if (step.suggestedTools?.includes('expensive_tool')) {
82
+ abort()
83
+ }
84
+ },
85
+ })
86
+ ```
87
+
88
+ ### Resume after crash
89
+
90
+ Wire a persistence adapter that implements `loadRun(runId)`, then resume with the run id:
91
+
92
+ ```ts
93
+ import { makeSqlitePersistence } from './examples/persistence-sqlite.ts'
94
+
95
+ const persistence = makeSqlitePersistence('./runs.db')
96
+ const agent = await createAgent({ ..., persistence, keepSandbox: true })
97
+
98
+ try {
99
+ await agent.run({ input: '...' })
100
+ } catch (err) {
101
+ // process crashed mid-run; the snapshot has the latest checkpoint.
102
+ }
103
+
104
+ // Later, in a new process:
105
+ await agent.run({ input: '', resumeFromRunId: '<saved-run-id>' })
106
+ ```
107
+
108
+ Caveats:
109
+
110
+ - **Idempotency.** Resume re-enters the loop at the saved checkpoint (the iteration boundary after the last successful step). A crash mid-step means the in-flight step's tool calls are lost; on resume, the runner re-executes that step from scratch. If your tools have side effects (writes, payments, emails), the same call may fire twice. Design tools to be idempotent or guard against replay.
111
+ - **Sandbox.** The per-run sandbox directory is auto-cleaned on completion. To resume, set `keepSandbox: true` so files written by earlier steps survive the crash. Without it, the trace's file references will point to a directory that no longer exists.
112
+ - **Plan changes.** The saved `currentPlan` (post any revise) is what gets used on resume — the planner is not re-invoked.
113
+ - **Caps inherit.** `iterations` and `revisions` carry over, so per-run caps still apply across the boundary.
114
+ - **Terminal status.** Resuming a run with `status: 'complete'` throws — re-read the saved `text` directly instead.
115
+ - **Event semantics.** On resume the runner re-emits a `plan.created` event so consumers attaching mid-resume see the canonical plan; consumers that store every event will observe `plan.created` twice for the same `runId`. `onRunStart` is **not** re-fired (the original run already emitted it) — code that counts run starts must use `runId` for de-duplication. `onStepComplete` only fires for steps the resumed run actually executes; pre-resume steps are already in the loaded `trace`.
116
+ - **Inputs are locked to the snapshot.** Both `options.input` and `options.history` passed to `agent.run({ resumeFromRunId })` are **silently ignored** in favor of the values stored at the original run start. This keeps the resumed prompt deterministic against the saved trace; pass an empty input (`input: ''`) to make the override explicit.
117
+ - **runId hygiene.** Persisted `runId`s end up in filesystem paths (`<sandboxRoot>/<runId>/`) and are validated against `^[a-zA-Z0-9_-]{1,128}$`. A persistence adapter that returns a snapshot whose `runId` differs from the requested one, or that contains path-unsafe characters, is rejected.
118
+
119
+ ### OpenTelemetry
120
+
121
+ The agent emits OTel spans for `agent.run`, `agent.plan`, `agent.execute_step`, `agent.replan`, and `agent.synthesize` via the `@opentelemetry/api` package. With no SDK installed, the calls are no-ops; install your favorite OTel exporter (jaeger, otlp, console) and you get traces and parent-child relationships out of the box. Span attributes are documented in [`src/tracing.ts`](./src/tracing.ts).
122
+
69
123
  ### Conversation history
70
124
 
71
125
  Pass prior turns as `history` on each run; the agent treats them as context but does not mutate the array.
@@ -90,9 +144,12 @@ Use `getHeaders` on a server config to inject fresh credentials at connect time,
90
144
  | --- | --- |
91
145
  | `providerType` | `'openai' \| 'anthropic' \| 'google' \| 'openai-compatible'` |
92
146
  | `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. |
147
+ | `model` | Default model for every stage (executor / planner / synthesizer) when no per-stage override is set. |
148
+ | `planner` / `synthesizer` | Optional per-stage override blocks: `{ providerType?, baseURL?, apiKey?, model? }`. Use these to mix providers (e.g. Gemini planner, Anthropic synthesizer). Cross-provider overrides MUST set their own `apiKey`. |
149
+ | `plannerModel` / `synthesizerModel` | **Deprecated** model-only shortcuts. Equivalent to `planner: { model }` / `synthesizer: { model }`. The override block, if present, wins. |
150
+ | `mcpServers` | `Record<name, { url, headers?, getHeaders? } \| { command, args?, env?, cwd? }>` — HTTP/SSE for remote, stdio for locally-spawned servers. |
151
+ | `tools` | Optional `ToolSet` of native AI-SDK tools registered alongside MCP-discovered ones. Names must not collide with MCP-prefixed names (`createAgent` throws on conflict). |
152
+ | `availableTools` / `excludedTools` | Whitelist / blacklist applied to **all** tools (MCP and native). |
96
153
  | `maxIterations` | Cap on **executed steps** across the run (every step counts, including those run after a `revise`). |
97
154
  | `maxStepsPerTask` | Cap on LLM steps inside a single executor call (multi-step tool calling). |
98
155
  | `maxRevisions` | Cap on `revise` decisions the replanner can make per run. Default `2`. |
@@ -100,8 +157,14 @@ Use `getHeaders` on a server config to inject fresh credentials at connect time,
100
157
  | `llmTimeoutMs` / `llmMaxRetries` | Per-LLM-call timeout and retry budget. |
101
158
  | `toolSelectionStrategy` | `'all'` (default) gives the executor every tool each step; `'plan-narrowed'` exposes only `step.suggestedTools`. |
102
159
  | `outputSanitizer` | Optional `(toolName, output) => unknown` hook to redact tool results before they reach the LLM. |
103
- | `systemPrompt` | Appended to the executor system prompt. |
160
+ | `inputSanitizer` | Optional `(toolName, input) => unknown` hook to redact LLM-generated tool args before they hit the MCP server **and** before they appear in `step.tool-call` events. **Must be idempotent** — applied at both the event boundary and the dispatch boundary. |
161
+ | `outputSanitizer` ordering | The sanitizer runs on the **raw MCP `result.content`** (image/audio base64 still inline), **before** the agent spills binary parts to the sandbox. This favors privacy: a sanitizer that drops a sensitive image keeps the bytes out of the disk entirely. If you want post-spill sanitization (e.g. redact a path), do it in your tool wrapper instead. |
162
+ | `sandboxRoot` | Per-run sandbox subdirs are created at `<sandboxRoot>/<runId>/` for tools that spill binary content (images, audio, blob resources). Defaults to `<os.tmpdir()>/agent-sandbox`. |
163
+ | `keepSandbox` | When `true`, the per-run directory is not removed after the run completes. Default `false`. |
164
+ | `systemPrompt` | Appended to the planner, executor, replanner, and synthesizer system prompts so the same domain context (persona, language, tone) reaches every stage. |
104
165
  | `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`. |
166
+ | `maxConcurrentRuns` | Hard cap on concurrent `agent.run()` calls. When reached, further calls reject synchronously. Default: unlimited. Intentionally a throw, not a queue — back-pressure belongs on the caller. |
167
+ | `persistence` | Optional `IPersistence` facade. Receives `IRunSnapshot` at run start, at every iteration boundary, and at run completion. Implementing the optional `loadRun(runId)` enables resume via `agent.run({ resumeFromRunId })`. See [`examples/persistence-sqlite.ts`](./examples/persistence-sqlite.ts) for a `node:sqlite`-backed adapter. |
105
168
  | `logLevel` | `'none' \| 'error' \| 'warn' \| 'info' \| 'debug'` |
106
169
 
107
170
  ## API
@@ -121,6 +184,7 @@ A single agent instance supports concurrent `run()` calls — each gets its own
121
184
  Top-level exports beyond `createAgent`:
122
185
 
123
186
  - `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.
187
+ - `getCurrentRunSandbox(): string | undefined` — absolute path to the active run's sandbox directory. Native tools that need to spill binary output should write into this path so files are auto-cleaned when the run completes (set `keepSandbox: true` to retain).
124
188
  - `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
189
 
126
190
  ### Closing the agent