@dudko.dev/agent 0.0.37 → 0.0.39
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 +76 -7
- package/dist/cli.js +111 -85
- package/dist/index.cjs +79 -62
- package/dist/index.d.cts +149 -2
- package/dist/index.d.ts +149 -2
- package/dist/index.js +79 -62
- package/dist/subagent-worker.js +67 -56
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -274,7 +274,8 @@ Long conversations and long runs are compacted automatically; everything is on b
|
|
|
274
274
|
compaction: {
|
|
275
275
|
auto: true, // default
|
|
276
276
|
contextWindowTokens: 128_000, // default
|
|
277
|
-
|
|
277
|
+
thresholdRatio: 0.85, // default: start at 85% of the window (0 < ratio <= 1)
|
|
278
|
+
// thresholdTokens: 100_000, // ...or an absolute number; it wins over the ratio
|
|
278
279
|
keepRecentTurns: 4, // history turns kept verbatim
|
|
279
280
|
keepRecentSteps: 3, // trace steps kept verbatim
|
|
280
281
|
summaryMaxTokens: 1024,
|
|
@@ -284,15 +285,23 @@ compaction: {
|
|
|
284
285
|
}
|
|
285
286
|
```
|
|
286
287
|
|
|
287
|
-
- **History, at run start.** When the
|
|
288
|
-
- **Trace, before each executor / replanner / synthesizer call.**
|
|
288
|
+
- **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.
|
|
289
|
+
- **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
290
|
- **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
291
|
- **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
292
|
|
|
293
|
+
**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).
|
|
294
|
+
|
|
295
|
+
**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.
|
|
296
|
+
|
|
292
297
|
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
298
|
|
|
294
299
|
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
300
|
|
|
301
|
+
## Usage: what a session has spent
|
|
302
|
+
|
|
303
|
+
`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.
|
|
304
|
+
|
|
296
305
|
## Skills
|
|
297
306
|
|
|
298
307
|
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.
|
|
@@ -302,7 +311,7 @@ import { createAgent, loadSkillsFromDir, parseSkillMarkdown, defineSkill } from
|
|
|
302
311
|
|
|
303
312
|
const skills = await loadSkillsFromDir('./skills') // every ./skills/<skill>/SKILL.md
|
|
304
313
|
const agent = await createAgent({ ...config, skills })
|
|
305
|
-
agent.listSkills() // [{ name, description }]
|
|
314
|
+
agent.listSkills() // [{ name, description }] (+ learned: true on the agent's own, see Learning)
|
|
306
315
|
```
|
|
307
316
|
|
|
308
317
|
Progressive disclosure keeps them cheap:
|
|
@@ -493,6 +502,62 @@ and the run are untouched. Only a child that has started is listed; one still wa
|
|
|
493
502
|
child stops them with it. What each child does is the `subagent.event` stream, the same events the
|
|
494
503
|
parent emits.
|
|
495
504
|
|
|
505
|
+
## Egress: what the model may fetch
|
|
506
|
+
|
|
507
|
+
By default the agent has **no way to reach the network of its own**: its only outbound paths are the provider API and the MCP servers and tools *you* configure. To let the model read the web, switch on `egress`:
|
|
508
|
+
|
|
509
|
+
```ts
|
|
510
|
+
const agent = await createAgent({
|
|
511
|
+
// ...
|
|
512
|
+
egress: {
|
|
513
|
+
allow: ['docs.example.com', '*.github.com'], // optional: only these (then web_fetch counts as read-only)
|
|
514
|
+
deny: ['internal.example.com', '10.0.0.0/8'], // optional: always refused, wins over allow
|
|
515
|
+
},
|
|
516
|
+
})
|
|
517
|
+
// egress: true = any public host over https. CLI: AGENT_EGRESS=on, AGENT_EGRESS_ALLOW, AGENT_EGRESS_DENY, ...
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
That registers one tool, `web_fetch({ url, maxChars? })`: a GET that returns the page as readable text (HTML reduced, JSON and text as they are), flagged `untrusted: true` — facts to use, never instructions. Every request goes through **`createSafeFetch`**, which you can also use on its own (it is a drop-in `fetch`, e.g. for an MCP transport):
|
|
521
|
+
|
|
522
|
+
- **Its own DNS lookup, inside the connect.** The addresses that were checked are the addresses that are connected to, so DNS rebinding has nowhere to hide. A name with *any* unacceptable address is refused whole.
|
|
523
|
+
- **Refused by default:** loopback, private networks, link-local, CGNAT, multicast, reserved and documentation ranges, and **cloud metadata endpoints** (`169.254.169.254`, `fd00:ec2::254`, Alibaba, Oracle). IPv4 hidden in IPv6 (mapped, NAT64, 6to4, compatible) is judged as the IPv4 it is; the URL parser's tricks (`2130706433`, `0x7f.1`, `127.1`) are normalized first. `allowPrivateNetwork: true` opens the private ranges for an intranet agent — metadata and the never-routable ranges stay refused.
|
|
524
|
+
- **Allow / deny** by host (`example.com`, `*.example.com` — subdomains, not the apex), IP or CIDR; deny wins; an allow list is exclusive. A deny CIDR also applies to what a *name* resolves to.
|
|
525
|
+
- **https only, port 443, GET/HEAD**, no credentials in URLs — widen with `protocols`, `ports`, `methods`.
|
|
526
|
+
- **Redirects** are followed up to `maxRedirects` (3), **each hop judged again**, never from https to http, credentials dropped across origins.
|
|
527
|
+
- **Bounded:** `timeoutMs` (15 s) for the whole request, `maxResponseBytes` (2 MB) on what is read *after decompression* (a small gzip cannot unpack into the heap).
|
|
528
|
+
- Certificates are always verified; `ca` adds a CA to trust (an internal one).
|
|
529
|
+
|
|
530
|
+
Approval: an open-internet `web_fetch` is a way to leak data through the URL, so it asks like a **write** (`ask-writes` prompts for it); with an `allow` list it is **read-only**. Each request emits `egress.request` (`url` is origin and path only — no query string — `allowed`, `status` / `reason`).
|
|
531
|
+
|
|
532
|
+
What it is not: a sandbox for what a fetched *page says* — that stays data the model reads, which is why the result is flagged untrusted. And it does not govern the provider's own calls, or the MCP servers and tools you configure — those are your configuration, not the model's. A subagent has its own `egress` (none unless you set it). The browser sibling cannot pin DNS; see `@dudko.dev/agent-web`.
|
|
533
|
+
|
|
534
|
+
## Learning: lessons that outlive the task
|
|
535
|
+
|
|
536
|
+
Switch on `learning` and the agent keeps a notebook. When it hits a problem and finds the way around it — a tool error it resolved, a wrong assumption it corrected, a procedure it had to look up — it writes the lesson down with `save_skill`, and the lesson **is a [skill](#skills)**: it shows up in the planner's `SKILLS:` index right away (even for the next step of the same run) and loads with `load_skill` like any other. Nothing new to learn on the reading side.
|
|
537
|
+
|
|
538
|
+
```ts
|
|
539
|
+
import { createAgent, DirSkillStore } from '@dudko.dev/agent'
|
|
540
|
+
|
|
541
|
+
const agent = await createAgent({ ...config, learning: true }) // this session (the process)
|
|
542
|
+
// ...or keep them as <dir>/<name>/SKILL.md, readable, editable and committable like your own:
|
|
543
|
+
const agent = await createAgent({ ...config, learning: { store: new DirSkillStore('./learned-skills') } })
|
|
544
|
+
|
|
545
|
+
agent.listSkills() // [{ name, description, learned }]
|
|
546
|
+
agent.listLearnedSkills() // the agent's own, with origin: when, which run, revision, where it read
|
|
547
|
+
await agent.forgetSkill('image-format-jpg') // one went stale
|
|
548
|
+
```
|
|
549
|
+
|
|
550
|
+
It is a *knowledge* feature and nothing else:
|
|
551
|
+
|
|
552
|
+
- **Knowledge, never policy.** A lesson is loaded under a header saying it is the agent's own hint, not an instruction from the user; the user's request and your rules win a conflict. It cannot grant a permission, switch a tool on or loosen `egress`.
|
|
553
|
+
- **A normal gated tool.** `save_skill` / `forget_skill` go through [tool approval](#tool-approval-and-autopilot) like any write — `ask-writes` asks a human first, `read-only` refuses, a `toolRules` entry can deny them.
|
|
554
|
+
- **No secrets.** Names, descriptions, instructions and sources are scanned for API keys, tokens, private keys and the like; a hit is refused to the model (and never stored). Sources keep origin and path only.
|
|
555
|
+
- **Yours stay yours.** A skill you configured is never overwritten or deleted by the agent; on a name clash yours wins. Caps: `maxSkills` (50), `maxSkillChars` (6000), a one-line description.
|
|
556
|
+
- **Provenance.** Each lesson records when it was written, by which run, its revision and — recorded by the harness, not by the model — the pages `web_fetch` read in that run.
|
|
557
|
+
- **Quiet by default for the rest.** Without `learning` there are no extra tools and not a word more in the prompts. `learning: { nudge: false }` keeps the tools but drops the guidance that tells the executor to write lessons down (and to look for a fix before giving up — with `egress` on, `web_fetch` can read the docs).
|
|
558
|
+
|
|
559
|
+
Every save emits `skill.learned` (`name`, `description`, `update`, `chars`, `sources`), every forget `skill.forgotten`. CLI: `AGENT_LEARNING=on`, `AGENT_LEARNING_DIR=<dir>`; in the REPL `/skills` lists skills (the agent's own marked) and `/forget <name>` deletes one.
|
|
560
|
+
|
|
496
561
|
## Autonomy
|
|
497
562
|
|
|
498
563
|
The stage prompts are written for an agent that acts on its own:
|
|
@@ -576,7 +641,11 @@ Notes:
|
|
|
576
641
|
interface IAgent {
|
|
577
642
|
run(options: IAgentRunOptions): Promise<IAgentRunResult>
|
|
578
643
|
listTools(): { name: string; description: string; server?: string; readOnly?: boolean }[]
|
|
579
|
-
listSkills(): { name: string; description: string }[]
|
|
644
|
+
listSkills(): { name: string; description: string; learned?: true }[]
|
|
645
|
+
listLearnedSkills(): ISkill[] // the agent's own lessons, with origin (see Learning)
|
|
646
|
+
readonly usage: IUsage // tokens this agent has spent over all its runs (a snapshot; see below)
|
|
647
|
+
resetUsage(): void
|
|
648
|
+
forgetSkill(name: string): Promise<boolean> // delete one of them; false if there is none
|
|
580
649
|
compact(options: { history: IConversationTurn[]; signal?: AbortSignal; force?: boolean }): Promise<{
|
|
581
650
|
history: IConversationTurn[]
|
|
582
651
|
summary?: string
|
|
@@ -626,9 +695,9 @@ The package ships a REPL CLI as `dd-agent`. After install, npm makes it availabl
|
|
|
626
695
|
dd-agent --env-file=.env
|
|
627
696
|
```
|
|
628
697
|
|
|
629
|
-
`--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`).
|
|
698
|
+
`--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`, `/agents`, `/stop`, `/exit`).
|
|
630
699
|
|
|
631
|
-
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_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.
|
|
700
|
+
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.
|
|
632
701
|
|
|
633
702
|
**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.
|
|
634
703
|
|