> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/reference/workflow-exports/javascript-typescript.md). Agents can also search and read this documentation through its [MCP server](https://dnotifier.gitbook.io/product-docs/~gitbook/mcp).

# JavaScript / TypeScript

## Imports

```js
import {
  DNotifier,
  defineAgent,
  Agent,
  Workflow,
  WorkflowContext,
  WorkflowRunner,
  WorkflowError,
} from "@dnotifier-realtime/dnotifier";
```

Static accessors on `DNotifier`:

```js
DNotifier.defineAgent(...)
DNotifier.Workflow
DNotifier.WorkflowContext
DNotifier.WorkflowRunner
DNotifier.WorkflowError
DNotifier.Agent
```

## `defineAgent({ name, run?, tools?, ... })`

| Parameter            | Type                                   | Required | Description                                                                      |
| -------------------- | -------------------------------------- | -------- | -------------------------------------------------------------------------------- |
| `name`               | `string`                               | ✅        | Unique, stable agent id within your app — a duplicate replaces the earlier agent |
| `run`                | `(ctx: WorkflowContext) => Promise<*>` | ✅\*      | Agent logic (\*required unless `tools` is set)                                   |
| `tools`              | `object[]`                             | —        | From `notifier.tools.register` or `mcp.tools()`                                  |
| `instructions`       | `string`                               | —        | System guidance for the tool agent                                               |
| `description`        | `string`                               | —        | Human-readable summary                                                           |
| `permissions`        | `Record<string, string[]>`             | —        | Tool permissions map                                                             |
| `observability`      | `boolean`                              | —        | Nested steps for standalone `runAgent`                                           |
| `provider` / `model` | `string`                               | —        | Default LLM provider/model                                                       |

**Returns:** `Agent`

```js
const intentAgent = DNotifier.defineAgent({
  name: "intent-agent",
  async run(ctx) {
    await ctx.sendAI({
      message: { text: "Classify: search or general?" },
      saveHistory: false,
      label: "Intent classification",
    });
    return { intent: "search" };
  },
});
```

Tool agents and MCP: [**Tools & MCP**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/tools-and-mcp/javascript-typescript.md).

## `notifier.tools` / `notifier.mcp` / `notifier.runAgent`

| API                                                                      | Description                |
| ------------------------------------------------------------------------ | -------------------------- |
| `notifier.tools.register({ name, description?, inputSchema?, execute })` | Register a local tool      |
| `await notifier.mcp.connect({ id, name, endpoint, transport? })`         | Connect MCP HTTP server    |
| `await notifier.runAgent(agent, { input, maxToolRounds?, ... })`         | Standalone tool-agent loop |

## `Workflow` class

```js
new DNotifier.Workflow({
  name: "my-workflow",
  description: "Optional, max 100 chars",
  observability: false,
  async entry(ctx) { /* ... */ },
})
```

| Option          | Type                  | Required | Default | Description                      |
| --------------- | --------------------- | -------- | ------- | -------------------------------- |
| `name`          | `string`              | ✅        | —       | Workflow identifier              |
| `description`   | `string`              | —        | —       | Short description (≤ 100 chars)  |
| `observability` | `boolean`             | —        | `false` | Send steps to workflow dashboard |
| `entry`         | `(ctx) => Promise<*>` | ✅        | —       | Main workflow function           |

### Methods

| Method                                                | Description                                                             |
| ----------------------------------------------------- | ----------------------------------------------------------------------- |
| `registerAgent(name, agent \| { receiverId })`        | Register one local or remote agent                                      |
| `registerAgents({ [name]: agent \| { receiverId } })` | Register local agents and/or remote `{ receiverId }` targets            |
| `getAgent(name)`                                      | Lookup a **local** agent                                                |
| `listen(notifier)`                                    | Host local agents for remote `runAgent`, MCP, and A2A calls (WebSocket) |
| `stopListening()`                                     | Stop answering remote calls                                             |

## `WorkflowContext` (inside `entry` and agent `run`)

| Member / method  | Signature                                                                  | Description                                        |
| ---------------- | -------------------------------------------------------------------------- | -------------------------------------------------- |
| `input`          | `*`                                                                        | Workflow input from `runWorkflow`                  |
| `state`          | `object`                                                                   | Shared mutable state for the run                   |
| `agentName`      | `string \| null`                                                           | Current agent name (inside agent handlers)         |
| `runAgent`       | `runAgent(name, { input? })`                                               | Invoke a registered agent                          |
| `runAgents`      | `runAgents(spec)`                                                          | Parallel agents → `{ results }`                    |
| `waitForMessage` | `waitForMessage({ timeoutMs? })`                                           | Wait for next inbound realtime message (WebSocket) |
| `sendAI`         | `sendAI({ message, saveHistory?, sessionId?, provider?, model?, label? })` | AI call with optional step label                   |
| `fetchAIHistory` | `fetchAIHistory({ label? })`                                               | Fetch AI history                                   |
| `search`         | `search({ query, limit?, minSimilarity?, filterbySource?, label? })`       | Semantic search                                    |
| `addDocument`    | `addDocument(opts)`                                                        | Add knowledge-base document                        |
| `updateDocument` | `updateDocument(opts)`                                                     | Update document                                    |
| `deleteDocument` | `deleteDocument(opts)`                                                     | Delete document                                    |
| `listDocuments`  | `listDocuments(opts?)`                                                     | List documents                                     |
| `getDocument`    | `getDocument(opts)`                                                        | Get document by id                                 |
| `recordStep`     | `recordStep({ label, input?, output?, status?, type? })`                   | Custom observability step                          |

When `observability: true`, SDK calls and `recordStep` are reported to the DNotifier workflow dashboard.

## `runWorkflow({ workflow, input, senderId? })`

| Parameter  | Type       | Required | Description                            |
| ---------- | ---------- | -------- | -------------------------------------- |
| `workflow` | `Workflow` | ✅        | Registered workflow instance           |
| `input`    | `*`        | ✅        | Input passed to `entry` as `ctx.input` |
| `senderId` | `string`   | —        | Defaults to constructor `userId`       |

**Returns:**

```js
{
  result,        // return value of entry()
  state,         // final shared state object
  executionId,   // present when observability: true
}
```

## `WorkflowRunner` (advanced)

```js
new WorkflowRunner({ notifier, senderId, workflow })
  .run({ input })
```

Use when you need custom hosting. Most apps should call `notifier.runWorkflow()` instead.

## `WorkflowError`

Thrown for:

* Missing workflow or agent names
* Agent `run` not a function
* Description longer than 100 characters
* `runAgent` called with unregistered name
