@dudko.dev/agent 0.0.38 → 0.0.40

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
@@ -92,19 +92,53 @@ await agent.close()
92
92
 
93
93
  ### Streaming events
94
94
 
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:
95
+ Pass an event handler as the second argument to `createAgent`, or per run via `onEvent`. Every event carries the `runId` of its run, so a handler shared by concurrent runs can tell them apart. The full union is [`AgentEvent`](./src/types.ts); this is the whole list, by stage.
96
+
97
+ **The loop**
96
98
 
97
99
  | Event | When |
98
100
  | --- | --- |
101
+ | `plan.thought-delta` | The planner's thought, streamed. |
102
+ | `plan.step-added` | A step of the plan is coherent enough to show (`step`, `index`). A hint for incremental UIs — it can still change before `plan.created`. |
103
+ | `plan.created` | The canonical plan (`plan`). |
104
+ | `plan.revised` | The replanner replaced the remaining steps (`plan`, `reason`). |
105
+ | `step.start` | A step began (`step`, `index`). |
106
+ | `step.text-delta` | The executor's text for the step. |
99
107
  | `step.reasoning-delta` / `final.reasoning-delta` | The executor's / synthesizer's thoughts, when [thinking](#thinking-reasoning) is on and the provider streams them. |
108
+ | `step.tool-call` / `step.tool-result` | A tool was called (`name`, `input`) / returned (`output`, `ok`). |
109
+ | `step.complete` | The step finished (`result`). |
110
+ | `replan.decision` | The replanner's verdict: `mode: 'continue' \| 'revise' \| 'finish'`, `reason`, and `cause: 'last-step' \| 'clean-step' \| 'llm-decision' \| 'user-message'`. |
111
+ | `revisions.exceeded` | The cap on plan revisions (`cap`) was reached; the run goes on to synthesize. |
112
+ | `final.text-delta` | The final answer, streamed. |
113
+ | `final` | The final answer, whole (`text`). |
114
+ | `retry` | A stage failed and is being retried (`phase`, `attempt`, `error`). |
115
+ | `error` | A stage failed for good (`error`, `phase: 'plan' \| 'execute' \| 'replan' \| 'synthesize' \| 'init'`). |
116
+ | `log` | A log line (`level`, `message`), the same ones `config.logger` gets. |
117
+
118
+ **Budgets, context and cost**
119
+
120
+ | Event | When |
121
+ | --- | --- |
122
+ | `usage` | Per LLM call; `phase` is `'plan' \| 'execute' \| 'replan' \| 'synthesize' \| 'compact' \| 'subagent'`. Counted live into [`agent.usage`](#usage-what-a-session-has-spent). |
100
123
  | `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`). |
124
+ | `context.compacted` | History, trace or stale tool results were compacted (`scope: 'history' \| 'trace' \| 'tool-results'`, `beforeTokens`, `afterTokens`). |
125
+
126
+ **Tools, skills and consent**
127
+
128
+ | Event | When |
129
+ | --- | --- |
102
130
  | `skill.activated` | A skill became active (`by: 'plan' \| 'tool'`). |
103
131
  | `tools.discovered` | `find_tools` activated tools (`query`, `names`). |
104
132
  | `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. |
133
+ | `egress.request` | A `web_fetch` request, allowed or refused by the [egress policy](#egress-what-the-model-may-fetch) (`url` is origin and path only, `allowed`, `status?`, `reason?`). |
134
+ | `skill.learned` / `skill.forgotten` | The agent wrote, rewrote (`update`) or removed a lesson — see [Learning](#learning-lessons-that-outlive-the-task) (`name`, and for a lesson `description`, `chars`, `sources`). |
135
+
136
+ **Subagents and steering**
137
+
138
+ | Event | When |
139
+ | --- | --- |
140
+ | `subagent.start` / `subagent.event` / `subagent.complete` / `subagent.error` | A subagent tool call's lifecycle and its forwarded child events (`error` carries `stopped` when the user stopped it). |
106
141
  | `message.queued` / `message.delivered` | A `RunControl.send()` message is waiting for a boundary / the model has seen it (`at: 'round' \| 'step' \| 'final'`). See [Steering a run](#steering-a-run-that-is-already-going). |
107
- | `usage` | Per LLM call; `phase` is `'plan' \| 'execute' \| 'replan' \| 'synthesize' \| 'compact' \| 'subagent'`. |
108
142
 
109
143
  ```ts
110
144
  const agent = await createAgent(config, (event) => {
@@ -274,7 +308,8 @@ Long conversations and long runs are compacted automatically; everything is on b
274
308
  compaction: {
275
309
  auto: true, // default
276
310
  contextWindowTokens: 128_000, // default
277
- thresholdTokens: 64_000, // default: 50% of the window
311
+ thresholdRatio: 0.85, // default: start at 85% of the window (0 < ratio <= 1)
312
+ // thresholdTokens: 100_000, // ...or an absolute number; it wins over the ratio
278
313
  keepRecentTurns: 4, // history turns kept verbatim
279
314
  keepRecentSteps: 3, // trace steps kept verbatim
280
315
  summaryMaxTokens: 1024,
@@ -284,15 +319,23 @@ compaction: {
284
319
  }
285
320
  ```
286
321
 
287
- - **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.
288
- - **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.
322
+ - **History, at run start.** When the history no longer fits (see below), 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.
323
+ - **Trace, before each executor / replanner / synthesizer call.** When it no longer fits, 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.
289
324
  - **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`.
290
325
  - **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.
291
326
 
327
+ **What "fits" means.** The threshold is a share of the window (85% by default) judged on the **whole context** of the next call: the fixed prompt (stage instructions, tool definitions, the skills index and active skills, your `systemPrompt`) **plus** the history **plus** the run's trace. Judging each part alone would let a long history and a long trace each stay under the line while together overflowing the window; the rest is room for the answer and for what one step adds before the next check. The fixed prompt is estimated (about 1 500 tokens + your `systemPrompt` + the tool definitions + the skills; under tool search only a few definitions are sent, so the tools count at most 3 000).
328
+
329
+ **The estimate** (`estimateTokens`) counts by kind of character, because text is not one thing: letters ~2.5 to a token, digits and punctuation about one each, a space a quarter, a newline one, other scripts (Russian) two characters, CJK and emoji one. It was calibrated against Claude's tokenizer over prose, markdown, code, JSON, a table, Russian and a mix, and comes out **1.1-1.4x the real count and never below it** (a flat "4 characters a token" was 0.4-0.7x for everything but Russian: JSON and code run 1.6-2.4 characters a token, and tool definitions 2x what 4 would give). It leans high on purpose: compacting a little early is cheap, overflowing the window is a failed run. So at the default 85% a Claude model has roughly 70-75% of its window really used when compaction starts; a tokenizer that packs tighter (OpenAI, Gemini) starts a little earlier still - raise `thresholdRatio` (0.9, 0.95) to compact later. **What the summariser is shown** is the newest part of what is being folded that fits 60% of the window. CLI: `AGENT_COMPACTION_THRESHOLD=90` (percent) moves the line; `AGENT_CONTEXT_WINDOW_TOKENS` sets the window the share is taken of.
330
+
292
331
  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.
293
332
 
294
333
  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.
295
334
 
335
+ ## Usage: what a session has spent
336
+
337
+ `result.usage` is one run's tokens (`inputTokens`, `outputTokens`, `totalTokens`, and `reasoningTokens` / `cachedInputTokens` / `cacheWriteTokens` when the provider reports them). `agent.usage` is the agent's total over all its runs and manual compactions since it was created (or `agent.resetUsage()`): a snapshot, counted call by call as the usage arrives, so a run that is stopped or fails still counts what it spent, a resumed run adds only what THIS process spent, and a subagent's tokens (charged to its parent run) count once. The REPL shows it: `/usage`, and `session=<total>` on every answer's `[meta]` line.
338
+
296
339
  ## Skills
297
340
 
298
341
  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.
@@ -634,6 +677,8 @@ interface IAgent {
634
677
  listTools(): { name: string; description: string; server?: string; readOnly?: boolean }[]
635
678
  listSkills(): { name: string; description: string; learned?: true }[]
636
679
  listLearnedSkills(): ISkill[] // the agent's own lessons, with origin (see Learning)
680
+ readonly usage: IUsage // tokens this agent has spent over all its runs (a snapshot; see below)
681
+ resetUsage(): void
637
682
  forgetSkill(name: string): Promise<boolean> // delete one of them; false if there is none
638
683
  compact(options: { history: IConversationTurn[]; signal?: AbortSignal; force?: boolean }): Promise<{
639
684
  history: IConversationTurn[]
@@ -684,9 +729,9 @@ The package ships a REPL CLI as `dd-agent`. After install, npm makes it availabl
684
729
  dd-agent --env-file=.env
685
730
  ```
686
731
 
687
- `--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`, `/agents`, `/stop`, `/exit`).
732
+ `--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`, `/usage`, `/tools`, `/history`, `/reset`, `/compact`, `/autopilot`, `/approval <mode>`, `/reconnect`, `/skills`, `/forget <name>`, `/agents`, `/stop [n]`, `/exit` — `/quit` does the same).
688
733
 
689
- 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_TOOL_RULES` (JSON `{ "<tool or glob*>": "allow" | "ask" | "deny" }`, beats the mode — e.g. `{"github__delete_*":"deny"}`), `AGENT_EGRESS` (`on | off`; with `AGENT_EGRESS_ALLOW`, `AGENT_EGRESS_DENY`, `AGENT_EGRESS_PROTOCOLS`, `AGENT_EGRESS_ALLOW_PRIVATE` — see [Egress](#egress-what-the-model-may-fetch)), `AGENT_SKILLS_DIR`, `AGENT_LEARNING` (`on | off`; `AGENT_LEARNING_DIR` keeps the lessons across sessions — see [Learning](#learning-lessons-that-outlive-the-task)), `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.
734
+ 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_TOOL_RULES` (JSON `{ "<tool or glob*>": "allow" | "ask" | "deny" }`, beats the mode — e.g. `{"github__delete_*":"deny"}`), `AGENT_EGRESS` (`on | off`; with `AGENT_EGRESS_ALLOW`, `AGENT_EGRESS_DENY`, `AGENT_EGRESS_PROTOCOLS`, `AGENT_EGRESS_ALLOW_PRIVATE` — see [Egress](#egress-what-the-model-may-fetch)), `AGENT_SKILLS_DIR`, `AGENT_LEARNING` (`on | off`; `AGENT_LEARNING_DIR` keeps the lessons across sessions — see [Learning](#learning-lessons-that-outlive-the-task)), `AGENT_TOOL_SELECTION_STRATEGY` (`auto | all | plan-narrowed | search`), `AGENT_CONTEXT_WINDOW_TOKENS`, `AGENT_COMPACTION_THRESHOLD` (percent of the window where auto-compaction starts, default 85) 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.
690
735
 
691
736
  **Talking to the agent while it works.** The REPL keeps reading while a run goes. Text you type then is said to the running agent (it sees it at its next boundary and the replanner re-checks the plan — see [Steering a run](#steering-a-run-that-is-already-going)): the REPL prints `[you->agent] queued` and then `delivered (round|step|final)`, and the message enters the history as a user turn. A message that arrives while the answer is being written is sent as the next prompt (`[follow-up]`). After Ctrl-C nothing is sent behind your back: what the agent never saw is listed as `[not delivered]`. While a run goes, `/agents` lists the running subagents and `/stop <n>` (or an id prefix, or just `/stop` when one runs) stops one — the run goes on; the other REPL commands work between runs. Each subagent's own steps and tool calls are logged as `[name id] ...` lines, so parallel ones can be told apart.
692
737
 
@@ -696,7 +741,18 @@ For local development against the source tree:
696
741
  npm start # node --experimental-strip-types src/cli/start.ts --env-file=.env
697
742
  ```
698
743
 
699
- The CLI source lives in [`src/cli`](./src/cli) — see [`env.example`](./env.example) for the full list of recognized env vars.
744
+ The CLI source lives in [`src/cli`](./src/cli) — [`env.example`](./env.example) is the full, commented list of recognized env vars. The core ones:
745
+
746
+ | Variable | What it sets |
747
+ | --- | --- |
748
+ | `AGENT_PROVIDER_TYPE`, `AGENT_MODEL`, `AGENT_API_KEY`, `AGENT_BASE_URL` | The provider, the executor's model, its key and endpoint (`AGENT_BASE_URL` is required for `openai-compatible` and `azure`). |
749
+ | `AGENT_PLANNER_MODEL`, `AGENT_SYNTHESIZER_MODEL` | A different model for the planner + replanner / the synthesizer; both default to `AGENT_MODEL`. |
750
+ | `AGENT_PLANNER_*`, `AGENT_SYNTHESIZER_*` (`PROVIDER_TYPE`, `BASE_URL`, `API_KEY`, `PROVIDER_OPTIONS`) | Run a stage on another provider (see [Picking models per stage](#picking-models-per-stage)). A key is never inherited across vendors. |
751
+ | `AGENT_PROVIDER_OPTIONS` | JSON spread into the provider factory (`{"region":"us-east-1"}`, Azure's `resourceName`, …). |
752
+ | `AGENT_MAX_ITERATIONS`, `AGENT_MAX_STEPS_PER_TASK`, `AGENT_MAX_REVISIONS` | Loop caps: plan/execute/replan rounds, LLM steps inside one executor call, replanner "revise" decisions. |
753
+ | `AGENT_LLM_TIMEOUT_MS`, `AGENT_LLM_MAX_RETRIES` | Per-call timeout (`0` = off) and retries on 5xx / 429 / network errors (default 2). |
754
+ | `AGENT_AVAILABLE_TOOLS`, `AGENT_EXCLUDED_TOOLS` | Comma lists of MCP tool names to offer / withhold (available wins). |
755
+ | `AGENT_CLIENT_NAME`, `AGENT_LOG_LEVEL` | The `User-Agent` sent on MCP / provider requests; `none \| error \| warn \| info \| debug`. |
700
756
 
701
757
  ## Build & test
702
758