@dudko.dev/agent 0.0.30 → 0.0.31
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 +274 -9
- package/dist/cli.js +126 -56
- package/dist/index.cjs +94 -41
- package/dist/index.d.cts +421 -16
- package/dist/index.d.ts +421 -16
- package/dist/index.js +94 -41
- package/dist/subagent-worker.js +120 -0
- package/package.json +12 -12
package/README.md
CHANGED
|
@@ -21,7 +21,19 @@ The agent runs a plan → execute → replan → synthesize loop:
|
|
|
21
21
|
3. **Replan** — after each step the replanner decides whether to continue, revise the plan, or finish.
|
|
22
22
|
4. **Synthesize** — once finished, the synthesizer LLM writes the final answer for the user.
|
|
23
23
|
|
|
24
|
-
Multi-provider out of the box: OpenAI, Anthropic, Google (Gemini), xAI (Grok), Azure OpenAI, Amazon Bedrock, Google Vertex, DeepSeek, Vercel AI Gateway, Cloudflare Workers AI, and any OpenAI-compatible endpoint. Streaming events, per-run cancellation via `AbortSignal`,
|
|
24
|
+
Multi-provider out of the box: OpenAI, Anthropic, Google (Gemini), xAI (Grok), Azure OpenAI, Amazon Bedrock, Google Vertex, DeepSeek, Vercel AI Gateway, Cloudflare Workers AI, and any OpenAI-compatible endpoint. Streaming events, per-run cancellation via `AbortSignal`, retry/timeout, and concurrent runs on a single agent instance.
|
|
25
|
+
|
|
26
|
+
On top of the loop:
|
|
27
|
+
|
|
28
|
+
- **[Thinking](#thinking-reasoning)** per stage, with the model's thoughts streamed as events.
|
|
29
|
+
- **[Token limits](#token-limits-and-step-caps)** — input / output / reasoning / total caps per run, enforced at every LLM step boundary, plus per-call output caps and a tool-call cap.
|
|
30
|
+
- **[Compaction](#compaction)** of long histories and traces (automatic and manual), and a cap on what the model sees of each tool result.
|
|
31
|
+
- **[Skills](#skills)** — agentskills.io-style `SKILL.md` instructions the planner picks and the executor loads on demand.
|
|
32
|
+
- **[Tool approval](#tool-approval-and-autopilot)** — autopilot, ask-for-writes, ask-for-all or read-only, with glob rules and a runtime toggle.
|
|
33
|
+
- **[Large MCP catalogs](#large-mcp-catalogs)** — tool search for hundreds of tools, `tools/list` pagination, connect timeouts.
|
|
34
|
+
- **[Prompt caching](#prompt-caching)** — run-stable system prompts, Anthropic cache breakpoints, OpenAI cache keys.
|
|
35
|
+
- **[Subagents](#subagents-worker_threads)** — a whole agent exposed as one tool, isolated in a `worker_thread`.
|
|
36
|
+
- **[Autonomy](#autonomy)** — the agent looks things up and decides on its own instead of asking.
|
|
25
37
|
|
|
26
38
|
## Install
|
|
27
39
|
|
|
@@ -80,7 +92,18 @@ await agent.close()
|
|
|
80
92
|
|
|
81
93
|
### Streaming events
|
|
82
94
|
|
|
83
|
-
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
|
|
95
|
+
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; the newer ones:
|
|
96
|
+
|
|
97
|
+
| Event | When |
|
|
98
|
+
| --- | --- |
|
|
99
|
+
| `step.reasoning-delta` / `final.reasoning-delta` | The executor's / synthesizer's thoughts, when [thinking](#thinking-reasoning) is on and the provider streams them. |
|
|
100
|
+
| `budget.exceeded` | A run cap was crossed; `kind: 'input' \| 'output' \| 'reasoning' \| 'total' \| 'tool-calls'`, `tokens`, `cap`. |
|
|
101
|
+
| `context.compacted` | History or trace was compacted (`scope`, `beforeTokens`, `afterTokens`). |
|
|
102
|
+
| `skill.activated` | A skill became active (`by: 'plan' \| 'tool'`). |
|
|
103
|
+
| `tools.discovered` | `find_tools` activated tools (`query`, `names`). |
|
|
104
|
+
| `tool.approval-requested` / `tool.approval-resolved` | The approval gate asked / decided (`automatic` for rule, mode and timeout denials). |
|
|
105
|
+
| `subagent.start` / `subagent.event` / `subagent.complete` / `subagent.error` | A subagent tool call's lifecycle and its forwarded child events. |
|
|
106
|
+
| `usage` | Per LLM call; `phase` is `'plan' \| 'execute' \| 'replan' \| 'synthesize' \| 'compact' \| 'subagent'`. |
|
|
84
107
|
|
|
85
108
|
```ts
|
|
86
109
|
const agent = await createAgent(config, (event) => {
|
|
@@ -135,7 +158,7 @@ Caveats:
|
|
|
135
158
|
- **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.
|
|
136
159
|
- **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.
|
|
137
160
|
- **Plan changes.** The saved `currentPlan` (post any revise) is what gets used on resume — the planner is not re-invoked.
|
|
138
|
-
- **Caps inherit.** `iterations` and `
|
|
161
|
+
- **Caps inherit.** `iterations`, `revisions`, usage and the tool-call count (`toolCallCount`) carry over, so per-run caps still apply across the boundary; so do the active skills (`activeSkills`) and the trace summary (`traceSummary` / `traceSummaryUpTo`).
|
|
139
162
|
- **Terminal status.** Resuming a run with `status: 'complete'` throws — re-read the saved `text` directly instead.
|
|
140
163
|
- **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`.
|
|
141
164
|
- **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.
|
|
@@ -186,6 +209,214 @@ await agent.reconnect()
|
|
|
186
209
|
|
|
187
210
|
Nothing is printed or opened on your behalf; `onAuthorizationUrl` and the loopback listener are yours to wire. `agent.listTools()` stays empty until the flow completes — a server that needs authorization reports `needsAuthorization: true` in its connect result rather than a generic failure. `MCP_SERVERS` (the CLI's env config) is JSON, so it can only express `headers`; OAuth is a library-level feature.
|
|
188
211
|
|
|
212
|
+
## Thinking (reasoning)
|
|
213
|
+
|
|
214
|
+
Turn on the model's reasoning for every stage with `thinking`, and override it per stage with `stageThinking` (a stage entry — even `false` — wins over the top-level value):
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
const agent = await createAgent({
|
|
218
|
+
...config,
|
|
219
|
+
thinking: 'medium', // boolean | level | { level?, budgetTokens?, includeThoughts? }
|
|
220
|
+
stageThinking: {
|
|
221
|
+
planner: 'high', // plans and revisions deserve the most
|
|
222
|
+
executor: { level: 'low' },
|
|
223
|
+
synthesizer: false, // provider default
|
|
224
|
+
},
|
|
225
|
+
})
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
| Setting | Sent to the provider |
|
|
229
|
+
| --- | --- |
|
|
230
|
+
| `false` / unset | nothing — the provider's default |
|
|
231
|
+
| `true` | `{ level: 'medium' }` |
|
|
232
|
+
| `'provider-default' \| 'minimal' \| 'low' \| 'medium' \| 'high' \| 'xhigh'` | the AI SDK's portable `reasoning` option, mapped onto each provider's own knob |
|
|
233
|
+
| `'none'` | `reasoning: 'none'` — explicitly off |
|
|
234
|
+
| `{ budgetTokens }` | an exact budget: Anthropic `thinking.budgetTokens`, Google `thinkingConfig.thinkingBudget` |
|
|
235
|
+
| `includeThoughts` (default `true`) | asks Google (`includeThoughts`) and OpenAI (`reasoningSummary: 'auto'`) to return their thoughts |
|
|
236
|
+
|
|
237
|
+
`resolveThinking(setting)` is exported (pure) if you want to see exactly what a setting becomes. Provider-specific options always win over the portable level inside the SDK.
|
|
238
|
+
|
|
239
|
+
The executor streams thoughts as `step.reasoning-delta` and the synthesizer as `final.reasoning-delta`. The planner and replanner use structured output, which has no reasoning stream. Compaction calls never think. Usage reports `reasoningTokens` (part of `outputTokens`).
|
|
240
|
+
|
|
241
|
+
> Some models refuse thinking together with forced structured output. If the planner fails with thinking on, disable it there: `stageThinking: { planner: false, replanner: false }`.
|
|
242
|
+
|
|
243
|
+
## Token limits and step caps
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
const agent = await createAgent({
|
|
247
|
+
...config,
|
|
248
|
+
limits: {
|
|
249
|
+
maxInputTokens: 400_000, // cumulative per run
|
|
250
|
+
maxOutputTokens: 40_000, // includes reasoning
|
|
251
|
+
maxReasoningTokens: 20_000,
|
|
252
|
+
maxTotalTokens: 500_000, // input + output (falls back to the legacy top-level maxTotalTokens)
|
|
253
|
+
perCall: { planner: 2_000, executor: 4_000, replanner: 1_000, synthesizer: 3_000, compaction: 1_024 },
|
|
254
|
+
},
|
|
255
|
+
maxToolCalls: 40, // tool calls per run, across steps
|
|
256
|
+
maxPlanSteps: 6, // hard cap on plan steps (default 8)
|
|
257
|
+
})
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
The run caps are **soft**: they are checked between steps *and* inside an executor step, as an extra `stopWhen` condition that adds the usage of the step's LLM calls to the run so far — so a runaway tool loop stops at its next LLM step instead of at the end of the step. When a cap is crossed the agent emits `budget.exceeded` (`kind: 'input' | 'output' | 'reasoning' | 'total' | 'tool-calls'`), stops executing steps and goes straight to synthesis, which still runs (capped by `perCall.synthesizer`). `checkLimits(usage, limits)` is the pure check, exported.
|
|
261
|
+
|
|
262
|
+
`maxToolCalls`: once reached, further tool calls in the run fail with `tool-call budget exhausted` (the model sees that as the tool result) and the run moves to synthesis with `budget.exceeded` of kind `'tool-calls'`. Built-in tools (`find_tools`, `load_skill`, `read_skill_file`) do not count.
|
|
263
|
+
|
|
264
|
+
The other step caps are unchanged: `maxIterations` (executed steps per run), `maxStepsPerTask` (LLM steps inside one executor call) and `maxRevisions` (replanner revisions per run).
|
|
265
|
+
|
|
266
|
+
`IUsage` reports `reasoningTokens`, `cachedInputTokens` (served from the provider's prompt cache) and `cacheWriteTokens` alongside the totals; `normalizeUsage` / `addUsage` are exported.
|
|
267
|
+
|
|
268
|
+
## Compaction
|
|
269
|
+
|
|
270
|
+
Long conversations and long runs are compacted automatically; everything is on by default and tuned with `compaction`:
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
compaction: {
|
|
274
|
+
auto: true, // default
|
|
275
|
+
contextWindowTokens: 128_000, // default
|
|
276
|
+
thresholdTokens: 64_000, // default: 50% of the window
|
|
277
|
+
keepRecentTurns: 4, // history turns kept verbatim
|
|
278
|
+
keepRecentSteps: 3, // trace steps kept verbatim
|
|
279
|
+
summaryMaxTokens: 1024,
|
|
280
|
+
maxToolOutputChars: 20_000, // per tool result the MODEL sees; 0 = unlimited
|
|
281
|
+
clearToolResultsAfterTokens: 32_000, // default: 25% of the window; 0 = never
|
|
282
|
+
keepToolResults: 3, // newest tool results kept verbatim when clearing
|
|
283
|
+
}
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
- **History, at run start.** When the estimated history (`estimateTokens` = chars / 4) exceeds the threshold, all but the last `keepRecentTurns` turns become ONE assistant turn starting with `[Summary of earlier conversation]`. The run works on the compacted copy; your array is never mutated, and the result carries it as `result.compactedHistory` so you can store it instead.
|
|
287
|
+
- **Trace, before each executor / replanner / synthesizer call.** Over the threshold, every step but the last `keepRecentSteps` is folded into a running summary; prompts show `Summary of earlier steps: …` followed by the recent steps verbatim. The trace itself stays intact in the result, the events and persistence; the summary is saved in the snapshot (`traceSummary`, `traceSummaryUpTo`) so a resumed run keeps it.
|
|
288
|
+
- **Tool results.** Every tool (MCP, native, built-in) gets a `toModelOutput` that clips what the model sees to `maxToolOutputChars` with a `… [truncated N chars]` marker. A tool's own `toModelOutput` runs first. The raw output still lands in the trace and in `step.tool-result`.
|
|
289
|
+
- **Stale tool results inside a step** (context editing, like Anthropic's `clear_tool_uses` and Claude Code's micro-compaction). Once a step's tool loop grows past `clearToolResultsAfterTokens`, the oldest results are replaced with a one-line stub (`[<tool> result cleared to save context — call the tool again if you still need it]`), keeping the newest `keepToolResults`. The calls stay, so the model knows what it did. Clearing is sticky (the cached prefix doesn't flip back) and keyed by position, so servers that repeat tool-call ids are fine. `createToolResultClearer` is exported.
|
|
290
|
+
|
|
291
|
+
Each compaction emits `context.compacted` (`scope: 'history' | 'trace' | 'tool-results'`, `beforeTokens`, `afterTokens`); the summary call's usage is reported as `usage` with `phase: 'compact'` and counts toward the run. The synthesizer model writes the summaries.
|
|
292
|
+
|
|
293
|
+
Manual: `agent.compact({ history, force?, signal? })` returns `{ history, summary?, beforeTokens, afterTokens, compacted }`; the CLI's `/compact` does exactly that for the REPL history. `compactHistory(turns, model, opts)` is exported for use without an agent. Compaction never throws — on any failure the input comes back unchanged.
|
|
294
|
+
|
|
295
|
+
## Skills
|
|
296
|
+
|
|
297
|
+
Skills are packaged instructions in the [agentskills.io](https://agentskills.io) format: a folder per skill with a `SKILL.md` (YAML frontmatter with `name` and `description`, then the instructions) and any bundled text files.
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
import { createAgent, loadSkillsFromDir, parseSkillMarkdown, defineSkill } from '@dudko.dev/agent'
|
|
301
|
+
|
|
302
|
+
const skills = await loadSkillsFromDir('./skills') // every ./skills/<skill>/SKILL.md
|
|
303
|
+
const agent = await createAgent({ ...config, skills })
|
|
304
|
+
agent.listSkills() // [{ name, description }]
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
Progressive disclosure keeps them cheap:
|
|
308
|
+
|
|
309
|
+
1. The planner and executor system prompts carry only an index: `- name: description`.
|
|
310
|
+
2. The planner's plan has an optional `skills` field naming the skills that apply (unknown names are dropped with a warning). Their instructions are injected into the executor, replanner and synthesizer system prompts for the rest of the run (24k chars in total, clipped beyond that).
|
|
311
|
+
3. The executor gets two read-only built-in tools: `load_skill({ name })` returns `{ name, content, files }` and activates the skill for later steps; `read_skill_file({ name, path })` returns a bundled file. Both always run without approval.
|
|
312
|
+
|
|
313
|
+
Every activation emits `skill.activated` (`by: 'plan' | 'tool'`). A host or MCP tool named `load_skill` / `read_skill_file` is a configuration error. `parseSkillMarkdown(markdown, files?)` and `defineSkill(skill)` validate skills you build yourself (names match `[a-z0-9-]{1,64}`). `loadSkillsFromDir` bundles text files (`.md .txt .json .yaml .yml .csv .ts .js .py .sh .html .css .xml .toml`, up to 256 KB each).
|
|
314
|
+
|
|
315
|
+
## Tool approval and autopilot
|
|
316
|
+
|
|
317
|
+
By default the agent runs every tool call (**autopilot**). `toolApproval` puts the host in charge of consent:
|
|
318
|
+
|
|
319
|
+
```ts
|
|
320
|
+
const agent = await createAgent({
|
|
321
|
+
...config,
|
|
322
|
+
toolApproval: {
|
|
323
|
+
mode: 'ask-writes', // 'autopilot' | 'ask-writes' | 'ask-all' | 'read-only'
|
|
324
|
+
rules: { 'github__delete_*': 'deny', github__get_me: 'allow' },
|
|
325
|
+
onRequest: async ({ toolName, input, readOnly, step, runId }) => {
|
|
326
|
+
const ok = await askTheUser(toolName, input)
|
|
327
|
+
return { approved: ok, remember: ok } // or just true / false
|
|
328
|
+
},
|
|
329
|
+
timeoutMs: 60_000, // no answer -> deny
|
|
330
|
+
},
|
|
331
|
+
})
|
|
332
|
+
|
|
333
|
+
agent.setToolApprovalMode('autopilot') // the toggle; applies to the next call, in-flight runs included
|
|
334
|
+
agent.getToolApprovalMode()
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
Each call is decided in this order: (1) a tool approved earlier with `remember: true` runs; (2) the most specific matching rule — exact name over the longest `*` glob — says `allow`, `ask` or `deny`; (3) the mode: `autopilot` allows, `read-only` allows read-only tools and denies the rest, `ask-writes` allows read-only tools and asks for the rest, `ask-all` asks. Built-in tools are always allowed. An `ask` without `onRequest` is a denial.
|
|
338
|
+
|
|
339
|
+
A tool is read-only when its MCP descriptor says `annotations.readOnlyHint: true`, or when a native tool is marked with `markReadOnly(tool)` (`isReadOnlyTool(tool)` checks). The request shows the input after `inputSanitizer`.
|
|
340
|
+
|
|
341
|
+
A denied call throws `ToolDeniedError` inside the tool, so the step records `ok: false` and the model reads *"Tool call denied by the user… Do not retry it; continue without it, or report what is blocked."* — the replanner sees it as any failed call. Events: `tool.approval-requested` (only when actually asking) and `tool.approval-resolved` (`automatic: true` for rule / mode / timeout denials; automatic allows emit nothing). The gate runs inside every tool's `execute` — MCP, native and subagent tools alike.
|
|
342
|
+
|
|
343
|
+
## Large MCP catalogs
|
|
344
|
+
|
|
345
|
+
**Tool search.** `toolSelectionStrategy` now defaults to `'auto'`: the executor gets every tool (`'all'`, exactly as before) while the filtered catalogue has at most `toolSearchThreshold` (default 40) tools, and switches to `'search'` above that. In `'search'` mode each step starts with the built-in tools, the step's `suggestedTools` and the tools discovered earlier in the run (the 16 most recent), plus `find_tools({ query, server?, limit? })`. It ranks the whole catalogue and **activates** the matches: they become callable from the model's next LLM step and stay active for the rest of the run (`tools.discovered` event). The planner sees an abridged catalogue grouped by server and treats `suggestedTools` as hints. The ranking is the exported pure `searchTools(catalog, query, { server?, limit? })` — terms matched in the name score 3, in the server 2, in the description 1, prefix-matched for terms of 3+ chars. `'all'` and `'plan-narrowed'` behave as before.
|
|
346
|
+
|
|
347
|
+
**Loading.** `tools/list` follows `nextCursor` (up to 100 pages), on connect and on `tools/list_changed` refreshes. Each server must connect and list within `connectTimeoutMs` (per server; default from the top-level `mcpConnectTimeoutMs`, 30 s; `0` disables) or it is reported failed (`connect timed out after Xms`) and closed while the others mount. `agent.listTools()` entries carry `server` and `readOnly`.
|
|
348
|
+
|
|
349
|
+
## Prompt caching
|
|
350
|
+
|
|
351
|
+
`promptCaching` is on by default. Every stage keeps its **system** prompt run-stable — role instructions, domain context (`systemPrompt`), the skills index, the tool catalogue where the stage shows one, and the active skills — and puts everything that changes (history, request, plan, trace) in the user message. That alone lets OpenAI and Gemini implicit caches hit. On top of it the system prompt is sent as a system message with an Anthropic ephemeral cache breakpoint, and each call carries an OpenAI `promptCacheKey` (`${clientName}:${stage}`). Unknown provider keys are ignored by other providers.
|
|
352
|
+
|
|
353
|
+
```ts
|
|
354
|
+
promptCaching: { ttl: '1h', key: 'my-app' } // or false to send plain system strings
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
Inside a step's tool loop a second Anthropic breakpoint **rolls to the newest message** every round, so each round reads all earlier rounds from the cache and writes only the new tail (`withRollingBreakpoint`; earlier message breakpoints are removed, so a request carries at most two — Anthropic allows four). Tools keep **declaration order** — servers connect concurrently but mount in the order they are configured — so the tool list that heads every cached prefix is identical from run to run without reordering what a server declared (a small model was measured to depend on that order).
|
|
358
|
+
|
|
359
|
+
Usage reports `cachedInputTokens` / `cacheWriteTokens`, so the effect is measurable.
|
|
360
|
+
|
|
361
|
+
### Token efficiency, in one place
|
|
362
|
+
|
|
363
|
+
The practices coding agents (Claude Code, the Claude and GitHub Copilot extensions) use to keep long sessions cheap, and the knob for each:
|
|
364
|
+
|
|
365
|
+
| Practice | How | Knob |
|
|
366
|
+
| --- | --- | --- |
|
|
367
|
+
| Stable, cacheable prefix | run-stable system prompts, deterministic tool order, dynamic content last | `promptCaching` |
|
|
368
|
+
| Cache the growing loop | rolling Anthropic breakpoint; OpenAI `promptCacheKey` per stage | `promptCaching: { ttl }` |
|
|
369
|
+
| Don't send every tool | compact catalogue + `find_tools` above the threshold (deferred tools) | `toolSelectionStrategy`, `toolSearchThreshold` |
|
|
370
|
+
| Load instructions on demand | skills: name + description in the prompt, body on activation | `skills` |
|
|
371
|
+
| Cap tool output | per result, as the model sees it | `compaction.maxToolOutputChars` |
|
|
372
|
+
| Clear stale tool results | oldest results in a long loop become stubs | `compaction.clearToolResultsAfterTokens` |
|
|
373
|
+
| Auto-compact | history and trace summarised past a threshold; `agent.compact()` | `compaction` |
|
|
374
|
+
| Isolate side quests | subagents (worker_threads) with their own context; only the answer returns | `createSubagentTool` |
|
|
375
|
+
| Pass results, not transcripts | later steps and the answer get step summaries + clipped findings | — |
|
|
376
|
+
| Bound everything | tokens per run / kind, per-call output caps, tool-call and plan-step caps | `limits`, `maxToolCalls`, `maxPlanSteps` |
|
|
377
|
+
| Think only where it pays | thinking per stage | `stageThinking` |
|
|
378
|
+
| Cheaper model for summaries | compaction and the answer use the synthesizer model | `synthesizer` stage |
|
|
379
|
+
|
|
380
|
+
## Subagents (worker_threads)
|
|
381
|
+
|
|
382
|
+
`createSubagentTool` exposes a whole agent as one tool of a parent agent: input `{ task }`, output the child's final text.
|
|
383
|
+
|
|
384
|
+
```ts
|
|
385
|
+
import { createAgent, createSubagentTool } from '@dudko.dev/agent'
|
|
386
|
+
|
|
387
|
+
const researcher = createSubagentTool({
|
|
388
|
+
name: 'researcher',
|
|
389
|
+
description: 'Research a self-contained question and report the findings',
|
|
390
|
+
config: { ...childConfig }, // a full IAgentConfig for the child
|
|
391
|
+
isolation: 'worker', // default; or 'in-process'
|
|
392
|
+
tools: { lookup }, // host tools for the child
|
|
393
|
+
maxConcurrent: 4, // parallel calls beyond this queue
|
|
394
|
+
timeoutMs: 120_000,
|
|
395
|
+
outputMaxChars: 8_000,
|
|
396
|
+
readOnly: true, // for tool approval
|
|
397
|
+
})
|
|
398
|
+
|
|
399
|
+
const agent = await createAgent({ ...config, tools: { researcher } })
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
- **`'worker'`** runs each call in its own `worker_thread` (terminated afterwards), so the child's CPU work and crashes stay off the parent's event loop. Its config must be structured-cloneable — a function anywhere (`getHeaders`, `authProvider`, `fetch`, sanitizers, `persistence`, `onRequest`, native `tools`) throws, naming the field. Host tools passed as `tools` are **proxied**: the child sees their schemas, every call runs on the parent thread.
|
|
403
|
+
- **`'in-process'`** builds the child on this thread; `tools` are merged into its config.
|
|
404
|
+
|
|
405
|
+
Several calls in one model step run in parallel (bounded by `maxConcurrent`). The parent's abort aborts the child. The child's usage is emitted on the parent as `usage` with `phase: 'subagent'` as it happens, so it counts against the parent's limits. Parent events: `subagent.start`, `subagent.event` (each child event, long strings clipped), `subagent.complete` (`text`, `usage`), `subagent.error`.
|
|
406
|
+
|
|
407
|
+
The worker entry ships as `dist/subagent-worker.js` and is resolved next to the bundle, from the ESM and the CJS build alike.
|
|
408
|
+
|
|
409
|
+
## Autonomy
|
|
410
|
+
|
|
411
|
+
The stage prompts are written for an agent that acts on its own:
|
|
412
|
+
|
|
413
|
+
- The **planner** plans tool use whenever the tools can obtain what the request needs — a question that needs data is actionable — and never plans a step that asks the user. An ambiguous request gets the most reasonable interpretation, with the assumption written into the step.
|
|
414
|
+
- The **executor** never asks questions or for confirmation, looks things up with tools, picks sensible defaults and states its assumptions in the step result. It ends with `[BLOCKER]` only when a step is truly impossible (missing credentials or permissions, a denied tool, unavailable data).
|
|
415
|
+
- The **replanner** prefers revising around a failure over finishing with nothing, and never revises into an "ask the user" step.
|
|
416
|
+
- The **synthesizer** reports what was done and found, mentions assumptions, and ends with a question only when the request genuinely cannot be completed without the user.
|
|
417
|
+
|
|
418
|
+
Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — the model never asks for permission in text.
|
|
419
|
+
|
|
189
420
|
## Configuration
|
|
190
421
|
|
|
191
422
|
`createAgent(config)` accepts an [`IAgentConfig`](./src/types.ts). Highlights:
|
|
@@ -199,16 +430,26 @@ Nothing is printed or opened on your behalf; `onAuthorizationUrl` and the loopba
|
|
|
199
430
|
| `model` | Default model for every stage (executor / planner / synthesizer) when no per-stage override is set. |
|
|
200
431
|
| `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`. |
|
|
201
432
|
| `plannerModel` / `synthesizerModel` | **Deprecated** model-only shortcuts. Equivalent to `planner: { model }` / `synthesizer: { model }`. The override block, if present, wins. |
|
|
202
|
-
| `mcpServers` | `Record<name, { url, headers?, getHeaders?, authProvider?, fetch? } \| { command, args?, env?, cwd? }>` — StreamableHTTP for remote (legacy HTTP+SSE servers are **not** supported), stdio for locally-spawned servers. |
|
|
203
|
-
| `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). |
|
|
433
|
+
| `mcpServers` | `Record<name, { url, headers?, getHeaders?, authProvider?, fetch?, connectTimeoutMs? } \| { command, args?, env?, cwd?, connectTimeoutMs? }>` — StreamableHTTP for remote (legacy HTTP+SSE servers are **not** supported), stdio for locally-spawned servers. |
|
|
434
|
+
| `tools` | Optional `ToolSet` of native AI-SDK tools registered alongside MCP-discovered ones. Names must not collide with MCP-prefixed names or the built-in tools (`createAgent` throws on conflict). Mark read-only tools with `markReadOnly(tool)`. |
|
|
204
435
|
| `availableTools` / `excludedTools` | Whitelist / blacklist applied to **all** tools (MCP and native). |
|
|
205
436
|
| `maxIterations` | Cap on **executed steps** across the run (every step counts, including those run after a `revise`). |
|
|
206
437
|
| `maxStepsPerTask` | Cap on LLM steps inside a single executor call (multi-step tool calling). |
|
|
207
438
|
| `maxRevisions` | Cap on `revise` decisions the replanner can make per run. Default `2`. |
|
|
208
439
|
| `replanAfter` | Replan trigger: `'failure'` (default; blocked step or a tool failure that stayed failed) \| `'always'` \| `(stepResult) => boolean \| Promise<boolean>` (bounded by `llmTimeoutMs`; falls back to `'failure'` on error). |
|
|
209
|
-
| `maxTotalTokens` | Soft cap on cumulative input + output tokens; checked between steps and triggers an early jump to synthesis when crossed. |
|
|
440
|
+
| `maxTotalTokens` | Soft cap on cumulative input + output tokens; checked between steps and triggers an early jump to synthesis when crossed. Legacy shortcut for `limits.maxTotalTokens` (which wins). |
|
|
441
|
+
| `limits` | `{ maxInputTokens?, maxOutputTokens?, maxReasoningTokens?, maxTotalTokens?, perCall?: { planner?, executor?, replanner?, synthesizer?, compaction? } }` — cumulative per-run caps (also enforced inside an executor step) and per-call output caps. See [Token limits](#token-limits-and-step-caps). |
|
|
442
|
+
| `maxToolCalls` | Cap on tool calls per run; further calls fail with "tool-call budget exhausted" and the run goes to synthesis. |
|
|
443
|
+
| `maxPlanSteps` | Hard cap on plan steps (initial and revised). Default `8`. |
|
|
444
|
+
| `thinking` / `stageThinking` | Reasoning for every stage / per stage (`planner`, `executor`, `replanner`, `synthesizer`). See [Thinking](#thinking-reasoning). |
|
|
445
|
+
| `compaction` | `{ auto?, contextWindowTokens?, thresholdTokens?, keepRecentTurns?, keepRecentSteps?, summaryMaxTokens?, maxToolOutputChars? }`. See [Compaction](#compaction). |
|
|
446
|
+
| `skills` | `ISkill[]` — see [Skills](#skills). |
|
|
447
|
+
| `toolApproval` | `{ mode?, rules?, onRequest?, timeoutMs? }` — default autopilot. See [Tool approval](#tool-approval-and-autopilot). |
|
|
210
448
|
| `llmTimeoutMs` / `llmMaxRetries` | Per-LLM-call timeout and retry budget. |
|
|
211
|
-
| `toolSelectionStrategy` | `'
|
|
449
|
+
| `toolSelectionStrategy` | `'auto'` (default: `'all'` up to `toolSearchThreshold` tools, `'search'` above), `'all'` (every tool each step), `'plan-narrowed'` (only `step.suggestedTools`), `'search'` (built-ins + suggested + discovered, plus `find_tools`). |
|
|
450
|
+
| `toolSearchThreshold` | Catalogue size above which `'auto'` switches to `'search'`. Default `40`. |
|
|
451
|
+
| `mcpConnectTimeoutMs` | Connect + `tools/list` budget per MCP server (each server's `connectTimeoutMs` wins). Default `30000`; `0` disables. |
|
|
452
|
+
| `promptCaching` | `true` (default) \| `false` \| `{ ttl?: '5m' \| '1h', key? }`. See [Prompt caching](#prompt-caching). |
|
|
212
453
|
| `outputSanitizer` | Optional `(toolName, output) => unknown` hook to redact tool results before they reach the LLM. |
|
|
213
454
|
| `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. |
|
|
214
455
|
| `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. |
|
|
@@ -247,13 +488,25 @@ Notes:
|
|
|
247
488
|
```ts
|
|
248
489
|
interface IAgent {
|
|
249
490
|
run(options: IAgentRunOptions): Promise<IAgentRunResult>
|
|
250
|
-
listTools(): { name: string; description: string }[]
|
|
491
|
+
listTools(): { name: string; description: string; server?: string; readOnly?: boolean }[]
|
|
492
|
+
listSkills(): { name: string; description: string }[]
|
|
493
|
+
compact(options: { history: IConversationTurn[]; signal?: AbortSignal; force?: boolean }): Promise<{
|
|
494
|
+
history: IConversationTurn[]
|
|
495
|
+
summary?: string
|
|
496
|
+
beforeTokens: number
|
|
497
|
+
afterTokens: number
|
|
498
|
+
compacted: boolean
|
|
499
|
+
}>
|
|
500
|
+
setToolApprovalMode(mode: ToolApprovalMode): void
|
|
501
|
+
getToolApprovalMode(): ToolApprovalMode
|
|
251
502
|
reconnect(): Promise<void>
|
|
252
503
|
close(options?: { waitForRuns?: boolean; timeoutMs?: number }): Promise<void>
|
|
253
504
|
activeRuns(): number
|
|
254
505
|
}
|
|
255
506
|
```
|
|
256
507
|
|
|
508
|
+
`IAgentRunResult` is `{ text, plan, trace, iterations, usage, compactedHistory? }`.
|
|
509
|
+
|
|
257
510
|
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.
|
|
258
511
|
|
|
259
512
|
Top-level exports beyond `createAgent`:
|
|
@@ -261,6 +514,14 @@ Top-level exports beyond `createAgent`:
|
|
|
261
514
|
- `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.
|
|
262
515
|
- `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).
|
|
263
516
|
- `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).
|
|
517
|
+
- `createSubagentTool(options)` — [subagents](#subagents-worker_threads).
|
|
518
|
+
- `resolveThinking(setting)`, `mergeProviderOptions(...layers)` — [thinking](#thinking-reasoning).
|
|
519
|
+
- `checkLimits(usage, limits)`, `resolveLimits(config)`, `normalizeUsage(sdkUsage)`, `addUsage(a, b)` — [token limits](#token-limits-and-step-caps).
|
|
520
|
+
- `compactHistory(turns, model, opts)`, `estimateTokens(text)`, `withToolOutputLimit(tool, maxChars)`, `truncateToolModelOutput(output, maxChars)` — [compaction](#compaction).
|
|
521
|
+
- `parseSkillMarkdown(markdown, files?)`, `defineSkill(skill)`, `loadSkillsFromDir(dir)` — [skills](#skills).
|
|
522
|
+
- `markReadOnly(tool)`, `isReadOnlyTool(tool)`, `decideToolPermission(input)`, `matchToolRule(rules, name)`, `ToolDeniedError`, `ToolBudgetError` — [tool approval](#tool-approval-and-autopilot).
|
|
523
|
+
- `searchTools(catalog, query, opts)` — [tool search](#large-mcp-catalogs).
|
|
524
|
+
- `resolvePromptCaching(setting)`, `buildInstructions(system, caching)` — [prompt caching](#prompt-caching).
|
|
264
525
|
|
|
265
526
|
### Closing the agent
|
|
266
527
|
|
|
@@ -278,7 +539,9 @@ The package ships a REPL CLI as `dd-agent`. After install, npm makes it availabl
|
|
|
278
539
|
dd-agent --env-file=.env
|
|
279
540
|
```
|
|
280
541
|
|
|
281
|
-
`--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`).
|
|
542
|
+
`--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`, `/compact`, `/autopilot`, `/approval <mode>`, `/reconnect`, `/exit`).
|
|
543
|
+
|
|
544
|
+
The newer features are env-driven too: `AGENT_THINKING` (`off | minimal | low | medium | high | xhigh | <budget tokens>`), `AGENT_MAX_INPUT_TOKENS` / `AGENT_MAX_OUTPUT_TOKENS` / `AGENT_MAX_REASONING_TOKENS` / `AGENT_MAX_TOTAL_TOKENS`, `AGENT_MAX_TOOL_CALLS`, `AGENT_TOOL_APPROVAL` (`autopilot | ask-writes | ask-all | read-only`), `AGENT_SKILLS_DIR`, `AGENT_TOOL_SELECTION_STRATEGY` (`auto | all | plan-narrowed | search`), `AGENT_CONTEXT_WINDOW_TOKENS` and `AGENT_COMPACTION=off`. The REPL prints the model's thoughts dimmed, auto-compacts its history with the same settings, and — when the approval mode asks — prompts `allow? [y]es / [n]o / [a]lways` right in the terminal; `/autopilot` toggles between autopilot and the last asking mode.
|
|
282
545
|
|
|
283
546
|
For local development against the source tree:
|
|
284
547
|
|
|
@@ -325,6 +588,8 @@ parsed — never the wording, which would make it a coin flip.
|
|
|
325
588
|
- **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. Servers connect concurrently, so one slow server no longer delays the ones declared after it; tools still mount in declaration order.
|
|
326
589
|
- **MCP tool errors.** A tool result carrying `isError: true` is surfaced as a **thrown** tool error, so the step records `ok: false` and `replanAfter: 'failure'` sees it. The error text the server returned becomes the error message (after `outputSanitizer`, if you set one).
|
|
327
590
|
- **MCP tool names.** Server and tool names are sanitized into `[a-zA-Z0-9_-]` (what OpenAI, Anthropic and Gemini accept) before being joined as `server__tool`, and a collision produced by that mapping gets a `_2` suffix rather than being dropped. `callTool` always uses the server's original name. If you pin `availableTools` / `excludedTools`, use the sanitized names.
|
|
591
|
+
- **Tool-output cap.** Since compaction landed, the model sees at most `compaction.maxToolOutputChars` (default 20 000) of each tool result; set it to `0` for the old unlimited behaviour. The trace and events keep the full output.
|
|
592
|
+
- **Default tool strategy.** `toolSelectionStrategy` defaults to `'auto'`, which is `'all'` (the previous default) up to 40 tools; set `'all'` explicitly to keep every tool in every step regardless of catalogue size.
|
|
328
593
|
- **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.
|
|
329
594
|
- **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.
|
|
330
595
|
- **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`.
|