@dudko.dev/agent 0.0.36 → 0.0.38

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
@@ -103,6 +103,7 @@ Pass an event handler as the second argument to `createAgent`, or per run via `o
103
103
  | `tools.discovered` | `find_tools` activated tools (`query`, `names`). |
104
104
  | `tool.approval-requested` / `tool.approval-resolved` | The approval gate asked / decided (`automatic` for rule, mode and timeout denials). |
105
105
  | `subagent.start` / `subagent.event` / `subagent.complete` / `subagent.error` | A subagent tool call's lifecycle and its forwarded child events. |
106
+ | `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). |
106
107
  | `usage` | Per LLM call; `phase` is `'plan' \| 'execute' \| 'replan' \| 'synthesize' \| 'compact' \| 'subagent'`. |
107
108
 
108
109
  ```ts
@@ -301,7 +302,7 @@ import { createAgent, loadSkillsFromDir, parseSkillMarkdown, defineSkill } from
301
302
 
302
303
  const skills = await loadSkillsFromDir('./skills') // every ./skills/<skill>/SKILL.md
303
304
  const agent = await createAgent({ ...config, skills })
304
- agent.listSkills() // [{ name, description }]
305
+ agent.listSkills() // [{ name, description }] (+ learned: true on the agent's own, see Learning)
305
306
  ```
306
307
 
307
308
  Progressive disclosure keeps them cheap:
@@ -406,6 +407,148 @@ Several calls in one model step run in parallel (bounded by `maxConcurrent`). Th
406
407
 
407
408
  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
 
410
+ ### Profiles: other models, params and context per call
411
+
412
+ A subagent normally has one fixed configuration. `profiles` lets the **parent model** choose between named variants of it, per call:
413
+
414
+ ```ts
415
+ const researcher = createSubagentTool({
416
+ name: 'researcher',
417
+ description: 'Research a question with the docs tools and report the facts',
418
+ config: { ...cheapConfig }, // the default: a small, quick model
419
+ profiles: {
420
+ deep: {
421
+ description: 'A hard question that needs a thorough, multi-source answer',
422
+ config: { model: 'a-strong-model', thinking: 'high', maxIterations: 8 },
423
+ },
424
+ skeptic: {
425
+ description: 'Check a claim someone else made; look for what contradicts it',
426
+ config: { systemPrompt: 'Assume the claim is wrong until the sources show otherwise.' },
427
+ },
428
+ },
429
+ })
430
+ ```
431
+
432
+ - The tool gains an optional `profile` argument, an enum of the names; leaving it out runs the base config. Each profile's `description` is appended to the tool's description, so the parent chooses by *when to use it* — write them that way.
433
+ - A profile's `config` is laid **over** the base config, field by field and shallow: a profile's `limits` replaces the base's `limits`, it is not merged into it. Anything in `IAgentConfig` can differ — the model (even another provider), `thinking`, limits, `systemPrompt`, `skills`, `tools`.
434
+ - With `'worker'` isolation a profile's `config` must be structured-cloneable like the base one, and that is checked when the tool is created — not hours into a run, when the profile is first chosen.
435
+ - The choice is bounded by what **you** listed: the parent cannot pick an arbitrary model, so cost stays in your hands. An unknown name is a tool error the model can correct, raised before any child starts or is announced.
436
+ - `subagent.start` carries `profile` when one was chosen. Child tokens are charged to the parent as always, whichever profile ran.
437
+ - The child's context is still just `task`. A different context means a profile that changes `systemPrompt`, `skills` or `tools` — the parent cannot hand a child more of its own conversation.
438
+
439
+ ## Steering a run that is already going
440
+
441
+ `run()` takes one input and resolves when the run is over. To say something in the meantime
442
+ ("use the staging database", "skip the report") or to stop one subagent out of several, make a
443
+ `RunControl` and pass it to the run:
444
+
445
+ ```ts
446
+ import { createAgent, createRunControl } from '@dudko.dev/agent'
447
+
448
+ const control = createRunControl()
449
+ const running = agent.run({ input: 'Triage the new tickets', control, onEvent })
450
+
451
+ control.send('Ignore anything older than a week') // any time while it runs
452
+ control.subagents() // [{ id, name, task, profile?, startedAt }] - who is running now
453
+ control.stopSubagent(id) // stops that one; the run goes on
454
+ const result = await running
455
+ result.undelivered // messages the run never got to show the model - send them as the next run
456
+ ```
457
+
458
+ A message is **not an interrupt**. The run never cuts a tool call short (it may be a write); the
459
+ message waits for the next boundary and is then shown to the model:
460
+
461
+ | It arrives... | It is shown... | `message.delivered` `at` |
462
+ | --- | --- | --- |
463
+ | during a step, while tools are being called | to the executor on its **next round** of that step, as a user turn after the tool results | `round` |
464
+ | between steps | to the **replanner**, and to every later step | `step` |
465
+ | after the last step, before the answer is written | to the synthesizer | `final` |
466
+ | while the answer is being written, or after the run ended | to **nobody** - it comes back in `result.undelivered` | - |
467
+
468
+ - **A message always makes the replanner look at the plan again**, at the end of the step it was
469
+ delivered in - also after the *last* planned step, where it may add work: a plan made before the
470
+ user spoke may no longer be the right one. That call (`replan.decision` with
471
+ `cause: 'user-message'`) ignores `maxRevisions`, a revise it makes is not counted against it, and
472
+ `replanAfter` does not matter. It costs one extra model call per boundary, not per message, and
473
+ there is no cap on messages. It does need an iteration left (`maxIterations`); without one the
474
+ message still reaches the synthesizer. A replanner that says `finish` ends the run early - that
475
+ is how "stop, that is enough" works.
476
+ - Every later stage sees what the user said (a "Messages from the user" block in its prompt), so a
477
+ correction is not forgotten two steps later - also on an executor retry. Run snapshots carry it
478
+ (`userUpdates`), so a resumed run still knows it. Prompts of a run **without** a control are
479
+ byte-for-byte what they were.
480
+ - A message sent **before** the run starts is queued and announced (`message.queued`) when it
481
+ starts. `send()` returns `false` for an empty text and once the run is over; it never throws.
482
+ - An aborted or failed run **throws**, so it cannot return `undelivered`: read
483
+ `control.pending()` - it keeps reporting what the run never delivered until the control serves
484
+ another run (which then starts clean).
485
+ - Use one control per run. A hand-made object in its place is refused: only the ones
486
+ `createRunControl()` makes are read.
487
+
488
+ **Stopping a subagent.** `stopSubagent(id)` aborts that child (and its worker thread, if it has
489
+ one). Its delegation fails with a message the parent model can route around ("stopped by the user
490
+ ... carry on without its result"), `subagent.error` carries `stopped: true`, and sibling subagents
491
+ and the run are untouched. Only a child that has started is listed; one still waiting for a
492
+ `maxConcurrent` slot is not. A child's own subagents are not individually stoppable - stopping the
493
+ child stops them with it. What each child does is the `subagent.event` stream, the same events the
494
+ parent emits.
495
+
496
+ ## Egress: what the model may fetch
497
+
498
+ 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`:
499
+
500
+ ```ts
501
+ const agent = await createAgent({
502
+ // ...
503
+ egress: {
504
+ allow: ['docs.example.com', '*.github.com'], // optional: only these (then web_fetch counts as read-only)
505
+ deny: ['internal.example.com', '10.0.0.0/8'], // optional: always refused, wins over allow
506
+ },
507
+ })
508
+ // egress: true = any public host over https. CLI: AGENT_EGRESS=on, AGENT_EGRESS_ALLOW, AGENT_EGRESS_DENY, ...
509
+ ```
510
+
511
+ 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):
512
+
513
+ - **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.
514
+ - **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.
515
+ - **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.
516
+ - **https only, port 443, GET/HEAD**, no credentials in URLs — widen with `protocols`, `ports`, `methods`.
517
+ - **Redirects** are followed up to `maxRedirects` (3), **each hop judged again**, never from https to http, credentials dropped across origins.
518
+ - **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).
519
+ - Certificates are always verified; `ca` adds a CA to trust (an internal one).
520
+
521
+ 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`).
522
+
523
+ 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`.
524
+
525
+ ## Learning: lessons that outlive the task
526
+
527
+ 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.
528
+
529
+ ```ts
530
+ import { createAgent, DirSkillStore } from '@dudko.dev/agent'
531
+
532
+ const agent = await createAgent({ ...config, learning: true }) // this session (the process)
533
+ // ...or keep them as <dir>/<name>/SKILL.md, readable, editable and committable like your own:
534
+ const agent = await createAgent({ ...config, learning: { store: new DirSkillStore('./learned-skills') } })
535
+
536
+ agent.listSkills() // [{ name, description, learned }]
537
+ agent.listLearnedSkills() // the agent's own, with origin: when, which run, revision, where it read
538
+ await agent.forgetSkill('image-format-jpg') // one went stale
539
+ ```
540
+
541
+ It is a *knowledge* feature and nothing else:
542
+
543
+ - **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`.
544
+ - **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.
545
+ - **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.
546
+ - **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.
547
+ - **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.
548
+ - **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).
549
+
550
+ 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.
551
+
409
552
  ## Autonomy
410
553
 
411
554
  The stage prompts are written for an agent that acts on its own:
@@ -489,7 +632,9 @@ Notes:
489
632
  interface IAgent {
490
633
  run(options: IAgentRunOptions): Promise<IAgentRunResult>
491
634
  listTools(): { name: string; description: string; server?: string; readOnly?: boolean }[]
492
- listSkills(): { name: string; description: string }[]
635
+ listSkills(): { name: string; description: string; learned?: true }[]
636
+ listLearnedSkills(): ISkill[] // the agent's own lessons, with origin (see Learning)
637
+ forgetSkill(name: string): Promise<boolean> // delete one of them; false if there is none
493
638
  compact(options: { history: IConversationTurn[]; signal?: AbortSignal; force?: boolean }): Promise<{
494
639
  history: IConversationTurn[]
495
640
  summary?: string
@@ -539,9 +684,11 @@ The package ships a REPL CLI as `dd-agent`. After install, npm makes it availabl
539
684
  dd-agent --env-file=.env
540
685
  ```
541
686
 
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`).
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`).
688
+
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.
543
690
 
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.
691
+ **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.
545
692
 
546
693
  For local development against the source tree:
547
694