@dudko.dev/agent 0.0.50 → 0.0.52
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 +307 -16
- package/dist/cli.js +134 -128
- package/dist/index.cjs +112 -106
- package/dist/index.d.cts +285 -229
- package/dist/index.d.ts +285 -229
- package/dist/index.js +112 -106
- package/dist/pipeline-engine.cjs +17 -0
- package/dist/pipeline-engine.d.cts +226 -0
- package/dist/pipeline-engine.d.ts +226 -0
- package/dist/pipeline-engine.js +17 -0
- package/dist/subagent-worker.js +98 -92
- package/package.json +15 -5
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
|
|
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,168 @@ 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).
|
|
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 start is on record, or the run does not go on.** With a journal, `onRunStart` is not fail-open: a run whose start cannot be written could never be resumed (no snapshot) nor started again under its id (it has journal entries), so what its tools wrote, the run that replaces it would write again. A throw ends the run as failed before its first step (an `error` event of phase `'plan'`, the snapshot `failed`); only the planner's call has been made, and it is on record. Without a journal, `onRunStart` stays a warning, as before.
|
|
265
|
+
- **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.
|
|
266
|
+
- **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.
|
|
267
|
+
- **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.
|
|
268
|
+
- 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).
|
|
269
|
+
|
|
270
|
+
### Running on many workers (scale-out hooks)
|
|
271
|
+
|
|
272
|
+
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).
|
|
273
|
+
|
|
274
|
+
**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.
|
|
275
|
+
|
|
276
|
+
**`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):
|
|
277
|
+
|
|
278
|
+
```ts
|
|
279
|
+
import { createAgent, RunLeaseError } from '@dudko.dev/agent'
|
|
280
|
+
|
|
281
|
+
const agent = await createAgent({
|
|
282
|
+
...config,
|
|
283
|
+
persistence,
|
|
284
|
+
runLease: {
|
|
285
|
+
acquire: (runId, { owner, ttlMs }) => store.takeIfFree(runId, owner, ttlMs), // true = held
|
|
286
|
+
renew: (runId, { owner, ttlMs }) => store.extendIfMine(runId, owner, ttlMs), // false = lost
|
|
287
|
+
release: (runId, { owner }) => store.dropIfMine(runId, owner),
|
|
288
|
+
ttlMs: 30_000, // default; renewed every ttlMs / 3
|
|
289
|
+
// owner: 'worker-7', // default: a random id per agent - agent.leaseOwner
|
|
290
|
+
},
|
|
291
|
+
})
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
- **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.
|
|
295
|
+
- **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.
|
|
296
|
+
- **Release.** When the run ends, every way (success, failure, stop, a resume that could not load); a failed release is only logged.
|
|
297
|
+
- 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.
|
|
298
|
+
- `ttlMs` must be 1000 ms to 2^31 - 1 ms, the owner 1-256 characters, all three methods functions - `createAgent` throws otherwise.
|
|
299
|
+
|
|
300
|
+
**`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:
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
const agent = await createAgent({
|
|
304
|
+
...config,
|
|
305
|
+
sharedLimits: {
|
|
306
|
+
// Wait (a rate limit) or throw (a refusal: a budget). `signal`: the call was given up.
|
|
307
|
+
beforeModelCall: async (call, { signal }) => {
|
|
308
|
+
await bucket.take(call.stage, { signal })
|
|
309
|
+
if (await budget.spent(call.runId)) throw new Error('budget spent')
|
|
310
|
+
},
|
|
311
|
+
// Not awaited; a throw is only logged.
|
|
312
|
+
afterModelCall: (call, usage, { ok }) => budget.add(call.runId, usage.totalTokens),
|
|
313
|
+
},
|
|
314
|
+
})
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
- `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).
|
|
318
|
+
- **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.
|
|
319
|
+
- **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.
|
|
320
|
+
- **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.
|
|
321
|
+
- **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.
|
|
322
|
+
- `afterModelCall(call, usage, { ok })`: once per call `beforeModelCall` let through, when it ends - finished, failed or cancelled.
|
|
323
|
+
|
|
324
|
+
**Remote subagents** (`createSubagentTool({ isolation: 'remote', dispatch })`) send a child to another worker: see [Remote subagents](#remote-subagents-isolation-remote).
|
|
325
|
+
|
|
326
|
+
[`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).
|
|
327
|
+
|
|
328
|
+
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).
|
|
329
|
+
|
|
330
|
+
### Parking a run: a person's answer or a result from outside
|
|
331
|
+
|
|
332
|
+
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.
|
|
333
|
+
|
|
334
|
+
**Two things park.**
|
|
335
|
+
|
|
336
|
+
- 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`).
|
|
337
|
+
- 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.
|
|
338
|
+
|
|
339
|
+
```ts
|
|
340
|
+
import { createAgent, deferResult } from '@dudko.dev/agent'
|
|
341
|
+
|
|
342
|
+
const agent = await createAgent({
|
|
343
|
+
...config,
|
|
344
|
+
persistence, // with journal, loadRun and (best) onRunPark
|
|
345
|
+
toolApproval: { mode: 'ask-writes', onRequest: () => ({ park: true }) }, // ask a person later
|
|
346
|
+
tools: {
|
|
347
|
+
render_video: tool({
|
|
348
|
+
inputSchema: z.object({ script: z.string() }),
|
|
349
|
+
execute: async ({ script }) => {
|
|
350
|
+
await jobs.submit({ script }) // the result arrives by webhook
|
|
351
|
+
return deferResult({ note: 'queued on the render farm' })
|
|
352
|
+
},
|
|
353
|
+
}),
|
|
354
|
+
},
|
|
355
|
+
})
|
|
356
|
+
|
|
357
|
+
const result = await agent.run({ input: 'Make the video and send it to the client' })
|
|
358
|
+
if (result.parked) {
|
|
359
|
+
const { runId, items } = result.parked // items: [{ id, kind: 'approval' | 'tool', ... }]
|
|
360
|
+
await store.saveWaiting(runId, items)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Later, anywhere - one way to resume:
|
|
364
|
+
await agent.run({
|
|
365
|
+
input: '',
|
|
366
|
+
resumeFromRunId: runId,
|
|
367
|
+
answers: {
|
|
368
|
+
[approvalId]: true, // or { approved: false, reason }, or { approved: true, remember: true }
|
|
369
|
+
[renderId]: { output: { url: 'https://cdn.example/video.mp4' } }, // or { error: 'render failed' }
|
|
370
|
+
},
|
|
371
|
+
})
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
**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:
|
|
375
|
+
|
|
376
|
+
- 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;
|
|
377
|
+
- one **`run.parked`** event carries the items; the question's `tool.approval-resolved` says `parked: true`;
|
|
378
|
+
- nothing more is sent: no model call, no deadline left behind; the lease is released;
|
|
379
|
+
- `agent.run()` **resolves** - not an error - with `text: ''` and `result.parked: { runId, items, at }`.
|
|
380
|
+
|
|
381
|
+
**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`:
|
|
382
|
+
|
|
383
|
+
- `'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);
|
|
384
|
+
- `'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.
|
|
385
|
+
|
|
386
|
+
**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).
|
|
387
|
+
|
|
388
|
+
**Guards.**
|
|
389
|
+
|
|
390
|
+
- 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.
|
|
391
|
+
- 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.
|
|
392
|
+
- 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.
|
|
393
|
+
- [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.
|
|
394
|
+
- **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.
|
|
395
|
+
- 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
396
|
|
|
239
397
|
### OpenTelemetry
|
|
240
398
|
|
|
@@ -700,6 +858,8 @@ agent.setToolApprovalMode('autopilot') // the toggle; applies to the next call,
|
|
|
700
858
|
agent.getToolApprovalMode()
|
|
701
859
|
```
|
|
702
860
|
|
|
861
|
+
`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.
|
|
862
|
+
|
|
703
863
|
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.
|
|
704
864
|
|
|
705
865
|
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`.
|
|
@@ -766,6 +926,8 @@ const agent = await createAgent({
|
|
|
766
926
|
})
|
|
767
927
|
```
|
|
768
928
|
|
|
929
|
+
**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).
|
|
930
|
+
|
|
769
931
|
**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.
|
|
770
932
|
|
|
771
933
|
**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.
|
|
@@ -859,7 +1021,7 @@ const researcher = createSubagentTool({
|
|
|
859
1021
|
name: 'researcher',
|
|
860
1022
|
description: 'Research a self-contained question and report the findings',
|
|
861
1023
|
config: { ...childConfig }, // a full IAgentConfig for the child
|
|
862
|
-
isolation: 'worker', // default; or 'in-process'
|
|
1024
|
+
isolation: 'worker', // default; or 'in-process' / 'remote' (below)
|
|
863
1025
|
tools: { lookup }, // host tools for the child
|
|
864
1026
|
maxConcurrent: 4, // parallel calls beyond this queue
|
|
865
1027
|
timeoutMs: 120_000,
|
|
@@ -877,6 +1039,35 @@ Several calls in one model step run in parallel (bounded by `maxConcurrent`). Th
|
|
|
877
1039
|
|
|
878
1040
|
The worker entry ships as `dist/subagent-worker.js` and is resolved next to the bundle, from the ESM and the CJS build alike.
|
|
879
1041
|
|
|
1042
|
+
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).
|
|
1043
|
+
|
|
1044
|
+
### Remote subagents (`isolation: 'remote'`)
|
|
1045
|
+
|
|
1046
|
+
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.
|
|
1047
|
+
|
|
1048
|
+
```ts
|
|
1049
|
+
const researcher = createSubagentTool({
|
|
1050
|
+
name: 'researcher',
|
|
1051
|
+
description: 'Research a self-contained question',
|
|
1052
|
+
isolation: 'remote',
|
|
1053
|
+
dispatch: async (task, { signal, emit }) => {
|
|
1054
|
+
// task: { id, name, profile?, input, parentRunId?, rootRunId?, depth }
|
|
1055
|
+
const job = await queue.submit({ input: task.input, profile: task.profile, signal })
|
|
1056
|
+
for await (const event of job.events()) emit(event) // forwarded as subagent.event
|
|
1057
|
+
return { text: job.answer, usage: job.usage } // usage: charged once, here
|
|
1058
|
+
},
|
|
1059
|
+
profiles: { deep: { description: 'A thorough look' } }, // names only: dispatch decides
|
|
1060
|
+
timeoutMs: 120_000,
|
|
1061
|
+
})
|
|
1062
|
+
```
|
|
1063
|
+
|
|
1064
|
+
- `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`.
|
|
1065
|
+
- `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.
|
|
1066
|
+
- **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.
|
|
1067
|
+
- 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.
|
|
1068
|
+
- 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.
|
|
1069
|
+
- `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.
|
|
1070
|
+
|
|
880
1071
|
### Profiles: other models, params and context per call
|
|
881
1072
|
|
|
882
1073
|
A subagent normally has one fixed configuration. `profiles` lets the **parent model** choose between named variants of it, per call:
|
|
@@ -1413,17 +1604,24 @@ validation. It answers the same as `RegExp.test` on what it accepts.
|
|
|
1413
1604
|
- **Join.** A node activated by several edges gets all their outputs in one visit. With
|
|
1414
1605
|
`join: 'all'` an activated node is *deferred* while any other activated node can still reach it
|
|
1415
1606
|
through the graph (conditions aside) - so a fan-in waits for its slower branch even when the
|
|
1416
|
-
branches have different lengths. If every activated node is deferred (they
|
|
1417
|
-
a
|
|
1418
|
-
|
|
1607
|
+
branches have different lengths. If every activated node is deferred (they reach each other
|
|
1608
|
+
through a loop), only the waits within one pass of the loop count: a wait that holds only by
|
|
1609
|
+
going round, back to the loop's *head* (the node every path from the entry into the loop
|
|
1610
|
+
passes), is for the next pass and is dropped. If that still leaves every node deferred, all of
|
|
1611
|
+
them run. `join: 'any'` never defers: the node runs once per wave it is activated in.
|
|
1419
1612
|
- **Loops** are allowed. When starting a node would exceed `maxNodeVisits` for it, or `maxRuns` for
|
|
1420
1613
|
the pipeline, that activation is dropped (`pipeline.node.skipped`); the run goes on with what is
|
|
1421
1614
|
left, ends normally, and the result carries `stoppedBy: 'maxNodeVisits'` or `'maxRuns'`
|
|
1422
1615
|
(`maxRuns` wins when both happened).
|
|
1423
|
-
- **A fan-in inside a loop
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1616
|
+
- **A fan-in inside a loop.** A loop that goes back to the fan-out or to any node before it
|
|
1617
|
+
(`a → b → join`, `a → c → d → join`, `join → a`) works: on every pass the join waits for its
|
|
1618
|
+
slower branch and runs once with both outputs, whatever the order of the edges. A loop that goes
|
|
1619
|
+
back *into* a branch (`join → c` instead) has no head - it is entered at `c` and at the join -,
|
|
1620
|
+
so the join and that branch wait for each other, both run, and the join fires without that
|
|
1621
|
+
branch: loop back to a node before the fan-out, or use `join: 'any'` there. The pass rule is
|
|
1622
|
+
asked only when every activated node waits: a node outside a loop that the loop feeds
|
|
1623
|
+
(`a ↔ b`, `a → x`) still waits while the loop goes on, and runs once, with the output of every
|
|
1624
|
+
pass.
|
|
1427
1625
|
- **The end.** The run ends when nothing is activated. A *terminal* visit is one that activated
|
|
1428
1626
|
nothing (no edge fired, or a cap dropped what it fired). `result.text` is the output of the last
|
|
1429
1627
|
terminal node to finish; several of the same wave are joined under `## <name>` headings.
|
|
@@ -1474,6 +1672,93 @@ process, the caps bound its loops, and it can only name what `nodeResolver` regi
|
|
|
1474
1672
|
`node.settings` reaches your `configure` and nothing else. The graph engine is the same file as in
|
|
1475
1673
|
the browser sibling, so a definition runs the same in both.
|
|
1476
1674
|
|
|
1675
|
+
### Running the graph yourself
|
|
1676
|
+
|
|
1677
|
+
`createPipeline` is a scheduler with `createAgent` as its node runner. Both halves are public, so a
|
|
1678
|
+
host can keep the scheduler and run every node its own way - a queue job, a remote worker, a child
|
|
1679
|
+
workflow - and make the route call where the node ran:
|
|
1680
|
+
|
|
1681
|
+
```ts
|
|
1682
|
+
import { pickPipelineRoute, preparePipeline, runPipelineGraph } from '@dudko.dev/agent'
|
|
1683
|
+
|
|
1684
|
+
const plan = preparePipeline(definition) // validates (PipelineValidationError) and compiles
|
|
1685
|
+
const result = await runPipelineGraph(
|
|
1686
|
+
plan,
|
|
1687
|
+
async (node, input, ctx) => {
|
|
1688
|
+
// input: { request, from: [{ nodeId, name?, text }], visit } - renderPipelineNodeInput(input)
|
|
1689
|
+
// is the text a createPipeline node is given.
|
|
1690
|
+
const text = await jobs.run(node.id, input, { signal: ctx.signal }) // your runner
|
|
1691
|
+
if (!node.routes?.length) return { text }
|
|
1692
|
+
// The route call createPipeline makes: the node's decision model, then its planner model.
|
|
1693
|
+
const { route, usage } = await pickPipelineRoute(node, text, {
|
|
1694
|
+
config: configOf(node), // the node's IAgentConfig
|
|
1695
|
+
signal: ctx.signal,
|
|
1696
|
+
onEvent: ctx.emit,
|
|
1697
|
+
})
|
|
1698
|
+
return { text, usage, route }
|
|
1699
|
+
},
|
|
1700
|
+
{ input: 'A release note for v2', signal, onEvent, onAbort: 'reject' },
|
|
1701
|
+
)
|
|
1702
|
+
```
|
|
1703
|
+
|
|
1704
|
+
The runner's contract:
|
|
1705
|
+
|
|
1706
|
+
- **When it is called.** Once per visit, never for an activation a cap refused (`plan.maxNodeVisits`
|
|
1707
|
+
/ `plan.maxRuns`: the definition's `limits` or the defaults). All visits of a wave are started, in
|
|
1708
|
+
the order their nodes were first activated, before any is awaited; the next wave starts when all
|
|
1709
|
+
of them have settled. A visit's answer is applied (events, trace, edges) when it settles.
|
|
1710
|
+
- **What it returns.** `{ text, usage?, route? }`. `text` is what the edges test (not a string
|
|
1711
|
+
counts as `''`); `usage` is added to `result.usage`, every numeric field; `route` must be one of
|
|
1712
|
+
`node.routes`' labels exactly as written - anything else, or none, is no route. To pick one with a
|
|
1713
|
+
model of your own: `PIPELINE_ROUTER_SYSTEM` and `renderPipelineRoutePrompt(node, text)` are the
|
|
1714
|
+
prompt, `matchPipelineRoute(node, answer)` turns the answer into a label.
|
|
1715
|
+
- **When it fails.** A runner that rejects fails the run with a `PipelineNodeError` (`nodeId`,
|
|
1716
|
+
`visit`, `cause`), whatever `onAbort` says: the other visits' `ctx.signal` aborts, and what they
|
|
1717
|
+
return afterwards is ignored.
|
|
1718
|
+
- **Abort.** `signal` aborts the visits in flight (their `ctx.signal`) and settles the run at once,
|
|
1719
|
+
without waiting for them: it rejects with an `AbortError` (`onAbort: 'reject'`, the default, as
|
|
1720
|
+
`createPipeline` does here) or resolves with what it has and `stoppedBy: 'aborted'` (`'resolve'`,
|
|
1721
|
+
as the browser sibling's does). Aborted before it starts: no visit at all.
|
|
1722
|
+
- **Events.** `onEvent` gets the `pipeline.*` events `createPipeline` sends; `ctx.emit(event)`
|
|
1723
|
+
forwards one of the node's own, with `nodeId` and `visit`, until the run is over.
|
|
1724
|
+
|
|
1725
|
+
`pickPipelineRoute(node, text, { config, signal?, onEvent? })` resolves with `{ route?, usage }`:
|
|
1726
|
+
the decision model of `config` first (`decisionModel`, when it is confident of a label), else a
|
|
1727
|
+
structured-output call to its planner model with its call options, `llmTimeoutMs`, `llmMaxRetries`
|
|
1728
|
+
and `sharedLimits`. No label, or a failed call, is no route; an abort rejects. The model is built
|
|
1729
|
+
once per config object.
|
|
1730
|
+
|
|
1731
|
+
**Deterministic by contract.** The engine - `preparePipeline`, `runPipelineGraph`, the conditions -
|
|
1732
|
+
reads no clock, no randomness and no timer, and does no I/O: the same definition, input and runner
|
|
1733
|
+
answers, arriving in the same order (and an abort at the same point), give the same calls, events,
|
|
1734
|
+
trace and result. So it can be a deterministic scheduler, replayed from a log of the runner's
|
|
1735
|
+
answers. It needs nothing but the JavaScript language: where there is no `AbortController`,
|
|
1736
|
+
`ctx.signal` is a stand-in (`aborted`, `reason`, `onabort`, `throwIfAborted()`, `addEventListener` /
|
|
1737
|
+
`removeEventListener`), where there is no `DOMException` the abort error is an `Error` named
|
|
1738
|
+
`AbortError`, and of your `signal` only `aborted` and `addEventListener` / `removeEventListener`
|
|
1739
|
+
for `'abort'` are read. `pickPipelineRoute` calls a model, so it is not part of that: it belongs
|
|
1740
|
+
where the node runs.
|
|
1741
|
+
|
|
1742
|
+
**The engine alone: `@dudko.dev/agent/pipeline-engine`.** The main entry loads the whole agent -
|
|
1743
|
+
`ai`, `zod`, the MCP client, `node:*` -, which a bundled orchestrator cannot import (a workflow
|
|
1744
|
+
sandbox has the language and little else). The engine has an entry point of its own, ESM and
|
|
1745
|
+
CommonJS with types, whose file imports nothing:
|
|
1746
|
+
|
|
1747
|
+
```ts
|
|
1748
|
+
// In the workflow: the scheduler only; every node runs outside it (an activity, a job).
|
|
1749
|
+
import { preparePipeline, runPipelineGraph } from '@dudko.dev/agent/pipeline-engine'
|
|
1750
|
+
```
|
|
1751
|
+
|
|
1752
|
+
It exports `preparePipeline`, `runPipelineGraph`, `validatePipeline`, `normalizePipeline`,
|
|
1753
|
+
`testPipelineCondition`, `renderPipelineNodeInput`, `renderPipelineRoutePrompt`,
|
|
1754
|
+
`matchPipelineRoute`, `PIPELINE_ROUTER_SYSTEM`, `PIPELINE_LIMITS`, `PipelineValidationError`,
|
|
1755
|
+
`PipelineNodeError` and every pipeline type - the same names as the main entry.
|
|
1756
|
+
`tests/pipeline-determinism.test.ts` holds the built ESM and CommonJS files to the contract: no
|
|
1757
|
+
import and no `require` (a shared chunk would be one), and the same runs inside a `node:vm`
|
|
1758
|
+
context with only the language's globals. It is a copy of the engine the main entry carries, not
|
|
1759
|
+
the same objects: an error thrown by one is not `instanceof` the other's class - compare
|
|
1760
|
+
`error.name`.
|
|
1761
|
+
|
|
1477
1762
|
## Autonomy
|
|
1478
1763
|
|
|
1479
1764
|
The stage prompts are written for an agent that acts on its own:
|
|
@@ -1537,7 +1822,9 @@ Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — th
|
|
|
1537
1822
|
| `systemPrompt` | Appended to the planner, executor, replanner, and synthesizer system prompts so the same domain context (persona, language, tone) reaches every stage. |
|
|
1538
1823
|
| `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`. |
|
|
1539
1824
|
| `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. |
|
|
1540
|
-
| `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. |
|
|
1825
|
+
| `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). With `journal`, `onRunStart` is not fail-open either (a throw fails the run before its first step). 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. |
|
|
1826
|
+
| `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). |
|
|
1827
|
+
| `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). |
|
|
1541
1828
|
| `logLevel` | `'none' \| 'error' \| 'warn' \| 'info' \| 'debug'` |
|
|
1542
1829
|
|
|
1543
1830
|
### Picking models per stage
|
|
@@ -1676,10 +1963,11 @@ interface IAgent {
|
|
|
1676
1963
|
reconnect(): Promise<void>
|
|
1677
1964
|
close(options?: { waitForRuns?: boolean; timeoutMs?: number }): Promise<void>
|
|
1678
1965
|
activeRuns(): number
|
|
1966
|
+
readonly leaseOwner?: string // with runLease: who this agent is to the lease
|
|
1679
1967
|
}
|
|
1680
1968
|
```
|
|
1681
1969
|
|
|
1682
|
-
`IAgentRunResult` is `{ text, plan, trace, iterations, usage, compactedHistory? }
|
|
1970
|
+
`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).
|
|
1683
1971
|
|
|
1684
1972
|
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.
|
|
1685
1973
|
|
|
@@ -1688,7 +1976,10 @@ Top-level exports beyond `createAgent`:
|
|
|
1688
1976
|
- `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.
|
|
1689
1977
|
- `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).
|
|
1690
1978
|
- `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).
|
|
1691
|
-
- `
|
|
1979
|
+
- `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".
|
|
1980
|
+
- `createSubagentTool(options)` — [subagents](#subagents-worker_threads); `REMOTE_SUBAGENT_LIMITS` — what a [remote](#remote-subagents-isolation-remote) child may send back.
|
|
1981
|
+
- `RunLeaseError`, `RUN_LEASE_DEFAULT_TTL_MS`, `ModelCallRefusedError`, `isModelCallRefused(err)` — [the scale-out hooks](#running-on-many-workers-scale-out-hooks) (`runLease`, `sharedLimits`).
|
|
1982
|
+
- `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).
|
|
1692
1983
|
- `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.
|
|
1693
1984
|
- `createPipeline(definition, options)`, `nodeResolver(registries)`, `validatePipeline(definition)`, `normalizePipeline(definition)`, `testPipelineCondition(when, output)`, `renderPipelineNodeInput(input)`, `PIPELINE_LIMITS`, `PipelineNodeError`, `PipelineValidationError` — [pipelines](#pipelines).
|
|
1694
1985
|
- `resolveThinking(setting)`, `mergeProviderOptions(...layers)` — [thinking](#thinking-reasoning).
|