@dudko.dev/agent 0.0.54 → 0.0.55

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
@@ -137,6 +137,7 @@ Pass an event handler as the second argument to `createAgent`, or per run via `o
137
137
  | `skill.activated` | A skill became active (`by: 'plan' \| 'tool'`; `server` for a skill an MCP server serves). |
138
138
  | `tools.discovered` | `find_tools` activated tools (`query`, `names`). |
139
139
  | `tool.approval-requested` / `tool.approval-resolved` | The approval gate asked / decided (`automatic` for rule, mode and timeout denials). `mcpSkills` on a request: the call runs code while the run acts on those MCP skills (always asked). `skill` on a request (`name: 'load_skill'`): an MCP server's skill about to enter the model's context - see [MCP skills](#mcp-skills-experimental). `parked: true` on a resolution: nobody answered yet - the run [parks](#parking-a-run-a-persons-answer-or-a-result-from-outside) with the question. |
140
+ | `user.question-asked` / `user.question-answered` | The model asked the person a question ([`askUser`](#asking-the-user-a-question-with-choices)) and `onQuestion` is being called (`id`, `question`, `options: { label, description? }[]`, `multiple`, `allowOther`, `step?`, `subagent?` - the model's text, cleaned) / how it ended (`id`, `action: 'choice' \| 'other' \| 'declined' \| 'timeout' \| 'stopped'`, `automatic`, `choice?` - the labels picked -, `reason?: 'handler-error' \| 'invalid-answer' \| 'cannot-park'`). Never the person's own words. With the journal the id is the id of the item a [park](#parking-a-run-a-persons-answer-or-a-result-from-outside) on it would have; a question the run parks on is answered in the attempt that resumes it. |
140
141
  | `mcp.elicitation-requested` / `mcp.elicitation-answered` | An MCP server asked the user for input during a tool call and `onElicitation` is being called (`id`, `server`, `tool`, `mode`, `message`, `requestedSchema?`, `url?`, `step?`, `subagent?` - the server's text, cleaned and capped) / the question was settled (`action`, `automatic`, `reason?`, `fields?` - field names, never a value). See [MCP elicitation](#mcp-elicitation-a-server-asks-the-user). |
141
142
  | `egress.request` | A `web_fetch` request (or `web_search`'s call to its [search API](#search-finding-the-page-to-fetch)), allowed or refused by the [egress policy](#egress-what-the-model-may-fetch) (`url` is origin and path only, `allowed`, `status?`, `reason?`). |
142
143
  | `media.generated` | A [media tool](#media-images-speech-and-transcription) wrote a file: `kind: 'image' \| 'speech'`, `path` (absolute), `mediaType`, `bytes`, `model`, `step?`. The bytes are in the file, never in an event. |
@@ -337,6 +338,7 @@ A run that needs something it cannot have now - a person's yes, the result of a
337
338
 
338
339
  - A question of the [approval gate](#tool-approval-and-autopilot) that `onRequest` answers with **`{ park: true }`**: a tool call to allow, or an [MCP server's skill](#mcp-skills-experimental) to let in (asked from `load_skill`).
339
340
  - A tool whose `execute` returns **`deferResult({ note? })`**: "the result will come from outside, later". Any tool may: a job queue, a webhook, a review. A [remote subagent](#remote-subagents-isolation-remote)'s `dispatch` may return it too, instead of awaiting the child.
341
+ - The model's own question ([`ask_user`](#asking-the-user-a-question-with-choices)) that `askUser.onQuestion` answers with **`{ park: true }`**: the call defers, and the item is a `'tool'` item with `toolName: 'ask_user'`, `note` the question and its options as plain text, and the `id` of its `user.question-asked` event. Answer it with `{ output: { choice: ['<label>'] } }`, `{ output: { other: '<text>' } }` or `{ output: { declined: true } }`: on the resume the answer is checked against the question (an answer that does not fit, or `{ error }`, counts as not answered), `user.question-answered` is emitted with the same id, and the model reads the plain-words result.
340
342
 
341
343
  ```ts
342
344
  import { createAgent, deferResult } from '@dudko.dev/agent'
@@ -875,6 +877,37 @@ A denied call throws `ToolDeniedError` inside the tool, so the step records `ok:
875
877
 
876
878
  **Time a person takes does not count.** From `tool.approval-requested` until the decision, the step's `llmTimeoutMs` is stopped, and so are the limits above it that the decision holds up: the `timeoutMs` of the subagent the call runs in, and the step of the run that called that subagent. When the decision is in they go on with the time they had left - not with a fresh limit, and with no more than the wait added. The same holds for an [MCP elicitation](#mcp-elicitation-a-server-asks-the-user). The wait's own bound is `timeoutMs` here (5 minutes unless you set it, above). Stopping the run (`signal`, `control.stopSubagent`) still ends a wait at once, and token and tool-call budgets are not affected. There is no run-level time limit in the config; a limit you put on the run's `signal` yourself (`AbortSignal.timeout()`) is a stop like any other and is not paused.
877
879
 
880
+ ## Asking the user: a question with choices
881
+
882
+ Off by default, the agent never asks: it picks the most reasonable reading and says what it assumed ([Autonomy](#autonomy)). With `askUser`, the **model** may ask the person ONE closed question instead of guessing - when the task leaves a choice only the person can make - and the host shows it with buttons:
883
+
884
+ ```ts
885
+ const agent = await createAgent({
886
+ ...config,
887
+ askUser: {
888
+ // the host decides, never the model; `signal` aborts when the agent stops waiting
889
+ onQuestion: async (req, { signal }) => {
890
+ // req.question, req.options ({ label, description? }[]), req.multiple, req.allowOther,
891
+ // req.step, req.runId, req.subagent - all the MODEL's text, cleaned: show it as plain text
892
+ const picked = await ui.ask(req, { signal })
893
+ return picked ? { choice: [picked] } : { declined: true } // or { other: 'own words' }
894
+ // under persistence.journal: return { park: true } to park the turn until the answer comes
895
+ },
896
+ timeoutMs: 300_000, // the default: 5 minutes; 0 or Infinity = until the run is stopped
897
+ maxPerRun: 3, // the default: an agent must not nag
898
+ },
899
+ })
900
+ ```
901
+
902
+ - **The tool.** The executor gets the built-in `ask_user` with `{ question, options: [{ label, description? }], multiple?, allowOther? }`. Its bounds are checked in the tool, not in the schema (Anthropic's structured output refuses `maxItems`): **2 to 6 options**, a label of at most **80** characters, a description of at most **200**, a question of at most **500**, no two labels alike (letter case and spaces aside), all measured after control and bidirectional-override characters are removed. A bad input is a tool error that says what to fix - nobody is asked, nothing is counted. No consent gate and no tool-call budget: it has a cap of its own. A host tool named `ask_user` is refused at `createAgent`.
903
+ - **The answer.** `{ choice: [label, ...] }` (labels exactly as offered; one unless `multiple`), `{ other: text }` (only when `allowOther`; cleaned, at most 2000 characters reach the model) or `{ declined: true }`. The model reads it in plain words (`The user chose: "Draw it (SVG)". Go on with that.`), or that the person declined, did not answer in time or could not be asked - and to go on with its best judgment and say what it assumed. A handler that throws, or answers anything else, counts as not answered (`automatic`); `{ park: true }` without the journal too (`reason: 'cannot-park'`).
904
+ - **Off is off.** Without `onQuestion` there is no tool: `askUser: true` / `{}` is "on, the handler comes later" (the [CLI](#cli) fills it in; a subagent gets its calling run's), and an agent without one sends exactly what it sends without `askUser`. With it the planner and the executor get one note each (`ASKING THE USER:`, the one exception to "never ask the user"; run-stable).
905
+ - **The cap.** `maxPerRun` (default 3) questions per run, its helpers' and subagents' included, a resumed run counting on (`IRunSnapshot.questionsAsked`; a question the journal replays counts too). Past it the host is not asked and nothing is emitted: the model is told to decide.
906
+ - **Time.** A question waits `timeoutMs` (default 300 000, `ASK_USER_TIMEOUT_MS`; `0`, `Infinity` or more than 2^31 - 1 = no bound of its own; negative or `NaN` fails `createAgent`), then counts as not answered (`action: 'timeout'`). The step's `llmTimeoutMs` - and a subagent's `timeoutMs` above it - stops meanwhile, as for an approval. A stop ends the wait at once (`action: 'stopped'`). The handler's `signal` aborts when the question ends without its answer (`TimeoutError`, the stop's reason, or the handler's own error), never after one.
907
+ - **Events.** `user.question-asked` and `user.question-answered` (see [Streaming events](#streaming-events)): the labels picked at most - **never the person's own words**, which go to the model as the tool's result only (so they are in `step.tool-result` and the trace like any tool result).
908
+ - **Subagents.** A helper the model started has `ask_user` when its caller has it and asks through the caller (the same handler, one count, marked `subagent: { id, depth }`). An in-process subagent the host defined (`createSubagentTool({ config, isolation: 'in-process' })`) has it only when its own config sets `askUser`, and asks through **the run that called it** - that run's handler, count and cap, marked with the subagent's id; its own `onQuestion` is used only when it runs on its own. A worker or remote subagent cannot ask (`onQuestion` cannot cross a worker: `createSubagentTool` refuses it there). A pipeline node asks through its own config's handler.
909
+ - **Parking.** Under [`persistence.journal`](#the-call-journal-exact-resume) `{ park: true }` parks the turn at the end of the tool round (see [Parking a run](#parking-a-run-a-persons-answer-or-a-result-from-outside)); a question answered live is recorded with the tool result and replayed on a resume - the person is never asked twice for one call.
910
+
878
911
  ## Large MCP catalogs
879
912
 
880
913
  **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.
@@ -1771,6 +1804,8 @@ The stage prompts are written for an agent that acts on its own:
1771
1804
  - The **replanner** prefers revising around a failure over finishing with nothing, and never revises into an "ask the user" step.
1772
1805
  - 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.
1773
1806
 
1807
+ With [`askUser`](#asking-the-user-a-question-with-choices) on, the planner and the executor get one exception: when only the person can make a choice, the executor may ask ONE closed question with 2-6 options (`ask_user`), at most `maxPerRun` times per run; otherwise everything above holds.
1808
+
1774
1809
  Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — the model never asks for permission in text.
1775
1810
 
1776
1811
  ## Configuration
@@ -1783,6 +1818,7 @@ Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — th
1783
1818
  | `baseURL` | Required for `openai-compatible` (point at your self-hosted server) and `azure` (point at your deployment URL). Optional for the rest. |
1784
1819
  | `apiKey` | Optional: unset, the provider's SDK reads its own environment variable (`OPENAI_API_KEY`, ...). **Ignored** for `google-vertex` (which authenticates via Google ADC) and by a model object. |
1785
1820
  | `providerOptions` | Escape hatch for provider-specific factory options. Spread into the SDK's `create*()` call after `baseURL` / `apiKey`, so anything documented for the underlying SDK works: e.g. `{ apiVersion, resourceName }` for Azure, `{ region, accessKeyId, secretAccessKey }` for Bedrock, `{ project, location, googleAuthOptions }` for Vertex, `{ accountId }` (or `{ binding }` inside a Worker) for Cloudflare. Per-stage override blocks have their own `providerOptions`; if absent, the top-level value is used. |
1821
+ | `askUser` | Off by default. `{ onQuestion(req, { signal }), timeoutMs?, maxPerRun? }` gives the model `ask_user`: ONE closed question with 2-6 options (`multiple`, `allowOther` optional), answered by the host with `{ choice: [label] }`, `{ other: text }`, `{ declined: true }` - or, under `persistence.journal`, `{ park: true }`. Without `onQuestion` no tool (`true` / `{}`: the handler comes later). At most `maxPerRun` (3) per run, each waiting `timeoutMs` (300000; the step's limit stops meanwhile). The question is the model's text, cleaned: show it as plain text. See [Asking the user](#asking-the-user-a-question-with-choices). |
1786
1822
  | `subagents` | Off by default. `{ dynamic: true }` or `{ dynamic: { maxDepth, maxChildren, maxConcurrent, budgetShare, minTokens, timeoutMs, defaultTools } }` gives the model `spawn_subagent`: it starts a helper agent for a sub-task, with a subset of its own tools and a share of what is left of its budgets. A helper can only have less than the run that starts it. See [Dynamic subagents](#dynamic-subagents-helpers-the-model-starts-itself). |
1787
1823
  | `sandbox` | Off by default. `true` or `{ timeoutMs, memoryLimitBytes, maxOutputChars, maxCodeChars }` gives the model `run_js`: JavaScript it wrote runs in QuickJS/WebAssembly inside a worker thread that is killed at the deadline. Needs the optional peer `quickjs-emscripten`. See [Running code](#running-code-the-sandbox). |
1788
1824
  | `model` | Default model for every stage (executor / planner / synthesizer) when no per-stage override is set: a model id of `providerType`, or a ready AI SDK model object (`AgentModel`), used as it is. See [Your own model object](#your-own-model-object). |
@@ -2043,6 +2079,8 @@ The newer features are env-driven too: `AGENT_THINKING` (`off | minimal | low |
2043
2079
 
2044
2080
  **`AGENT_MCP_ELICITATION`** (`off` by default, `form`, `all`) lets a connected MCP server ask *you* something in the middle of a tool call ([MCP elicitation](#mcp-elicitation-a-server-asks-the-user)). The question is printed as a quotation (`| …` in front of every line: the server's words, not the CLI's) and answered at the prompt, in the same queue as the approval questions: `y` fills in the form field by field (Enter takes a field's default or skips an optional one, a value of the wrong kind is asked for again up to three times, `/cancel` dismisses), `n` declines, anything else cancels. `all` also accepts URL mode: the link is printed for you to open yourself - the CLI never opens it. What you type goes to that server only; a question nobody decided (a cap, a timeout, a form that cannot be shown) is reported as `!! <tool>: the server's question was answered "cancel" automatically (<reason>)`. The defaults of the library apply (5 minutes per question, 5 per tool call, 20 per run); helpers started with `AGENT_SUBAGENTS` cannot ask.
2045
2081
 
2082
+ **`AGENT_ASK_USER`** (`off` by default, `on`) lets the agent ask *you* a closed question instead of guessing ([Asking the user](#asking-the-user-a-question-with-choices)). It is printed with numbered choices - `[question] the agent asks: How should I make the picture?`, then `1. Generate an image - uses the image quota`, `2. Draw it (SVG)` and what you may type - in the same queue as the approval questions: a number (several, `1 3`, when the question allows it), your own answer when it allows one, or Enter (`0`, `skip`) to skip; a line that is none of those is asked for again up to three times, then counts as skipped. The agent then goes on with your answer, or with its own judgment and says what it assumed. The library's defaults apply (3 questions per task, 5 minutes each); a question nobody answers is closed with one line (`[question] closed: <why> - the agent goes on with its own judgment`), and one that ended without you (`!! the agent's question went unanswered (...)`) is reported. Your own answer goes to the model - it is the answer - and never into a question event; helpers started with `AGENT_SUBAGENTS` ask through the same prompt (`a helper (…) asks`).
2083
+
2046
2084
  **MCP skills at the prompt.** A server in `MCP_SERVERS` may add `"skills": true` (or `{"consent": "once-per-skill" | "ask" | "never", "dynamic": true}` - `dynamic` also takes the server's generated skills, no checksums; any other value of it is refused at start, by the server's name) with `"protocol": "auto"` or `"modern"` - `skills` without one of those is refused at start, by the server's name, since the extension is written against 2026-07-28 and would otherwise be silently off ([MCP skills](#mcp-skills-experimental)). Before one of its skills reaches the model you are shown it at the prompt, in the same queue as the approval questions: `[skill] the server "docs" offers the skill "pdf-processing" (docs/pdf-processing)`, its description, size and URI, and the first 12 lines of exactly what the model would read, each behind `| ` (the server's words, not the CLI's; control characters removed); a generated skill adds `the server publishes no checksums for this skill: you approve the copy the agent just read, and only that copy is used` (and, from a server that cannot list its files, `the server cannot list this skill's files: that copy is its SKILL.md alone`); then `allow? [y]es / [n]o / [a]lways for this server`. `y` lets it in (for the session under `once-per-skill`, the default; for this task under `ask`), `a` every skill of that server except nested ones, anything else declines (`the user declined the skill`). A question nobody answers is closed like an approval's: `[skill] closed: <why> - docs/pdf-processing was not loaded`. `/skills` lists the server's skills with the others. `"connectTimeoutMs"` (default 30000, `0` = no bound) bounds one server's connect.
2047
2085
 
2048
2086
  **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.
@@ -2121,6 +2159,7 @@ This package moved from `@modelcontextprotocol/sdk` 1.x to `@modelcontextprotoco
2121
2159
  - **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.
2122
2160
  - **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.
2123
2161
  - **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`.
2162
+ - **`ask_user` is opt-in and capped by design.** An agent that asks is an agent that waits: off by default, and without a handler there is no tool and no prompt note - the wire is the one without `askUser`. Three questions a run by default, because an agent must not nag; the person's own words go to the model only, never into a question event. The browser sibling's [`docs/design.md`](https://github.com/dudko-dev/agents/blob/main/packages/agent-web/docs/design.md) ("Asking the user") has the reasons; the rules are one file shared byte for byte by both packages (`src/ask-user-shared.ts`).
2124
2163
  - **`.npmignore` is mostly inert.** `package.json#files` is an explicit allowlist (`["dist", "README.md"]`), so `.npmignore` only affects what npm strips **inside** that allowlist. The file is kept as a backstop in case `files` is ever broadened.
2125
2164
 
2126
2165
  ## License