# Zervice Chatbot — Agent-First Management Plane Zervice Chatbot is an agent-first platform for building, grounding, orchestrating, and testing AI assistants across websites and external A2A workflows. - **Canonical Documentation Source of Truth:** `https://chat.zervice.us/api/v1/admin/llms.txt` and `https://chat.zervice.us/docs` (applies identically to both Zervice Cloud and self-hosted deployments). - **Target Workspace Base URL:** Point `Authorization: Bearer zrv_pat_...` requests and MCP clients to `https://chat.zervice.us` (Managed Cloud) or `https://chat.zervice.us` / your custom self-hosted domain (`https://`). Every deployment exposes the exact same concepts, FlowSpecs, REST endpoints, and MCP tools. ## Documentation ### Guides & Mental Model - [5-Minute Agent Quickstart](https://chat.zervice.us/docs/quickstart.md): Create a workspace Personal Access Token, connect via MCP or REST, and run your first discovery and dry-run simulation. - [Core Concepts & Mental Model](https://chat.zervice.us/docs/concepts.md): How Workspaces, Bots, the Workspace Library, the 4-layer visitor turn pipeline, and Draft vs Published states work. - [Declarative FlowSpec Reference](https://chat.zervice.us/docs/flow-spec.md): Complete specification for validating, authoring, and exporting Dialog Flows as declarative JSON. - [Knowledge Base, Simulation & Quality Loop](https://chat.zervice.us/docs/knowledge-and-quality.md): How to structure Markdown knowledge for high search recall, run isolated multi-turn simulations, and diagnose quality gaps. - [REST API & MCP Reference](https://chat.zervice.us/docs/api.md): Authentication, capability scopes, error semantics, Streamable HTTP MCP usage, and full endpoint catalog. - [Autonomous Agent Playbooks](https://chat.zervice.us/docs/workflows.md): Step-by-step end-to-end playbooks for setup, CI doc sync, workflow authoring, and weekly quality tuning. ### Machine-Readable Discovery - [Full Handbook (/api/v1/admin/llms-full.txt)](https://chat.zervice.us/api/v1/admin/llms-full.txt): Single-fetch concatenation of all guides and references - [OpenAPI 3.1 Specification (/api/v1/admin/openapi.json)](https://chat.zervice.us/api/v1/admin/openapi.json): Complete typed REST API schema - [Docs Portal (/docs)](https://chat.zervice.us/docs): Human-browseable documentation hub ## Quick Integration Workflow (5-Step Autonomous Agent Playbook) 1. **Discover**: Call `GET /api/v1/admin/whoami` and `GET /api/v1/admin/discover` (or MCP `workspace_whoami` + `workspace_discover`) for a one-shot snapshot of bots, Knowledge Collections, Knowledge Sources, Dialog Flows, integrations, and 7-day quality signals. 2. **Idempotent Upsert**: Supply a stable `externalId` (`^[a-z0-9][a-z0-9_-]{1,62}$`) when creating bots, collections, sources, items, flows, or integrations so retries safely update in place. 3. **Author Declarative FlowSpecs**: Validate with `POST /api/v1/admin/flows/validate` before persisting with `PUT /api/v1/admin/flows/by-external-id/:externalId/spec`. Always give nodes concise human-readable `"name"` titles (2–5 words, especially `condition` routers and jump targets), give branches clear `"intentName"` labels, and stage drafts using `status: "build"` (`content:draft`). 4. **Dry-Run Simulation**: Test turns safely with `POST /api/v1/admin/bots/:botId/simulate` (`toolMode: "mock"`, `useDrafts: true`) in an isolated temporary session with zero writes to conversation logs, leads, or analytics. 5. **Close Quality Gaps**: Query `GET /api/v1/admin/analytics/gaps?days=7` and `GET /api/v1/admin/logs?bot_id=all&outcome=fallback`, fill missing Knowledge Items or review-queued Hot Questions, and re-verify in simulation. ## Key Concepts - **Workspace Isolation & Multi-Bot Library**: A PAT is strictly scoped to one Workspace (tenant) and filtered by capability scopes. Workspaces hold shared Knowledge Collections, Dialog Flows, Integrations, and Secrets bound flexibly to one or more Bots (e.g., Public Website Bot vs. Signed-In Customer Bot). - **4-Layer Visitor Turn Pipeline**: Every visitor query evaluates in order: (1) **Dialog Flows** (typed Saved Fields `{{slot_name}}`, deterministic branching, terminal `agent` handoffs, and mid-flow off-topic Q&A escape + resume), (2) **Hot Questions Instant Cache** (`review` draft queue vs `active` live FAQ), (3) **Business Integrations** (live lookups & visitor Confirmation Gates), and (4) **Knowledge Base Q&A** (grounded answers with citations, polite declines when ungrounded). - **Secrets Vault**: Outbound credentials live in write-only workspace storage and are interpolated only at runtime via `{{secret.NAME}}` inside Business Integrations. - **Common Mistakes to Avoid**: - Do NOT leave `condition` nodes or shared jump targets without a concise human-readable `"name"` (Flow Studio cards and Goto jumps render `name` instead of raw slot rules). - Do NOT mix `branches[]` and `next`/`end` on the same FlowSpec `bot` node. - Do NOT attach `branches[]`, `next`, or `end` to a FlowSpec `agent` node (`agent` is terminal). - Do NOT skip `flow_validate_spec` before `flow_put_spec`. - Do NOT try to publish (`status: "published"` / `"active"`) with a `content:draft` token; stage as `"build"` / `"review"` and test via `bot_simulate_turn`. ## Authentication & Scopes Granted PAT Scopes: - `bots:read` - `bots:write` - `bots:delete` - `content:read` - `content:draft` - `content:write` - `analytics:read` - `leads:read` - `integrations:read` - `integrations:write` - `api_keys:manage` - `users:manage` - `tenant:settings` Role Presets: - `draft_builder` (Draft Builder Agent (Safe Mode — Recommended)): bots:read, content:read, content:draft, analytics:read - `observer` (Observer / Analytics Agent): bots:read, content:read, analytics:read - `full_builder` (Full Workspace Builder Agent): bots:read, bots:write, bots:delete, content:read, content:draft, content:write, integrations:read, integrations:write, leads:read, analytics:read, tenant:settings - `ci_docs_sync` (CI Docs Sync): content:read, content:write ## MCP Client Configuration ```json { "mcpServers": { "zervice-admin": { "type": "http", "url": "https://chat.zervice.us/api/v1/admin/mcp", "headers": { "Authorization": "Bearer zrv_pat_YOUR_KEY" } } } } ``` ## Curated Tools & REST Endpoints (42 total) ### Domain: workspace - `workspace_whoami` (GET `/api/v1/admin/whoami`, scopes: none): Returns the authenticated workspace principal, authentication type (pat or session), role, and resolved capability scopes. - `workspace_discover` (GET `/api/v1/admin/discover`, scopes: none): Returns a single scope-filtered snapshot of all workspace resources: bots, Knowledge Collections, Knowledge Sources, Dialog Flows, integrations, secret names, Account Lead Notification Webhook status, starter templates, and 7-day quality metrics. - `workspace_embed_get` (GET `/api/v1/admin/workspace/embed`, scopes: `bots:read`): Reads the workspace embed key, URL routing rules, exclusion globs, and default bot fallback action for the single-line website widget. - `workspace_embed_put` (PUT `/api/v1/admin/workspace/embed`, scopes: `bots:write`): Updates global website widget URL routing rules, excluded path globs, and fallback bot selection. - `account_lead_webhook_get` (GET `/api/v1/admin/account/lead-webhook`, scopes: `tenant:settings`): Reads the account-wide outbound lead notification webhook configuration (enabled, target URL, and masked signing secret hint). - `account_lead_webhook_put` (PUT `/api/v1/admin/account/lead-webhook`, scopes: `tenant:settings`): Configures the account-wide outbound webhook URL and HMAC-SHA256 signing secret notified with lead.created JSON events whenever any bot captures a lead. - `account_lead_webhook_test` (POST `/api/v1/admin/account/lead-webhook/test`, scopes: `tenant:settings`): Sends a signed sample lead.created event to the configured (or candidate) Account Lead Notification Webhook URL and returns HTTP status telemetry. ### Domain: bots - `bot_list` (GET `/api/v1/admin/bots`, scopes: `bots:read`): Lists every chatbot agent in the current workspace along with configuration and stats. - `bot_get` (GET `/api/v1/admin/bots/{botId}`, scopes: `bots:read`): Fetches a single bot configuration record by botId. - `bot_upsert` (POST `/api/v1/admin/bots`, scopes: `bots:write`): Creates a bot or idempotently updates the existing bot when externalId already exists in the workspace. - `bot_patch` (PATCH `/api/v1/admin/bots/{botId}`, scopes: `bots:write`): Partially updates an existing bot’s name, description, persona prompt, greeting, fallback message, brand color, or settings by botId. - `bot_delete` (DELETE `/api/v1/admin/bots/{botId}`, scopes: `bots:delete`): Deletes a non-default bot from the workspace. - `bot_assign_assets` (PUT `/api/v1/admin/bots/{botId}/assets`, scopes: `content:write`): Replaces a bot’s assigned Knowledge Collections, Dialog Flows, and Integrations in a single atomic payload. Accepts internal IDs or external_id values. - `bot_simulate_turn` (POST `/api/v1/admin/bots/{botId}/simulate`, scopes: `bots:read`, `content:read`): Runs the deterministic production conversation pipeline (Dialog Flows, Hot Questions Instant Cache, Social turns, Business Tools, and Knowledge Base retrieval) in an isolated ephemeral session with zero writes to conversation logs, leads, or analytics. ### Domain: knowledge - `kb_collection_list` (GET `/api/v1/admin/knowledge/collections`, scopes: `content:read`): Lists all Knowledge Collections in the workspace along with document counts. - `kb_collection_upsert` (POST `/api/v1/admin/knowledge/collections`, scopes: `content:write`): Creates a Knowledge Collection or idempotently updates the existing collection matching externalId. - `kb_collection_delete` (DELETE `/api/v1/admin/knowledge/collections/{collectionId}`, scopes: `content:write`): Deletes a Knowledge Collection and all of its indexed Knowledge Items. - `kb_source_list` (GET `/api/v1/admin/knowledge/connectors`, scopes: `content:read`): Lists configured Knowledge Sources (sitemaps, website crawlers, and remote feeds) in the workspace. - `kb_source_upsert` (POST `/api/v1/admin/knowledge/collections/{collectionId}/connectors`, scopes: `content:write`): Creates or idempotently updates a Knowledge Source (crawler, sitemap, or document feed) under a Knowledge Collection using externalId or (kind, rootUrl). - `kb_source_sync` (POST `/api/v1/admin/knowledge/connectors/{connectorId}/sync`, scopes: `content:write`): Triggers a synchronous/manual sync run on a Knowledge Source and returns sync stats. Rate-limited to 20 calls/min per workspace. - `kb_item_list` (GET `/api/v1/admin/knowledge/collections/{collectionId}/items`, scopes: `content:read`): Lists Knowledge Items inside a Knowledge Collection along with status and chunk count. - `kb_item_get` (GET `/api/v1/admin/knowledge/items/{itemId}`, scopes: `content:read`): Returns a Knowledge Item record, stored document preview, and indexed sections. - `kb_item_upsert` (PUT `/api/v1/admin/knowledge/collections/{collectionId}/items`, scopes: `content:write`): Idempotently creates or updates a markdown/text Knowledge Item in a collection by externalId, id, or uri, skipping re-indexing and returning action="unchanged" when contentHash and title match. ### Domain: flows - `flow_list` (GET `/api/v1/admin/flows`, scopes: `content:read`): Lists Dialog Flows in the workspace (optionally filtered by botId) along with publish status. - `flow_get_spec` (GET `/api/v1/admin/flows/{flowId}/spec`, scopes: `content:read`): Exports an existing Dialog Flow and its node graph as a clean declarative JSON FlowSpec. - `flow_validate_spec` (POST `/api/v1/admin/flows/validate`, scopes: `content:read`): Runs structural, reachability, cycle, display-name, and variable checks against a declarative JSON FlowSpec without saving changes. Give nodes concise human-readable "name" titles so Studio cards and Goto jumps stay readable. - `flow_put_spec` (PUT `/api/v1/admin/flows/{flowId}/spec`, scopes: `content:draft`): Validates, compiles, and atomically writes a declarative JSON FlowSpec by flowId or externalId. Provide concise "name" display labels on bot, condition, agent, and call nodes. Publishing (status="published") or modifying botIds requires content:write. - `flow_delete` (DELETE `/api/v1/admin/flows/{flowId}`, scopes: `content:draft`): Deletes a Dialog Flow and unbinds it from workspace bots. ### Domain: hot_questions - `hot_question_list` (GET `/api/v1/admin/hot-questions`, scopes: `content:read`): Lists cached FAQ Hot Questions (active and review queue) for a bot. - `hot_question_upsert` (POST `/api/v1/admin/hot-questions`, scopes: `content:draft`): Creates a Hot Question or upserts by normalized question when upsert=true. Draft status "review" needs content:draft; active/pinned requires content:write. - `hot_question_delete` (DELETE `/api/v1/admin/hot-questions/{id}`, scopes: `content:draft`): Deletes a Hot Question FAQ entry from the cache or review queue. ### Domain: integrations - `integration_list` (GET `/api/v1/admin/integrations`, scopes: `integrations:read`): Lists HTTP REST Tool, MCP Server, and A2A Agent integrations registered in the workspace. - `integration_upsert` (POST `/api/v1/admin/integrations`, scopes: `integrations:write`): Registers an HTTP REST tool, remote MCP server, or A2A agent integration, idempotently updating existing records with the same externalId. - `integration_discover` (POST `/api/v1/admin/integrations/discover`, scopes: `integrations:write`): Queries a remote MCP server (tools/list) or A2A agent card to preview available tools and skills before saving an integration. - `integration_test` (POST `/api/v1/admin/integrations/test`, scopes: `integrations:write`): Executes a live test invocation against a saved integration (integrationId) or inline draft config and returns the response payload and HTTP status. - `integration_delete` (DELETE `/api/v1/admin/integrations/{integrationId}`, scopes: `integrations:write`): Deletes a Workspace Integration and removes its bot bindings. - `workspace_secret_list` (GET `/api/v1/admin/workspace/secrets`, scopes: `integrations:read`): Lists configured secret identifiers and masked value hints in the workspace vault (never returns plaintext secret values). - `workspace_secret_put` (PUT `/api/v1/admin/workspace/secrets`, scopes: `integrations:write`): Stores or updates a write-only encrypted credential in the workspace secrets vault (referenced via {{secret.NAME}}). Secret values are never returned. - `workspace_secret_delete` (DELETE `/api/v1/admin/workspace/secrets/{name}`, scopes: `integrations:write`): Deletes a named credential from the workspace secrets vault. ### Domain: analytics - `analytics_logs_query` (GET `/api/v1/admin/logs`, scopes: `analytics:read`): Queries conversation logs across a bot or entire workspace ("all") filtered by outcome tier, feedback, timeframe, session, or text search. - `analytics_gaps_report` (GET `/api/v1/admin/analytics/gaps`, scopes: `analytics:read`): Aggregates fallback rates, clustered unanswered visitor queries, negative feedback, failing tool calls, and Knowledge Source sync errors. - `leads_list` (GET `/api/v1/admin/leads`, scopes: `leads:read`): Lists captured leads for a bot (including contact details, inquiry, and flow metadata). --- # 5-Minute Agent Quickstart Connect any coding agent or automation script to manage a Zervice Chatbot workspace safely in under five minutes. ## 1. Issue a Scoped Workspace Key (PAT) 1. Sign in to the Zervice Chatbot Workspace Console and open **Workspace → API Keys & Agents**. 2. Click **Create API Key** and select a permission preset: - **Draft Builder Agent (Safe Mode — Recommended):** Lets the agent inspect everything, analyze quality gaps, stage `build` Dialog Flows, and queue `review` Hot Questions without changing live visitor experiences. - **Observer / Analytics Agent:** Strictly read-only access across bots, content, and analytics. - **Full Workspace Builder Agent:** Full configuration access to create/update/delete bots, publish Knowledge Collections and Dialog Flows, manage integrations and secrets, inspect leads and analytics, and configure the Account Lead Notification Webhook. 3. Copy the one-time token (`zrv_pat_...`). All admin requests authenticate with: ```http Authorization: Bearer zrv_pat_YOUR_KEY ``` ### Canonical Docs vs. Target Deployment URL - **Canonical Documentation Source of Truth:** `https://chat.zervice.us/api/v1/admin/llms.txt` and `https://chat.zervice.us/docs` always host the latest agent documentation, concepts, FlowSpec reference, and playbooks—identical across Zervice Cloud and self-hosted BYOC instances. - **Target API / MCP Base URL (``):** Use `https://chat.zervice.us` for Managed Cloud workspaces, or your own deployment domain (e.g. `https://chat.yourcompany.com`) for self-hosted workspaces. Every self-hosted instance also mirrors these same `/docs` and `/api/v1/admin/llms.txt` endpoints locally. ## 2. Choose Your Transport (MCP or REST) Every workspace exposes both interfaces over one unified capability set: - **Stateless Streamable HTTP MCP** (recommended for Claude Code, Cursor, Antigravity): `POST https:///api/v1/admin/mcp` - **REST API** (great for scripts, CI pipelines, and `curl`): `https:///api/v1/admin/...` - **Open Machine-Readable Contract** (no authentication required): - `GET https:///api/v1/admin/llms.txt` — compact orientation and index - `GET https:///api/v1/admin/llms-full.txt` — complete conceptual & API handbook - `GET https:///api/v1/admin/openapi.json` — OpenAPI 3.1 schema ### MCP Configuration Snippet ```json { "mcpServers": { "zervice-admin": { "type": "http", "url": "https:///api/v1/admin/mcp", "headers": { "Authorization": "Bearer zrv_pat_YOUR_KEY" } } } } ``` ## 3. Run Your First Discovery & Verification Check Before creating anything, inspect your identity and workspace inventory in two calls: ```bash # 1. Confirm token identity, workspace ID, and active capability scopes curl -sS https:///api/v1/admin/whoami \ -H "Authorization: Bearer $ZERVICE_ADMIN_TOKEN" # 2. Fetch the one-shot workspace topology (bots, collections, sources, flows, 7-day metrics) curl -sS https:///api/v1/admin/discover \ -H "Authorization: Bearer $ZERVICE_ADMIN_TOKEN" ``` If using MCP, call `workspace_whoami` followed by `workspace_discover`, then dry-run a sample visitor turn against an assistant using `bot_simulate_turn`: ```json { "botId": "default", "message": "What plans do you offer?", "useDrafts": true } ``` Simulation executes inside an isolated temporary session and never writes to live conversation logs, leads, or analytics. ## Next Reading - Read [Core Concepts & Mental Model](/docs/concepts.md) to understand workspaces, bots, and how visitor turns are routed. - Read [Declarative FlowSpec Reference](/docs/flow-spec.md) before authoring multi-step workflows. - Read [Knowledge Base, Simulation & Quality Loop](/docs/knowledge-and-quality.md) to structure high-recall content and close unanswered query gaps. --- # Core Concepts & Mental Model Before editing resources through the API or MCP, understand how Zervice Chatbot organizes workspaces, bots, content, and live visitor turns. ## 1. Workspace & Shared Asset Library A **Workspace** is the top-level isolation boundary owned by a team or tenant. Everything a PAT accesses stays strictly inside its workspace. Inside a workspace: - **Bots** are distinct visitor-facing assistants (for example, a *Public Website Bot* on marketing pages and a *Customer Support Bot* inside your signed-in app). Each bot has its own name, greeting, persona instructions, fallback message, theme color, Hot Questions cache, and conversation logs. - **Website Routing Rules** inspect the current page path, domain, or visitor sign-in status to decide which bot loads on each URL via one global embed snippet. - **Shared Workspace Library** stores reusable assets that can be assigned to one bot or shared across multiple bots at once: - **Knowledge Collections** (grouping **Knowledge Sources** like website crawlers and uploaded **Knowledge Items**) - **Dialog Flows** (structured multi-turn intake, branching, and terminal AI specialist handoffs) - **Business Integrations** (wrapped HTTP REST tools, remote MCP servers, and A2A agent connectors) - **Workspace Secrets Vault** (write-only credentials referenced inside Integrations as `{{secret.NAME}}`) - **Account-Level Lead Notification Webhook** (configured under **Profile & Account**): subscribes external CRMs or alert systems to real-time `lead.created` HTTP POST notifications signed with `X-Signature-SHA256`, independent of individual bots or flows. ## 2. How Every Visitor Turn Is Answered (4-Layer Pipeline) When a visitor or A2A consumer sends a message to a bot, Zervice evaluates four layers in priority order: | Priority | Layer | Purpose | Behavior | | :--- | :--- | :--- | :--- | | **1** | **Dialog Flows** | Multi-step guided tasks | Matches trigger keywords or active session state; collects typed Saved Fields (`{{slot_name}}`), evaluates `condition` branches, or hands off to a terminal `agent` specialist with scoped integrations. | | **2** | **Hot Questions** | Instant curated answers | Matches verified high-frequency FAQ pairs nearly instantaneously with exact authored wording. | | **3** | **Business Integrations** | Real-time actions & lookups | Selects a bound tool when the visitor asks for live account/order data, enforcing sign-in checks and visitor Confirmation Gates before mutating state. | | **4** | **Knowledge Base Q&A** | Open-ended grounded answers | Retrieves relevant sections from the bot's assigned **Knowledge Collections**, answers strictly from approved text with citations, and declines politely if ungrounded. | ### Mid-Flow Off-Topic Q&A Escape & Resume Visitors rarely follow a straight line. If a visitor is halfway through a **Dialog Flow** (for example, after providing their order number) and suddenly asks an unrelated question like *"What is your refund policy?"*, Zervice: 1. Answers the off-topic question from Hot Questions or the Knowledge Base. 2. Keeps every collected Saved Field intact. 3. Conversationally reminds the visitor when they're ready to continue where they left off (no distracting "Resume Flow" button on the UI). ## 3. Choosing the Right Mechanism for a Problem When auditing logs or onboarding a new business, choose the right primitive: - **Use Knowledge Items** for policies, guides, product explanations, troubleshooting docs, and pricing pages where natural-language synthesis with citations works well. - **Use Hot Questions** for high-traffic questions where you want exact, consistent wording every time (hours, contact links, compliance statements, common objections). - **Use Dialog Flows** when the assistant must reliably walk through ordered steps, capture structured inputs (emails, order IDs, budgets), branch on business rules, or capture a lead. - **Use Business Integrations** when answers depend on live external data (order status, calendar availability, ticket creation) rather than static documentation. ## 4. Draft Staging vs. Live Publishing Zervice separates **staging** from **production** so coding agents and editors can iterate safely: - **Drafts (`content:draft`):** - Dialog Flows created or updated with `status: "build"` are saved and editable in the visual studio, without serving live visitors unless actively bound and published. - Hot Questions created with `status: "review"` wait in the human review queue until approved. - **Live (`content:write`):** - Publishing a Dialog Flow (`status: "published"`) or activating a Hot Question (`status: "active"`) serves real website traffic. - In **Turn Simulation** (`bot_simulate_turn`), `useDrafts: true` (default) exercises both `build` flows and `review` Hot Questions inside a zero-side-effect sandbox so you can verify quality before requesting human publish approval. ## 5. Idempotency via `externalId` Every top-level asset—Bots, Knowledge Collections, Knowledge Sources, Knowledge Items, Dialog Flows, and Integrations—supports an optional caller-chosen `externalId` matching `^[a-z0-9][a-z0-9_-]{1,62}$`. Always set stable `externalId` slugs (such as `docs-collection`, `refund-triage`, or `billing-guide`) so setup scripts and CI pipelines can re-run safely without duplicating resources. --- # Declarative FlowSpec Reference Agents author and inspect Zervice **Dialog Flows** using declarative JSON **FlowSpecs** rather than low-level visual canvas graphs. Every FlowSpec passes through a strict zero-I/O validator (`flow_validate_spec`) and compiler (`flow_put_spec`), ensuring 100% compatibility with the visual Flow Editor—including preserving any manual card layout positions created by human designers. ## 1. Top-Level Structure ```json { "schemaVersion": 1, "externalId": "order-lookup", "name": "Order Lookup Assistant", "description": "Looks up an order status by order ID and handles exceptions.", "status": "build", "triggerKeywords": ["track order", "order status", "where is my order"], "epilogueText": "Let me know if you need help with another order!", "widget": { "showInWidget": true, "widgetLabel": "Track an Order", "isSubroutineOnly": false, "confirmBeforeSubmit": false }, "variables": [ { "name": "order_id", "type": "text", "description": "Customer order identifier" } ], "entry": "ask_order", "nodes": {} } ``` ### Top-Level Fields - `schemaVersion`: Optional, defaults to `1`. - `externalId`: Stable slug (`^[a-z0-9][a-z0-9_-]{1,62}$`) for idempotent `PUT /by-external-id/:externalId/spec` updates. - `name` *(required)*: Human-readable workflow title. - `description`: Summary used both in the UI and as intent context when routing visitor requests. - `status`: `"build"` (draft; permitted for `content:draft` keys), `"published"` (live; requires `content:write`), or `"archived"`. - `triggerKeywords`: Array of phrases that deterministically launch this flow. - `epilogueText`: Optional closing message appended when the flow completes. - `widget`: Widget shortcut controls (`showInWidget`, `widgetLabel`, `isSubroutineOnly`, `confirmBeforeSubmit`). - `variables`: Declared workflow slots (`{ name, type, description }`). - `entry` *(required)*: Key inside `nodes` where execution begins. Entry node must be `bot`, `agent`, `condition`, or `call`. - `nodes` *(required)*: Object map of node keys (`[a-zA-Z0-9_.:-]{1,80}`) to node definitions. ## 2. Supported Node Types > **Important Authoring Rule — Give Every Node a Concise Display `name` (2–5 Words):** > Always set a short, human-readable `"name"` on `bot`, `condition`, `agent`, and `call` nodes (plus `"intentName"` on `branches[]` and `"label"` on `condition.cases[]`). Flow Studio displays `name` on canvas cards, hover previews, validation callouts, and `Goto` jump links so non-technical authors see clear step names (e.g. `"Check Missing Contact Info"`, `"Ask Company Name"`) instead of raw rule syntax or internal IDs. `flow_validate_spec` emits `MISSING_DISPLAY_NAME` warnings if `condition` routers or multi-branch jump targets omit `"name"`. ### `bot` — Assistant Message & Optional Visitor Branches Sends a response (with optional quick-reply chips) and either waits for visitor input via `branches[]` or chains automatically via `next` / `end`. ```json { "type": "bot", "name": "Ask Topic or Work Email", "text": "Please choose an option below or share your email.", "quickReplies": ["Pricing Question", "Talk to Sales"], "branches": [ { "intentName": "Sales Inquiry", "intention": "Visitor wants a demo or wishes to speak with sales", "slotName": "work_email", "slotType": "email", "saveAsLead": true, "next": "confirm_sales" }, { "intentName": "Pricing Question", "intention": "Visitor asks about plan pricing", "next": "pricing_specialist" } ] } ``` > **Rule:** A `bot` node can define **either** `branches[]` (wait for visitor turn) **or** `next` / `end` (auto-advance), never both at once. Branch fields inside `bot.branches[]`: - `intentName` *(recommended)*: Concise branch label shown on the Flow Studio card and quick-reply button fallback. - `intention`: Natural-language intent criteria evaluated during routing. - `quickReplies`: Optional button labels on the parent message; selecting one matches deterministically. - `slotName` & `slotType` (`"text"` | `"email"` | `"number"`): Captures the visitor's reply into a Saved Field (enforces format checks for `email` / `number` on single-branch intake). - `skipIfPresent`: Set `true` in multi-slot Switch-Hub loops so already-collected fields are skipped automatically. - `saveAsLead`: Set `true` on the email-capturing branch when this flow qualifies a sales or demo lead (see Section 3 below). - `setVariables`: Array of `{ "variable": "...", "value": "..." }` (supports `{{slot}}` interpolation) applied on match. - `next` or `end`: Required target (`end: true` or `{ "status": "completed", "name": "Intake Completed" }`). ### `agent` — Terminal AI Specialist Handoff (Knowledge + Business Integrations) `agent` is a **terminal** node in a Dialog Flow (`branches[]`, `next`, and `end` are disallowed). Once deterministic triage and slot collection reach an `agent` step, that specialist receives all collected `{{slots}}`, its configured Knowledge Base context, and its scoped Workspace Integrations (wrapped HTTP REST tools, MCP servers, and A2A agents), and handles multi-turn Q&A, live lookups, and confirmation-gated write actions until the visitor finishes or switches topics. ```json { "type": "agent", "name": "Order & Refund Specialist", "prompt": "Assist with order {{order_id}} using connected order tools. Always ask confirmation before cancelling.", "knowledge": "bot", "integrations": { "integrationIds": ["orders-api"] } } ``` - `name`: Concise display title shown on canvas cards and handoff traces. - `knowledge`: `"bot"` *(default)* or `"none"`. - `integrations`: `"bot"` *(default — inherit bot's active integrations)*, `"none"`, or `{ "integrationIds": ["..."] }` *(scope explicitly to specific Workspace Integrations by ID or `externalId`)*. ### `condition` — Deterministic Business Branching Evaluates ordered `cases[]` against collected Saved Fields before falling back to `else` or `elseEnd`. Always give `condition` nodes a concise `"name"` and each case a short human-readable `"label"`. ```json { "type": "condition", "name": "Route by Order Tier", "cases": [ { "label": "High Value Order", "logicalOperator": "AND", "rules": [ { "variable": "order_total", "operator": ">=", "value": "500" } ], "next": "vip_handoff" }, { "label": "Shipped", "rules": [ { "variable": "shipping_state", "operator": "==", "value": "shipped" } ], "next": "reply_shipped" } ], "else": "reply_pending" } ``` - `else` or `elseEnd`: Use `else: "node_key"` to branch to a fallback node, or `elseEnd: true` / `{ "status": "completed", "name": "Intake Complete" }` to close directly when no case matches. - Supported operators: `==`, `=`, `!=`, `>`, `<`, `>=`, `<=`, `contains`, `not_contains`, `!contains`, `exists`, `is_set`, `is_empty`, `matches_regex`. ### `call` — Invoke a Reusable Sub-Flow Executes another flow in your workspace (`targetFlowId`) as a subroutine (`subroutine: true`) and resumes at `next` once it completes. ```json { "type": "call", "name": "Verify Customer Identity", "targetFlowId": "flow_verify_customer", "subroutine": true, "next": "continue_refund" } ``` ## 3. Lead Capture in Flows (`saveAsLead: true`) & Account Lead Webhook - **Mark the Email Branch with `saveAsLead: true`:** Any `branches[]` item with `slotType: "email"` (or an email-shaped `slotName`) should set `"saveAsLead": true`. - **Automatic Deferred Lead Emission:** If additional scripted `branches[]` prompts follow (for example, collecting `inquiry` after `visitor_email`), Zervice holds the lead until scripted intake finishes or hands off to a terminal `agent`. Every collected Saved Field is stored together on the lead record and dispatched in one signed `lead.created` webhook event to your Account Lead Notification Webhook. - **Recommended Slot Names for CRM Interoperability:** Use `visitor_name` (or `name`), `company_name` (or `company`), `phone` (or `phone_or_wechat`), `visitor_email` (or `work_email`), and `inquiry` so top-level `data.name`, `data.company`, `data.phone`, `data.email`, and `data.inquiry` are automatically populated alongside `data.slots`. ## 4. Slot & Secret Interpolation - **Visitor Saved Fields:** Write `{{slot_name}}` (or `{slot_name}`) in bot text or specialist prompts. Default fallback values are supported via `{{slot_name | 'default'}}`. - **Workspace Secrets:** Store credentials via `PUT /api/v1/admin/workspace/secrets` and reference them in **Workspace Integrations** (`{{secret.SECRET_NAME}}`). Secrets are never returned by read endpoints or traces. ## 5. Complete Runnable FlowSpec Example ```flowspec { "schemaVersion": 1, "externalId": "order-status-example", "name": "Order Status & Action Assistant", "description": "Collects an order ID, checks fast-path rules, and hands off to a tool-enabled AI specialist.", "status": "build", "triggerKeywords": ["order status", "track order"], "entry": "ask_order", "nodes": { "ask_order": { "type": "bot", "name": "Ask Order Number", "text": "Sure! What is your order number?", "branches": [ { "intentName": "Provide Order ID", "intention": "Visitor enters an order identifier", "slotName": "order_id", "slotType": "text", "validationPattern": "^[A-Z0-9-]+$", "next": "check_vip" } ] }, "check_vip": { "type": "condition", "name": "Check VIP Prefix", "cases": [ { "label": "VIP Prefix", "rules": [ { "variable": "order_id", "operator": "contains", "value": "VIP" } ], "next": "vip_agent" } ], "else": "order_specialist" }, "vip_agent": { "type": "agent", "name": "VIP Order Concierge", "prompt": "Provide priority tracking and white-glove assistance for VIP order {{order_id}}.", "knowledge": "bot", "integrations": { "integrationIds": ["orders-api"] } }, "order_specialist": { "type": "agent", "name": "Order Specialist", "prompt": "Look up order {{order_id}} using connected order tools, answer follow-up questions, and request confirmation before any cancellation.", "knowledge": "bot", "integrations": "bot" } } } ``` ## 6. Common Mistakes to Avoid - **Leaving nodes unnamed** → set a concise `"name"` (2–5 words) on `bot`, `condition`, `agent`, and `call` nodes—especially condition routers and multi-branch jump targets—so Flow Studio cards and `Goto` links never show raw slot rules. - **Attaching children to an `agent` node** → `agent` is terminal; put all triage/branch steps (`bot`, `user`, `condition`) before the `agent` handoff. - **Using legacy `webhook` nodes in FlowSpecs** → outside-world HTTP/MCP/A2A calls live in **Workspace Integrations** invoked by `agent` steps, while lead delivery uses the **Account Lead Notification Webhook**. - **Mixing `branches[]` and `next`/`end`** on the same `bot` node → use one or the other. - **Branches without targets** → every branch entry in `branches[]` must set either `next` or `end: true`. - **Unbalanced braces** in templates → ensure every `{{` closes with `}}`. - **Calling `PUT` without running `validate` first** → always validate via `POST /api/v1/admin/flows/validate` so structural errors include exact JSON paths before persisting. --- # Knowledge Base, Simulation & Quality Loop Great chatbots continuously improve based on real visitor questions. Use this lifecycle to publish accurate knowledge, test changes safely, and fix gaps surfaced in production telemetry. ## 1. Organizing Knowledge Collections, Sources & Items - **Knowledge Collection:** A reusable topic container (e.g., `product-docs`, `billing-policies`, `internal-it`) assigned to one or more bots. - **Knowledge Source:** An automated crawler or URL connector (`site_crawl` or `single_url`) belonging to a collection. Use `kb_source_upsert` and `kb_source_sync` to keep live web documentation synchronized: ```json { "collectionId": "col_123", "externalId": "main-docs-crawl", "kind": "site_crawl", "name": "Developer Docs Crawl", "rootUrl": "https://docs.example.com", "syncMode": "daily", "updateStrategy": "incremental", "maxPages": 40, "syncNow": true } ``` - **Knowledge Item:** Individual text, Markdown, or uploaded file inside a collection. Use `kb_item_upsert` (`PUT /api/v1/admin/knowledge/collections/:collectionId/items`) with a stable `externalId`: - Zervice hashes the content automatically; re-uploading unchanged text returns `action: "unchanged"` and skips re-indexing. ### Writing High-Recall Markdown Knowledge Items Zervice splits uploaded Markdown along `#`, `##`, and `###` headings so each section can be retrieved independently with a section citation: 1. **Use clear task- or question-shaped headings** (e.g., `## How to Reset SSO SAML Metadata` instead of `## Overview`). 2. **Keep each section focused (~150–350 words)** covering one topic or policy cleanly. 3. **Repeat the subject noun inside every section** (say *"Refunds are processed within 5 business days"* rather than *"It takes 5 days"*), so retrieved passages remain clear on their own. ### Single-Language Authoring for Multi-Language Visitors You only need to author Knowledge Items, Dialog Flows, Bot Greetings, and Hot Questions once in a single canonical language (no duplicated per-language copies required): - The public widget resolves the visitor's active BCP-47 locale automatically (site language switcher / `data-locale`, page `lang` attribute, browser locale, or typed script) and passes it on every request. - Flow prompts, quick-reply chips, greetings, and Hot Questions translate on demand with placeholders (`{{slot}}`) preserved intact and cached per workspace and locale. - Answers synthesized from your Knowledge Base automatically respond in the visitor's language with cross-language search recall. ## 2. Safe Dry-Run Simulation (`bot_simulate_turn`) Always test edits via `POST /api/v1/admin/bots/:botId/simulate` before notifying a user or publishing drafts: ```json { "message": "track order", "locale": "zh-CN", "pinFlowId": "flow_123", "useDrafts": true, "toolMode": "mock", "toolMocks": { "orders_lookup": { "status": 200, "ok": true, "data": { "state": "delivered" } } } } ``` ### Key Simulator Guarantees - **Zero Side Effects:** Simulation runs in a temporary in-memory session and never inserts into visitor chat logs, leads, or daily analytics. - **Multi-Locale Verification (`locale`):** Pass an optional BCP-47 `locale` (e.g. `"zh-CN"`, `"ja"`, `"fr"`) to verify localized flow prompts, quick replies, and RAG answers, and inspect `trace.locale` / `state.locale`. - **Draft Testing (`useDrafts: true`):** Default behavior evaluates staged `build` Dialog Flows and `review` Hot Questions on the bot (set `useDrafts: false` to test strictly live published behavior). - **Stateless Multi-Turn Replay:** Pass the `state` object returned by turn 1 back as `sessionState` on turn 2 to step through multi-turn slot capture and conditions deterministically. - **Mock Tools by Default (`toolMode: "mock"`):** Outbound HTTP tools, MCP servers, and A2A agents are intercepted and recorded in `trace.tools` without firing external side effects (sensitive auth headers are redacted automatically). - **Rich Execution Trace:** Inspect `trace.outcome` (`flow`, `hot`, `social`, `tool`, `tool_error`, `rag`, `fallback`), `trace.flow`, `trace.rag`, `trace.tool`, and `trace.isFallback`. - **Rate Limit:** Up to 30 simulation requests per minute per workspace. ## 3. Diagnosing Quality Gaps & Closing the Loop Every live conversation turn records structured `outcome` and `meta` diagnostics (when did the bot fall back, hit an error, or get a thumbs-down rating?). ### Step 1 — Fetch Quality Gap Summary Call `analytics_gaps_report` (`GET /api/v1/admin/analytics/gaps?days=7`): - `summary`: Breakdown across `flowHits`, `hotHits`, `toolHits`, `ragHits`, `fallbacks`, `toolErrors`, `negativeFeedback`, and `fallbackRate`. - `topUnansweredClusters`: Normalized clusters of repeated unanswered visitor questions and negative feedback ratings. - `toolFailures`: External integration or tool calls returning errors. - `kbSyncIssues`: Failing Knowledge Sources or Knowledge Items needing attention. ### Step 2 — Inspect Specific Transcripts Call `analytics_logs_query` (`GET /api/v1/admin/logs?bot_id=all&outcome=fallback`): - Filter across one bot or the whole workspace (`bot_id=all`) by `outcome`, `feedback` (`1` or `-1`), `since`, `until`, `session_id`, or substring `q`. ### Step 3 — Remediate & Verify 1. Upload missing documentation with `kb_item_upsert` or trigger `kb_source_sync`. 2. Stage exact FAQ answers via `hot_question_upsert` (`status: "review"`, `upsert: true`). 3. Fix workflow edge cases via `flow_validate_spec` + `flow_put_spec`. 4. Re-run `bot_simulate_turn` against every clustered question and confirm `trace.isFallback === false`. --- # REST API & MCP Reference Zervice Chatbot exposes its entire Workspace Management Plane identically over HTTP REST and stateless Streamable HTTP MCP. ## 1. Authentication & Capability Scopes All admin endpoints (except open documentation endpoints) require a workspace token or session cookie: ```http Authorization: Bearer zrv_pat_YOUR_KEY ``` Granular capability scopes: - `bots:read`, `bots:write`, `bots:delete` - `content:read`, `content:draft`, `content:write` - `analytics:read` - `leads:read` - `integrations:read`, `integrations:write` - `api_keys:manage` *(session admin only — PATs cannot mint new PATs)* - `users:manage`, `tenant:settings` Every PAT is evaluated at request time as the intersection of its granted `scopes` and the creator user's active role. ## 2. Standard HTTP Status Codes & Idempotency | Code | Meaning | | :--- | :--- | | `200` / `201` | Success (returns `{ status: "success", action?, data }`) | | `400` | Invalid payload, malformed `externalId`, or failed `FlowSpec` validation (`errors[]`) | | `401` | Missing, expired, invalid, or revoked token | | `403` | Token lacks the required capability scope (for example `content:draft` trying to set `status: "published"`) | | `404` | Resource not found in caller's workspace | | `409` | Optimistic concurrency conflict when `ifUpdatedAt` no longer matches, or multi-bot modification without `confirmMultiBot: true` | | `429` | Rate limit exceeded (source sync: 20/min; simulator: 30/min) | All upsert endpoints accept `externalId` (`^[a-z0-9][a-z0-9_-]{1,62}$`) and return `action`: `"created"`, `"updated"`, or `"unchanged"`. ## 3. MCP Protocol Details (`POST /api/v1/admin/mcp`) - Send JSON-RPC 2.0 requests via HTTP `POST` (stateless; `GET` and `DELETE` return `405 Method Not Allowed`). - Supported methods: `initialize`, `notifications/initialized`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`. - `tools/list` automatically hides tools whose `requiredScopes` exceed your token's permissions. - `GET /api/v1/admin/tools` returns the same authorized tool schemas as plain JSON for function-calling frameworks. ## 4. Endpoints & Curated Tools by Domain (42 Tools) ### Workspace Discovery, Routing & Account Lead Webhook - `GET /api/v1/admin/whoami` (`workspace_whoami`) — Inspect principal, auth type, role, and scopes. - `GET /api/v1/admin/discover` (`workspace_discover`) — Scope-filtered snapshot of all workspace assets, secret names, `leadWebhook` status, and 7-day metrics. - `GET /api/v1/admin/workspace/embed` (`workspace_embed_get`) — Global widget embed key, routing rules, and fallback bot. - `PUT /api/v1/admin/workspace/embed` (`workspace_embed_put`) — Update global widget URL routing rules, excluded paths, and default bot. - `GET /api/v1/admin/account/lead-webhook` (`account_lead_webhook_get`) — Read Account Lead Notification Webhook URL, enabled state, and masked secret hint (`tenant:settings`). - `PUT /api/v1/admin/account/lead-webhook` (`account_lead_webhook_put`) — Configure Account Lead Notification Webhook `url`, `enabled`, and signing `secret` (`tenant:settings`). - `POST /api/v1/admin/account/lead-webhook/test` (`account_lead_webhook_test`) — Send a signed test `lead.created` notification and inspect HTTP delivery telemetry (`tenant:settings`). ### Bots & Routing - `GET /api/v1/admin/bots` (`bot_list`) — List workspace bots. - `GET /api/v1/admin/bots/:botId` (`bot_get`) — Fetch a single bot configuration. - `POST /api/v1/admin/bots` (`bot_upsert`) — Idempotently create or update a bot via `externalId`. - `PATCH /api/v1/admin/bots/:botId` (`bot_patch`) — Partially update an existing bot's name, persona prompt, greeting, fallback message, or settings. - `DELETE /api/v1/admin/bots/:botId` (`bot_delete`) — Delete a non-default bot. - `PUT /api/v1/admin/bots/:botId/assets` (`bot_assign_assets`) — Atomically assign Knowledge Collections, Dialog Flows, and Integrations (by ID or `externalId`). - `POST /api/v1/admin/bots/:botId/simulate` (`bot_simulate_turn`) — Deterministic zero-side-effect dry-run simulation (accepts optional `locale` override such as `"zh-CN"`, `"ja"`, or `"fr"`). ### Knowledge Collections, Sources & Items - `GET /api/v1/admin/knowledge/collections` (`kb_collection_list`) — List collections and counts. - `POST /api/v1/admin/knowledge/collections` (`kb_collection_upsert`) — Idempotent create/update via `externalId`. - `DELETE /api/v1/admin/knowledge/collections/:collectionId` (`kb_collection_delete`) — Delete collection and its indexed content. - `GET /api/v1/admin/knowledge/connectors` (`kb_source_list`) — List Knowledge Sources (optional `?collectionId=`). - `POST /api/v1/admin/knowledge/collections/:collectionId/connectors` (`kb_source_upsert`) — Upsert Knowledge Source (`kind`: `"site_crawl"` | `"single_url"`) via `externalId` or `(kind, rootUrl)`. - `POST /api/v1/admin/knowledge/connectors/:connectorId/sync` (`kb_source_sync`) — Trigger a Knowledge Source sync run. - `GET /api/v1/admin/knowledge/collections/:collectionId/items` (`kb_item_list`) — List Knowledge Items in a collection. - `GET /api/v1/admin/knowledge/items/:itemId` (`kb_item_get`) — Inspect an item and its indexed sections. - `PUT /api/v1/admin/knowledge/collections/:collectionId/items` (`kb_item_upsert`) — Idempotent upsert with unchanged-hash dedup. ### Declarative Dialog Flows - `GET /api/v1/admin/flows` (`flow_list`) — List workspace flows (optional `?botId=`). - `GET /api/v1/admin/flows/:flowId/spec` (`flow_get_spec`) — Decompile flow to declarative JSON FlowSpec. - `POST /api/v1/admin/flows/validate` (`flow_validate_spec`) — Dry-run FlowSpec validator. - `PUT /api/v1/admin/flows/:flowId/spec` & `PUT /api/v1/admin/flows/by-external-id/:externalId/spec` (`flow_put_spec`) — Compile and atomically apply a FlowSpec. - `DELETE /api/v1/admin/flows/:flowId` (`flow_delete`) — Delete a Dialog Flow and remove bot bindings. ### Hot Questions Cache - `GET /api/v1/admin/hot-questions` (`hot_question_list`) — List active and review FAQ entries. - `POST /api/v1/admin/hot-questions` (`hot_question_upsert`) — Create or upsert (`upsert: true`) FAQ entries. - `DELETE /api/v1/admin/hot-questions/:id` (`hot_question_delete`) — Delete a Hot Question entry. ### Integrations & Secrets - `GET /api/v1/admin/integrations` (`integration_list`) — List workspace integrations. - `POST /api/v1/admin/integrations` (`integration_upsert`) — Idempotently register or update an HTTP REST tool (`http_tool`), remote MCP server (`mcp_server`), or A2A agent (`a2a_agent`). - `POST /api/v1/admin/integrations/discover` (`integration_discover`) — Preview tools/skills exposed by a remote MCP server or A2A agent. - `POST /api/v1/admin/integrations/test` (`integration_test`) — Execute a live test call against a saved integration or inline config. - `DELETE /api/v1/admin/integrations/:integrationId` (`integration_delete`) — Remove an integration and its bot bindings. - `GET /api/v1/admin/workspace/secrets` (`workspace_secret_list`) — List configured secret names and masked hints. - `PUT /api/v1/admin/workspace/secrets` (`workspace_secret_put`) — Store write-only secret value for `{{secret.NAME}}`. - `DELETE /api/v1/admin/workspace/secrets/:name` (`workspace_secret_delete`) — Delete a named secret from the vault. Example `integration_upsert` (`http_tool`) payload: ```json { "externalId": "orders-api", "kind": "http_tool", "name": "Orders Lookup API", "endpointUrl": "https://api.example.com/v1/orders/{{order_id}}", "config": { "method": "GET", "headers": { "Authorization": "Bearer {{secret.ORDERS_API_KEY}}" }, "requiresConfirmation": false }, "toolsManifest": [ { "name": "lookup_order", "description": "Fetch live order shipping status by order_id", "inputSchema": { "type": "object", "properties": { "order_id": { "type": "string" } }, "required": ["order_id"] }, "enabled": true } ] } ``` ### Account Lead Notification Webhook (`lead.created`) Configure one account-wide outbound notification webhook under **Profile & Account** or via `account_lead_webhook_put` (`GET / PUT / POST /api/v1/admin/account/lead-webhook`) to receive signed HTTP `POST` events whenever any assistant captures a lead (from widget contact forms or Dialog Flow *Save as Lead* steps): ```json { "url": "https://crm.example.com/webhooks/zervice", "enabled": true, "secret": "your-webhook-signing-secret" } ``` - **Headers:** `Content-Type: application/json`, `X-Zervice-Event: lead.created`, `X-Zervice-Delivery: evt_...`, and `X-Signature-SHA256: ` (when a signing secret is set). - **Payload Envelope:** `{ "id": "evt_...", "event": "lead.created", "timestamp": "", "timestampMs": 1764403200000, "data": { "leadId", "botId", "botName", "source", "name", "company", "company_name", "phone", "email", "inquiry", "slots", "flow", "sessionId", "createdAt" } }`. ### Analytics, Leads & Quality Diagnostics - `GET /api/v1/admin/logs` (`analytics_logs_query`) — Filter logs across one bot or `bot_id=all` by outcome, feedback, timeframe, session, or keyword. - `GET /api/v1/admin/analytics/gaps` (`analytics_gaps_report`) — Aggregate fallback clusters, tool failures, and Knowledge Source sync issues. - `GET /api/v1/admin/leads` (`leads_list`) — List captured leads (contact fields, inquiry, session, and flow metadata). --- # Autonomous Agent Playbooks Follow these complete end-to-end recipes when operating Zervice Chatbot autonomously on behalf of a team. ## Playbook 1 — Bootstrap a New Grounded Support Assistant **Recommended scopes:** `bots:read`, `bots:write`, `content:write` 1. **Discover existing resources** with `workspace_discover` so you don't overwrite an active production bot. 2. **Create a Knowledge Collection** via `kb_collection_upsert` (`externalId: "support-docs"`, `name: "Support Documentation"`). 3. **Upload authoritative Markdown items** via `kb_item_upsert` (e.g. `externalId: "pricing-faq"`, `"security-overview"`) and/or register a website crawler source via `kb_source_upsert` + `kb_source_sync`. 4. **Create or update the bot** via `bot_upsert` (`externalId: "public-support"`, `name: "Acme Support Assistant"`, clear `system_prompt` and helpful `fallback_message`). 5. **Bind assets atomically** with `bot_assign_assets` passing `collectionIds: ["support-docs"]`. 6. **Verify via simulation** using `bot_simulate_turn` across 3–5 representative customer questions, confirming grounded replies and `trace.isFallback === false`. ## Playbook 2 — Idempotent CI Documentation Sync **Recommended scopes:** `content:read`, `content:write` Keep your public documentation repo synchronized automatically on every release: 1. Ensure target collection exists via `PUT`/`POST` `kb_collection_upsert` with `externalId: "product-docs"`. 2. Iterate through your repository Markdown files and call `PUT /api/v1/admin/knowledge/collections/:collectionId/items` with `externalId` set to the file slug and `title` + `content`. 3. Unmodified documents return `action: "unchanged"` in milliseconds without re-indexing; modified files re-index cleanly in place. ## Playbook 3 — Build, Validate & Dry-Run a Dialog Flow (Safe Mode) **Recommended scopes:** `bots:read`, `content:read`, `content:draft` 1. Author a declarative FlowSpec with `status: "build"` and `externalId`. 2. Call `flow_validate_spec` (`POST /api/v1/admin/flows/validate`) and fix any reported `errors[]`. 3. Persist via `flow_put_spec` (`PUT /api/v1/admin/flows/by-external-id/:externalId/spec`). 4. Run multi-turn dry-run tests with `bot_simulate_turn` (`pinFlowId`, `useDrafts: true`, `toolMode: "mock"`): - Send turn 1 (`"track order"`) and capture `response.data.state`. - Send turn 2 (`"ORD-420"`, `sessionState: turn1.state`, `toolMocks`) and assert `trace.tools` recorded the mocked call and `reply` reflects mocked data. 5. Hand back a summary to a human workspace admin to approve and switch `status` to `"published"` when ready. ## Playbook 4 — Weekly Quality Gap Audit & Remediation **Recommended scopes:** `bots:read`, `content:read`, `content:draft`, `analytics:read` 1. Pull the 7-day report via `analytics_gaps_report` (`GET /api/v1/admin/analytics/gaps?days=7`). 2. Check `kbSyncIssues` first—if any Knowledge Source is failing, inspect `root_url` / error details and alert the owner or trigger a retry if allowed. 3. Inspect `topUnansweredClusters` sorted by frequency and negative feedback. Drill into transcripts with `analytics_logs_query` (`outcome=fallback,bot_id=all`). 4. Stage draft Hot Questions (`hot_question_upsert` with `status: "review"`, `upsert: true`) for direct FAQs, or add missing sections to Knowledge Items. 5. Verify every previously failing cluster query using `bot_simulate_turn` (`useDrafts: true`) and verify `trace.isFallback === false`. ## Playbook 5 — Configure Lead Intake Flow & External CRM Webhook **Recommended scopes:** `bots:read`, `content:read`, `content:write`, `leads:read`, `tenant:settings` 1. **Configure the Account Lead Notification Webhook** via `account_lead_webhook_put` (`url`, `secret`, `enabled: true`). 2. **Verify webhook reachability & HMAC signing** with `account_lead_webhook_test` and confirm `ok: true` and HTTP `200`/`201`. 3. **Validate & deploy the intake FlowSpec** (`flow_validate_spec` then `flow_put_spec`) with concise display `name` labels on all nodes, `saveAsLead: true` on the email branch, and `status: "published"`. 4. **Bind the flow to target bots** with `bot_assign_assets` (`flowIds: [{ flowId, isActive: true, priority: 1 }]`). 5. **Rehearse end-to-end in simulation** with `bot_simulate_turn` across every intake prompt, then monitor live captures with `leads_list`.