@dudko.dev/agent 0.0.44 → 0.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -142,6 +142,17 @@ Pass an event handler as the second argument to `createAgent`, or per run via `o
142
142
  | `subagent.start` / `subagent.event` / `subagent.complete` / `subagent.error` | A subagent tool call's lifecycle and its forwarded child events (`error` carries `stopped` when the user stopped it). |
143
143
  | `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). |
144
144
 
145
+ **Pipelines**
146
+
147
+ | Event | When |
148
+ | --- | --- |
149
+ | `pipeline.started` / `pipeline.finished` | A [pipeline](#pipelines) run began (`pipeline?`) / ended (`stoppedBy?`, `runs`). |
150
+ | `pipeline.node.started` / `pipeline.node.finished` / `pipeline.node.failed` | A node visit began (`nodeId`, `visit`, `from`), answered (`text`, `route?`, `usage?`) or failed (`error`, a string). |
151
+ | `pipeline.node.skipped` | An edge fired towards a node but a cap refused the visit (`nodeId`, `from`, `reason: 'maxRuns' \| 'maxNodeVisits'`). |
152
+ | `pipeline.edge` | An edge was decided (`from`, `to`, `edgeId`, `visit` of the source node, `fired`). |
153
+
154
+ Events a pipeline forwards from a node's agent carry `nodeId` and `visit` next to `runId`.
155
+
145
156
  ```ts
146
157
  const agent = await createAgent(config, (event) => {
147
158
  if (event.type === 'final.text-delta') process.stdout.write(event.delta)
@@ -240,12 +251,109 @@ const agent = await createAgent({ /* … */ mcpServers: { docs: { url: auth.serv
240
251
 
241
252
  // First run only: the server answers 401, the connect result carries
242
253
  // needsAuthorization, and the operator visits the URL above. Feed the code back:
243
- await finishMcpOAuth(auth, { code, state })
254
+ await finishMcpOAuth(auth, { code, state, iss }) // iss: pass it when the redirect carries one
244
255
  await agent.reconnect()
245
256
  ```
246
257
 
247
258
  Nothing is printed or opened on your behalf; `onAuthorizationUrl` and the loopback listener are yours to wire. `agent.listTools()` stays empty until the flow completes — a server that needs authorization reports `needsAuthorization: true` in its connect result rather than a generic failure. `MCP_SERVERS` (the CLI's env config) is JSON, so it can only express `headers`; OAuth is a library-level feature.
248
259
 
260
+ - **`iss` (RFC 9207).** `finishMcpOAuth` checks the `iss` query parameter of the redirect against the authorization server the flow was started with, after `state` and before the code is exchanged. A different issuer is refused (a mix-up attack: a code meant for one server sent to another), and so is a missing `iss` when the server's metadata says `authorization_response_iss_parameter_supported: true`. The comparison is exact, character for character. Read `iss` off the callback URL together with `code` and `state`; `checkAuthorizationResponseIssuer` is the rule on its own.
261
+ - **`clientMetadataUrl` (CIMD).** Host a client ID metadata document and pass its URL: an authorization server that advertises `client_id_metadata_document_supported` takes the URL as the `client_id`, and no registration request is made. Other servers get dynamic registration as before, and a registration already in the store wins over both. The URL must be https with a path (anything else throws when the provider is built), and the document must list the same `redirect_uris` as `redirectUrl`.
262
+ - **Registration** describes a public PKCE client. `application_type` follows the redirect URL: `'native'` for a loopback address (the usual CLI callback), `'web'` for an https one. Change any field through `clientMetadata`.
263
+ - **Discovery is stored** next to the tokens (the authorization server and its metadata), so later calls skip it and the issuer check has something to compare with. `auth.reset()` forgets it with everything else - use it when a server moved to another authorization server.
264
+
265
+ ### MCP with enterprise-managed authorization (ID-JAG)
266
+
267
+ When the company's identity provider decides who may use which MCP server (the MCP extension `io.modelcontextprotocol/enterprise-managed-authorization`, also called Cross App Access), there is no consent page and nobody to send anywhere. Your application already holds the user's OpenID Connect ID token from single sign-on; the provider turns it into an access token in two POSTs:
268
+
269
+ 1. **at the IdP** - an RFC 8693 token exchange: the ID token goes in, an Identity Assertion JWT Authorization Grant (**ID-JAG**) addressed to the MCP server's authorization server comes out;
270
+ 2. **at the MCP server's authorization server** - an RFC 7523 `jwt-bearer` grant: the ID-JAG goes in, an ordinary access token comes out.
271
+
272
+ ```ts
273
+ import { createAgent, createEnterpriseOAuthProvider } from '@dudko.dev/agent'
274
+
275
+ const auth = createEnterpriseOAuthProvider({
276
+ serverUrl: 'https://mcp.example.com/mcp',
277
+ // This client as registered at the MCP server's authorization server.
278
+ clientId: 'agent',
279
+ clientSecret: process.env.MCP_AS_CLIENT_SECRET,
280
+ expectedIssuer: 'https://auth.example.com', // required with clientSecret: nothing goes to any other
281
+ // This client as registered at the IdP (the audience of the ID token).
282
+ idp: {
283
+ tokenEndpoint: 'https://acme.idp.example/oauth2/token',
284
+ clientId: 'agent-at-idp',
285
+ clientSecret: process.env.IDP_CLIENT_SECRET,
286
+ },
287
+ getIdToken: () => session.idToken, // yours: called each time a new ID-JAG is needed
288
+ scope: 'mcp:tools', // optional
289
+ })
290
+
291
+ const agent = await createAgent({
292
+ ...config,
293
+ mcpServers: { docs: { url: 'https://mcp.example.com/mcp', authProvider: auth } },
294
+ })
295
+ ```
296
+
297
+ - **When it runs.** Before the first request when there is no usable token, and again whenever the token expires or the server answers 401. Each time is a fresh ID token from `getIdToken` and a fresh exchange: the ID-JAG takes the place of a refresh token, and a refresh token the authorization server returns anyway is not used.
298
+ - **What is stored.** The access token and what discovery found, in the same kind of store as the interactive provider (`store`, default the `0600` file). The ID token, the ID-JAG, the client assertions and the private key are never stored, logged or put in an error. Use one store per user.
299
+ - **What is checked before anything is sent.** `serverUrl`, the IdP token endpoint, the authorization server and its token endpoint must be https (or loopback). The ID-JAG is requested for the issuer and the resource that discovery found for this server - never for a value you pass - and the authorization server's metadata must name the URL it was fetched from as its issuer. With `expectedIssuer`, any other authorization server gets nothing. The IdP's answer must be a 200 with `issued_token_type` `urn:ietf:params:oauth:token-type:id-jag` and a token; otherwise nothing reaches the authorization server. A redirect from the IdP is refused.
300
+ - **`expectedIssuer` is required with `clientSecret` and with `private_key_jwt`.** Without it the MCP server's metadata would choose who receives the secret, or which audience a signed assertion is made for, so the provider throws when it is built (`clientSecret needs expectedIssuer`, `private_key_jwt needs expectedIssuer`). A client with no credential at the authorization server may omit it: the only thing sent there is then the ID-JAG, which the IdP addressed to that one server and which no other can use. (The latest draft lets an authorization server accept such a client only with a key-bound ID-JAG, which is not supported here, so expect most servers to want a credential.)
301
+ - **Client authentication, per hop.** At the IdP: `idp.clientAuthMethod` is `'client_secret_basic'` (the default with a secret), `'client_secret_post'` or `'private_key_jwt'`; no secret sends `client_id` alone. At the authorization server: `clientAuthMethod` is one of those or `'none'`; left out, the SDK picks from the server's metadata.
302
+ - **`private_key_jwt`** (RFC 7523 section 2.2) signs a client assertion instead of sending a secret. Give `privateKey` (a PEM string, a JWK object or a `KeyObject`), `algorithm` (`ES256`, `RS256`; also `ES384`, `ES512`, `RS384`, `RS512`, `PS256`, `PS384`, `PS512`) and optionally `keyId` - on the provider for the authorization server, inside `idp` (with `idp.issuer`) for the IdP. The key must be one for that algorithm, or signing is refused. Each assertion has `iss` = `sub` = the client id, a random `jti`, an `exp` 60 seconds away, the header `typ: client-authentication+jwt`, and as its only `aud` the **issuer identifier** of the server it is for (`idp.issuer`, or the authorization server's issuer once it matched `expectedIssuer`) - not the token endpoint URL, unless `assertionAudience` says so (below). That is the rule of `draft-ietf-oauth-rfc7523bis`: an assertion made for the IdP is useless at the authorization server and the other way round. The key and the assertions are never stored, logged or put in an error, and the provider does not show them when printed or serialized. Signing uses `node:crypto`; there is no new dependency.
303
+
304
+ ```ts
305
+ createEnterpriseOAuthProvider({
306
+ serverUrl: 'https://mcp.example.com/mcp',
307
+ clientId: 'agent',
308
+ clientAuthMethod: 'private_key_jwt',
309
+ privateKey: process.env.MCP_AS_PRIVATE_KEY_PEM,
310
+ algorithm: 'ES256',
311
+ keyId: 'agent-2026',
312
+ expectedIssuer: 'https://auth.example.com',
313
+ idp: {
314
+ tokenEndpoint: 'https://acme.idp.example/oauth2/token',
315
+ issuer: 'https://acme.idp.example',
316
+ clientId: 'agent-at-idp',
317
+ clientAuthMethod: 'private_key_jwt',
318
+ privateKey: idpJwk,
319
+ algorithm: 'RS256',
320
+ },
321
+ getIdToken: () => session.idToken,
322
+ })
323
+ ```
324
+ - **`assertionAudience` and `assertionType`: for a server built to RFC 7523.** The assertion above follows `draft-ietf-oauth-rfc7523bis`. Many deployed identity providers were built to RFC 7523 as published: they expect the **token endpoint URL** as `aud` and may refuse a `typ` they do not know. Two options, each available on the provider (for the authorization server) and inside `idp` (for the IdP), each only with `private_key_jwt`, and independent of each other and of the other hop:
325
+
326
+ | Option | Values | Default |
327
+ | --- | --- | --- |
328
+ | `assertionAudience` / `idp.assertionAudience` | `'issuer'`: the server's issuer identifier. `'token-endpoint'`: its token endpoint URL - `idp.tokenEndpoint` for the IdP; for the authorization server the `token_endpoint` of the discovered metadata, used only after that metadata matched `expectedIssuer` and the endpoint passed the https-or-loopback check | `'issuer'` |
329
+ | `assertionType` / `idp.assertionType` | `'client-authentication+jwt'` or `'JWT'`: the `typ` header | `'client-authentication+jwt'` |
330
+
331
+ With `idp.assertionAudience: 'token-endpoint'`, `idp.issuer` is no longer required. The default stays the issuer because an assertion addressed to a token endpoint URL is what the bis draft forbids: the token endpoint is one field of a metadata document, and a client that takes its audience from metadata can be handed a document naming an honest server's endpoint (audience injection) and made to sign an assertion that is valid there. Here neither value ever comes from the MCP server alone, so `'token-endpoint'` gives up the defence in depth and not the check itself - use it only for a server that refuses the issuer form. A value other than the ones listed, or either option without `private_key_jwt`, throws when the provider is built.
332
+
333
+ ```ts
334
+ createEnterpriseOAuthProvider({
335
+ // ...as above, for an IdP and an authorization server built to RFC 7523
336
+ clientAuthMethod: 'private_key_jwt',
337
+ assertionAudience: 'token-endpoint', // aud = the discovered token endpoint
338
+ assertionType: 'JWT',
339
+ expectedIssuer: 'https://auth.example.com',
340
+ idp: {
341
+ tokenEndpoint: 'https://acme.idp.example/oauth2/token', // aud of the IdP assertion
342
+ clientId: 'agent-at-idp',
343
+ clientAuthMethod: 'private_key_jwt',
344
+ privateKey: idpJwk,
345
+ algorithm: 'RS256',
346
+ assertionAudience: 'token-endpoint',
347
+ assertionType: 'JWT',
348
+ },
349
+ // ...
350
+ })
351
+ ```
352
+ - **A client ID metadata document as `clientId`.** `clientId` may be the https URL of a client ID metadata document (CIMD) you host, for an authorization server that resolves clients that way instead of pre-registering them. The URL must be https with a path of its own, and takes no `clientSecret` (a public document establishes no shared secret): such a client uses `private_key_jwt`, with the keys the document lists in `jwks` / `jwks_uri` and `token_endpoint_auth_method: 'private_key_jwt'`, or no credential. The IdP must know the client by the same URL, because it goes into the ID-JAG's `client_id`.
353
+ - **Errors say who refused, and say it briefly.** `EnterpriseOAuthError` has `hop`: `'idp'` (the exchange: `Enterprise IdP token exchange failed: ...`), `'authorization-server'` (the grant) or `'discovery'`, and `code` with the OAuth error. A refusal by the authorization server reads `MCP authorization server refused the ID-JAG grant: invalid_grant (HTTP 400)` - the code and the status, never the server's own text. What the server said goes to the log (`connectMcpServers`' log at `warn`, or the provider's `onLog`), with the ID token, the ID-JAG, the client assertion, the secrets and the key cut out first. This holds at connect and in the middle of a session: when a token dies during a run and the server refuses a new one, the tool call fails with the same `EnterpriseOAuthError`. A refusal fails that server's connect (`results[].error`) with no `needsAuthorization` - there is nobody to ask - and is not retried, since every grant is already a fresh one. `auth.authorize()` runs the flow on its own if you want to fail early. If you hand the provider to an SDK transport yourself, give that transport `auth.transportFetch(fetch, log)` as its `fetch` to get the same behaviour.
354
+ - **Not supported:** SAML assertions or a refresh token as the subject token, key-bound (DPoP) ID-JAGs, `client_secret_jwt`.
355
+ - **How it was verified.** Against a test identity provider that signs real tokens and an authorization server that verifies them (`tests/mcp-enterprise-oauth.test.ts`, over real sockets), following `draft-ietf-oauth-identity-assertion-authz-grant` and the extension's 2026-07-28 revision; both test servers verify client assertions (signature, `iss`/`sub`, audience, expiry, `jti` replay) and the test authorization server resolves a CIMD client by fetching its document. It has **not** been run against a commercial IdP (Okta, Ping, ...); expect to find differences there.
356
+
249
357
  ## Thinking (reasoning)
250
358
 
251
359
  Turn on the model's reasoning for every stage with `thinking`, and override it per stage with `stageThinking` (a stage entry — even `false` — wins over the top-level value):
@@ -610,6 +718,199 @@ It is a *knowledge* feature and nothing else:
610
718
 
611
719
  Every save emits `skill.learned` (`name`, `description`, `update`, `chars`, `sources`), every forget `skill.forgotten`. CLI: `AGENT_LEARNING=on`, `AGENT_LEARNING_DIR=<dir>`; in the REPL `/skills` lists skills (the agent's own marked) and `/forget <name>` deletes one.
612
720
 
721
+ ## Running code: the sandbox
722
+
723
+ Ask a model to "run it on the test data" and, with nothing to run it in, it writes the code and *describes* an output. Switch on `sandbox` and the run is a real tool call whose output you can see:
724
+
725
+ ```ts
726
+ // npm install quickjs-emscripten (an optional peer: only needed with `sandbox`)
727
+ const agent = await createAgent({
728
+ ...config,
729
+ sandbox: true,
730
+ // or: sandbox: { timeoutMs: 5000, memoryLimitBytes: 32 * 1024 * 1024, maxOutputChars: 8000, maxCodeChars: 100_000 }
731
+ })
732
+ // CLI: AGENT_SANDBOX=on, AGENT_SANDBOX_TIMEOUT_MS, AGENT_SANDBOX_MEMORY_MB
733
+ ```
734
+
735
+ That registers one tool, `run_js({ code })`, which returns `{ ok, stdout, result?, error?, truncated, durationMs }`:
736
+
737
+ - `stdout` — everything `console.log / info / warn / error` printed, in order (`warn` and `error` lines are prefixed).
738
+ - `result` — the value of the **last expression** of the program (a returned promise is awaited; for a program written as an ES module, its `default` export), copied out as JSON-like data: functions, symbols and cycles become strings, depth and size are bounded.
739
+ - `error` — `{ name, message, stack }` when the program threw, ran out of time or memory. The stack has the guest's frames only. A failing program is a **result**, not a failed tool call, so the model reads the error and fixes its code.
740
+
741
+ **Off by default.** Without the flag the tool does not exist, nothing is added to the prompts, the engine is never loaded and no thread is started. With it, the planner, executor and synthesizer are told — in the run-stable system prompt — what `run_js` is and that code is never reported as run unless it was.
742
+
743
+ **What the guest is.** The code runs in [QuickJS](https://bellard.org/quickjs/) compiled to WebAssembly ([`quickjs-emscripten`](https://github.com/justjake/quickjs-emscripten), MIT) — *not* in Node's own engine and not in `node:vm`, which shares the process's heap and is documented as not being a security mechanism. The guest has standard JavaScript (ES2023, top-level `await`, `setTimeout` / `setInterval` bounded by the run) and nothing else: no `process`, no `require` of host modules, no `import` of anything, no `fetch`, no file system, no environment. In this package the sandbox **computes only** — the Node agent has no workspace to bind (the browser sibling binds its virtual file system).
744
+
745
+ **What bounds it.**
746
+
747
+ | | Default | At most | How |
748
+ | --- | --- | --- | --- |
749
+ | `timeoutMs` | 5000 | 60000 | QuickJS's interrupt handler stops JavaScript that loops (and a guest cannot catch it). A single long native call cannot be interrupted, so every run is in its own **worker thread**, which is **terminated** at `timeoutMs` + 1 s. The agent's thread is never blocked. |
750
+ | `memoryLimitBytes` | 32 MiB | 256 MiB | The whole WebAssembly memory of the guest's engine instance (the engine's own 16 MiB minimum included) has this as its hard maximum, enforced by the wasm runtime. Allocation past it fails *inside the guest* as `out of memory`. |
751
+ | `maxOutputChars` | 8000 | 100000 | `stdout` and `result` together; cut in the engine and again on the agent's side. `truncated: true` says so. |
752
+ | `maxCodeChars` | 100000 | 1000000 | A longer program is refused before anything starts. |
753
+
754
+ Each run gets a fresh engine instance in a fresh worker (nothing is shared between runs, and a run after a killed one is unaffected); at most four run at once, the rest wait. The worker is given an empty environment.
755
+
756
+ **Gates.** `run_js` is an ordinary tool: it is in `listTools()` and the tool search, it counts against `maxToolCalls`, its output is capped like any other, and for [tool approval](#tool-approval-and-autopilot) it is a **write** — `ask-writes` shows the user the code before each run, `read-only` refuses it. A UI sees it as the usual `step.tool-call` / `step.tool-result` events; there is no separate event.
757
+
758
+ **What it does not protect against.** A bug in the WebAssembly runtime or in QuickJS itself (the guest is confined by the wasm sandbox, not by a second process: for hostile multi-tenant code, run the agent in a container too); timing side channels; and the CPU a run may burn within its deadline, times four. The installed peer is checked when the agent is created: without `quickjs-emscripten`, `createAgent` throws and names the package.
759
+
760
+ ## Pipelines
761
+
762
+ A pipeline is a graph of agents: each node is an agent with its own role, model and tools, each
763
+ edge passes one node's output to the next, optionally on a condition, and loops are allowed. The
764
+ whole graph is plain JSON, so it can be stored, sent and drawn by an editor.
765
+
766
+ ```ts
767
+ import { createPipeline, nodeResolver } from '@dudko.dev/agent'
768
+
769
+ const definition = {
770
+ version: 1,
771
+ entry: 'writer',
772
+ nodes: [
773
+ { id: 'writer', name: 'Writer', instructions: 'Write the text the request asks for.', model: 'smart' },
774
+ {
775
+ id: 'reviewer',
776
+ name: 'Reviewer',
777
+ instructions: 'Review the text. Be strict.',
778
+ routes: [{ label: 'approve', description: 'ready to publish' }, { label: 'revise' }],
779
+ },
780
+ { id: 'publisher', instructions: 'Format the approved text for publication.', tools: ['files'] },
781
+ ],
782
+ edges: [
783
+ { from: 'writer', to: 'reviewer' },
784
+ { from: 'reviewer', to: 'publisher', when: { kind: 'route', label: 'approve' } },
785
+ { from: 'reviewer', to: 'writer', when: { kind: 'otherwise' } }, // the loop
786
+ ],
787
+ limits: { maxNodeVisits: 3, maxRuns: 25 }, // the defaults
788
+ }
789
+
790
+ const pipeline = createPipeline(definition, {
791
+ // What the names in the definition stand for. A name that is not here fails its node.
792
+ resolveNode: nodeResolver({
793
+ base: config, // an IAgentConfig: every node starts from it
794
+ models: { smart: { model: 'gpt-4.1-mini' } },
795
+ tools: { files: fileTools },
796
+ // skills: { ... }, mcpServers: { ... },
797
+ // configure: (config, node) => config // the place to read node.settings
798
+ }),
799
+ })
800
+
801
+ const result = await pipeline.run({
802
+ input: 'A release note for v2',
803
+ onEvent: (e) => {
804
+ if (e.type === 'pipeline.node.started') console.log('→', e.nodeId, `#${e.visit}`)
805
+ if (e.type === 'pipeline.edge' && e.fired) console.log(` ${e.from} → ${e.to}`)
806
+ },
807
+ })
808
+ console.log(result.text, result.runs, result.stoppedBy)
809
+ await pipeline.close() // closes the node agents (their MCP connections)
810
+ ```
811
+
812
+ **The definition** is data: `{ version: 1, name?, entry, nodes, edges, limits? }`.
813
+
814
+ | Field | Meaning |
815
+ | --- | --- |
816
+ | `entry` | The id of the node that receives the request. |
817
+ | `nodes[].id`, `name?` | The id is unique; the name is what other nodes and a UI see. |
818
+ | `nodes[].instructions?` | The node's role, added to its agent's system prompt. |
819
+ | `nodes[].model?`, `skills?`, `tools?`, `mcpServers?` | **Names** the host resolves - never a model object, never a key. |
820
+ | `nodes[].routes?` | `{ label, description? }[]`: after it answers, the node picks one. |
821
+ | `nodes[].join?` | `'all'` (default) or `'any'`, see below. |
822
+ | `nodes[].settings?` | Handed to the host's resolver untouched; never applied by itself. |
823
+ | `nodes[].position?` | `{ x, y }` for an editor; the runner ignores it. |
824
+ | `edges[]` | `{ id?, from, to, when? }`. Ids are unique; an edge without one is given `e<its position>` (`e0`, `e1`, ...). `pipeline.definition` and `normalizePipeline(definition)` return the definition with every id filled in. |
825
+ | `limits?` | `maxNodeVisits` (per node, default 3, 1-100), `maxRuns` (all nodes, default 25, 1-1000). |
826
+
827
+ **Conditions** (`edge.when`; absent = `always`):
828
+
829
+ | `kind` | Fires when |
830
+ | --- | --- |
831
+ | `always` | Always. |
832
+ | `contains` | The output contains `text` - a plain substring, case-insensitive unless `caseSensitive: true`. |
833
+ | `matches` | `pattern` (with `flags` from `imsu`) occurs in the output. |
834
+ | `route` | The node picked the route `label`. |
835
+ | `otherwise` | No other edge of the same node fired. At most one per node. |
836
+
837
+ `contains` and `matches` look at the first 50,000 characters of an output. A pattern is at most 500
838
+ characters and is **not** run by `RegExp`: it is compiled to a matcher that cannot backtrack, so
839
+ `(a+)+$` costs the same as any other pattern (time grows with input length x pattern size, both
840
+ capped). The price is a subset of the syntax: literals, classes, `.`, `^ $ \b \B`, groups,
841
+ alternation, `* + ? {n,m}`; no backreferences, no lookaround, no `\p{...}` - those are refused at
842
+ validation. It answers the same as `RegExp.test` on what it accepts.
843
+
844
+ **How it runs**
845
+
846
+ - **Waves.** Wave 0 is the entry node. All nodes of a wave run concurrently. When a node finishes,
847
+ its outgoing edges are evaluated against its output: every edge whose condition holds fires;
848
+ `otherwise` fires only if none of the node's other edges did. A fired edge activates its target
849
+ for a later wave and carries the source's output to it.
850
+ - **Join.** A node activated by several edges gets all their outputs in one visit. With
851
+ `join: 'all'` an activated node is *deferred* while any other activated node can still reach it
852
+ through the graph (conditions aside) - so a fan-in waits for its slower branch even when the
853
+ branches have different lengths. If every activated node is deferred (they wait for each other in
854
+ a cycle), all of them run. `join: 'any'` never defers: the node runs once per wave it is
855
+ activated in.
856
+ - **Loops** are allowed. When starting a node would exceed `maxNodeVisits` for it, or `maxRuns` for
857
+ the pipeline, that activation is dropped (`pipeline.node.skipped`); the run goes on with what is
858
+ left, ends normally, and the result carries `stoppedBy: 'maxNodeVisits'` or `'maxRuns'`
859
+ (`maxRuns` wins when both happened).
860
+ - **A fan-in inside a loop** has a limit: when a `join: 'all'` node and a slower branch that leads
861
+ to it can also reach each other through the loop, they wait for each other, so both run and the
862
+ join fires without that branch. Use `join: 'any'` there, or keep the fan-in out of the cycle (a
863
+ loop around the whole fan-out and fan-in works).
864
+ - **The end.** The run ends when nothing is activated. A *terminal* visit is one that activated
865
+ nothing (no edge fired, or a cap dropped what it fired). `result.text` is the output of the last
866
+ terminal node to finish; several of the same wave are joined under `## <name>` headings.
867
+ - **A node that throws fails the pipeline**: `run` rejects with a `PipelineNodeError` (`nodeId`,
868
+ `visit`, `cause`), the other running nodes are aborted through their signal, and the last event
869
+ is `pipeline.node.failed` (no `pipeline.finished`).
870
+ - **Routes.** For a node with `routes`, the adapter asks the node's planner model to pick one
871
+ label with a small structured-output call after the node answered. An answer that is not one of
872
+ the labels - or a call that fails - is no route: only `always`, the text conditions and
873
+ `otherwise` can fire. Its tokens are part of the node's `usage`.
874
+ - **A node's input** is the original request, then each activating node's output under its name.
875
+ One agent is created per node on its first visit and kept (with whatever memory its config gives
876
+ it) until `pipeline.close()`. An agent of this package keeps no conversation between runs, so a
877
+ node remembers nothing from its earlier visits: what it needs is in its input (in a review loop,
878
+ let the reviewer quote the draft, or route the draft back with a second edge).
879
+
880
+ **The result**: `{ text, outputs, trace, usage, stoppedBy?, runs }` - `outputs[nodeId]` is
881
+ `{ visit, text, route? }[]`, `trace` lists node runs, edge decisions and dropped activations in
882
+ order, `usage` is the sum over all nodes.
883
+
884
+ **Events** (through `run({ onEvent })`):
885
+
886
+ | Event | Payload |
887
+ | --- | --- |
888
+ | `pipeline.started` | `pipeline?` - the definition's name |
889
+ | `pipeline.node.started` | `nodeId, visit, from` - the ids of the nodes whose outputs it got |
890
+ | `pipeline.node.finished` | `nodeId, visit, text, route?, usage?` |
891
+ | `pipeline.node.failed` | `nodeId, visit, error` (a string) |
892
+ | `pipeline.node.skipped` | `nodeId, from, reason: 'maxRuns' \| 'maxNodeVisits'` - an edge fired towards the node, a cap refused the visit |
893
+ | `pipeline.edge` | `from, to, edgeId, visit, fired` - one per outgoing edge, right after the source finished; `visit` is the visit of the source node |
894
+ | `pipeline.finished` | `stoppedBy?: 'maxRuns' \| 'maxNodeVisits' \| 'aborted', runs` |
895
+
896
+ Every event of a node's own agent is forwarded unchanged, plus `nodeId` and `visit`.
897
+
898
+ `validatePipeline(definition)` returns `{ ok, errors, warnings }` without running anything (each
899
+ issue has a `code`, a `message` and the `nodeId` / `edgeId` / `edgeIndex` it is about) - errors for
900
+ a wrong version, empty or duplicate ids, a missing entry, an edge to or from an unknown node, a
901
+ duplicate edge id, a `route` edge whose label the source node does not have, a second `otherwise`, a bad pattern or
902
+ flag, limits out of range; warnings for unreachable nodes, routes no edge uses, and a loop (allowed:
903
+ the caps bound it). `createPipeline` throws a `PipelineValidationError` on errors.
904
+ `options.runNode(node, input, ctx)` replaces the agent altogether - the pipeline then only
905
+ schedules - which is also how to test a graph without a model.
906
+
907
+ **Abort:** `signal` aborts every running node and `run` rejects with an `AbortError`, as `agent.run` does (after a `pipeline.finished` event with `stoppedBy: 'aborted'`); the browser sibling resolves with `stoppedBy: 'aborted'` instead, as its `agent.run` does.
908
+
909
+ A definition is safe to load from someone else: it holds no code, its patterns cannot hang the
910
+ process, the caps bound its loops, and it can only name what `nodeResolver` registered -
911
+ `node.settings` reaches your `configure` and nothing else. The graph engine is the same file as in
912
+ the browser sibling, so a definition runs the same in both.
913
+
613
914
  ## Autonomy
614
915
 
615
916
  The stage prompts are written for an agent that acts on its own:
@@ -631,6 +932,7 @@ Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — th
631
932
  | `baseURL` | Required for `openai-compatible` (point at your self-hosted server) and `azure` (point at your deployment URL). Optional for the rest. |
632
933
  | `apiKey` | Required by the type, but **ignored** for `google-vertex` (which authenticates via Google ADC). |
633
934
  | `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. |
935
+ | `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). |
634
936
  | `model` | Default model for every stage (executor / planner / synthesizer) when no per-stage override is set. |
635
937
  | `planner` / `synthesizer` | Optional per-stage override blocks: `{ providerType?, baseURL?, apiKey?, model? }`. Use these to mix providers (e.g. Gemini planner, Anthropic synthesizer). Cross-provider overrides MUST set their own `apiKey`. |
636
938
  | `plannerModel` / `synthesizerModel` | **Deprecated** model-only shortcuts. Equivalent to `planner: { model }` / `synthesizer: { model }`. The override block, if present, wins. |
@@ -723,6 +1025,7 @@ Top-level exports beyond `createAgent`:
723
1025
  - `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).
724
1026
  - `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).
725
1027
  - `createSubagentTool(options)` — [subagents](#subagents-worker_threads).
1028
+ - `createPipeline(definition, options)`, `nodeResolver(registries)`, `validatePipeline(definition)`, `normalizePipeline(definition)`, `testPipelineCondition(when, output)`, `renderPipelineNodeInput(input)`, `PIPELINE_LIMITS`, `PipelineNodeError`, `PipelineValidationError` — [pipelines](#pipelines).
726
1029
  - `resolveThinking(setting)`, `mergeProviderOptions(...layers)` — [thinking](#thinking-reasoning).
727
1030
  - `checkLimits(usage, limits)`, `resolveLimits(config)`, `normalizeUsage(sdkUsage)`, `addUsage(a, b)` — [token limits](#token-limits-and-step-caps).
728
1031
  - `compactHistory(turns, model, opts)`, `estimateTokens(text)`, `withToolOutputLimit(tool, maxChars)`, `truncateToolModelOutput(output, maxChars)` — [compaction](#compaction).
@@ -749,7 +1052,7 @@ dd-agent --env-file=.env
749
1052
 
750
1053
  `--env-file=<path>` is loaded via Node's built-in `process.loadEnvFile`, so no `dotenv` dependency is needed. Without the flag the CLI reads the ambient process env. `-h` / `--help` prints the supported flags and the in-REPL slash commands (`/status`, `/usage`, `/tools`, `/history`, `/reset`, `/compact`, `/autopilot`, `/approval <mode>`, `/reconnect`, `/skills`, `/forget <name>`, `/agents`, `/stop [n]`, `/exit` — `/quit` does the same).
751
1054
 
752
- The newer features are env-driven too: `AGENT_THINKING` (`off | minimal | low | medium | high | xhigh | <budget tokens>`), `AGENT_MAX_INPUT_TOKENS` / `AGENT_MAX_OUTPUT_TOKENS` / `AGENT_MAX_REASONING_TOKENS` / `AGENT_MAX_TOTAL_TOKENS`, `AGENT_MAX_TOOL_CALLS`, `AGENT_PER_CALL_TOKENS` (JSON `{"executor":16000,"synthesizer":0}` — per-stage output caps, `0` = no cap, see [Token limits](#token-limits-and-step-caps)), `AGENT_TOOL_APPROVAL` (`autopilot | ask-writes | ask-all | read-only`), `AGENT_TOOL_RULES` (JSON `{ "<tool or glob*>": "allow" | "ask" | "deny" }`, beats the mode — e.g. `{"github__delete_*":"deny"}`), `AGENT_EGRESS` (`on | off`; with `AGENT_EGRESS_ALLOW`, `AGENT_EGRESS_DENY`, `AGENT_EGRESS_PROTOCOLS`, `AGENT_EGRESS_ALLOW_PRIVATE` — see [Egress](#egress-what-the-model-may-fetch)), `AGENT_SKILLS_DIR`, `AGENT_LEARNING` (`on | off`; `AGENT_LEARNING_DIR` keeps the lessons across sessions — see [Learning](#learning-lessons-that-outlive-the-task)), `AGENT_TOOL_SELECTION_STRATEGY` (`auto | all | plan-narrowed | search`), `AGENT_CONTEXT_WINDOW_TOKENS`, `AGENT_COMPACTION_THRESHOLD` (percent of the window where auto-compaction starts, default 85) and `AGENT_COMPACTION=off`. The REPL prints the model's thoughts dimmed, auto-compacts its history with the same settings, and — when the approval mode asks — prompts `allow? [y]es / [n]o / [a]lways` right in the terminal; `/autopilot` toggles between autopilot and the last asking mode.
1055
+ The newer features are env-driven too: `AGENT_THINKING` (`off | minimal | low | medium | high | xhigh | <budget tokens>`), `AGENT_MAX_INPUT_TOKENS` / `AGENT_MAX_OUTPUT_TOKENS` / `AGENT_MAX_REASONING_TOKENS` / `AGENT_MAX_TOTAL_TOKENS`, `AGENT_MAX_TOOL_CALLS`, `AGENT_PER_CALL_TOKENS` (JSON `{"executor":16000,"synthesizer":0}` — per-stage output caps, `0` = no cap, see [Token limits](#token-limits-and-step-caps)), `AGENT_TOOL_APPROVAL` (`autopilot | ask-writes | ask-all | read-only`), `AGENT_TOOL_RULES` (JSON `{ "<tool or glob*>": "allow" | "ask" | "deny" }`, beats the mode — e.g. `{"github__delete_*":"deny"}`), `AGENT_EGRESS` (`on | off`; with `AGENT_EGRESS_ALLOW`, `AGENT_EGRESS_DENY`, `AGENT_EGRESS_PROTOCOLS`, `AGENT_EGRESS_ALLOW_PRIVATE` — see [Egress](#egress-what-the-model-may-fetch)), `AGENT_SANDBOX` (`on | off`; with `AGENT_SANDBOX_TIMEOUT_MS`, `AGENT_SANDBOX_MEMORY_MB` — see [Running code](#running-code-the-sandbox)), `AGENT_SKILLS_DIR`, `AGENT_LEARNING` (`on | off`; `AGENT_LEARNING_DIR` keeps the lessons across sessions — see [Learning](#learning-lessons-that-outlive-the-task)), `AGENT_TOOL_SELECTION_STRATEGY` (`auto | all | plan-narrowed | search`), `AGENT_CONTEXT_WINDOW_TOKENS`, `AGENT_COMPACTION_THRESHOLD` (percent of the window where auto-compaction starts, default 85) and `AGENT_COMPACTION=off`. The REPL prints the model's thoughts dimmed, auto-compacts its history with the same settings, and — when the approval mode asks — prompts `allow? [y]es / [n]o / [a]lways` right in the terminal; `/autopilot` toggles between autopilot and the last asking mode.
753
1056
 
754
1057
  **Talking to the agent while it works.** The REPL keeps reading while a run goes. Text you type then is said to the running agent (it sees it at its next boundary and the replanner re-checks the plan — see [Steering a run](#steering-a-run-that-is-already-going)): the REPL prints `[you->agent] queued` and then `delivered (round|step|final)`, and the message enters the history as a user turn. A message that arrives while the answer is being written is sent as the next prompt (`[follow-up]`). After Ctrl-C nothing is sent behind your back: what the agent never saw is listed as `[not delivered]`. While a run goes, `/agents` lists the running subagents and `/stop <n>` (or an id prefix, or just `/stop` when one runs) stops one — the run goes on; the other REPL commands work between runs. Each subagent's own steps and tool calls are logged as `[name id] ...` lines, so parallel ones can be told apart.
755
1058