=== Sohay — AI Chatbot for Knowledge Base & Support ===
Contributors: bhoot
Tags: chatbot, ai, knowledge-base, helpdesk, customer-support
Requires at least: 6.6
Tested up to: 7.0
Requires PHP: 8.1
Stable tag: 1.0.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

An AI chatbot that answers visitor questions from articles you publish — with a built-in inbox so your team can take over any chat.

== Description ==

Sohay adds an AI chat widget to your WordPress site that answers visitor questions from the articles you publish. You write articles in the built-in Knowledge Base, and the chatbot looks up the best matches before it replies — so it stays on-topic and uses your real content instead of guessing.

Designed with WooCommerce stores in mind, but works on any WordPress site. Every conversation is saved in a built-in inbox under **Sohay → Conversations** — your team can read, search, filter, assign, and reply from one place.

= Why site owners pick Sohay =

* **Answers from your own content** — the chatbot reads the articles you publish in your Knowledge Base. It doesn't make up product details or invent prices.
* **No coding to set up** — paste an OpenAI API key, publish a few articles, click "Sync All Articles". The widget appears on every page.
* **A real inbox for your team** — every conversation is saved. Search, filter by status, assign one to a teammate, or reply yourself.
* **Predictable costs** — set a daily OpenAI token cap and the plugin stops calling OpenAI for the rest of the day once you hit it. A runaway loop or a hostile bot can't drain your account overnight.
* **GDPR-friendly out of the box** — conversations are stored on your own site, in your own database. Signed-in visitors' chats flow through WordPress's built-in **Export / Erase Personal Data** tools; anonymous guest chats (which have no email to match on) are erased by deleting them from the **Conversations** inbox. See **Privacy** below.
* **Designed for WooCommerce, works anywhere** — declares HPOS and Cart-Checkout-Blocks compatibility, but the chat widget and Knowledge Base work on any WordPress site.

= What's included =

* A **chat widget** that drops into every page (you can hide it on pages you don't want it on).
* A **Knowledge Base** section in the WordPress admin, with a "Sync All Articles" button.
* A **Conversations admin** where you can read, search, filter, assign, reply, pin, and close chats.
* An **AI Settings** screen for picking the OpenAI model, writing the welcome message, and setting daily spend caps.
* A **Diagnostics** screen that shows today's OpenAI token usage and the most recent plugin log entries.
* **Fast page loads** — the chat code only downloads when a visitor actually opens the chat, not on every page view.
* **Your OpenAI key is encrypted** in the database and never shown in the admin UI after you save it.

= You'll need =

* A WordPress site running version 6.6 or later, on PHP 8.1 or later.
* An OpenAI account and API key. You pay OpenAI directly for the model usage — Sohay does not resell access. A typical small support site stays in single-digit dollars per month.

= External services =

Sohay sends data to OpenAI (https://openai.com) to generate chat answers and index your Knowledge Base. Without an OpenAI account and API key, the plugin has no upstream model to call and the chat widget cannot answer questions.

**What is sent, and when**

* **When a visitor sends a chat message** — the message text and recent conversation history are forwarded over HTTPS to `https://api.openai.com/v1/responses` (or the equivalent streaming endpoint for the model you selected) and processed by the OpenAI model configured under **Sohay → AI Settings**.
* **When you publish or update a Knowledge Base article** — the title and body are sent in the background to OpenAI Files and Vector Stores (`https://api.openai.com/v1/files`, `/v1/vector_stores`, `/v1/vector_stores/*/files`) so the chat can retrieve them. The sync runs in the background, not while you click Save.
* **When you open AI Settings** — the plugin makes a one-off call to `https://api.openai.com/v1/models` to populate the model-picker dropdown.

**Where it goes**

All requests go to `api.openai.com` over HTTPS. The plugin does not contact any other external service — no analytics, no telemetry, no third-party fonts or CDN assets, and no phone-home for updates. Updates come from WordPress.org.

**How your API key is handled**

The OpenAI API key you enter under **AI Settings** authenticates every request. It is encrypted at rest (AES-256-GCM) in your WordPress database, masked in the admin UI after the first save, and excluded from the WordPress REST API. The plugin never sends the key anywhere other than `api.openai.com`.

**Your responsibilities**

Before activating the plugin, please review OpenAI's [Terms of Use](https://openai.com/policies/terms-of-use) and [Privacy Policy](https://openai.com/policies/privacy-policy). Site owners are responsible for obtaining the appropriate legal basis (consent, contract, legitimate interest, etc.) to share visitor messages with OpenAI under GDPR, CCPA, and other applicable privacy regimes in the jurisdictions they operate in.

= Privacy =

Conversations and messages are stored in custom database tables on your own site.

For **signed-in visitors**, the plugin registers WordPress's personal-data exporter and eraser, so the standard **Tools → Export Personal Data** and **Tools → Erase Personal Data** flows include their Sohay conversations, matched on their account email.

**Anonymous (logged-out) visitors' chats** aren't tied to an email address, so those email-based tools can't locate them. To erase a specific guest conversation, open it under **Sohay → Conversations** and delete it (available to users with the AI-settings capability); it leaves the inbox immediately and is permanently purged after the retention window — 30 days by default, filterable in code. A visitor can also delete their own chat from the widget, and every soft-delete follows the same purge path.

See the **External services** section above for what gets sent to OpenAI.

== Installation ==

1. From the **Plugins → Add New** screen, search for **Sohay** and click **Install Now**, then **Activate**. A new **Sohay** menu appears in your WordPress admin sidebar.
2. Visit **Sohay → AI Settings** and paste your OpenAI API key into the first field. (If you don't have one yet, you can create one at platform.openai.com.) Click **Save**. The key is stored encrypted — the field shows a masked placeholder from now on.
3. While still on **AI Settings**, pick the OpenAI model you want to use, set a daily token cap under **Spend protection**, and (optionally) write a welcome message that greets visitors when they open the chat.
4. Add at least one article under **KB Articles → Add New**. This is the content the chatbot draws from. You can write as many as you like; longer-form support articles work best.
5. Visit **Sohay → KB Settings → Dashboard** and click **Sync All Articles**. The sync runs in the background — articles become searchable to the chatbot within a minute or two.
6. Visit your site's front-end. The chat launcher appears in the bottom-right corner. Click it to open the chat and try a question your Knowledge Base can answer.

== Frequently Asked Questions ==

= Do I need an OpenAI account? =

Yes. Sohay is a front-end for OpenAI's models — without an OpenAI API key the plugin has no model to call and the chat cannot answer questions. OpenAI bills you directly per token; Sohay does not resell access. The **Spend protection** controls under **AI Settings** let you cap daily token usage to keep costs predictable.

= How much will OpenAI cost me? =

OpenAI charges per token, and the per-token rate depends on the model you pick (the cheaper models cost a fraction of a cent per chat reply). A small support site typically stays in single-digit dollars per month. The **Spend protection** controls under **AI Settings** let you cap daily token usage — once the cap is hit, the plugin stops calling OpenAI for the rest of the day. The **Diagnostics** page shows today's usage so you can spot a runaway loop or a hostile bot before it costs you real money.

= Will the chatbot make things up? =

The chatbot is *grounded* in the articles you publish — if it can't find a matching article, it tells the visitor it doesn't know instead of inventing an answer. To improve answer quality, publish articles covering the questions you actually get asked, and write a fallback "Contact us" article so the chatbot can route off-topic questions to your human support team.

= Where can I see what visitors are asking? =

**Sohay → Conversations** lists every chat — search them, filter by status, assign a chat to a teammate, or reply yourself. The **Diagnostics** page shows OpenAI errors if you're investigating a technical problem.

= Will my visitors' chats be visible to other admins? =

By default, every WordPress administrator can read every conversation. The plugin ships with five granular capabilities so you can delegate access — for example, give a support agent the ability to read and reply to chats without granting them access to AI Settings. See the developer questions below for an overview, and the capability documentation in the plugin's GitHub repository for the full matrix with worked role-configuration examples.

= Does this slow down my site? =

A tiny launcher (~8 KB) loads on every page. The full chat code only downloads when a visitor actually clicks to open the chat, so most visitors never download it. No third-party scripts, fonts, or trackers are loaded from external CDNs.

= Does the plugin work without WooCommerce? =

Yes. The chat widget and Knowledge Base work on any WordPress site. WooCommerce-specific niceties are opt-in; the plugin declares HPOS and Cart-Checkout-Blocks compatibility so WooCommerce stores don't see an "uncertified plugin" banner.

= Can I hide the widget on specific pages? =

Uncheck **Show widget** under **Sohay → AI Settings** to hide it everywhere. To hide it only on certain pages or post types, see the developer questions below.

= Can I customize the welcome message and system prompt? =

Yes. **Sohay → AI Settings** has a Welcome Message field (max 280 characters). **Sohay → KB Settings → Settings** has a Custom System Prompt field (max 4000 characters) for the instructions the chatbot follows when it generates answers. The Custom System Prompt field recognises `{site_name}` and `{current_date}` placeholders — they are replaced with your site's title and today's date before the prompt is sent to the model.

= Where is my OpenAI API key stored? =

Encrypted with AES-256-GCM in your WordPress database. The admin UI shows a masked placeholder once you've saved the key, and the value is excluded from the WordPress REST API. The plugin never sends the key anywhere other than `api.openai.com`.

= What happens to my data if I uninstall Sohay? =

Uninstalling deletes the plugin's own database tables (conversations, messages, sync jobs, diagnostic logs), its settings, and the capabilities it added. **Your Knowledge Base articles are kept** — they're regular WordPress content, so removing the plugin doesn't delete them, and they're still there if you reinstall. If you want them gone too, delete the articles under **KB Articles** before you uninstall.

= Does Sohay work on WordPress Multisite? =

Yes. Each site in the network keeps its own conversations, Knowledge Base, and settings — nothing is shared across the network. Network-activate to enable Sohay everywhere (each site sets itself up on first load) or activate it per-site. Uninstalling from the network removes Sohay's data from every site.

= For developers =

The questions below cover code-level customization. Sohay exposes 26 filters and 7 actions in total; the most-used ones appear here, and the full catalog lives in `docs/HOOKS.md` in the plugin's GitHub repository, alongside `docs/CAPABILITIES.md` for the full capability matrix.

= How do I customize the plugin with code? =

The most commonly customized filters:

* `sohaychat_should_render_widget` (bool) — per-request gate on the chat widget. Combine with `is_singular()` / `is_product()` to scope the widget to specific pages.
* `sohaychat_allowed_openai_models` (string[]) — allowlist of OpenAI model slugs the proxy may call. Restrict to cheaper models to cap spend.
* `sohaychat_help_url` and `sohaychat_upgrade_url` (string) — override the admin-header "Help" and "Upgrade" links for resellers.
* `sohaychat_admin_conversation_scope` — restrict which conversations a non-admin operator can see.

Example — hide the widget everywhere except the WooCommerce shop and product pages:

`add_filter( 'sohaychat_should_render_widget', function ( $enabled ) {
    if ( ! $enabled ) { return false; }
    return function_exists( 'is_shop' ) && ( is_shop() || is_product() );
} );`

The constants on `Bengal_Studio\Sohaychat\Sohaychat_Hooks` are the recommended form for new code; the legacy literal form continues to work across releases.

= How do I delegate access to non-admin roles? =

Five granular capabilities let you delegate parts of the plugin to non-admin roles:

* `sohaychat_manage` — AI Settings page, OpenAI key reveal, model selection. Implicitly grants all four other plugin caps.
* `sohaychat_view_conversations` — Sohay menu, Dashboard + Conversations submenus (read-only). Non-admin users with this cap are scoped to "assigned to me or unassigned" conversations.
* `sohaychat_reply_conversations` — everything `sohaychat_view_conversations` grants, plus operator reply, assignee changes, pin / unpin, close / reopen. Implicitly grants `sohaychat_view_conversations`.
* `sohaychat_manage_kb` — KB Settings admin page and KB sync routes.
* `sohaychat_view_logs` — Diagnostics admin page (read-only). Clearing the log buffer is escalated to `sohaychat_manage` for forensics integrity.

WordPress's built-in `manage_options` capability implicitly grants all five, so administrators keep working unchanged. Use Members, User Role Editor, or WP-CLI (`wp cap add <role> sohaychat_view_conversations`) to delegate caps to non-admin roles. See `docs/CAPABILITIES.md` in the GitHub repository for the full matrix, every REST route's required cap, three worked role-configuration examples, and the conversation-scope filter contract.

= How do I adjust rate limits or the daily OpenAI token budget in code? =

Three independent limiter filters. The chat-message rate limit (`limit` requests per rolling `window` seconds, per visitor):

`add_filter( 'sohaychat_rate_limit_options', function ( $opts ) {
    $opts['limit']  = 60;
    $opts['window'] = 60;
    return $opts;
} );`

Behind Cloudflare or another reverse proxy, enable proxy-aware client-IP detection so per-visitor limits key off the real visitor rather than the proxy:

`add_filter( 'sohaychat_rate_limit_options', function ( $opts ) {
    $opts['proxy_support'] = true;
    return $opts;
} );`

Enable `proxy_support` **only** when your site is reachable exclusively through the trusted proxy, and that proxy overwrites the `CF-Connecting-IP` / `X-Real-IP` / `X-Forwarded-For` headers on every request. On an origin that's also reachable directly, a visitor could forge those headers to sidestep per-visitor limits; the site-wide daily token budget still caps total spend.

The public `/auth/guest-token` mint rate limit (separate so token-mint amplification protection can be tuned independently):

`add_filter( 'sohaychat_auth_rate_limit_options', function ( $opts ) {
    $opts['limit']  = 5;
    $opts['window'] = 60;
    return $opts;
} );`

The daily OpenAI token budget (caps also configurable under **AI Settings → Spend protection**; ceilings reset at UTC midnight; setting either value to 0 disables that particular ceiling):

`add_filter( 'sohaychat_usage_tracker_options', function ( $opts ) {
    $opts['site_cap']  = 5000000;
    $opts['actor_cap'] = 25000;
    return $opts;
} );`

The live readout on the Diagnostics page shows today's usage so you can spot a runaway loop before it 429s real visitors.

= Can I disable the KB search cache? =

KB vector-search results are memoized in the `sohaychat_kb` object-cache group for 5 minutes by default. To shorten the window, lengthen it, or disable the cache entirely, use the `sohaychat_kb_search_cache_ttl` filter (return 0 to disable):

`add_filter( 'sohaychat_kb_search_cache_ttl', '__return_zero' );`

KB sync events flush the cache automatically, so content updates don't get masked.

= Why does the streaming response cut off behind my CDN? =

The plugin sets `Cache-Control: no-cache`, `X-Accel-Buffering: no`, and clears output buffers, but some CDNs still buffer Server-Sent Events. If your CDN supports it, mark the chat REST route as bypassing the cache and disable transformations on the response.

= Where can I see streaming/proxy errors? =

**Sohay → Diagnostics** shows the last 100 plugin log entries with timestamps and context. Each entry also fires the `sohaychat_log_error` action for integration with Sentry, Stackdriver, Query Monitor, etc.

== Screenshots ==

1. The chat launcher sitting in the bottom-right of the site, respecting iOS safe-area-inset above the home indicator.
2. The expanded chat panel mid-conversation, streaming an answer grounded in a Knowledge Base article.
3. **Sohay → Conversations** — the admin SPA listing recent conversations with filter, search, and assignee controls.
4. A single conversation opened in the admin, showing message history and the reply composer.
5. **Sohay → AI Settings → Spend protection** — daily per-visitor and site-wide token caps with the live usage readout.
6. **Sohay → KB Settings → Dashboard** — sync status for the Knowledge Base and the "Sync All Articles" action.

== Changelog ==

= 1.0.0 =

* Initial release on WordPress.org.

== Upgrade Notice ==

= 1.0.0 =

Initial release.
