@dudko.dev/agent 0.0.51 → 0.0.53
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 +43 -12
- package/dist/cli.js +110 -110
- 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,7 +261,9 @@ 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.
|
|
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.
|
|
264
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.
|
|
265
268
|
- **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
269
|
- **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.
|
|
@@ -377,7 +380,7 @@ await agent.run({
|
|
|
377
380
|
- nothing more is sent: no model call, no deadline left behind; the lease is released;
|
|
378
381
|
- `agent.run()` **resolves** - not an error - with `text: ''` and `result.parked: { runId, items, at }`.
|
|
379
382
|
|
|
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`:
|
|
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`:
|
|
381
384
|
|
|
382
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);
|
|
383
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.
|
|
@@ -906,7 +909,7 @@ Server "docs":
|
|
|
906
909
|
|
|
907
910
|
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).
|
|
908
911
|
|
|
909
|
-
**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.
|
|
912
|
+
**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.
|
|
910
913
|
|
|
911
914
|
## MCP elicitation: a server asks the user
|
|
912
915
|
|
|
@@ -1031,7 +1034,7 @@ const researcher = createSubagentTool({
|
|
|
1031
1034
|
const agent = await createAgent({ ...config, tools: { researcher } })
|
|
1032
1035
|
```
|
|
1033
1036
|
|
|
1034
|
-
- **`'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.
|
|
1037
|
+
- **`'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.
|
|
1035
1038
|
- **`'in-process'`** builds the child on this thread; `tools` are merged into its config.
|
|
1036
1039
|
|
|
1037
1040
|
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`.
|
|
@@ -1544,7 +1547,7 @@ const pipeline = createPipeline(definition, {
|
|
|
1544
1547
|
// What the names in the definition stand for. A name that is not here fails its node.
|
|
1545
1548
|
resolveNode: nodeResolver({
|
|
1546
1549
|
base: config, // an IAgentConfig: every node starts from it
|
|
1547
|
-
models: { smart: { model: 'gpt-4.1-mini' } },
|
|
1550
|
+
models: { smart: { model: 'gpt-4.1-mini' } }, // or a model object: { model: openai('gpt-5') }
|
|
1548
1551
|
tools: { files: fileTools },
|
|
1549
1552
|
// skills: { ... }, mcpServers: { ... },
|
|
1550
1553
|
// configure: (config, node) => config // the place to read node.settings
|
|
@@ -1775,15 +1778,15 @@ Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — th
|
|
|
1775
1778
|
|
|
1776
1779
|
| Field | Notes |
|
|
1777
1780
|
| --- | --- |
|
|
1778
|
-
| `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. |
|
|
1781
|
+
| `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. |
|
|
1779
1782
|
| `baseURL` | Required for `openai-compatible` (point at your self-hosted server) and `azure` (point at your deployment URL). Optional for the rest. |
|
|
1780
|
-
| `apiKey` |
|
|
1783
|
+
| `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. |
|
|
1781
1784
|
| `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. |
|
|
1782
1785
|
| `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). |
|
|
1783
1786
|
| `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). |
|
|
1784
|
-
| `model` | Default model for every stage (executor / planner / synthesizer) when no per-stage override is set. |
|
|
1785
|
-
| `planner` / `synthesizer` | Optional per-stage override blocks: `{ providerType?, baseURL?, apiKey?, model? }
|
|
1786
|
-
| `executorTiers` | Off by default. `{ light?, standard?, strong? }`, each a stage override like `planner
|
|
1787
|
+
| `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). |
|
|
1788
|
+
| `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`. |
|
|
1789
|
+
| `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). |
|
|
1787
1790
|
| `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. |
|
|
1788
1791
|
| `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. |
|
|
1789
1792
|
| `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. |
|
|
@@ -1821,11 +1824,39 @@ Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — th
|
|
|
1821
1824
|
| `systemPrompt` | Appended to the planner, executor, replanner, and synthesizer system prompts so the same domain context (persona, language, tone) reaches every stage. |
|
|
1822
1825
|
| `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`. |
|
|
1823
1826
|
| `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. |
|
|
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. |
|
|
1827
|
+
| `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. |
|
|
1825
1828
|
| `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
1829
|
| `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). |
|
|
1827
1830
|
| `logLevel` | `'none' \| 'error' \| 'warn' \| 'info' \| 'debug'` |
|
|
1828
1831
|
|
|
1832
|
+
### Your own model object
|
|
1833
|
+
|
|
1834
|
+
`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`.
|
|
1835
|
+
|
|
1836
|
+
```ts
|
|
1837
|
+
import { createOpenAI } from '@ai-sdk/openai'
|
|
1838
|
+
import { createAgent } from '@dudko.dev/agent'
|
|
1839
|
+
|
|
1840
|
+
const openai = createOpenAI({ apiKey: env.OPENAI_API_KEY })
|
|
1841
|
+
|
|
1842
|
+
const agent = await createAgent({
|
|
1843
|
+
clientName: 'my-worker',
|
|
1844
|
+
model: openai('gpt-5-mini'), // every stage
|
|
1845
|
+
planner: openai('gpt-5'), // a stage of its own: an object, or a block as before
|
|
1846
|
+
mcpServers: {},
|
|
1847
|
+
maxIterations: 6,
|
|
1848
|
+
maxStepsPerTask: 8,
|
|
1849
|
+
})
|
|
1850
|
+
```
|
|
1851
|
+
|
|
1852
|
+
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.
|
|
1853
|
+
|
|
1854
|
+
- **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.
|
|
1855
|
+
- **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`.
|
|
1856
|
+
- **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 ...`).
|
|
1857
|
+
- **Pipelines.** A registry entry may be an object: `models: { smart: { model: openai('gpt-5') } }`. Its node's route call runs on it too.
|
|
1858
|
+
- **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.
|
|
1859
|
+
|
|
1829
1860
|
### Picking models per stage
|
|
1830
1861
|
|
|
1831
1862
|
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.
|