@dudko.dev/agent 0.0.49 → 0.0.51

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
@@ -37,6 +37,7 @@ On top of the loop:
37
37
  - **[Subagents](#subagents-worker_threads)** — a whole agent exposed as one tool, isolated in a `worker_thread`.
38
38
  - **[Images, speech, transcription](#media-images-speech-and-transcription)** — three optional tools, each mounted only when its model is configured; files on disk, never bytes in the context.
39
39
  - **[Dynamic subagents](#dynamic-subagents-helpers-the-model-starts-itself)** — opt-in: the model starts a helper for a sub-task itself, with a subset of its own tools and a share of its budgets; a helper can only have less than its parent.
40
+ - **[Call journal](#the-call-journal-exact-resume) and [parking](#parking-a-run-a-persons-answer-or-a-result-from-outside)** — opt-in: a resume replays the interrupted step instead of running it again (no write twice), and a run that waits for a person's answer or a result from outside parks without failing and is resumed later, by any worker.
40
41
  - **[Autonomy](#autonomy)** — the agent looks things up and decides on its own instead of asking.
41
42
 
42
43
  ## Install
@@ -96,7 +97,7 @@ await agent.close()
96
97
 
97
98
  ### Streaming events
98
99
 
99
- 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.
100
+ 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, and `seq` / `attempt`, its place in the run: `attempt` is 1 for a fresh run and one more for every [resume](#resume-after-crash), `seq` counts the events of one attempt from 1. Ordered by `(attempt, seq)`, the events of a run are a total order, across crashes and resumes (see [Running on many workers](#running-on-many-workers-scale-out-hooks)). The full union is [`AgentEvent`](./src/types.ts); this is the whole list, by stage.
100
101
 
101
102
  **The loop**
102
103
 
@@ -135,7 +136,7 @@ Pass an event handler as the second argument to `createAgent`, or per run via `o
135
136
  | --- | --- |
136
137
  | `skill.activated` | A skill became active (`by: 'plan' \| 'tool'`; `server` for a skill an MCP server serves). |
137
138
  | `tools.discovered` | `find_tools` activated tools (`query`, `names`). |
138
- | `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). |
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. |
139
140
  | `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). |
140
141
  | `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?`). |
141
142
  | `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. |
@@ -146,8 +147,11 @@ Pass an event handler as the second argument to `createAgent`, or per run via `o
146
147
 
147
148
  | Event | When |
148
149
  | --- | --- |
149
- | `subagent.start` / `subagent.event` / `subagent.complete` / `subagent.error` | A subagent's lifecycle and its forwarded child events - a static one (`createSubagentTool`) or a helper the model started (`subagents.dynamic`, `dynamic: true`). `start` carries `parentId` and `depth`, `error` carries `stopped` when the user stopped it. See [the subagent tree](#the-subagent-tree-from-the-events). |
150
+ | `subagent.start` / `subagent.event` / `subagent.complete` / `subagent.error` | A subagent's lifecycle and its forwarded child events - a static one (`createSubagentTool`, local or [remote](#remote-subagents-isolation-remote)) or a helper the model started (`subagents.dynamic`, `dynamic: true`). `start` carries `parentId` and `depth`, `error` carries `stopped` when the user stopped it. A `subagent.event` envelope is numbered (`seq`) in the parent run; the child event inside keeps its own `runId` / `seq` / `attempt`. See [the subagent tree](#the-subagent-tree-from-the-events). |
150
151
  | `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). |
152
+ | `lease.lost` | With [`runLease`](#running-on-many-workers-scale-out-hooks): a renew answered false (`reason: 'refused'`), threw (`'error'`, the message in `error`) or did not answer before the lease ran out (`'expired'`); `owner`. The run is aborted at once and persists nothing more; it rejects with `RunLeaseError` (`lost: true`). |
153
+ | `run.parked` | The run [parked](#parking-a-run-a-persons-answer-or-a-result-from-outside): `items` (what it waits for, each with its stable `id` and `kind: 'approval' \| 'tool'`), `at`. `run()` resolves with `result.parked`; the snapshot is `'waiting'`. |
154
+ | `journal.diverged` | A resumed run's request at `position` is not the one [recorded there](#the-call-journal-exact-resume) (`kind: 'model' \| 'tool'`, `stage?`): from here the run is live. Positions only, never content; once per run (and per run inside one of its calls). |
151
155
 
152
156
  **Pipelines**
153
157
 
@@ -227,14 +231,167 @@ await agent.run({ input: '', resumeFromRunId: '<saved-run-id>' })
227
231
 
228
232
  Caveats:
229
233
 
230
- - **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.
234
+ - **Idempotency.** Resume re-enters the loop at the saved checkpoint (the iteration boundary after the last successful step). Without a [call journal](#the-call-journal-exact-resume), 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 - or give the agent `persistence.journal`, which replays the step instead of running it again (below).
231
235
  - **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.
232
236
  - **Plan changes.** The saved `currentPlan` (post any revise) is what gets used on resume — the planner is not re-invoked.
233
237
  - **Caps inherit.** `iterations`, `revisions`, usage, the tool-call count (`toolCallCount`) and the escalation count (`escalations`) carry over, so per-run caps still apply across the boundary; so do the active skills (`activeSkills`) and the trace summary (`traceSummary` / `traceSummaryUpTo`).
234
238
  - **Terminal status.** Resuming a run with `status: 'complete'` throws — re-read the saved `text` directly instead.
235
- - **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`.
239
+ - **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. Instead, a resume writes `onRunResume` (the loaded snapshot with the new `attempt`, status `'executing'`) **before** it emits anything - or, without that hook, the same write to `onStepComplete`. Unlike the other write hooks a failure there refuses the resume (see [Running on many workers](#running-on-many-workers-scale-out-hooks)). Otherwise `onStepComplete` only fires for steps the resumed run actually executes; pre-resume steps are already in the loaded `trace`.
240
+ - **Attempts.** Every snapshot carries the `attempt` that wrote it (1 for the run as first started; a snapshot written before the field existed reads as 1); a resume runs as the next one, and its events say so. A snapshot whose `attempt` is not a positive integer is not resumed.
236
241
  - **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.
237
242
  - **runId hygiene.** Persisted `runId`s end up in filesystem paths (`<sandboxRoot>/<runId>/`) and are validated against `^[a-zA-Z0-9_-]{1,128}$`. A persistence adapter that returns a snapshot whose `runId` differs from the requested one, or that contains path-unsafe characters, is rejected.
243
+ - **Your own run id.** `agent.run({ input, runId })` starts a fresh run under an id you choose instead of a random UUID - a host that keys runs by ids of its own (a session and a turn) gives one, so that a retry finds the same run: start it with `runId`, and if that is refused because the run exists, resume it with `resumeFromRunId`. The id follows the rule above (anything else is refused, a non-string too). `run()` rejects before anything of the run - no lease kept, no model call, no event, no write - for `runId` together with `resumeFromRunId` (a resume keeps the id of the run it resumes), when `persistence.loadRun` has a snapshot for the id (`Run "<id>" already exists (status "…"); resume it with resumeFromRunId…`: a run on record is never written over, whatever its status), and when `persistence.journal` has entries for an id `loadRun` does not know (a run under it stopped before its first snapshot: it cannot be resumed, and the two runs would share one journal - clear it, or use another id). A `loadRun` or `journal.load` that throws refuses the run as well. With `runLease` the lookup happens while the run's lease is held, so two workers cannot both find the id free; without one it is a check, not a lock. The run's sandbox directory is named by the id, so a fresh run under an id finds what a crashed run under it left there.
244
+
245
+ #### The call journal: exact resume
246
+
247
+ `persistence.journal` records, as the run goes, every language-model response and every tool result, and a resume **replays** the step a crash interrupted instead of running it again:
248
+
249
+ ```ts
250
+ const persistence: IPersistence = {
251
+ ...snapshots, // onRunStart / onStepComplete / onRunResume / onRunPark / loadRun (needed)
252
+ journal: {
253
+ // Append-only, per run, read back whole and in order. Entries are plain JSON.
254
+ append: (runId, entry) => db.insert('journal', { runId, entry: JSON.stringify(entry) }),
255
+ load: async (runId) => (await db.select('journal', { runId })).map((r) => JSON.parse(r.entry)),
256
+ },
257
+ }
258
+ ```
259
+
260
+ - **What is recorded.** For a model call: the parts the SDK needs to continue (text, reasoning and its provider metadata, tool calls, the finish reason) and what the call cost (`usage`). For a tool call: the result **as the model saw it** (after the output cap), the result itself when it is small, or the error the model read. Built-in tools (`load_skill`, `read_skill_file`, `find_tools`) are not recorded: their effects are on the run's own state, so they run again on a replay. A call that runs a run inside it - a [helper the model started](#dynamic-subagents-helpers-the-model-starts-itself), an in-process [subagent](#subagents-worker_threads) - runs again too, and **its** calls replay from the same journal. A worker's or a remote child's calls are not recorded one by one: their tool call's result is.
261
+ - **Where.** Every entry has a `position` that is the same on every attempt: `<segment>.<n>` is the n-th recorded model call of a segment (`0` before the loop, `1`, `2`, ... the loop's iterations, `f` the answer; a failed call and its retry share one), `.t<i>` the i-th tool call of that response, `.q<j>` a question asked inside that tool call, `/c<k>/` a run started inside it. A model entry carries a sha256 `hash` of its request (prompt, tools, tool choice, response format - a stable serialization), a tool entry the hash of its name and arguments and the id of the response that asked for it (`parent`), so a call is never answered from another branch of the run.
262
+ - **Order.** A model response is appended **before** any tool call it contains runs (its tool calls are held until it is on record; text streams live); a tool result is appended right after the tool returns, before the model sees it.
263
+ - **Fail-closed.** An append that throws ends the run as failed (`JournalError`, an `error` event, the snapshot `failed`): a side effect the journal does not know about would break the guarantee. A failed `load` refuses the resume. With [`runLease`](#running-on-many-workers-scale-out-hooks), nothing is appended once the lease is lost.
264
+ - **The replay.** On `resumeFromRunId` the run loads the journal and goes through the interrupted step in order: a model call whose request matches the one recorded at its position gets the recorded response - no request goes out, [`sharedLimits`](#running-on-many-workers-scale-out-hooks) is not asked; a tool call whose name and arguments match gets the recorded result - the tool does not run (it still counts against `maxToolCalls`). At the first call that does not match, the run **diverged**: one `journal.diverged` event (positions, never content), and from there it is live. At the end of the journal it goes on live without a word.
265
+ - **Events and usage.** Replayed calls emit their events again under the new attempt, as a re-run step did. A replayed model call is **not charged again**: its usage events carry nothing for it, `agent.usage` and `sharedLimits.afterModelCall` never hear of it. The run's own total (`result.usage`, the snapshots, the run's limits) counts it once, from the journal, at the moment the stage that made it reports.
266
+ - **The one window that cannot be closed.** A tool that ran, but whose result was not appended before the process died, runs again on the resume. Everything before it replays; everything after it never happened. A tool that must never run twice still needs its own guard (an idempotency key) for that window.
267
+ - Without `persistence.journal` nothing changes: no wrapper around the models, the same requests on the wire. With it, a fresh run sends exactly what it sends without it (a test compares the two).
268
+
269
+ ### Running on many workers (scale-out hooks)
270
+
271
+ One agent process is one worker. To run many - a queue of runs, workers that crash, a run that one worker started and another finishes - the package gives three small **optional** hooks (and the [call journal](#the-call-journal-exact-resume) for exact resume and [parking](#parking-a-run-a-persons-answer-or-a-result-from-outside)); the broker, the store and the deployment are yours. Without them nothing changes: no timer, no wrapper around the models, the same requests on the wire (the golden fixtures pin it).
272
+
273
+ **Event order.** Every event of a run carries `seq` and `attempt` (see [Streaming events](#streaming-events)). A client that orders by `(attempt, seq)` gets one total order of the run's events, however often its workers died. A resume puts its attempt on record **before** its first event (`persistence.onRunResume`, else `onStepComplete`), so a crash at any point - even before the resumed run's first checkpoint - never lets two attempts share a number. Delivery is **at-least-once**: the step a crash interrupted runs again under the next attempt, so its events (and its tool calls: see "Idempotency" above) come again, with the new attempt's numbers. A consumer that deduplicates keeps the last attempt's copy of a step.
274
+
275
+ **`runLease`: one worker at a time owns a run.** The host's lease, anything with an atomic "take it if nobody holds it" (Redis `SET NX PX`, a database row, etcd):
276
+
277
+ ```ts
278
+ import { createAgent, RunLeaseError } from '@dudko.dev/agent'
279
+
280
+ const agent = await createAgent({
281
+ ...config,
282
+ persistence,
283
+ runLease: {
284
+ acquire: (runId, { owner, ttlMs }) => store.takeIfFree(runId, owner, ttlMs), // true = held
285
+ renew: (runId, { owner, ttlMs }) => store.extendIfMine(runId, owner, ttlMs), // false = lost
286
+ release: (runId, { owner }) => store.dropIfMine(runId, owner),
287
+ ttlMs: 30_000, // default; renewed every ttlMs / 3
288
+ // owner: 'worker-7', // default: a random id per agent - agent.leaseOwner
289
+ },
290
+ })
291
+ ```
292
+
293
+ - **Acquire.** Before a run - fresh or resumed - does anything (a resume even before it reads its snapshot). `false` or a throw ends the run there: it rejects with `RunLeaseError` (`lost: false`), no model was called, no event was emitted, nothing was persisted.
294
+ - **Renew.** Every `ttlMs / 3` while the run goes. `false`, a throw, or no answer before the lease would run out (`ttlMs` after the last answer that kept it) means the lease is **lost**, and the reading is strict: the run is aborted at once (its tools' signals too), **no further snapshot is written**, terminal or not - another worker may own the run by now, and a late write would corrupt its state - one `lease.lost` event says so, and the run rejects with `RunLeaseError` (`lost: true`, `reason: 'refused' | 'error' | 'expired'`). A lost lease is not released: it is not this worker's any more.
295
+ - **Release.** When the run ends, every way (success, failure, stop, a resume that could not load); a failed release is only logged.
296
+ - The timers never keep a process alive and stop on every way out. Subagents and the helpers the model starts run under their parent's lease: never one of their own (a `runLease` in a subagent's config is dropped). With a lease every snapshot carries `leaseOwner`, so a store can refuse a write from anyone but the owner (fencing) - the TTL alone cannot rule out a paused worker writing late.
297
+ - `ttlMs` must be 1000 ms to 2^31 - 1 ms, the owner 1-256 characters, all three methods functions - `createAgent` throws otherwise.
298
+
299
+ **`sharedLimits`: limits shared by every worker.** A provider's rate limit or a tenant's budget lives in the host's store; the agent asks before every language-model call and says what each used:
300
+
301
+ ```ts
302
+ const agent = await createAgent({
303
+ ...config,
304
+ sharedLimits: {
305
+ // Wait (a rate limit) or throw (a refusal: a budget). `signal`: the call was given up.
306
+ beforeModelCall: async (call, { signal }) => {
307
+ await bucket.take(call.stage, { signal })
308
+ if (await budget.spent(call.runId)) throw new Error('budget spent')
309
+ },
310
+ // Not awaited; a throw is only logged.
311
+ afterModelCall: (call, usage, { ok }) => budget.add(call.runId, usage.totalTokens),
312
+ },
313
+ })
314
+ ```
315
+
316
+ - `call` is `{ runId?, stage, provider?, modelId, estimatedInputTokens?, maxOutputTokens? }`. `stage` is `'planner' | 'executor' | 'replanner' | 'synthesizer' | 'compaction' | 'route'`; `runId` is the run the **host** started (a helper's, a subagent's calls carry it: they are spent for it) and is absent for a call outside a run (`agent.compact()`, a pipeline's route call); `estimatedInputTokens` is the prompt and the tool definitions, estimated like compaction does (errs high).
317
+ - **Every** language-model call goes through it: the four stages, the compaction summaries (and `agent.compact()`), a pipeline's route call, escalated tiers, the helpers the model starts, and subagents - an in-process one under its own config's `sharedLimits` or else the calling run's, a worker one through the calling run's (asked over the worker protocol: functions cannot cross). A remote subagent's calls are the host's business. A test counts the calls per stage against the requests the model endpoint saw.
318
+ - **Not** through it: the [media models](#media-images-speech-and-transcription), the [Google search grounding call](#the-google-provider-google-search-through-gemini-grounding) and [decision models](#decision-models) - none is a language-model call of a stage, and each has its own `usage` phase. When the decision model is not confident, the ordinary replanner / route call that follows is a language-model call and is asked about.
319
+ - **A wait** counts against the call's own timeout (`llmTimeoutMs`, the step's limit) like a slow answer: it is not a person waiting, so the run's clock is not stopped. A call given up while `beforeModelCall` still decides is not sent; if the hook lets it through later, `afterModelCall` is told it ended (`ok: false`, zero usage), so a host counting slots gets every one back.
320
+ - **A refusal** fails that call with `ModelCallRefusedError` (exported; `isModelCallRefused(err)` reads it anywhere down a `cause` chain), which is **never retried** - not by the package's retry, not by the AI SDK's, not on a stronger tier - even when its cause looks retryable (a 429). The stage then fails as it fails on any error: a refused **planner** call falls back to the one-step "answer directly" plan; a refused **executor** call fails the step and with it the run (`error` of phase `'execute'`, the snapshot `failed`), without escalation; a refused **replanner** call degrades to `continue` (`replan.decision.failed`, see [When the replanner fails](#when-the-replanner-fails)); a refused **synthesizer** call fails the run; a refused **compaction** call leaves the history / trace as it was (the next call carries the full context); a refused **route** call is no route. Inside a helper or a subagent the same rules apply to its run, and its failure is the tool call's.
321
+ - `afterModelCall(call, usage, { ok })`: once per call `beforeModelCall` let through, when it ends - finished, failed or cancelled.
322
+
323
+ **Remote subagents** (`createSubagentTool({ isolation: 'remote', dispatch })`) send a child to another worker: see [Remote subagents](#remote-subagents-isolation-remote).
324
+
325
+ [`examples/scale-out-memory.ts`](./examples/scale-out-memory.ts) has in-memory reference implementations of both hooks - a lease map with a TTL and a token bucket with a per-run budget - to show the wiring and the contract without a broker (single process only; the same logic in a shared store is the multi-worker version).
326
+
327
+ A whole deployment built on these hooks - sessions as Temporal workflows, each turn one `agent.run` in an activity whose heartbeat is the `runLease`, snapshots, events (`LISTEN/NOTIFY`) and a shared token bucket in Postgres, a stateless gateway with SSE, one Docker image and a Compose file - is in the monorepo: [`examples/swarm`](https://github.com/dudko-dev/agents/tree/main/examples/swarm).
328
+
329
+ ### Parking a run: a person's answer or a result from outside
330
+
331
+ A run that needs something it cannot have now - a person's yes, the result of a long job, a webhook, a review in another system - can **park**: it stops without failing, frees its worker, and is resumed later with the answer, by any worker, hours or days later. Parking needs the [call journal](#the-call-journal-exact-resume): the resume replays the run up to where it parked, so the model cannot ask for something else on the way back.
332
+
333
+ **Two things park.**
334
+
335
+ - 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`).
336
+ - 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.
337
+
338
+ ```ts
339
+ import { createAgent, deferResult } from '@dudko.dev/agent'
340
+
341
+ const agent = await createAgent({
342
+ ...config,
343
+ persistence, // with journal, loadRun and (best) onRunPark
344
+ toolApproval: { mode: 'ask-writes', onRequest: () => ({ park: true }) }, // ask a person later
345
+ tools: {
346
+ render_video: tool({
347
+ inputSchema: z.object({ script: z.string() }),
348
+ execute: async ({ script }) => {
349
+ await jobs.submit({ script }) // the result arrives by webhook
350
+ return deferResult({ note: 'queued on the render farm' })
351
+ },
352
+ }),
353
+ },
354
+ })
355
+
356
+ const result = await agent.run({ input: 'Make the video and send it to the client' })
357
+ if (result.parked) {
358
+ const { runId, items } = result.parked // items: [{ id, kind: 'approval' | 'tool', ... }]
359
+ await store.saveWaiting(runId, items)
360
+ }
361
+
362
+ // Later, anywhere - one way to resume:
363
+ await agent.run({
364
+ input: '',
365
+ resumeFromRunId: runId,
366
+ answers: {
367
+ [approvalId]: true, // or { approved: false, reason }, or { approved: true, remember: true }
368
+ [renderId]: { output: { url: 'https://cdn.example/video.mp4' } }, // or { error: 'render failed' }
369
+ },
370
+ })
371
+ ```
372
+
373
+ **At the end of the round.** When a call of a tool round parks, the round's other parallel calls settle first: a call that completes is recorded as usual, another park or deferral joins the list. Then, before the next model call (or when the step's tool loop ends), the run parks with **every** pending item of that round:
374
+
375
+ - its snapshot has status **`'waiting'`** and `parked: { runId, items, at }` - the rest of it is the run as it stood when the step started, which is where a resume replays from; it is written to `persistence.onRunPark` (else `onStepComplete`), and **not** fail-open: a park that cannot be put on record fails the run;
376
+ - one **`run.parked`** event carries the items; the question's `tool.approval-resolved` says `parked: true`;
377
+ - nothing more is sent: no model call, no deadline left behind; the lease is released;
378
+ - `agent.run()` **resolves** - not an error - with `text: ''` and `result.parked: { runId, items, at }`.
379
+
380
+ **The items.** Each has a stable `id` - derived from its journal position, so the same item has the same id however often the run is resumed (with the journal, an approval request's `id` is that id too) - and a `kind`:
381
+
382
+ - `'approval'`: `request` - the approval request as `onRequest` saw it (`toolName`, `input` after `inputSanitizer`, `step`, `subagent?`, and `skill` for an MCP skill's consent). Answer with a decision: `true` / `false`, `{ approved, reason?, remember? }` (`remember` as for any approval: for that agent instance's life);
383
+ - `'tool'`: `toolName`, `input` (after `inputSanitizer`), `note?`, `step?`, `subagent?`. Answer with the tool's result: `{ output: <JSON value> }`, or `{ error: string }` for a failure. The answer is **untrusted** external data: its shape is checked (plain JSON, nested at most 64 levels, at most 1 000 000 characters - `JOURNAL_LIMITS`), invisible characters are removed, `outputSanitizer` runs on it, and the model sees it through the tool's output cap - what any tool result goes through.
384
+
385
+ **Resuming.** `agent.run({ resumeFromRunId, answers })`: the run replays up to the round that parked - its completed calls are answered from the journal, the pending ones from `answers` - and goes on live. Answers go on record as they are used: a crash after the resume does not need them again (a retried resume that still sends one is not an error). An item left unanswered parks the run again at once, with the rest - nobody is asked again, the answered ones stay answered. An answer for an id that is not pending, or of the wrong shape for its item, is **refused** before the resume starts (nothing runs, no attempt goes on record). A resume that diverges before it reaches an item does not use its answer (a warning says so).
386
+
387
+ **Guards.**
388
+
389
+ - Without `persistence.journal`, `{ park: true }` is a denial (`cannot park: parking a run needs config.persistence.journal`) and `deferResult()` fails its tool call with a clear error. A `'waiting'` run cannot be resumed without the journal.
390
+ - Only a question asked **from a tool call** can park. The consent asked outside one - an MCP skill the planner picked, a resumed run's active skills - is a denial on `{ park: true }`: the model can still `load_skill` it.
391
+ - Inside a [helper the model started](#dynamic-subagents-helpers-the-model-starts-itself) or an in-process [subagent](#subagents-worker_threads), a park or a deferral **parks the whole run**, with the item (its `subagent` says which helper). On the resume the helper's call runs again and its own calls replay from the journal, up to the item. A subagent whose own agent has a journal while the calling agent has none cannot wait: its tool call fails. A pipeline node whose run parks fails the node.
392
+ - [MCP elicitation](#mcp-elicitation-a-server-asks-the-user) does not park. A 2025-revision question is a request bound to the open connection and to the tool call in flight, which cannot outlive the worker; the 2026-07-28 `input_required` answer could be parked later (the call is sent again with the answer), but is not in this release.
393
+ - **The core keeps no timers and no retries for pending items**: how long an item may wait, reminders, escalation to another person, a job's own retries - those are the host's. A parked run's wait counts against no limit (it is not running); the resumed attempt runs on a new clock, and the step that parked gets its full `llmTimeoutMs` again, as a retried step does.
394
+ - A round parks when **all** its calls have settled: a question of the round that is still open with a person (not answered `{ park: true }`) holds the park until it is answered or its `toolApproval.timeoutMs` runs out.
238
395
 
239
396
  ### OpenTelemetry
240
397
 
@@ -292,7 +449,7 @@ What is different on 2026-07-28:
292
449
  - **OAuth** is unchanged: the probe is simply the first request to get the 401.
293
450
  - **stdio.** `'auto'` and `'modern'` ask on a **second, short-lived process** started from the same `command` (a 2025 server may exit on a request it does not know; that must not cost the session its process): the command runs twice per connect. A server that does not answer the probe at all is taken for a 2025 one after 5 s (half the connect timeout, if that is less).
294
451
 
295
- `MCP_SERVERS` (the CLI) takes the field as it is: `{"crm":{"url":"https://…","protocol":"auto"}}`.
452
+ `MCP_SERVERS` (the CLI) takes the field as it is: `{"crm":{"url":"https://…","protocol":"auto"}}` - and `skills` and `connectTimeoutMs` the same way (see [CLI](#cli)).
296
453
 
297
454
  ### MCP over OAuth 2.1
298
455
 
@@ -315,7 +472,7 @@ await finishMcpOAuth(auth, { code, state, iss }) // iss: pass it when the redire
315
472
  await agent.reconnect()
316
473
  ```
317
474
 
318
- 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.
475
+ 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 static `headers` (plus `protocol`, `skills` and `connectTimeoutMs`); OAuth is a library-level feature.
319
476
 
320
477
  - **`iss` (RFC 9207).** `finishMcpOAuth` checks the `iss` query parameter of the redirect against the authorization server the flow was started with, after `state` and before the code is exchanged. A different issuer is refused (a mix-up attack: a code meant for one server sent to another), and so is a missing `iss` when the server's metadata says `authorization_response_iss_parameter_supported: true`. The comparison is exact, character for character. Read `iss` off the callback URL together with `code` and `state`; `checkAuthorizationResponseIssuer` is the rule on its own.
321
478
  - **`clientMetadataUrl` (CIMD).** Host a client ID metadata document and pass its URL: an authorization server that advertises `client_id_metadata_document_supported` takes the URL as the `client_id`, and no registration request is made. Other servers get dynamic registration as before, and a registration already in the store wins over both. The URL must be https with a path (anything else throws when the provider is built), and the document must list the same `redirect_uris` as `redirectUrl`.
@@ -554,7 +711,7 @@ Progressive disclosure keeps them cheap:
554
711
 
555
712
  1. The planner and executor system prompts carry only an index: `- name: description`.
556
713
  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).
557
- 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 (an MCP server's skill is the one exception: a person sees it first - [MCP skills](#mcp-skills-experimental)).
714
+ 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 - or, when `path` names a directory of the skill (`templates/`, `.` for the root), its listing: `{ name, directory, files, directories, more? }`, the direct children by their paths inside the skill, sorted, at most 64 (`more` counts the rest; a file of that name wins). Both always run without approval (an MCP server's skill is the one exception: a person sees it first - [MCP skills](#mcp-skills-experimental)).
558
715
 
559
716
  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).
560
717
 
@@ -570,6 +727,8 @@ const agent = await createAgent({
570
727
  docs: { url: 'https://docs.example.com/mcp', protocol: 'auto', skills: true },
571
728
  // A server you vetted: its skills load without asking anyone.
572
729
  ours: { url: 'https://mcp.internal.example/mcp', protocol: 'auto', skills: { consent: 'never' } },
730
+ // A server you trust with its GENERATED skills (no checksums): see "Generated skills" below.
731
+ gen: { url: 'https://gen.example.com/mcp', protocol: 'auto', skills: { dynamic: true } },
573
732
  },
574
733
  // A person sees each skill before the model does (see "Consent" below).
575
734
  toolApproval: { onRequest: askThePerson },
@@ -578,7 +737,7 @@ agent.listSkills()
578
737
  // [{ name: 'docs/pdf-processing', description: 'Extract, fill and assemble PDF documents [from the MCP server "docs" - third-party]', server: 'docs' }, ...]
579
738
  ```
580
739
 
581
- - **Off by default.** Without `skills` (`true`, or `{ consent }`) the extension is not declared
740
+ - **Off by default.** Without `skills` (`true`, or `{ consent, dynamic }`) the extension is not declared
582
741
  and nothing of it is sent. With it, the extension is declared only where 2026-07-28 may be spoken (`protocol:
583
742
  'auto'` or `'modern'`): on `protocol: 'legacy'` (or none) a warning says so and nothing is
584
743
  asked, and an `'auto'` connection that ends on a 2025 revision lists no skills. There is no
@@ -604,16 +763,48 @@ agent.listSkills()
604
763
  whatever the mode, a rule or an earlier "always allow" say; with no `onRequest`, it is refused.
605
764
  - **Caps.** At most 32 skills per server and 64 in all in the catalog, 16 000 characters of a
606
765
  skill's instructions and 32 000 of one file - each cut said, never silent. Entries over the
607
- extension's own limits (512 files, 16 MiB), `"dynamic"` ones (no digests to check), and ones
608
- whose URI and frontmatter name disagree are refused, with a warning.
766
+ extension's own limits (512 files, 16 MiB), `"dynamic"` ones (no digests to check; unless the
767
+ server has `skills: { dynamic: true }`, below), and ones whose URI and frontmatter name disagree
768
+ are refused, with a warning.
609
769
  - **Changes.** A change of a server's skills is announced as a resource list change: the agent
610
770
  re-lists them the way it re-lists tools after a `tools/list_changed` (between runs).
771
+ - **Directories.** `read_skill_file` with a directory of an MCP skill (`templates/`, `.`) lists
772
+ it from the entry the skill was loaded and approved with - the held entry is authoritative, and
773
+ the same consent comes first as for a file. When the server declared `directoryRead`, the agent
774
+ also sends `resources/directory/read` for that directory (`skill://<path>/<dir>`, no trailing
775
+ slash) to THAT server, only to see whether the skill changed there: a child the server lists and
776
+ the entry does not is never shown - not its name, URI or type; the listing gets a fixed `note`
777
+ ("The server now lists 1 more item(s) here than the approved entry of this skill: the skill
778
+ changed on the server ..."), a warning is logged (counts only) and the server's skills are
779
+ listed again between runs (as after a resource list change; a changed entry is asked about
780
+ again). A child of the entry the server no longer lists stays in the listing and is also named
781
+ in `notServed` (a read of it will fail). If the directory read fails, the listing comes from the
782
+ entry alone (a log line); a stop of the run still stops it. Without `directoryRead` the method
783
+ is never called. A generated skill's directories are listed from its snapshot, the same way.
784
+ - **Generated skills (opt-in, per server).** A `"dynamic"` entry - the server generates the skill
785
+ and publishes no checksums - is declined unless THAT server has `skills: { dynamic: true }`
786
+ (no agent-wide switch). It then joins the catalog like any other, its line ending
787
+ `[from the MCP server "gen" - third-party, no checksums]`. When it would enter the context -
788
+ BEFORE anyone is asked - the agent reads all of it once: `SKILL.md` (its frontmatter compared
789
+ with the entry's) and, if the server declared `directoryRead`, its directory tree (direct
790
+ children each time, only `inode/directory` children inside the skill, never twice) and every
791
+ file found. Bounds: 512 files and 16 MiB read (the extension's limits, counted on what is
792
+ read), 64 directories, 8 levels deep, and 64 MiB held by all of the agent's copies
793
+ (`MCP_SKILL_SNAPSHOTS_MAX_BYTES`); past any of them it is declined - nobody is asked, the model
794
+ is told why, a warning says it. The agent computes each file's size and SHA-256 itself, and that
795
+ copy (a "snapshot") is the skill's entry from then on: the request carries `skill.dynamic` and
796
+ the copy's size, files and text; a yes binds to the copy's digests (after a refresh the agent
797
+ takes a new copy - one that differs is asked about again under `'once-per-skill'`, the same
798
+ bytes are not); and the model gets that copy only - its body, and every file from memory, never
799
+ read from the server again. Without `directoryRead` the copy is `SKILL.md` alone
800
+ (`skill.noFileListing`; no other file can be read). Nothing of a copy is written anywhere -
801
+ not to a checkpoint, an event or a log. `'never'` works too, for a vetted server.
611
802
  - **Consent: a person sees a skill before the model does.** The first time a server's skill would
612
803
  enter the model's context - `load_skill`, the planner picking it, a resumed run, or
613
804
  `read_skill_file` of one of its files - its `SKILL.md` is read and verified, then put to
614
805
  `toolApproval.onRequest` as a request with `skill` (`McpSkillConsentView`: `server`, `name`,
615
806
  `skill`, `uri`, `description`, `size` / `totalSize`, `files` / `fileCount`, `byUri`, `nestedIn`,
616
- `consent`, and `body` - the very text the model would read, cleaned and capped as the model gets
807
+ `dynamic` / `noFileListing` (a generated skill: the copy just read), `consent`, and `body` - the very text the model would read, cleaned and capped as the model gets
617
808
  it); `toolName` is `load_skill`, `input` what it was called with. A yes lets it in; `remember:
618
809
  true` ("Always for this server") lets in that server's other skills for the agent's life; a no
619
810
  keeps all of it out - the model is told so ("The user did not allow the skill ... nothing of it
@@ -640,8 +831,9 @@ agent.listSkills()
640
831
  [security notes](https://github.com/dudko-dev/agents/blob/main/packages/agent-web/docs/security.md#mcp-skills-third-party-instructions)
641
832
  say what a server's skill can and cannot do; its
642
833
  [design notes](https://github.com/dudko-dev/agents/blob/main/packages/agent-web/docs/design.md#mcp-skills-one-catalog-namespaced-under-a-preamble-opt-in)
643
- why it is namespaced, loaded under a preamble and opt-in, and why the consent is what it is. Not
644
- done (yet): `resources/directory/read`.
834
+ why it is namespaced, loaded under a preamble and opt-in, why the consent is what it is, why
835
+ a directory is listed from the entry with the server asked only for staleness, and why a
836
+ generated skill is a snapshot served from memory, opt-in per server.
645
837
 
646
838
  ## Tool approval and autopilot
647
839
 
@@ -665,6 +857,8 @@ agent.setToolApprovalMode('autopilot') // the toggle; applies to the next call,
665
857
  agent.getToolApprovalMode()
666
858
  ```
667
859
 
860
+ `onRequest` may also answer **`{ park: true }`**: "the answer will come later, from outside the run" - the run parks at the end of the tool round and is resumed with the answer (needs `persistence.journal`; see [Parking a run](#parking-a-run-a-persons-answer-or-a-result-from-outside)). Without the journal it is a denial.
861
+
668
862
  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.
669
863
 
670
864
  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`.
@@ -731,6 +925,8 @@ const agent = await createAgent({
731
925
  })
732
926
  ```
733
927
 
928
+ **It does not park.** A question here is answered while the tool call waits; it cannot [park the run](#parking-a-run-a-persons-answer-or-a-result-from-outside) (see why there).
929
+
734
930
  **The host decides, never the model.** The question is not shown to the model and the model cannot answer it. The callback returns `{ action: 'accept', content }`, `{ action: 'decline' }` (a no) or `{ action: 'cancel' }` (dismissed). An `accept` or a user's own `decline` / `cancel` goes to the server and the tool call ends with whatever the server then answers.
735
931
 
736
932
  **Off by default, and off means nothing changes.** Without `onElicitation` no capability is declared, so a server cannot ask (on 2026-07-28 it refuses the call; a server that asks anyway gets the `input_required` error [above](#mcp-protocol-revision)), and every request is byte for byte what it was (`tests/mcp-elicitation.test.ts` compares the wire with the fixture recorded before the option existed). `elicitation` settings without a callback change nothing either.
@@ -824,7 +1020,7 @@ const researcher = createSubagentTool({
824
1020
  name: 'researcher',
825
1021
  description: 'Research a self-contained question and report the findings',
826
1022
  config: { ...childConfig }, // a full IAgentConfig for the child
827
- isolation: 'worker', // default; or 'in-process'
1023
+ isolation: 'worker', // default; or 'in-process' / 'remote' (below)
828
1024
  tools: { lookup }, // host tools for the child
829
1025
  maxConcurrent: 4, // parallel calls beyond this queue
830
1026
  timeoutMs: 120_000,
@@ -842,6 +1038,35 @@ Several calls in one model step run in parallel (bounded by `maxConcurrent`). Th
842
1038
 
843
1039
  The worker entry ships as `dist/subagent-worker.js` and is resolved next to the bundle, from the ESM and the CJS build alike.
844
1040
 
1041
+ A subagent runs under its parent's [lease](#running-on-many-workers-scale-out-hooks) (a `runLease` in its config is dropped) and its model calls go through the parent run's [`sharedLimits`](#running-on-many-workers-scale-out-hooks) unless its own config has one (a worker child's are asked over the worker protocol).
1042
+
1043
+ ### Remote subagents (`isolation: 'remote'`)
1044
+
1045
+ The child runs wherever your `dispatch` sends it - another worker, another machine, a queue. No config crosses: you decide the child's config over there.
1046
+
1047
+ ```ts
1048
+ const researcher = createSubagentTool({
1049
+ name: 'researcher',
1050
+ description: 'Research a self-contained question',
1051
+ isolation: 'remote',
1052
+ dispatch: async (task, { signal, emit }) => {
1053
+ // task: { id, name, profile?, input, parentRunId?, rootRunId?, depth }
1054
+ const job = await queue.submit({ input: task.input, profile: task.profile, signal })
1055
+ for await (const event of job.events()) emit(event) // forwarded as subagent.event
1056
+ return { text: job.answer, usage: job.usage } // usage: charged once, here
1057
+ },
1058
+ profiles: { deep: { description: 'A thorough look' } }, // names only: dispatch decides
1059
+ timeoutMs: 120_000,
1060
+ })
1061
+ ```
1062
+
1063
+ - `task` is the child's input (what the parent model wrote) and who it is for: the subagent's `id` (the one its `subagent.*` events carry), the tool's `name`, the `profile` the parent model chose, the calling run (`parentRunId`), the run the host started (`rootRunId`) and the `depth`.
1064
+ - `emit` forwards the remote child's events into the parent's stream as the same `subagent.event` envelopes a local child produces. They are **untrusted**: each must be a plain object with a well-formed `type`, at most 64 000 characters as JSON, at most 10 000 per call (`REMOTE_SUBAGENT_LIMITS`); long strings are clipped like a local child's; anything else is dropped, with one warning; an `emit` after `dispatch` settled is ignored. Forwarded `…-requested` / `…-resolved` waits stop the caller's clock as a local child's do.
1065
+ - **Usage is charged once**, from what `dispatch` resolves with (a `usage` event of phase `'subagent'`; a forwarded `usage` event is shown, never charged). Every count is clamped to a non-negative number (a remote child cannot hand budget back). A `dispatch` that throws an error with a `usage` field is charged that.
1066
+ - The answer must be `{ text: string }` (clipped to `outputMaxChars`); anything else fails the tool call. Or `dispatch` resolves with **`deferResult({ note? })`** when the answer will come later: the run [parks](#parking-a-run-a-persons-answer-or-a-result-from-outside) with the call pending (needs `persistence.journal`), and the host resumes it with the child's answer as `{ output }` - no `subagent.complete` is emitted for it.
1067
+ - A stop of the parent (the run, the step, `stopSubagent`, `timeoutMs`) aborts `signal`, and the tool call does not wait for a `dispatch` that ignores it.
1068
+ - `config`, `tools` and a profile's `config` make no sense here and are refused when the tool is made, as is `dispatch` on a local isolation. A remote child's tool approvals and questions are the host's business: they are not bridged to the parent's gate.
1069
+
845
1070
  ### Profiles: other models, params and context per call
846
1071
 
847
1072
  A subagent normally has one fixed configuration. `profiles` lets the **parent model** choose between named variants of it, per call:
@@ -1378,17 +1603,24 @@ validation. It answers the same as `RegExp.test` on what it accepts.
1378
1603
  - **Join.** A node activated by several edges gets all their outputs in one visit. With
1379
1604
  `join: 'all'` an activated node is *deferred* while any other activated node can still reach it
1380
1605
  through the graph (conditions aside) - so a fan-in waits for its slower branch even when the
1381
- branches have different lengths. If every activated node is deferred (they wait for each other in
1382
- a cycle), all of them run. `join: 'any'` never defers: the node runs once per wave it is
1383
- activated in.
1606
+ branches have different lengths. If every activated node is deferred (they reach each other
1607
+ through a loop), only the waits within one pass of the loop count: a wait that holds only by
1608
+ going round, back to the loop's *head* (the node every path from the entry into the loop
1609
+ passes), is for the next pass and is dropped. If that still leaves every node deferred, all of
1610
+ them run. `join: 'any'` never defers: the node runs once per wave it is activated in.
1384
1611
  - **Loops** are allowed. When starting a node would exceed `maxNodeVisits` for it, or `maxRuns` for
1385
1612
  the pipeline, that activation is dropped (`pipeline.node.skipped`); the run goes on with what is
1386
1613
  left, ends normally, and the result carries `stoppedBy: 'maxNodeVisits'` or `'maxRuns'`
1387
1614
  (`maxRuns` wins when both happened).
1388
- - **A fan-in inside a loop** has a limit: when a `join: 'all'` node and a slower branch that leads
1389
- to it can also reach each other through the loop, they wait for each other, so both run and the
1390
- join fires without that branch. Use `join: 'any'` there, or keep the fan-in out of the cycle (a
1391
- loop around the whole fan-out and fan-in works).
1615
+ - **A fan-in inside a loop.** A loop that goes back to the fan-out or to any node before it
1616
+ (`a → b → join`, `a → c → d → join`, `join → a`) works: on every pass the join waits for its
1617
+ slower branch and runs once with both outputs, whatever the order of the edges. A loop that goes
1618
+ back *into* a branch (`join → c` instead) has no head - it is entered at `c` and at the join -,
1619
+ so the join and that branch wait for each other, both run, and the join fires without that
1620
+ branch: loop back to a node before the fan-out, or use `join: 'any'` there. The pass rule is
1621
+ asked only when every activated node waits: a node outside a loop that the loop feeds
1622
+ (`a ↔ b`, `a → x`) still waits while the loop goes on, and runs once, with the output of every
1623
+ pass.
1392
1624
  - **The end.** The run ends when nothing is activated. A *terminal* visit is one that activated
1393
1625
  nothing (no edge fired, or a cap dropped what it fired). `result.text` is the output of the last
1394
1626
  terminal node to finish; several of the same wave are joined under `## <name>` headings.
@@ -1439,6 +1671,93 @@ process, the caps bound its loops, and it can only name what `nodeResolver` regi
1439
1671
  `node.settings` reaches your `configure` and nothing else. The graph engine is the same file as in
1440
1672
  the browser sibling, so a definition runs the same in both.
1441
1673
 
1674
+ ### Running the graph yourself
1675
+
1676
+ `createPipeline` is a scheduler with `createAgent` as its node runner. Both halves are public, so a
1677
+ host can keep the scheduler and run every node its own way - a queue job, a remote worker, a child
1678
+ workflow - and make the route call where the node ran:
1679
+
1680
+ ```ts
1681
+ import { pickPipelineRoute, preparePipeline, runPipelineGraph } from '@dudko.dev/agent'
1682
+
1683
+ const plan = preparePipeline(definition) // validates (PipelineValidationError) and compiles
1684
+ const result = await runPipelineGraph(
1685
+ plan,
1686
+ async (node, input, ctx) => {
1687
+ // input: { request, from: [{ nodeId, name?, text }], visit } - renderPipelineNodeInput(input)
1688
+ // is the text a createPipeline node is given.
1689
+ const text = await jobs.run(node.id, input, { signal: ctx.signal }) // your runner
1690
+ if (!node.routes?.length) return { text }
1691
+ // The route call createPipeline makes: the node's decision model, then its planner model.
1692
+ const { route, usage } = await pickPipelineRoute(node, text, {
1693
+ config: configOf(node), // the node's IAgentConfig
1694
+ signal: ctx.signal,
1695
+ onEvent: ctx.emit,
1696
+ })
1697
+ return { text, usage, route }
1698
+ },
1699
+ { input: 'A release note for v2', signal, onEvent, onAbort: 'reject' },
1700
+ )
1701
+ ```
1702
+
1703
+ The runner's contract:
1704
+
1705
+ - **When it is called.** Once per visit, never for an activation a cap refused (`plan.maxNodeVisits`
1706
+ / `plan.maxRuns`: the definition's `limits` or the defaults). All visits of a wave are started, in
1707
+ the order their nodes were first activated, before any is awaited; the next wave starts when all
1708
+ of them have settled. A visit's answer is applied (events, trace, edges) when it settles.
1709
+ - **What it returns.** `{ text, usage?, route? }`. `text` is what the edges test (not a string
1710
+ counts as `''`); `usage` is added to `result.usage`, every numeric field; `route` must be one of
1711
+ `node.routes`' labels exactly as written - anything else, or none, is no route. To pick one with a
1712
+ model of your own: `PIPELINE_ROUTER_SYSTEM` and `renderPipelineRoutePrompt(node, text)` are the
1713
+ prompt, `matchPipelineRoute(node, answer)` turns the answer into a label.
1714
+ - **When it fails.** A runner that rejects fails the run with a `PipelineNodeError` (`nodeId`,
1715
+ `visit`, `cause`), whatever `onAbort` says: the other visits' `ctx.signal` aborts, and what they
1716
+ return afterwards is ignored.
1717
+ - **Abort.** `signal` aborts the visits in flight (their `ctx.signal`) and settles the run at once,
1718
+ without waiting for them: it rejects with an `AbortError` (`onAbort: 'reject'`, the default, as
1719
+ `createPipeline` does here) or resolves with what it has and `stoppedBy: 'aborted'` (`'resolve'`,
1720
+ as the browser sibling's does). Aborted before it starts: no visit at all.
1721
+ - **Events.** `onEvent` gets the `pipeline.*` events `createPipeline` sends; `ctx.emit(event)`
1722
+ forwards one of the node's own, with `nodeId` and `visit`, until the run is over.
1723
+
1724
+ `pickPipelineRoute(node, text, { config, signal?, onEvent? })` resolves with `{ route?, usage }`:
1725
+ the decision model of `config` first (`decisionModel`, when it is confident of a label), else a
1726
+ structured-output call to its planner model with its call options, `llmTimeoutMs`, `llmMaxRetries`
1727
+ and `sharedLimits`. No label, or a failed call, is no route; an abort rejects. The model is built
1728
+ once per config object.
1729
+
1730
+ **Deterministic by contract.** The engine - `preparePipeline`, `runPipelineGraph`, the conditions -
1731
+ reads no clock, no randomness and no timer, and does no I/O: the same definition, input and runner
1732
+ answers, arriving in the same order (and an abort at the same point), give the same calls, events,
1733
+ trace and result. So it can be a deterministic scheduler, replayed from a log of the runner's
1734
+ answers. It needs nothing but the JavaScript language: where there is no `AbortController`,
1735
+ `ctx.signal` is a stand-in (`aborted`, `reason`, `onabort`, `throwIfAborted()`, `addEventListener` /
1736
+ `removeEventListener`), where there is no `DOMException` the abort error is an `Error` named
1737
+ `AbortError`, and of your `signal` only `aborted` and `addEventListener` / `removeEventListener`
1738
+ for `'abort'` are read. `pickPipelineRoute` calls a model, so it is not part of that: it belongs
1739
+ where the node runs.
1740
+
1741
+ **The engine alone: `@dudko.dev/agent/pipeline-engine`.** The main entry loads the whole agent -
1742
+ `ai`, `zod`, the MCP client, `node:*` -, which a bundled orchestrator cannot import (a workflow
1743
+ sandbox has the language and little else). The engine has an entry point of its own, ESM and
1744
+ CommonJS with types, whose file imports nothing:
1745
+
1746
+ ```ts
1747
+ // In the workflow: the scheduler only; every node runs outside it (an activity, a job).
1748
+ import { preparePipeline, runPipelineGraph } from '@dudko.dev/agent/pipeline-engine'
1749
+ ```
1750
+
1751
+ It exports `preparePipeline`, `runPipelineGraph`, `validatePipeline`, `normalizePipeline`,
1752
+ `testPipelineCondition`, `renderPipelineNodeInput`, `renderPipelineRoutePrompt`,
1753
+ `matchPipelineRoute`, `PIPELINE_ROUTER_SYSTEM`, `PIPELINE_LIMITS`, `PipelineValidationError`,
1754
+ `PipelineNodeError` and every pipeline type - the same names as the main entry.
1755
+ `tests/pipeline-determinism.test.ts` holds the built ESM and CommonJS files to the contract: no
1756
+ import and no `require` (a shared chunk would be one), and the same runs inside a `node:vm`
1757
+ context with only the language's globals. It is a copy of the engine the main entry carries, not
1758
+ the same objects: an error thrown by one is not `instanceof` the other's class - compare
1759
+ `error.name`.
1760
+
1442
1761
  ## Autonomy
1443
1762
 
1444
1763
  The stage prompts are written for an agent that acts on its own:
@@ -1469,7 +1788,7 @@ Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — th
1469
1788
  | `decisionModel` | Off by default. A [decision model](#decision-models): an object with `decide(question, { abortSignal })` that answers a closed question with `{ choice, confidence }` (`decisionModelFromAiSdk(...)` adapts Gemini Decision 1, TypeSafe's Jev or any AI SDK decision model). Where it is confident it replaces the replanner's continue / finish call and a pipeline node's route call. Never consulted for tool approval or egress. |
1470
1789
  | `decision` | `{ confidenceThreshold?, timeoutMs?, replan?, route? }` (defaults `0.8`, `5000`, `true`, `true`). Below the threshold, on an error, a timeout or an answer that is not an option, the ordinary model call runs unchanged. |
1471
1790
  | `plannerModel` / `synthesizerModel` | **Deprecated** model-only shortcuts. Equivalent to `planner: { model }` / `synthesizer: { model }`. The override block, if present, wins. |
1472
- | `mcpServers` | `Record<name, { url, headers?, getHeaders?, authProvider?, fetch?, connectTimeoutMs?, protocol? } \| { command, args?, env?, cwd?, connectTimeoutMs?, protocol? }>` — StreamableHTTP for remote (legacy HTTP+SSE servers are **not** supported), stdio for locally-spawned servers. `protocol`: `'legacy'` (default) \| `'auto'` \| `'modern'` - the 2025 revisions, 2026-07-28 when the server offers it, or 2026-07-28 only; see [MCP protocol revision](#mcp-protocol-revision). `skills: true` or `{ consent: 'once-per-skill' \| 'ask' \| 'never' }` (**experimental**, needs `'auto'` / `'modern'`): load the server's skills into the catalog as `<server>/<skill>`, each let into the model's context only once a person allowed it (`consent`); off by default - see [MCP skills](#mcp-skills-experimental). |
1791
+ | `mcpServers` | `Record<name, { url, headers?, getHeaders?, authProvider?, fetch?, connectTimeoutMs?, protocol? } \| { command, args?, env?, cwd?, connectTimeoutMs?, protocol? }>` — StreamableHTTP for remote (legacy HTTP+SSE servers are **not** supported), stdio for locally-spawned servers. `protocol`: `'legacy'` (default) \| `'auto'` \| `'modern'` - the 2025 revisions, 2026-07-28 when the server offers it, or 2026-07-28 only; see [MCP protocol revision](#mcp-protocol-revision). `skills: true` or `{ consent: 'once-per-skill' \| 'ask' \| 'never', dynamic?: boolean }` (**experimental**, needs `'auto'` / `'modern'`): load the server's skills into the catalog as `<server>/<skill>`, each let into the model's context only once a person allowed it (`consent`); `dynamic: true` also takes its generated skills (no checksums: each read whole into a snapshot before anyone is asked, and only that copy used); off by default - see [MCP skills](#mcp-skills-experimental). |
1473
1792
  | `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)`, and tools that run code with `markCodeExecution(tool)` (always asked while a run acts on an MCP server's skill). |
1474
1793
  | `availableTools` / `excludedTools` | Whitelist / blacklist applied to **all** tools (MCP and native). |
1475
1794
  | `maxIterations` | Cap on **executed steps** across the run (every step counts, including those run after a `revise`). |
@@ -1502,7 +1821,9 @@ Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — th
1502
1821
  | `systemPrompt` | Appended to the planner, executor, replanner, and synthesizer system prompts so the same domain context (persona, language, tone) reaches every stage. |
1503
1822
  | `failOnNoTools` | When `true`, `createAgent` throws if every configured MCP server failed to connect (otherwise the agent starts with zero tools and emits an `error`-level log). Default `false`. |
1504
1823
  | `maxConcurrentRuns` | Hard cap on concurrent `agent.run()` calls. When reached, further calls reject synchronously. Default: unlimited. Intentionally a throw, not a queue — back-pressure belongs on the caller. |
1505
- | `persistence` | Optional `IPersistence` facade. Receives `IRunSnapshot` at run start, at every iteration boundary, and at run completion. Implementing the optional `loadRun(runId)` enables resume via `agent.run({ resumeFromRunId })`. See [`examples/persistence-sqlite.ts`](./examples/persistence-sqlite.ts) for a `node:sqlite`-backed adapter. |
1824
+ | `persistence` | Optional `IPersistence` facade. Receives `IRunSnapshot` at run start, at every iteration boundary, and at run completion, `onRunResume` when a resume starts (the new `attempt`, before any event; else that write goes to `onStepComplete`) and `onRunPark` when a run parks (status `'waiting'`; else `onStepComplete`; not fail-open). Implementing the optional `loadRun(runId)` enables resume via `agent.run({ resumeFromRunId })`. `journal: { append(runId, entry), load(runId) }` (needs `loadRun`): the [call journal](#the-call-journal-exact-resume) - a resume replays the interrupted step instead of running it again, and a run can [park](#parking-a-run-a-persons-answer-or-a-result-from-outside). See [`examples/persistence-sqlite.ts`](./examples/persistence-sqlite.ts) for a `node:sqlite`-backed adapter. |
1825
+ | `runLease` | Off by default. `{ acquire, renew, release, ttlMs?, owner? }`: one worker at a time owns a run - acquired before it starts, renewed every `ttlMs / 3` (default `30000`), released at the end; a lost lease aborts the run and stops every persistence write (`RunLeaseError`, `lease.lost`). `agent.leaseOwner`. See [Running on many workers](#running-on-many-workers-scale-out-hooks). |
1826
+ | `sharedLimits` | Off by default. `{ beforeModelCall(call, { signal }), afterModelCall?(call, usage, { ok }) }`: asked before every language-model call (wait = a rate limit, throw = a refusal, `ModelCallRefusedError`, never retried) and told its usage. Not for media, search grounding or decision models. See [Running on many workers](#running-on-many-workers-scale-out-hooks). |
1506
1827
  | `logLevel` | `'none' \| 'error' \| 'warn' \| 'info' \| 'debug'` |
1507
1828
 
1508
1829
  ### Picking models per stage
@@ -1641,10 +1962,11 @@ interface IAgent {
1641
1962
  reconnect(): Promise<void>
1642
1963
  close(options?: { waitForRuns?: boolean; timeoutMs?: number }): Promise<void>
1643
1964
  activeRuns(): number
1965
+ readonly leaseOwner?: string // with runLease: who this agent is to the lease
1644
1966
  }
1645
1967
  ```
1646
1968
 
1647
- `IAgentRunResult` is `{ text, plan, trace, iterations, usage, compactedHistory? }`. `run()` also takes `files` (audio attachments, with `media.transcriptionModel` - see [Media](#media-images-speech-and-transcription)).
1969
+ `IAgentRunResult` is `{ runId, text, plan, trace, iterations, usage, compactedHistory?, undelivered?, parked? }` (`runId`: the run's id, the one its events and snapshots carry - always set by `run()`, optional in the type only so that a hand-made result stays valid; `parked`: the run [parked](#parking-a-run-a-persons-answer-or-a-result-from-outside) and waits for `parked.items`). `run()` also takes `files` (audio attachments, with `media.transcriptionModel` - see [Media](#media-images-speech-and-transcription)), `runId` (a fresh run under an id of yours - see [Your own run id](#resume-after-crash)) and, with `resumeFromRunId`, `answers` (the answers to a parked run's items, by id).
1648
1970
 
1649
1971
  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.
1650
1972
 
@@ -1653,7 +1975,10 @@ Top-level exports beyond `createAgent`:
1653
1975
  - `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.
1654
1976
  - `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).
1655
1977
  - `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).
1656
- - `createSubagentTool(options)` — [subagents](#subagents-worker_threads).
1978
+ - `isAuthError(err): boolean` — whether an error is refused credentials: a `401` / `403` `statusCode` or `status` on the error or anywhere down its `cause` / `lastError` chain (the AI SDK's `RetryError` keeps the last attempt there). The test the agent itself uses to let such a failure through instead of degrading on it (a failed replanner, for one); a host that retries runs can use it to tell "the key is wrong" from "try again".
1979
+ - `createSubagentTool(options)` — [subagents](#subagents-worker_threads); `REMOTE_SUBAGENT_LIMITS` — what a [remote](#remote-subagents-isolation-remote) child may send back.
1980
+ - `RunLeaseError`, `RUN_LEASE_DEFAULT_TTL_MS`, `ModelCallRefusedError`, `isModelCallRefused(err)` — [the scale-out hooks](#running-on-many-workers-scale-out-hooks) (`runLease`, `sharedLimits`).
1981
+ - `deferResult({ note? })`, `isDeferredResult(value)`, `JournalError`, `JOURNAL_LIMITS` and the types `IRunJournal`, `IJournalEntry` (`IJournalModelEntry` / `IJournalToolEntry` / `IJournalPendingEntry` / `IJournalAnswerEntry`), `IParkedRun`, `ParkedItem`, `ParkAnswer`, `ToolApprovalAnswer`, `ToolResultAnswer` — [the call journal](#the-call-journal-exact-resume) and [parking](#parking-a-run-a-persons-answer-or-a-result-from-outside).
1657
1982
  - `SPAWN_SUBAGENT_TOOL`, `SPAWN_INPUT_SCHEMA`, `SUBAGENT_DEFAULTS`, `SUBAGENT_MAX_DEPTH_LIMIT`, `resolveDynamicSubagents(subagents)`, `SubagentSpawnError`, `adoptSubagentEvent(event, parentId)` — [dynamic subagents](#dynamic-subagents-helpers-the-model-starts-itself): the tool's name and input, the defaults, the validated settings, the refusal a model reads, and the rule that places a forwarded `subagent.start` in the tree.
1658
1983
  - `createPipeline(definition, options)`, `nodeResolver(registries)`, `validatePipeline(definition)`, `normalizePipeline(definition)`, `testPipelineCondition(when, output)`, `renderPipelineNodeInput(input)`, `PIPELINE_LIMITS`, `PipelineNodeError`, `PipelineValidationError` — [pipelines](#pipelines).
1659
1984
  - `resolveThinking(setting)`, `mergeProviderOptions(...layers)` — [thinking](#thinking-reasoning).
@@ -1686,6 +2011,8 @@ The newer features are env-driven too: `AGENT_THINKING` (`off | minimal | low |
1686
2011
 
1687
2012
  **`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.
1688
2013
 
2014
+ **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.
2015
+
1689
2016
  **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.
1690
2017
 
1691
2018
  For local development against the source tree: