@dudko.dev/agent 0.0.52 → 0.0.54
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 +44 -13
- package/dist/cli.js +111 -111
- package/dist/index.cjs +98 -98
- package/dist/index.d.cts +9 -8
- package/dist/index.d.ts +9 -8
- package/dist/index.js +98 -98
- package/dist/sandbox-worker.js +6 -6
- package/dist/subagent-worker.js +88 -88
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -65,7 +65,7 @@ npm install workers-ai-provider # cloudflare
|
|
|
65
65
|
# gateway: no extra install — ships inside `ai`
|
|
66
66
|
```
|
|
67
67
|
|
|
68
|
-
Setting `providerType` to a value whose SDK isn't installed throws a clear `"Provider package "@ai-sdk/X" is not installed"` error at `createAgent` time.
|
|
68
|
+
Setting `providerType` to a value whose SDK isn't installed throws a clear `"Provider package "@ai-sdk/X" is not installed"` error at `createAgent` time. Or build the model yourself and pass the object as `model`: the agent then imports no provider package at all (see [Your own model object](#your-own-model-object)).
|
|
69
69
|
|
|
70
70
|
## Quick start
|
|
71
71
|
|
|
@@ -232,6 +232,7 @@ await agent.run({ input: '', resumeFromRunId: '<saved-run-id>' })
|
|
|
232
232
|
Caveats:
|
|
233
233
|
|
|
234
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).
|
|
235
|
+
- **A run that failed or was stopped.** Its last snapshot (`onRunComplete`, status `failed` / `cancelled`) names the place a resume picks it up, and no step counts twice against `maxIterations`. A run that stopped **in a step** is recorded with that step still to run, and not counted: the resume runs the step again from its start (its tool calls run again - or, with the call journal, are replayed). One that stopped **after a step, at the replanner** (a stop, refused credentials) is recorded with the step in its trace and the next step to run: the resume carries on with the plan as it is, as a run does when the replanner fails. One that stopped **while the answer was written** is recorded with no step left: the resume writes the answer and runs nothing again. With the call journal the record is instead the run as it stood when the step in flight started (the step is not in `trace` yet, `usage` and `toolCallCount` are as they were then: the journal holds the rest and the replay brings it back) - as a parked run's is.
|
|
235
236
|
- **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.
|
|
236
237
|
- **Plan changes.** The saved `currentPlan` (post any revise) is what gets used on resume — the planner is not re-invoked.
|
|
237
238
|
- **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`).
|
|
@@ -244,7 +245,7 @@ Caveats:
|
|
|
244
245
|
|
|
245
246
|
#### The call journal: exact resume
|
|
246
247
|
|
|
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
|
+
`persistence.journal` records, as the run goes, every language-model response and every tool result, and a resume **replays** the step a crash - or a failure of the run, or a stop - interrupted instead of running it again:
|
|
248
249
|
|
|
249
250
|
```ts
|
|
250
251
|
const persistence: IPersistence = {
|
|
@@ -260,6 +261,7 @@ const persistence: IPersistence = {
|
|
|
260
261
|
- **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
262
|
- **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
263
|
- **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.
|
|
264
|
+
- **A failed run replays too.** A run that fails in the middle of a step (a provider error past the retries on a later round, a timeout, refused credentials at the replanner) or is stopped there writes its `failed` / `cancelled` snapshot as the run stood **when that step started**, so the resume opens the same journal segment and replays what the step had done: its tools do not run again, its recorded model calls are not sent again, and the attempt that failed does not count against `maxIterations`. A run that fails while the answer is written resumes at the answer. A step that had [escalated](#model-tiers-and-escalation) replays up to the call that failed; if the stronger tier had recorded calls of its own before the run failed, the replay stops matching there - one `journal.diverged`, and the rest of the step is live. The same holds when the user [sent a message](#steering-a-run-that-is-already-going) during the step that failed: the message is kept in the record, the step's prompt has it now, and the replay says it diverged at the step's first call.
|
|
263
265
|
- **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
266
|
- **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
267
|
- **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.
|
|
@@ -378,7 +380,7 @@ await agent.run({
|
|
|
378
380
|
- nothing more is sent: no model call, no deadline left behind; the lease is released;
|
|
379
381
|
- `agent.run()` **resolves** - not an error - with `text: ''` and `result.parked: { runId, items, at }`.
|
|
380
382
|
|
|
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`:
|
|
383
|
+
**The items.** They are listed in the order of the calls in the run (their journal positions: the order of the tool calls in the model's response), the same on every attempt - not in the order their records reached the store, which the calls of one round race for. 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
384
|
|
|
383
385
|
- `'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
386
|
- `'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.
|
|
@@ -649,8 +651,9 @@ The run caps are **soft**: they are checked between steps *and* inside an execut
|
|
|
649
651
|
|
|
650
652
|
- **Yours wins.** Any `limits.perCall.<stage>` replaces the default, and **`0` means no cap** (the provider's own maximum applies — what Node did before these defaults existed).
|
|
651
653
|
- **A stage that thinks gets no default cap.** On OpenAI and Gemini the reasoning counts against `max_output_tokens`, so a default sized for the answer alone could leave a thinking model no room to write it. Set `perCall` yourself if you want a cap there (Anthropic adds the thinking budget on top of it).
|
|
654
|
+
- **A model that thinks without being asked to is noticed.** Gemini 2.5+, GPT-5 and others reason by default, with no `thinking` in the config, so the config alone cannot say that a stage thinks. The usage of every call does: once a call of a stage reports reasoning tokens, that stage has no default cap for this agent any more, and a plan, a replanner decision or a pipeline's route call that the default cap **cut off while the model reasoned** is asked for once more, without the cap - a `retry` event says why, and what the cut attempt cost is counted. It is not one of the `llmMaxRetries`. An executor step is not repeated (its tools may have run); its next step is uncapped. A cap you set yourself stays, and the call is not repeated.
|
|
652
655
|
- **A call the cap cuts off says so.** The executor and synthesizer emit a `log` warning (`[synthesizer] the model's output was cut off at 4000 tokens, the default cap for this stage …`); a plan or a replanner decision cut in half fails with the same reason in its error instead of a bare "could not parse the response" (the run survives both: see [When the replanner fails](#when-the-replanner-fails)).
|
|
653
|
-
- The browser sibling `@dudko.dev/agent-web` follows the same rules (yours wins and `0` is no cap, none for a stage that thinks, a cut-off call says so), with its own, smaller shares (800 / 1,200 / 400 / 3,000 at 128k).
|
|
656
|
+
- The browser sibling `@dudko.dev/agent-web` follows the same rules (yours wins and `0` is no cap, none for a stage that thinks or is seen to, a cut-off call says so), with its own, smaller shares (800 / 1,200 / 400 / 3,000 at 128k).
|
|
654
657
|
|
|
655
658
|
`maxToolCalls`: once reached, further tool calls in the run fail with `tool-call budget exhausted` (the model sees that as the tool result) and the run moves to synthesis with `budget.exceeded` of kind `'tool-calls'`. Built-in tools (`find_tools`, `load_skill`, `read_skill_file`) do not count.
|
|
656
659
|
|
|
@@ -876,7 +879,7 @@ A denied call throws `ToolDeniedError` inside the tool, so the step records `ok:
|
|
|
876
879
|
|
|
877
880
|
**Tool search.** `toolSelectionStrategy` now defaults to `'auto'`: the executor gets every tool (`'all'`, exactly as before) while the filtered catalogue has at most `toolSearchThreshold` (default 40) tools, and switches to `'search'` above that. In `'search'` mode each step starts with the built-in tools, the step's `suggestedTools` and the tools discovered earlier in the run (the 16 most recent), plus `find_tools({ query, server?, limit? })`. It ranks the whole catalogue and **activates** the matches: they become callable from the model's next LLM step and stay active for the rest of the run (`tools.discovered` event). The planner sees an abridged catalogue grouped by server and treats `suggestedTools` as hints. The ranking is the exported pure `searchTools(catalog, query, { server?, limit? })` — terms matched in the name score 3, in the server 2, in the description 1, prefix-matched for terms of 3+ chars. `'all'` and `'plan-narrowed'` behave as before.
|
|
878
881
|
|
|
879
|
-
**Loading.** `tools/list` follows `nextCursor` (up to 100 pages), on connect and on `tools/list_changed` refreshes. Each server must connect and list within `connectTimeoutMs` (per server; default from the top-level `mcpConnectTimeoutMs`, 30 s; `0` disables) or it is reported failed (`connect timed out after Xms`) and closed while the others mount. `agent.listTools()` entries carry `server` and `readOnly`.
|
|
882
|
+
**Loading.** `tools/list` follows `nextCursor` (up to 100 pages), on connect and on `tools/list_changed` refreshes. Each server must connect and list within `connectTimeoutMs` (per server; default from the top-level `mcpConnectTimeoutMs`, 30 s; `0` disables) or it is reported failed (`connect timed out after Xms`) and closed while the others mount. `agent.listTools()` entries carry `server` and `readOnly`. A refresh is applied between runs, never behind one: a change announced during a run is listed when no run is going, and an `agent.run()` or `agent.reconnect()` that arrives while that listing is in flight waits for it and works on the refreshed tools (it is not refused; the wait ends with the listing, or with the run's `signal`).
|
|
880
883
|
|
|
881
884
|
## MCP server instructions and structured results
|
|
882
885
|
|
|
@@ -907,7 +910,7 @@ Server "docs":
|
|
|
907
910
|
|
|
908
911
|
Images, audio and resources are handled as before (spilled to the run's sandbox directory), and `compaction.maxToolOutputChars` caps the result whatever its shape. With an `outputSanitizer`, the structured value goes through it in a call of its own (it receives the object; the duplicate text part is dropped first).
|
|
909
912
|
|
|
910
|
-
**A result that breaks its `outputSchema`.** `structuredContent` is validated against the schema from `tools/list` (with the MCP SDK's own validator: JSON Schema 2020-12 unless the schema declares another `$schema`); it may not match, and a tool that declares a schema may return none. The agent does **not** turn that into a failed call: the call ran on the server, and a tool the model is told failed is a tool it calls again — a second write. The result is passed on with a note instead (`{ note, structuredContent?, content? }`: *"The tool "x" ran, but its result does not follow the output schema the server declared… do not call the tool again only because of this note"*), and a `warn` line is logged. A request that really failed (transport, protocol, abort) is a failed tool call as before — never a crashed run. A tool whose `outputSchema` cannot be compiled at all (an unsupported dialect, an unresolvable `$ref`) is refused before anything is sent: `Tool 'x' has an invalid outputSchema: …`; the server's other tools are unaffected.
|
|
913
|
+
**A result that breaks its `outputSchema`.** `structuredContent` is validated against the schema from `tools/list` (with the MCP SDK's own validator: JSON Schema 2020-12 unless the schema declares another `$schema`; Ajv, or - where the runtime forbids code generation from strings, as Cloudflare Workers does - the SDK's code-free `@cfworker/json-schema` validator, with the same dialects); it may not match, and a tool that declares a schema may return none. The agent does **not** turn that into a failed call: the call ran on the server, and a tool the model is told failed is a tool it calls again — a second write. The result is passed on with a note instead (`{ note, structuredContent?, content? }`: *"The tool "x" ran, but its result does not follow the output schema the server declared… do not call the tool again only because of this note"*), and a `warn` line is logged. A request that really failed (transport, protocol, abort) is a failed tool call as before — never a crashed run. A tool whose `outputSchema` cannot be compiled at all (an unsupported dialect, an unresolvable `$ref`) is refused before anything is sent: `Tool 'x' has an invalid outputSchema: …`; the server's other tools are unaffected.
|
|
911
914
|
|
|
912
915
|
## MCP elicitation: a server asks the user
|
|
913
916
|
|
|
@@ -1032,7 +1035,7 @@ const researcher = createSubagentTool({
|
|
|
1032
1035
|
const agent = await createAgent({ ...config, tools: { researcher } })
|
|
1033
1036
|
```
|
|
1034
1037
|
|
|
1035
|
-
- **`'worker'`** runs each call in its own `worker_thread` (terminated afterwards), so the child's CPU work and crashes stay off the parent's event loop. Its config must be structured-cloneable — a function anywhere (`getHeaders`, `authProvider`, `fetch`, sanitizers, `persistence`, `onRequest`, native `tools`) throws, naming the field. Host tools passed as `tools` are **proxied**: the child sees their schemas, every call runs on the parent thread.
|
|
1038
|
+
- **`'worker'`** runs each call in its own `worker_thread` (terminated afterwards), so the child's CPU work and crashes stay off the parent's event loop. Its config must be structured-cloneable — a function anywhere (`getHeaders`, `authProvider`, `fetch`, sanitizers, `persistence`, `onRequest`, native `tools`) or a [model object](#your-own-model-object) (`model`, a stage, a tier, a media model) throws when the tool is created, naming the field. Host tools passed as `tools` are **proxied**: the child sees their schemas, every call runs on the parent thread.
|
|
1036
1039
|
- **`'in-process'`** builds the child on this thread; `tools` are merged into its config.
|
|
1037
1040
|
|
|
1038
1041
|
Several calls in one model step run in parallel (bounded by `maxConcurrent`). The parent's abort aborts the child. `timeoutMs` does not count the time a person takes to answer the child's questions (an approval, an MCP elicitation) or the calling run's: while one waits, the subagent's limit and the calling step's `llmTimeoutMs` are stopped, and a worker child whose proxied host tool call is in flight stops its own step limit too. The child's usage is emitted on the parent as `usage` with `phase: 'subagent'` as it happens, so it counts against the parent's limits. Parent events: `subagent.start`, `subagent.event` (each child event, long strings clipped), `subagent.complete` (`text`, `usage`), `subagent.error`.
|
|
@@ -1545,7 +1548,7 @@ const pipeline = createPipeline(definition, {
|
|
|
1545
1548
|
// What the names in the definition stand for. A name that is not here fails its node.
|
|
1546
1549
|
resolveNode: nodeResolver({
|
|
1547
1550
|
base: config, // an IAgentConfig: every node starts from it
|
|
1548
|
-
models: { smart: { model: 'gpt-4.1-mini' } },
|
|
1551
|
+
models: { smart: { model: 'gpt-4.1-mini' } }, // or a model object: { model: openai('gpt-5') }
|
|
1549
1552
|
tools: { files: fileTools },
|
|
1550
1553
|
// skills: { ... }, mcpServers: { ... },
|
|
1551
1554
|
// configure: (config, node) => config // the place to read node.settings
|
|
@@ -1776,15 +1779,15 @@ Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — th
|
|
|
1776
1779
|
|
|
1777
1780
|
| Field | Notes |
|
|
1778
1781
|
| --- | --- |
|
|
1779
|
-
| `providerType` | `'openai' \| 'anthropic' \| 'google' \| 'openai-compatible' \| 'xai' \| 'azure' \| 'amazon-bedrock' \| 'google-vertex' \| 'deepseek' \| 'gateway' \| 'cloudflare'`. Each provider's SDK is an **optional peerDependency** — install only the package(s) you intend to use; setting `providerType` to a missing one throws at `createAgent` time. |
|
|
1782
|
+
| `providerType` | `'openai' \| 'anthropic' \| 'google' \| 'openai-compatible' \| 'xai' \| 'azure' \| 'amazon-bedrock' \| 'google-vertex' \| 'deepseek' \| 'gateway' \| 'cloudflare'`. Each provider's SDK is an **optional peerDependency** — install only the package(s) you intend to use; setting `providerType` to a missing one throws at `createAgent` time. The provider of every model given as an id; optional when every stage runs on a [model object](#your-own-model-object), and a model id with no `providerType` (its block's or the top level's) throws at `createAgent`, naming the block. |
|
|
1780
1783
|
| `baseURL` | Required for `openai-compatible` (point at your self-hosted server) and `azure` (point at your deployment URL). Optional for the rest. |
|
|
1781
|
-
| `apiKey` |
|
|
1784
|
+
| `apiKey` | Optional: unset, the provider's SDK reads its own environment variable (`OPENAI_API_KEY`, ...). **Ignored** for `google-vertex` (which authenticates via Google ADC) and by a model object. |
|
|
1782
1785
|
| `providerOptions` | Escape hatch for provider-specific factory options. Spread into the SDK's `create*()` call after `baseURL` / `apiKey`, so anything documented for the underlying SDK works: e.g. `{ apiVersion, resourceName }` for Azure, `{ region, accessKeyId, secretAccessKey }` for Bedrock, `{ project, location, googleAuthOptions }` for Vertex, `{ accountId }` (or `{ binding }` inside a Worker) for Cloudflare. Per-stage override blocks have their own `providerOptions`; if absent, the top-level value is used. |
|
|
1783
1786
|
| `subagents` | Off by default. `{ dynamic: true }` or `{ dynamic: { maxDepth, maxChildren, maxConcurrent, budgetShare, minTokens, timeoutMs, defaultTools } }` gives the model `spawn_subagent`: it starts a helper agent for a sub-task, with a subset of its own tools and a share of what is left of its budgets. A helper can only have less than the run that starts it. See [Dynamic subagents](#dynamic-subagents-helpers-the-model-starts-itself). |
|
|
1784
1787
|
| `sandbox` | Off by default. `true` or `{ timeoutMs, memoryLimitBytes, maxOutputChars, maxCodeChars }` gives the model `run_js`: JavaScript it wrote runs in QuickJS/WebAssembly inside a worker thread that is killed at the deadline. Needs the optional peer `quickjs-emscripten`. See [Running code](#running-code-the-sandbox). |
|
|
1785
|
-
| `model` | Default model for every stage (executor / planner / synthesizer) when no per-stage override is set. |
|
|
1786
|
-
| `planner` / `synthesizer` | Optional per-stage override blocks: `{ providerType?, baseURL?, apiKey?, model? }
|
|
1787
|
-
| `executorTiers` | Off by default. `{ light?, standard?, strong? }`, each a stage override like `planner
|
|
1788
|
+
| `model` | Default model for every stage (executor / planner / synthesizer) when no per-stage override is set: a model id of `providerType`, or a ready AI SDK model object (`AgentModel`), used as it is. See [Your own model object](#your-own-model-object). |
|
|
1789
|
+
| `planner` / `synthesizer` | Optional per-stage override blocks: `{ providerType?, baseURL?, apiKey?, model? }`, or a model object for the stage. Use these to mix providers (e.g. Gemini planner, Anthropic synthesizer). Cross-provider overrides MUST set their own `apiKey`. |
|
|
1790
|
+
| `executorTiers` | Off by default. `{ light?, standard?, strong? }`, each a stage override like `planner` (a block or a model object): the planner rates every step `low` / `medium` / `high` and the executor runs it on that tier's model; a tier that is not configured falls back to the nearest one. See [Model tiers and escalation](#model-tiers-and-escalation). |
|
|
1788
1791
|
| `escalation` | `true` (default once `executorTiers` is on) \| `false` \| `{ maxPerStep?, maxPerRun? }` (defaults 1 / 3). A step that fails in a way a stronger model could fix is retried on the next stronger tier before the replanner is consulted. Nothing without tiers. |
|
|
1789
1792
|
| `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. |
|
|
1790
1793
|
| `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. |
|
|
@@ -1827,6 +1830,34 @@ Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — th
|
|
|
1827
1830
|
| `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). |
|
|
1828
1831
|
| `logLevel` | `'none' \| 'error' \| 'warn' \| 'info' \| 'debug'` |
|
|
1829
1832
|
|
|
1833
|
+
### Your own model object
|
|
1834
|
+
|
|
1835
|
+
`model` - and `planner`, `synthesizer` and each `executorTiers` entry - also takes a ready AI SDK language model object: the agent uses it as it is, imports no provider package for it, and needs no `providerType` or `apiKey`.
|
|
1836
|
+
|
|
1837
|
+
```ts
|
|
1838
|
+
import { createOpenAI } from '@ai-sdk/openai'
|
|
1839
|
+
import { createAgent } from '@dudko.dev/agent'
|
|
1840
|
+
|
|
1841
|
+
const openai = createOpenAI({ apiKey: env.OPENAI_API_KEY })
|
|
1842
|
+
|
|
1843
|
+
const agent = await createAgent({
|
|
1844
|
+
clientName: 'my-worker',
|
|
1845
|
+
model: openai('gpt-5-mini'), // every stage
|
|
1846
|
+
planner: openai('gpt-5'), // a stage of its own: an object, or a block as before
|
|
1847
|
+
mcpServers: {},
|
|
1848
|
+
maxIterations: 6,
|
|
1849
|
+
maxStepsPerTask: 8,
|
|
1850
|
+
})
|
|
1851
|
+
```
|
|
1852
|
+
|
|
1853
|
+
Why: with a model id the agent builds the model itself, with a dynamic `import()` of the provider package `providerType` names - which a runtime that bundles everything ahead of time (Cloudflare Workers / workerd) cannot do. A model object also carries what only the host has: a model wrapped in its own middleware (`wrapLanguageModel`), a Workers AI binding's model, a test mock.
|
|
1854
|
+
|
|
1855
|
+
- **Mixing.** Stages can mix objects and ids. Over a top-level object, a stage with no block (or a block that sets nothing) runs on that object; a block that names a model id goes the provider way and needs a `providerType` - its own or the top level's (createAgent throws, naming the block, when there is none). A block with provider fields but no model id over an object throws too: there is nothing to apply them to. The top-level `providerType` / `apiKey` / `baseURL` / `providerOptions` are then only the defaults of such blocks; a block that names another provider and inherits a top-level `apiKey` throws as ever (cross-provider key inheritance), since a top level with no `providerType` has a key of no named provider. `plannerModel` / `synthesizerModel` are `{ model }` blocks.
|
|
1856
|
+
- **Names.** Where a model is named - `step.start`'s `model` with tiers, the `agent.model` / `agent.provider` span attributes - an object is named by its `modelId` / `provider`.
|
|
1857
|
+
- **Media.** `media.*Model` took objects already; a media block with a model id over a top-level object needs a `providerType` as well (`media.imageModel: model "..." is a model id, so a providerType is needed ...`).
|
|
1858
|
+
- **Pipelines.** A registry entry may be an object: `models: { smart: { model: openai('gpt-5') } }`. Its node's route call runs on it too.
|
|
1859
|
+
- **Worker subagents: no.** A model object is a class instance with methods: it cannot cross into a worker thread. `createSubagentTool` with `isolation: 'worker'` (the default) throws when the tool is created if the child's config or a profile's carries one anywhere (`config.model is a model object, which cannot cross into a worker thread ...`). Use `isolation: 'in-process'`, or give the worker child a provider config (`providerType` + a model id). In-process subagents, dynamic helpers (`spawn_subagent`, which use the caller's models) and remote subagents (no config crosses) are not affected.
|
|
1860
|
+
|
|
1830
1861
|
### Picking models per stage
|
|
1831
1862
|
|
|
1832
1863
|
Match each stage to the **thinking level** the role needs, not to a specific model name (vendors rename and re-tier often). When in doubt, set `model` once and let every stage inherit it — split per stage only when cost or quality becomes a real constraint.
|