Skip to content

Configuration Reference ​

See Language and localization for project, personal, and Console language settings.

This is the complete reference for zhin.config.yml. When configuring for the first time, run npx zhin setup to generate a config that boots, then come back here for the fields you need to change.

Most common changes ​

I want to…See
Change the HTTP port or expose Console externallyhttp
Connect a databasedatabase
Configure a plugin or adapter, add platform credentialsplugin and plugins
Log one adapter into several accountsendpoints array
Set the command prefixAdapter instances
Configure AI modelsai, or the AI overview
Reference secrets from .envEnvironment variable expansion
Apply configuration changes selectivelyApplying configuration changes
See a complete minimal configMinimal configuration

Where the config file lives ​

At startup (zhin start), the instance checks these project-root candidates in order. If more than one exists, startup fails instead of guessing:

  1. config.yml
  2. config.yaml
  3. config.json
  4. zhin.config.yml
  5. zhin.config.yaml
  6. zhin.config.json

It is recommended to use zhin.config.yml consistently. All examples in this document use it.

For field-by-field types, required fields, defaults, and plugin schemas, use the generated configuration field reference. It is generated from Runtime source and each plugin’s single configuration declaration (config: Schema.object(...) or schema.json), with drift blocked in CI.

How to use this reference ​

Run npx zhin doctor before committing. After startup, trust what Console shows is actually running — what the file says isn't necessarily what's live (for example, if a new config fails validation, the old one keeps running).

What you need to changeWhere it belongs
Installed plugins and Featuresdependencies and package.json#zhin
Host, plugin-instance, and AI valueszhin.config.yml
Secrets and environment differences.env / .env.<environment>, referenced with ${VAR}
Multi-Bot collaboration venuesai.venues in zhin.config.yml
Which Agents may contact each other, and collaboration budget ceilingscollaboration in agents/<name>/agent.json
What the runtime actually publishedEndpoint, capability catalog, and generation state in Console

Use configVersion: 2. Install dependencies, map instance aliases to packages in plugins, and place business values in same-named top-level blocks. disable_plugins lists inactive instances (change it with zhin disable / zhin enable or the Console's global switch; while running, the gateway writes it and the instance applies it in place without a restart; plugins that need one fall back to a stop and start that rolls back on failure, plugin.manage required); Feature requirements remain in package.json#zhin.features. See the migration guide.

Loading and Validation Flow ​

Configuration passes JSON Schema validation, and only the keys listed below are allowed at the top level. A misspelled key produces Invalid Plugin config in zhin.config.yml at startup.

Host sections are consumed by the instance composition root (zhin.js/instance) and the management gateway. Each plugin receives only its own same-named business block.

Applying configuration changes ​

zhin start watches changes only when --watch is explicit. Without it, editing a file does not apply it automatically. Development scripts that need watching should select their scopes:

bash
npx zhin start --foreground --watch source config  # Source and configuration
npx zhin start --foreground --watch config         # Configuration only
npx zhin start --foreground --watch source         # Source only
npx zhin start --foreground --mode production      # Neither

--no-watch remains a compatibility alias for watching neither and cannot be combined with --watch. Source watching does not enable configuration watching; a source reload does not pull in configuration that is still pending a restart.

A successful save does not mean every change is active. Console configuration forms request application after saving and display the file revision separately from each application result. Even with watching disabled, the new Console's runtime status panel offers “Apply saved configuration”: it applies the saved revision, without saving an unsubmitted form draft or restarting the process. An older Host without application details is explicitly shown as unconfirmed.

ChangeApplication boundary
Only the configured nickname / profile fallback of an adapter declaring in-place profile updatesNew profile reads use the new fallback while retaining the connection. No platform profile write is made; an observed platform nickname still takes precedence
Profile or purpose selection in model managementA separate domain transaction persists the graph. New operations read it; in-flight operations retain their graph, model and leases. This is not a file-application group
HTTP listeners, database connections, .env inputs, YAML account roles, and other startup dependenciesParts without a safe replacement path remain pending a process restart and keep their old effective values
Other plugin configurationUses the owning plugin's existing local reload path; an undeclared update capability does not imply an in-place update

A file save can apply partially. For example, an account nickname fallback may apply while an HTTP port change waits for restart. Model graph changes have separate domain revisions and mutation receipts; file save/apply does not mutate that graph, credentials or personal bindings. If the complete candidate fails validation, the current runtime is retained. Failure, an unconfirmed outcome, and supersession by a newer revision are distinct; refresh read-only to verify an unconfirmed outcome rather than submitting it again.

Agent installation, role permissions and other startup dependencies without declared replacement support remain pending restart. Profile model/parameter edits apply to the next turn; deleting and recreating a resource does not transfer its old account identity. Plugins use the operation-bound InferenceClient instead of retaining SDK/provider instances.

Manage configuration in chat ​

With the root Command Feature installed, a Bot owner can send config (Chinese alias 配置) in a private chat with the Bot to see its usage. There are exactly four subcommands:

  • config fields [scope]: list chat-manageable field paths and types, without values;
  • config get <path>: read one field's saved value;
  • config set <path> <value>: change one field;
  • config unset <path>: remove one optional field.

Hints use the account's actual command prefix and namespace. AI Agent is not required.

Who can use it: only someone holding the chat role owner on the same adapter that received the private message — globally, at the adapter level or on any account of that adapter (Chat roles); identities are registered per adapter, so owners of other adapters (including another plugin instance of the same adapter package) cannot use it. Groups, channels and forged metadata never reach the save path.

Entry is per adapter; field scope is project-wide: authorization (entry) only considers masters on the same Adapter instance that received the message. Once authorized, the manageable field scope is every chat-safe leaf in the project plus the Host allowlist HOST_CONFIG_PATCH_PATHS; it is not limited to the authorizing adapter's own plugin, so any legitimate owner can manage chat-safe fields globally (including other plugins' fields). If an owner should not change other plugins, do not grant them master, or manage those settings with the CLI/Console.

What can change:

  • Host config is limited to the same allowlist as ordinary Console pages (HOST_CONFIG_PATCH_PATHS, currently fields under ai.trigger.ambient). Use the CLI or Console for locale, http, database and other Host settings.
  • Plugin config must be proven safe by its schema. Secrets, tokens, passwords, missing schemas and uncertain scopes are rejected.
  • Permission fields such as owners, trust lists, approvals and tool gates (master, trusted, roles, endpoints[*].roles, toolHardGate.*; the people lists themselves moved into the database, see Upgrading to chat roles) cannot be read or changed in chat. Matching is by contains/prefix/suffix, so compound names are refused too, e.g. adminIds, ownerId, masterId, trustedUsers, superUsers, whitelist/allowlist/blacklist and bypass (such as content-moderation's inbound.whitelist.userIds and inbound.bypass). The rule is deliberately conservative: ordinary fields whose names contain these words (e.g. masterVolume) must be changed with the CLI.
  • endpoints[*].id / endpoints[*].name bind account-level masters and trust lists, so remapping them is an indirect permission change and is refused in chat; set/unset only target fields listed by config fields <root>.
  • A set value cannot contain a ${…} or env:// environment reference (regardless of whether the name looks like a secret), so a later read or echo cannot leak an environment value; existing references are not affected by other operations.
  • Chat reads and writes a single leaf field (a scalar or scalar array) only; whole objects cannot be overwritten or removed, and required fields cannot be unset. configVersion, plugins, disable_plugins, root plugin and undeclared instances cannot be changed either.

Paths accept dotted notation such as mybot.nickname or JSON Pointer such as /mybot/dot.key (~1 escapes /, ~0 escapes ~). Values are parsed by field type: numbers, booleans and arrays use JSON; string fields accept plain text, for example config set mybot.nickname -- My Bot (add the actual prefix). Object values are not accepted.

Saving follows the complete candidate validation and selective application described above. Failures before saving are reported as not saved. A lost commit acknowledgement is reported as unconfirmed: do not resend, check with get first; the command never retries or rolls back automatically. Denials only state a reason and never echo values, defaults or raw exceptions.

Files and database records have separate ownership ​

Where a setting lives depends on who changes it, when, and how many entries it has (ADR 0057, Chinese):

StoreHoldsWritten by
zhin.config.ymlDeclarations fixed at deploy time, reviewed in git, applied by reload or restart: plugin instances and plugin config, disable_plugins, Host infrastructure (http, database connection, console, gateway, mcp, a2a, log_level, locale), ai.* behaviour and security policy, global feature defaults and features.selfServicePeople: by hand, the CLI, Console config forms (all through the gateway config transaction)
DatabaseRuntime state: chat roles, accounts and credentials, model directory, adapter / account / conversation feature overrides (table feature_overrides), control-plane switches, schedules, messages / sessions / memory, plugin stateConsole RPCs, chat commands, AI tools, plugins
.envSecrets and per-environment values; the YAML only holds ${VAR} referencesPeople, zhin doctor --fix, the gateway
.zhin/Machine-local runtime files: sockets, locks, logs, caches, onboarding progress, encryption keys; the gateway's Console account store gateway.db (accounts, sessions, API tokens, audit, ADR 0059). keys/ and gateway.db must persist and be backed upRuntime, gateway

Secret fields are annotated with x-zhin-secret: true in the schema (the Host schema marks http.token, database.password, mcp.token, a2a.token and others; Schema.string().secret() emits it for plugins). Without an annotation the field name decides (token, password, secret, apiKey, privateKey, *Token, *Secret, …). At startup a literal value in such a field (not a ${…} reference) produces one warning listing the paths, never the values. zhin doctor reports the same; zhin doctor --fix writes each literal into .env as ZHIN_<PATH_UPPER_SNAKE> (for example ZHIN_HTTP_TOKEN; an existing variable with the same value is reused, a name holding another value gets _2, _3) and replaces the YAML value with ${NAME}. The YAML goes through the config file transaction (revision check, file lock, atomic replace); .env is written under the same kind of lock as a temporary file that is fsynced and renamed, keeping the file mode (0600 for a new file). With the gateway running, these files are still edited directly (like the other zhin doctor fixes; the shared lock prevents lost writes) and the instance picks up the references the next time it loads the configuration.

Feature overrides: a feature's global default is the plugin's own block in the YAML, and its global switch is disable_plugins. Adapter, account and conversation overrides all live in the project database table feature_overrides; the Console feature page and the chat command (feature set / enable / disable) write them, effective at once without a restart. The YAML no longer accepts overrides under a plugin block: an existing project imports them into the database on its first start and then removes them from the YAML (backing up the original file to .zhin/backups/ first); a block written afterwards stops startup, see Upgrading: feature overrides move to the database. With a MongoDB, Redis or memory database these overrides cannot be saved and writes are refused.

Still being migrated (later ADR 0057 steps; current behaviour is unchanged):

  • endpoints[] in plugin blocks and the project's ai.plan.yml are still seeds imported into the database on first start: once imported, YAML account seeds do not rewrite existing managed accounts, while adapter profile defaults still apply to accounts that inherit them; when the two differ, the startup log and the Console attention inbox say so and each account can be imported or written back, see Configuration file accounts and saved accounts;
  • Permanent approvals are still stored in data/owner-approve-always.json;
  • Encryption keys are still in .zhin/inference/ and .zhin/endpoint-credentials/, and there is no zhin backup yet — back up these keys together with the database, or credentials cannot be decrypted.

File updates do not overwrite explicit records in the database or clear personal Session choices.

Environment Variable Expansion ​

${VAR}, ${VAR:-default}, and ${VAR:=default} within string values are expanded:

yaml
http:
  token: ${HTTP_TOKEN:-dev-token}   # Falls back to dev-token when HTTP_TOKEN is not set

An unset variable without a default expands to an empty string. For fields such as apiKey, this triggers AI-provider soft pruning.

Dotenv loads .env then .env.<environment>. --environment selects the name and defaults to development. Keep secrets in environment variables, never in the configuration file.

Rules (the instance, the gateway, the Console and the CLI share one parser, so recognition always matches expansion):

  • A variable name starts with a letter or _, followed by letters, digits or _. ${1A}, ${A-B}, ${A:x} and an unclosed ${A are not references and stay as written.
  • A default runs from :- / := to the first } and may be empty (${VAR:-}). Both forms behave the same: the default applies when the variable is unset or empty; := does not assign the variable.
  • A default is stored in plain text in the configuration file: never put a secret in a default. ${VAR:-…} counts as a reference, so the startup warning and zhin doctor do not report it as a literal secret, and the Console database wizard keeps ${DB_PASS:-…} as written; keep secrets in .env only and write ${VAR} in the configuration.
  • A value may hold several references and surrounding text (http://${HOST}:${PORT:-80}). There is no escape: $${VAR} expands to $ followed by the value.
  • "Missing environment variable" reports (the startup warning, missingEnv in Console validation results) list only references without a default whose variable is unset; a reference with a default (even an empty one) is never missing.
  • Fields that take a whole reference only (such as http.port) accept ${VAR} and both default forms; surrounding whitespace is ignored.

${VAR} versus env:// ​

SyntaxWhereMeaning
${VAR} / ${VAR:-default}Any string value in zhin.config.ymlExpanded to the variable's value when the configuration loads; may be embedded in text and may carry a default
env://VAROnly AI account credential sources, ai.accounts.*.auth.source (written by zhin ai account add, the scaffold and legacy-config migration)The whole value names one variable: the Host reads it when it authorizes the account, and it is never expanded into the configuration; no default, no surrounding text

An env://… value in an ordinary configuration field is not expanded and stays as written; write ${VAR} to reference an environment variable there.

Top-Level Keys ​

KeyTypeDescription
log_levelstring | numberLog level (e.g., info, debug); ZHIN_LOG_LEVEL / LOG_LEVEL environment variables can temporarily override
httpobjectHTTP Host (Console / API entry point)
databaseobjectDatabase
speechobjectSpeech STT/TTS (requires @zhin.js/speech installed)
assistantobjectAssistant Runtime (scheduled tasks / event API)
aiobjectAI stack (requires @zhin.js/agent etc., see below)
mcpobjectMCP Host (exposes bot tools as an MCP Server)
a2aobjectA2A Host (Agent Card / remote Agent interop)
htmlRendererobjectShotium HTML rendering (e.g., width / viewport / scale)
menuKeywordstring | falseBuilt-in menu keyword; defaults to 菜单, false or an empty string disables it
menuStyleobjectMenu title, subtitle, accent color and background when rendering is available
commandSuggestionboolean | objectReply "did you mean" for near-miss commands instead of the AI; false disables it, maxDistance / limit tune it
pluginobjectRoot Plugin (the application itself) configuration
configVersionnumberMust be 2
pluginsobjectInstance alias to package mapping
disable_pluginsstring[]Disabled aliases; values are retained
<instanceKey>objectBusiness configuration of a declared instance

http ​

yaml
http:
  port: 8068                 # default when unset; only 1–65535 integers or ${VAR} references
  host: 127.0.0.1            # Default 127.0.0.1
  token: ${HTTP_TOKEN}       # bootstrap token: only creates the first Console owner, refused afterwards
  corsOrigins:               # Allowed cross-origin sources
    - "https://console.zhin.dev"
  base: /api                 # API mount path

Without http.port the gateway listens on 8068, the value the scaffold writes (early 1.x runtimes defaulted to 8086; projects that set a port are unaffected). http.port accepts only an integer from 1 to 65535, or a ${VAR} reference that expands to one (0 lets the system pick a free port, for tests); anything else is refused by zhin config set, Console saves and zhin config check, and startup fails instead of silently using the default port.

Local development can access without token; production must set one. tokens supports multiple scoped tokens.

database ​

Use the CLI to generate both the config references and the .env connection values:

bash
npx zhin setup --database
npx zhin config check

setup writes the non-secret structure to zhin.config.yml and the actual connection values to the project-root .env. Runtime reads .env first, then overrides matching keys from the selected .env.<environment>. For example, use zhin start --mode production to load .env.production by default; an explicit --environment <name> selects a different environment overlay.

SQLite ​

yaml
database:
  dialect: sqlite            # Default sqlite
  filename: ./data/bot.db

When database is omitted entirely, it defaults to <project-root>/.zhin/data.sqlite. SQLite uses the built-in Node.js driver and needs no connection environment variables.

PostgreSQL ​

The dialect name is pg (not postgres):

yaml
database:
  dialect: pg
  host: ${DB_HOST}
  port: ${DB_PORT}
  user: ${DB_USER}
  password: ${DB_PASSWORD}
  database: ${DB_DATABASE}
dotenv
DB_HOST=127.0.0.1
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=change-me
DB_DATABASE=zhin_bot

DB_PORT must contain only the port number; do not include http://, a host name, or host:port. Create DB_DATABASE first and allow DB_USER to connect from the machine running the bot. If the bot runs in a container, 127.0.0.1 points to that container; use the PostgreSQL service name or a reachable host address instead.

Restricted account of the Console SQL editor (database.console) ​

On PostgreSQL / MySQL the SQL editor of the Console database page runs only on a separately logged-in restricted account (ADR 0059, Chinese). Create it with the CLI:

bash
npx zhin db console-role            # created with the main account; add --print-sql for a DBA when it may not create accounts

It writes a random password to .env and references it from the configuration:

yaml
database:
  dialect: pg
  # …main account connection fields…
  console:
    user: ${ZHIN_DB_CONSOLE_USER}
    password: ${ZHIN_DB_CONSOLE_PASSWORD}
  • Only user and password; they are removed before the main connection's driver sees the block, and user must differ from the main account. With both variables unset the block counts as absent (SQL editor off, everything else works).
  • At start the instance probes the account's privileges; if it holds too much, the SQL editor is off and the page says why (capabilities.sqlReason). The instance never creates the account by itself.
  • SQLite, MongoDB, Redis and memory ignore the block. The instance's SQLite connection always refuses ATTACH (not configurable).
  • Console accounts are not in the project database but in .zhin/gateway.db; see the upgrade notes.

Other dialects ​

The CLI database selector shows both the currently supported, live-tested server version and the driver version generated for the project:

DialectCurrently supported live-tested versionGenerated driver dependency
sqliteBuilt-in Node.js node:sqlite (Node.js 22.5+)none
mysqlMySQL 8.4 LTSmysql2 ^3.23.2
pgPostgreSQL 17pg ^8.22.0
mongodbMongoDB 7mongodb ^7.5.0
redisRedis 8redis ^6.1.0
memoryBuilt into Zhinnone

The live acceptance baseline is the concrete version covered by maintainer tests. It is not a claim that the driver can connect only to that server version; the wider compatibility range depends on the driver and the database server protocol.

DialectConfiguration fieldsEnvironment variables generated by the CLI
mysqlhost, port, user, password, databaseDB_HOST, DB_PORT (default 3306), DB_USER, DB_PASSWORD, DB_DATABASE
mongodburl, dbNameDB_URL (for example mongodb://127.0.0.1:27017), DB_NAME
redissocket.host, socket.port, password, databaseREDIS_HOST, REDIS_PORT (default 6379), REDIS_PASSWORD, REDIS_DB
memorynonenone

The network database drivers are mysql2, pg, mongodb, and redis. When you select a database in project creation or zhin setup --database, the CLI writes the accepted driver version shown above to package.json. create-zhin-app installs dependencies automatically; after zhin setup, run the prompted pnpm install command yourself.

Run npx zhin config check before startup. If the values only exist in .env.production, run npx zhin config check --environment production. Missing database environment variables are reported as errors. An empty, non-integer, or out-of-range port is rejected before the driver loads, with the exact config path and .env variable in the message. On older versions, ERR_SOCKET_BAD_PORT / Received type number (NaN) usually means ${DB_PORT} is missing from the project-root .env; add it or rerun npx zhin setup --database.

speech ​

yaml
speech:
  stt: { provider: ollama, model: whisper, host: http://localhost:11434 }
  tts: { provider: edge, voice: zh-CN-XiaoxiaoNeural }

When configured, this enables the speech pipeline and exposes voice_stt / voice_tts tools to the Agent. @zhin.js/speech is an optional peer dependency and must be installed separately.

assistant ​

yaml
assistant:
  enabled: true                    # Enable unified JobStore, default false
  profile:
    enabled: true
    file: assistant.profile.yml    # Profile file, drives scheduled tasks
  events:
    enabled: true                  # Open POST /api/assistant/events
    rateLimitPerMinute: 60         # Default 60
  defaults:
    notifyOnFailure: false         # Whether to notify on Job failure, default false

The remaining sub-key is queue (Schedule execution concurrency/retry/timeout). Schedule facts are persisted in the database (falling back to schedule-jobs.json when no relational database is configured); manage them on a running bot with zhin schedule.

mcp / a2a ​

yaml
mcp:
  enabled: true
  path: /mcp
  token: ${MCP_TOKEN}                   # MCP protocol token; does not fall back to http.token
  allowUnauthenticatedLocalhost: false  # Recommend false for production

a2a:
  enabled: true
  path: /a2a
  token: ${A2A_TOKEN}                   # A2A protocol token; does not fall back to http.token

Both sections are mounted on the HTTP Host and enabled as needed; when not configured, the corresponding SDK is not loaded.

Authentication: the Bearer accepts two kinds of credential:

  • the protocol token mcp.token / a2a.token;
  • a Console API token issued after the account (or one of its roles) has been granted the global permission mcp.access / a2a.access; see Access control · API tokens. A token never holds more than the account that issued it, and stops working as soon as the account is disabled or the token revoked.

http.token is the bootstrap token: it is valid only until the first owner exists (MCP / A2A accept it until then too) and is refused everywhere afterwards, so it is not a protocol credential. Outside production, A2A without a2a.token accepts loopback requests only, and MCP accepts local requests by default (turn that off with allowUnauthenticatedLocalhost: false). Production always requires a Bearer.

Cross-process Agent collaboration travels over a2a.mailbox (ADR 0048): each Mail is signed together with its Authority and budget grant, so a remote peer cannot widen authority or exceed the granted budget.

yaml
a2a:
  enabled: true
  mailbox:
    enabled: true
    path: /a2a/mailbox                  # inbound route, defaults to /a2a/mailbox
    secret: ${A2A_MAILBOX_SECRET}       # signing secret; required in production
    peers:
      - actor: remote-reviewer          # the name local Agents list under contacts
        url: https://agents.example.com/a2a/mailbox
        secret: ${A2A_MAILBOX_SECRET}   # optional, overrides the global secret

a2a.workroomCallbacks and a2a.workroomRemoteExecutors were removed with ADR 0048; startup fails if either is present. See Configuration Fields (Generated) for the field list.

ai ​

ai stores Agent startup behavior and tool permissions. Models are managed through the Console or explicit plan imports and persisted in the inference database. An empty graph still permits management startup; inference reports a missing Profile when its purpose is not configured.

providers: Runtime model resources ​

Startup configuration no longer accepts ai.providers, modelCatalog, modelPolicy, decisions, or an Agent's provider/model/preset selectors. A Service describes its protocol, an Account owns authentication and private credential references, and a Profile selects a model and parameters. Chat, summary, ambient, image, perception and decision purposes select Profiles. Personal Sessions can select an authorized language Profile.

ai.plan.yml in the project root is imported automatically only once, when the model database is empty, as the initial configuration; after that it is explicit review/apply/export input that never overwrites existing settings, and it is not an ai.plan property in zhin.config.yml. See the model interface upgrade for migration, backup and recovery boundaries.

agents: Roles and tool permissions ​

yaml
ai:
  enabled: true
  agents:
    zhin:
      mcpServers: [icqq]             # References names in ai.mcpServers
    researcher:
      nickname: 'Researcher'         # Task role name; IM identity comes from the Endpoint
      mcpServers:
        - name: icqq                 # Object form: one more permit layer that can only narrow
          permit: { default: deny }
FieldDescription
nicknameTask role display name; the Endpoint supplies the current account profile
mcpServersMCP Servers this Agent can use: a server name (a name from ai.mcpServers), or { name, permit }; a server not listed here is unusable for this Agent even when connected. The object form's permit is ANDed with the server layer, can only narrow, and omitted keys add no restriction; a server may appear only once

Model role bindings belong to runtime purpose configuration. IM messages always enter zhin. priority / match are deprecated (they never took effect); zhin config check --fix removes them.

mcpServers: External MCP Servers ​

yaml
ai:
  mcpServers:
    - name: icqq
      transport: streamable-http     # stdio | streamable-http | sse
      url: ${ICQQ_MCP_URL}
      headers:
        Authorization: Bearer ${ICQQ_MCP_TOKEN}
    - name: local-tools
      transport: stdio
      command: npx
      args: ["-y", "some-mcp-server"]
      env: { FOO: bar }

ai.mcpServers only connects. A connected Server's tools go only to the Agents that bind it in ai.agents.<name>.mcpServers; for a Server no Agent binds, zhin status, zhin doctor and the Console attention inbox say "connected, but no Agent can use it". See ai.mcpServers for a complete example.

Bound tools are also filtered by the turn sender's chat role.

permit: who may use which tools ​

yaml
ai:
  mcpServers:
    - name: github
      transport: stdio
      command: npx
      args: ['-y', '@modelcontextprotocol/server-github']
      permit:
        readOnly: everyone          # tools annotated read-only and not matched by tools; default everyone
        default: owner@global       # every other tool; default owner@global
        tools:                      # overrides by upstream tool name; default {}
          get_me: trusted
          search_*: everyone
          create_*: deny
          merge_pull_request: [owner@global, private(*)]
KeyDescription
readOnlyTier of tools annotated readOnlyHint: true upstream (and not destructiveHint: true) that no tools rule matched; default everyone
defaultTier of every other tool (not annotated, annotated as writing, contradictory); default owner@global
toolsOverrides by the raw upstream tool name (no server prefix, case-sensitive). An exact name wins; otherwise the * pattern with the most literal characters, and tied patterns must all hold; non-ASCII tool names are matched only by their exact name

A tier is everyone, deny (nobody; the tool is not expanded), one permit string (the same as one item of a plugin tool's permissions, e.g. trusted, owner@global, platform:admin), or a list of strings (all must hold). everyone / deny cannot go into a list; an empty list, an unknown key or an invalid permit (including the removed master) fails startup. Upstream annotations only pick the tier and never relax approval. Upgrade impact and common shapes: Upgrading: MCP tools authorized by chat role.

Other ai Sub-sections ​

yaml
ai:
  sessions:                # Session storage
    maxHistory: 200        # Default 200 in database mode, 100 in memory mode
    expireMs: 604800000    # Default 7 days in database mode, 24h in memory mode
    useDatabase: true      # Default true; uses Database Root Host (.zhin/data.sqlite when database is omitted)
  context:                 # Group chat context recording
    enabled: true
    maxRecentMessages: 100
    summaryThreshold: 50
    keepAfterSummary: 10
    maxContextTokens: 4000
  memory:                  # Three-layer Markdown file memory, enabled by default
    semantic:
      enabled: true        # Generation-owned memory_search/memory_upsert; requires the Database Host
      autoConsolidate: false
      recall:              # per-turn BM25 recall, on by default
        topK: 5
        maxTokens: 400
    # memory_entries must be ready during candidate activation or that generation fails closed
    # memoryMcp is deprecated; use the native memory_search / memory_upsert tools above
  access:                  # AI access control
    mode: open             # open | closed | whitelist, default open
    users: []              # Allowed user IDs in whitelist mode
    groups: []
    denyMessage: ...
  agent:                   # Tool execution security
    mailbox:
      groupMode: supersede # supersede (default) | fifo
    execSecurity: allowlist    # deny | allowlist | full
    execPreset: readonly       # readonly | network | development | custom
    execAllowlist: ["^ls ", "^cat "]
    maxIterations: 15          # Maximum tool iterations per turn, default 15
    thinkingPreview: false     # Show LLM actual thinking content (truncated) in activity feedback instead of static "Thinking...", default false
    thinkingPreviewMaxLength: 200  # Max chars for thinkingPreview, default 200
  trigger:                 # AI trigger rules
    prefixes: ["ai:"]          # Trigger prefixes, default ['#', 'AI:', 'ai:']
    respondToAt: true          # Respond to @bot, default true
    respondToPrivate: true     # Private chats bypass prefix requirement, default true
    ignorePrefixes: ['/', '!', '!']  # Avoid conflicting with commands
    timeout: 60000

ai.multimodal governs multimodal input and output. When the main model cannot see images, the perception purpose in model management selects a Profile to describe them first; see AI · ai.multimodal.perception. knowledge_search is published only when ai.knowledge.baseDir is explicitly configured, and that directory must stay inside the project root. With it configured, the system prompt carries a knowledge base index (file names with level-1 and level-2 headings, within about 1,500 characters, marked as data) and tells the model to search the knowledge base first for questions about this bot or project; the index shares the search cache, which is dropped when files in the directory change. Treat the knowledge directory as owner-trusted content: its file names and headings enter the system prompt, so like skills/ it is protected, and the Agent's file-writing tools need a fresh human approval (a self operation) to write there. Do not feed files from untrusted sources (such as documents uploaded by group members) into it automatically.

ai.remoteAgents and ai.workroom / ai.workrooms were removed with ADR 0048; startup fails if any of them is present. Declare remote Agents under a2a.mailbox.peers, groups or channels shared by several Bots under ai.venues, and each Agent's contacts and per-collaboration budget ceiling under collaboration in agents/<name>/agent.json. See Multi-Agent Collaboration and Venues.

plugin and plugins ​

yaml
configVersion: 2
# Root Plugin (the application itself) configuration; keys are determined by the application's config schema
plugin:
  terminal:
    interactive: true

# Child plugin configuration, keyed by instanceKey
plugins:
  sandbox: "@zhin.js/adapter-sandbox"
sandbox:
  endpoints:
    - id: sandbox-bot
      owner: sandbox-user

instanceKey defaults to the last package-name segment without the adapter-, plugin-, or service- prefix. For example, @zhin.js/adapter-icqq becomes icqq.

zhin install writes the package reference under plugins.<instanceKey> and business settings under the top-level alias. It no longer writes manifest mounts.

Adapter Instances: commandPrefix ​

Platform adapter plugin instance configurations support a common key:

KeyLocationDescription
commandPrefixInstance top-level / per-endpointCommand prefix, default ''; per-endpoint values override top-level

The owner and trusted users are no longer configured here: manage them in the Roles tab of the Console object pages or with role grant in chat; old master / trusted fields move into the database on the first start, see Upgrading to chat roles. Platform standing is not mapped into zhin roles: roles (mapping rules) was removed and stops startup (see Upgrading to chat roles).

endpoints Array: One Instance with Multiple Accounts ​

Multi-account adapters use the endpoints array to declare multiple Endpoints:

yaml
configVersion: 2
plugins:
  icqq: "@zhin.js/adapter-icqq"
icqq:
  endpoints:
    # Per-entry: id is required, other fields merge with top-level (per-entry takes priority)
    - id: "${ICQQ_ACCOUNT_1}"
    - id: "${ICQQ_ACCOUNT_2}"

Expansion rules (@zhin.js/adapter's expandEndpointConfigs):

  • Connection fields are shallow-merged, with per-entry fields taking precedence. Profile fallbacks merge separately per field.
  • Every entry requires a non-empty id. Reserved delimiters (~ and NUL), duplicate IDs and invalid entries are rejected.
  • Missing or empty endpoints creates one Endpoint using the top-level id, or the instance key when it is absent.

Configuration file accounts and saved accounts ​

endpoints is only a first-start seed: while the project database holds no accounts for the adapter, startup creates them from this list; afterwards the database (the encrypted account document, keys in .zhin/endpoint-credentials/) is authoritative, and everything the Console adds, edits, starts or stops changes those records. Later edits of endpoints in the YAML file therefore do not take effect on their own: a removed account still signs in, an added one does not run.

When the two differ:

  • startup (and a reload triggered by a configuration change) logs one endpoint_config_drift warning with the account ids and kinds of difference, never field values;
  • the Console attention inbox shows "Accounts … in the configuration file differ from the saved ones" per adapter instance, in three groups: only in the configuration file (not running), only in the saved accounts (not in the configuration file; they still run as saved — if you removed them on purpose, delete them on the accounts page, or write them back to the configuration file), configured differently;
  • an account added in the Console is not a difference: it was never in the configuration file and, once the saved accounts are the authority, it simply runs; it is left out of the startup warning, the attention inbox, zhin status and zhin doctor. The drift endpoint still lists it as snapshot_only with origin: "console", so it can be written back. An account that came from the file (the first seed, or "Import from configuration", which drops the mark) and is later deleted from it is still a difference; "Write back to configuration" drops the mark of the accounts it writes as well (a failed write-back keeps it), so a Console account that was written back and is later deleted from the file is a difference too. Accounts an older version added in the Console carry no such mark and still show under "only in the saved accounts"; they run as saved. If you removed one from the file on purpose, delete it on the accounts page; otherwise you can write it back to the configuration file;
  • the accounts page resolves each account:
    • Import from configuration (plugin.<instance>.endpoint-import, optionally starting it): writes that YAML account into the saved accounts. ${VAR} references are saved as references and resolved against the current environment only when the account starts; the database never stores the resolved value. An existing account with that id takes the YAML configuration (its identity is kept). When the YAML entry's identity fields (the platform's declared account identity, such as a bot uin or appid) differ from the saved account, the import is refused — that is another platform account: replace the account, or delete it and import again. Imported configuration is validated and prepared by the adapter like an add or update. The call must carry expectedRevision (the account list revision; a missing one is rejected). Importing an account that is not saved yet adds an account and needs endpoint.manage at the adapter level (a binding to one account is not enough);
    • Write back to the configuration file (plugin.<instance>.endpoint-writeback): writes saved accounts into the YAML endpoints. Credential fields are written only as ${VAR} references; a credential value is never written into the file:
      • a reference already in the file (the entry's own or one inherited from the instance block) is kept only when it resolves to the saved value — compared in-process, the value is never output or logged; when it resolves to something else or a variable is unset, a new placeholder reference is written (such as ${QQ_MAIN_SECRET}, with _NEW appended when the old reference has that name) and reported in placeholders with its reason (reference_mismatch / reference_unresolved) for you to set in .env;
      • a credential field without a reference gets a placeholder reference (no reason means credential);
      • besides key names, credentials are recognized by value: URL userinfo (ws://user:pass@host) and credential-like query parameters (?access_token=…, ?sign=…, …) become placeholder references; a list holding credentials (such as tokens: [...], or items carrying a password) cannot be referenced as a whole and the write-back is refused — edit the file directly;
      • the single-account form (the account of a block without an endpoints list) is edited in the file directly. Because it rewrites the configuration file, it needs a global ops.config.write (like every configuration write) on top of endpoint.manage for that adapter;
      • write-back regenerates the whole endpoints sequence: comments inside the list are lost and entries that were not written back are re-serialized in the standard format (same content);
      • it changes the instance's configuration block, which reloads that plugin instance: every account of that adapter instance reconnects, not only the written ones (the result carries reconnectsAll: true and says so in its message).
    • An account not in the file that you do not want to keep is deleted on the accounts page.

Comparison: accounts are matched by id (an id written as ${VAR} is matched by its resolved value); a reference equals the same reference. When the file holds a reference and the saved account a value (every account seeded before this release), the reference is resolved in-process and compared (the value is never output): a different value counts as a (sensitive) difference, an unset variable lists the field as unverified rather than different. Importing the account once turns such fields into references.

Real-world example (QQ official bot, main account through proxy gateway + sandbox account coexisting):

yaml
configVersion: 2
plugins:
  qq: "@zhin.js/adapter-qq"
  slack: "@zhin.js/adapter-slack"
qq:
  endpoints:
    - id: zhin
      appid: "${QQ_APPID}"
      secret: "${QQ_SECRET}"
      mode: websocket
      sandbox: false
      gatewayUrl: "https://bots.example.com/gateway/102005927"
      intents: [ GUILDS, GROUP_AND_C2C_EVENT, PUBLIC_GUILD_MESSAGES ]
    - id: "102069707"
      appid: "${QQ_SANDBOX_APPID}"
      secret: "${QQ_SANDBOX_SECRET}"
      mode: websocket
      sandbox: true
      intents: [ GUILDS, GROUP_AND_C2C_EVENT ]
slack:
  endpoints:
    - id: zhin
      token: "${SLACK_TOKEN}"
      appToken: "${SLACK_APP_TOKEN}"
      signingSecret: "${SLACK_SIGNING_SECRET}"
      socketMode: true

For adapter-specific fields (appid, intents, socketMode, url, access_token, etc.), see the README of the corresponding adapter package.

Minimal Configuration ​

You can run without any Host sections -- this is the entire configuration for examples/minimal-bot:

yaml
configVersion: 2
plugin:
  terminal:
    interactive: true

plugins: {}

After starting, use the zhin setup wizard to progressively add database / adapters / AI (see CLI Reference); for how to run, see zhin start in Detail.

Account self profile ​

The Agent uses the current Endpoint's platform facts first. Adapter-level nickname and profile are missing-field fallbacks; each endpoints[] entry can override them. profile is merged per field. Saving these defaults never changes the platform account. A known empty signature or interests list stays empty, and group cards remain separate. The existing AI nickname is the final fallback; internal task agents keep their role identities.

yaml
icqq:
  nickname: Zhin
  profile:
    gender: unknown
    interests: [music, photography]
    bio: A conversational assistant
  endpoints:
    - id: "bot QQ ID"
      nickname: Zhin Bot
      profile:
        interests: [music, reading]

profile accepts gender, age, birthday (YYYY-MM-DD), signature, avatar (image URL), interests (string array), and bio. Missing information stays unknown. Ordinary turns reuse facts read for that account incarnation; get_self_profile refreshes them explicitly. set_self_profile changes one actually supported platform field under the existing identity approval policy. Editing fallback configuration and changing platform profile are separate operations.