AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(providers): read PDFs through each provider's own file support (#257)
Rufus9e0bbc4dea17
diff --git a/.env.example b/.env.exampleindex 00dcf2da..2997383d 100644--- a/.env.example+++ b/.env.example@@ -293,11 +293,21 @@ GOOGLE_OAUTH_CLIENT_SECRET=# WORKFLOW_FILE_DIRS=# Scanned PDFs (optional tuning)-# A PDF with no text layer (a scan, or one printed to PDF as images) is-# converted to text wherever the Executive reads one. With ANTHROPIC_API_KEY-# and OpenRouter off, PDF_VISION_MODEL reads the pages; on every other setup-# (OpenRouter, local models) the server OCRs them locally — no key, no cost.-# PDF_VISION_MODEL=claude-sonnet-5+# A PDF with no text layer (a scan, or one printed to PDF as images) is OCR'd on+# this server by default. With PDF_PROVIDER_READING=true it is instead read by+# the deployment's model through its provider's own PDF support: Anthropic+# natively; OpenRouter via its file-parser (models that read files natively+# get "native", others PDF_OPENROUTER_ENGINE: mistral-ocr | cloudflare-ai);+# a local server only with LOCAL_PDF_INPUT=true (e.g. LOCAL_BASE_URL pointed at+# https://api.openai.com/v1). Otherwise the server OCRs the pages locally.+# The model that reads them; unset means DEFAULT_MODEL.+# PDF_VISION_MODEL=+# PDF_OPENROUTER_ENGINE=mistral-ocr+# LOCAL_PDF_INPUT=false+# Opt-in. Off (the default), scanned PDFs never leave this server: local OCR+# reads them. On, they go to the provider as described above (on OpenRouter+# possibly through its third-party parser).+# PDF_PROVIDER_READING=false# PDF_VISION_MAX_PAGES=100# PDF_VISION_PAGES_PER_CALL=20# PDF_OCR_ENABLED=truediff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 20169d3c..c0bfcfcf 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -343,6 +343,18 @@ providers:executive_reflection loops never enable thinking and drop the blockharmlessly (each consults `reasoning_replay_block`, so the echo isalready wired should deep reasoning ever be added to them).+ Anthropic base64 PDF ``document`` block → OpenAI ``{"type":"file",+ "file":{"filename","file_data":"data:application/pdf;base64,…"}}`` part+ (the user message then goes out as a typed array, text and files in+ order; a URL/text-source document has no faithful shape and is left+ out). ``FeatureSpec.supports_pdf_input`` gates it per model: false for a+ local server unless LOCAL_PDF_INPUT, and a gated-off block becomes the+ text note "[PDF omitted: …]" rather than vanishing. OpenRouterProvider's+ ``_extend_body`` hook adds ``plugins=[{"id":"file-parser","pdf":+ {"engine": …}}]`` when a file part is present: ``native`` for+ anthropic/claude-* or a catalog entry whose input_modalities has+ "file" (openrouter_catalog.accepts_files), else PDF_OPENROUTER_ENGINE+ (default mistral-ocr). No file part → the body is byte-identical.The Anthropicserver-side web_search tool (no input_schema) cannot be executed byOpenRouter, so it is replaced in ``tools[]`` by OpenRouter's@@ -1453,17 +1465,30 @@ knowledge:Scanned / image-only PDFs (no text layer) are read, not returned empty.knowledge.pdf_reader.read_pdf_text tries, in order, and never raises:1. pypdf's text layer — kept when it has >= ~20 visible chars per page.- 2. Claude: base64 `document` blocks, PDF_VISION_PAGES_PER_CALL pages- (default 20) per request, 3 concurrent, transcribed to Markdown by- PDF_VISION_MODEL (default claude-sonnet-5). ONLY when that model- resolves to AnthropicProvider — providers/translator.py drops- `document` (and `image`) blocks on OpenRouter / local routes, so the- PDF would be silently lost there.+ 2. The deployment's own model, through its provider's PDF support:+ base64 `document` blocks, PDF_VISION_PAGES_PER_CALL pages (default+ 20) per request, 3 concurrent, transcribed to Markdown by+ PDF_VISION_MODEL (unset = DEFAULT_MODEL). Sent only when+ providers.registry.pdf_input_supported(model): Anthropic direct and+ every OpenRouter model (translator -> `file` part; OpenRouter's+ file-parser: native for file-input models, else+ PDF_OPENROUTER_ENGINE, default mistral-ocr), a local server only with+ LOCAL_PDF_INPUT (e.g. LOCAL_BASE_URL = OpenAI's API). OpenAI models+ are reached through OpenRouter (openai/...) — there is no direct+ OpenAI provider.+ OPT-IN: PDF_PROVIDER_READING (default false). It is data egress (to+ the provider, and on OpenRouter possibly to Mistral OCR), so an+ upgrade must not start it: off, this step is skipped and scanned+ PDFs never leave the server. That default also moves Anthropic-+ direct deployments off #254's default (Claude read scans there);+ they OCR locally until they opt in. When on, the destination is+ logged once per process. PDF_OCR_ENABLED only governs step 3.3. Local OCR: pypdfium2 renders each page (scale 2), RapidOCR(rapidocr-onnxruntime, models bundled in the wheel; opencv-python isoverridden to opencv-python-headless in pyproject so python:3.11-slim- needs no libGL) reads it. Offline, no key, every provider; also the- fallback when step 2 errors, refuses or returns nothing.+ needs no libGL) reads it. Offline, no key: what a local model without+ PDF input gets, and the fallback on every provider when step 2+ errors, refuses or returns nothing.PDF_OCR_ENABLED=false turns it off. Not installed on Python >= 3.13(the wheel's cap) — the note then says OCR is not installed.PDF_VISION_MAX_PAGES (default 100) caps pages read (note says so).diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.jsonindex 78d09809..4ccd85d9 100644--- a/packages/core/openexecutive/architecture/prebuilt/agents.json+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json@@ -1,7 +1,7 @@{"section_id": "agents","title": "Agent Council",- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), in solo mode `<principal_role>` (what kind of principal the advice is for, in plain words, with their title and remit — `router.principal_role_context`), `<department_memory>`, `<past_decisions>`, `<failure_cases>`, `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The role tag follows the turn's mode: a chat turn pins the role on its session with the mode (`pin_turn_principal_role`: the session's `principal_role` override, else the workspace settings) and sends it in solo and nothing in team, so the org block, every specialist in the turn and any workflow the turn starts see the same role; callers with no chat turn read it fresh (`load_principal_role`: the current session's mode and role, else the workspace's), and a failed read sends no tag rather than failing the consult. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Goals have three tools: `list_department_goals`, `update_department_goal` (progress the user reports) and `create_goal` (a new goal the principal states, filed under an area by slug or title and creating the area when none matches — see Org). `create_goal` runs only for the principal on a verified surface, and no unattended run is offered it: the tools in `schedule_tools.UNATTENDED_WITHHELD_TOOLS` are dropped from reflection's and research's toolkits by `unattended_toolkit`, and from the chat loop when its Session is marked `unattended` — the scheduler's PROACTIVE TRIGGER run, whose prompt quotes stored intent text; a call the model emits anyway gets an error tool_result. `record_decision_outcome` records how a past decision turned out — the weekly review lists decisions older than 30 days with no outcome as `[decision N]` — writing `decisions.outcome` (`episodic.update_decision`) and auditing the rationale; it has `create_goal`'s gate (the principal on a verified surface only; everyone else gets an audited refusal) and is in `UNATTENDED_WITHHELD_TOOLS` too. A missing or unknown id returns the decisions still waiting on an outcome, so the model can retry with the right one. Its schema is static; the solo persona has one line on it, and team mode learns it from the tool description, so the team persona is byte-identical. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a team member's People row is also the web sign-in and outbound-email allow-list. `upsert_person` takes `kind` (`team` / `contact`; a new person defaults to `contact` in solo mode, an update keeps the current kind) and `list_people` returns both kinds with `kind` — contacts only on the principal's own verified turn (they are private to the principal; anyone else gets the team as if no contact existed) — while `lookup_person` searches the team only. The same verified-principal rule, as `people_tools.contacts_reachable_now()`, decides whether a turn may reach a **contact** at all: `message_person`, the raw DM tools, `create_calendar_event` / `create_instant_meeting` attendees and the MCP gateway's Gmail / Calendar / Drive gates treat a contact exactly like an unknown person on every other turn, so no refusal reveals that one exists. A turn about the principal's private mail (`Session.private_to_principal`) reaches the principal only. It is neither offered nor allowed to run `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` — everything that reaches someone else, publishes where the team reads, or starts work outside the turn: the broadcasts, meeting bookings and cancellations, `run_workflow` and research, follow-ups and workflow nudges, watches, artifacts, goal updates, saved workflows, skill drafts, and `load_mcp_server` (it connects to any URL, which can carry the turn's content). Through `search_tools` and `call_tool` it reaches only `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads and the Gmail send and draft the gateway narrows to the principal. A search shows it nothing else, and a call to anything else (Google Chat, a Docs or Drive write, `manage_event`, another server) is refused (`schedule_tools.private_turn_withholds`). A call the model emits anyway, MCP tools included, gets an error tool_result and writes an audit row, and every audit row the turn writes is the principal's alone. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.solo_hint(role_kind)`, one static constant per role kind from the onboarding role step): the draft names only the principal, as principal, and no departments; an owner is asked about the offer, customers, pricing, cash and runway, an in-house executive about their organisation (drafted as the company — their employer), function, remit, manager, team size as context and what they are measured on, an independent about their practice, clients and pricing, and with no role given the role-neutral `SOLO_HINT` asks which they are. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\n**Solo mode.** When the workspace (or the turn's session) is solo — one person using Open Executive for themselves — the Executive works for that one person, the principal, whatever their role: they may run their own business, lead a function inside a larger organisation, or work independently, and the persona reads which from the context instead of assuming it — the role lines under \"Your Principal\" in the org block, when the principal gave their role (workspace settings: kind, title, reports to, remit, measured on). Its persona swaps the team sections (\"You Are a Member of This Executive Team\", \"Choosing Who to Tell\", \"Departments & Org Coordination\") for \"You Work for One Person\", \"The People in Their World\", \"Who Hears From You\" and \"Goals and Areas\". Solo means only the principal uses Open Executive — not that they have no people: their manager, direct reports, peers, clients, investors and board are contacts. The Executive helps the principal work with them (a 1:1 or review prep, an update or budget case for their manager or board, a negotiation) but does not coordinate them, contacts them only when the principal asks and only if they are a contact, and never offers to loop the principal in. Every specialist stays relevant — HR for the principal's own reports, board and investor communications for reporting upward. Goals are grouped by *area* (the tools' `department_slug` is the area's slug). The chat loop withholds `send_department_message`, `send_company_broadcast` and `set_department_head` from its tool list, and a call to one of them anyway gets a JSON error tool_result instead of running. The mode is resolved once per turn and pinned on the session, so the persona, the org block, the tools and every tool handler agree — a switch made mid-turn applies from the next turn. Team mode is unchanged.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nOne tool writes under someone else's name, and it is fenced in code rather than the prompt. `ghostwrite_email` (**Act as me**, `orchestrator.delegation_tools`) writes an email as the person the Executive is speaking with and saves it as a draft in their own Gmail; it never sends. It lives in its own registry, never `_ALL_SKILL_TOOLS`, so reflection, research and workflow toolkits can never carry it. The chat loop adds it only on a turn `delegation.settings.pin_turn_delegation` offered it to — the principal, with it on, verified, in a conversation private to them (the web chat, a Slack or Discord DM, a verified private Telegram chat), on an attended turn — and builds that turn's handler map from both registries, so on any other turn a call to it is an unknown tool. Recipients are chosen in code, never by the model, and the text comes from the **ghostwriter** (`delegation.ghostwriter`), a tool-less call with a constant prompt plus the person's \"How I write\" profile. The ghostwriter is deliberately not a Council agent: the Council's edit routes have no principal check. See **Act as Me (Delegation)**.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). `run_workflow` runs the weekly review, and in solo mode the morning brief, only for the principal on a verified surface (`Workflow.principal_only_modes`, `create_goal`'s rule); anyone else gets an audited refusal that does not name the rule. This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nDocuments come in the other way through `read_document` (`orchestrator.document_tools`): it reads a PDF, Word, Excel, CSV, Markdown or text file by `path` — one another tool saved, such as a Gmail attachment (`get_gmail_attachment_content`) or a Drive file (`get_drive_file_download_url`) — or a company document by `filename`, with an optional PDF `pages` range. A scanned PDF is converted (`knowledge.pdf_reader`: Claude when reached directly, local OCR otherwise) rather than returned empty. Reads are confined to the tool download folders — the same resolve-then-contain check as `oe__read_file` — plus the company docs folder, and it is withheld on turns private to the principal (`PRIVATE_TURN_WITHHELD_TOOLS`): those come from a contact's email, whose own attachments the poller has already read into the turn, and must not steer the Executive into company documents.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider. That context is per call and never cached: `<company_stage>` (the stage from the company profile — specialists never see the profile itself), in solo mode `<principal_role>` (what kind of principal the advice is for, in plain words, with their title and remit — `router.principal_role_context`), `<department_memory>`, `<past_decisions>`, `<failure_cases>`, `<relevant_knowledge>` and `<conversation_context>`, outermost first. The specialist's own system prompt is a static domain constant under one `cache_control` block, so it stays byte-identical across companies and profile edits. A chat turn takes the stage from its session's profile (the one the Executive reasons over, and the one an eval scenario injects); workflow steps and the MCP server's `consult_specialist` read it fresh from the profile on disk. The role tag follows the turn's mode: a chat turn pins the role on its session with the mode (`pin_turn_principal_role`: the session's `principal_role` override, else the workspace settings) and sends it in solo and nothing in team, so the org block, every specialist in the turn and any workflow the turn starts see the same role; callers with no chat turn read it fresh (`load_principal_role`: the current session's mode and role, else the workspace's), and a failed read sends no tag rather than failing the consult. The CFO, CSO and sales prompts key their advice on it: for a bootstrapped, self-funded or solo company they drop venture fundraising benchmarks and work from cash, and raise only if the founder wants to.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. Goals have three tools: `list_department_goals`, `update_department_goal` (progress the user reports) and `create_goal` (a new goal the principal states, filed under an area by slug or title and creating the area when none matches — see Org). `create_goal` runs only for the principal on a verified surface, and no unattended run is offered it: the tools in `schedule_tools.UNATTENDED_WITHHELD_TOOLS` are dropped from reflection's and research's toolkits by `unattended_toolkit`, and from the chat loop when its Session is marked `unattended` — the scheduler's PROACTIVE TRIGGER run, whose prompt quotes stored intent text; a call the model emits anyway gets an error tool_result. `record_decision_outcome` records how a past decision turned out — the weekly review lists decisions older than 30 days with no outcome as `[decision N]` — writing `decisions.outcome` (`episodic.update_decision`) and auditing the rationale; it has `create_goal`'s gate (the principal on a verified surface only; everyone else gets an audited refusal) and is in `UNATTENDED_WITHHELD_TOOLS` too. A missing or unknown id returns the decisions still waiting on an outcome, so the model can retry with the right one. Its schema is static; the solo persona has one line on it, and team mode learns it from the tool description, so the team persona is byte-identical. Attunement adds `list_open_loops` (what a person owes — everyone's for the principal only in a private conversation, otherwise the caller's own) and `close_open_loop`, which only closes a loop when the turn's resolved speaker is the principal or the loop's owner — an unrostered sender, a signed-in web user not on the roster, and unattended sessions are refused. The roster write tools (`upsert_person`, `archive_person`, `set_department_head`) are the principal's alone, and only on a surface that verified the speaker — the web chat, the principal's own Slack or Discord, or a private Telegram chat when `TELEGRAM_WEBHOOK_SECRET` is set to a value Telegram can send (Telegram identifies the chat rather than the sender, and without that secret its webhook accepts anyone's update). A teammate, an email (even from the principal's address), Google Chat, the CLI, the MCP server and unattended runs get `status: refused` (audited, and no action chip), because a team member's People row is also the web sign-in and outbound-email allow-list. `upsert_person` takes `kind` (`team` / `contact`; a new person defaults to `contact` in solo mode, an update keeps the current kind) and `list_people` returns both kinds with `kind` — contacts only on the principal's own verified turn (they are private to the principal; anyone else gets the team as if no contact existed) — while `lookup_person` searches the team only. The same verified-principal rule, as `people_tools.contacts_reachable_now()`, decides whether a turn may reach a **contact** at all: `message_person`, the raw DM tools, `create_calendar_event` / `create_instant_meeting` attendees and the MCP gateway's Gmail / Calendar / Drive gates treat a contact exactly like an unknown person on every other turn, so no refusal reveals that one exists. A turn about the principal's private mail (`Session.private_to_principal`) reaches the principal only. It is neither offered nor allowed to run `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS` — everything that reaches someone else, publishes where the team reads, or starts work outside the turn: the broadcasts, meeting bookings and cancellations, `run_workflow` and research, follow-ups and workflow nudges, watches, artifacts, goal updates, saved workflows, skill drafts, and `load_mcp_server` (it connects to any URL, which can carry the turn's content). Through `search_tools` and `call_tool` it reaches only `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads and the Gmail send and draft the gateway narrows to the principal. A search shows it nothing else, and a call to anything else (Google Chat, a Docs or Drive write, `manage_event`, another server) is refused (`schedule_tools.private_turn_withholds`). A call the model emits anyway, MCP tools included, gets an error tool_result and writes an audit row, and every audit row the turn writes is the principal's alone. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The fan-out is failure-isolated per call: a specialist that raises or returns no text becomes an `UNAVAILABLE` tool_result (`router.specialist_unavailable_result`) instead of failing the whole turn, and its area — \"finance\", \"legal\", never the specialist's name — is reported to the user under the web reply, or by the Executive in its reply on other channels, unless another call to it answered that turn. A failed specialist does not count as consulted, so it takes no committee seat. Cancellation (Stop) still propagates. The Executive then synthesizes the returned analyses into one reply.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `sales` | `SalesAgent` | sales |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. A PDF `document` block is translated too: it becomes an OpenAI `file` part, and OpenRouter requests carrying one add the `file-parser` plugin (`native` for models whose catalog entry lists `file` input, else `PDF_OPENROUTER_ENGINE`, default `mistral-ocr`). `FeatureSpec.supports_pdf_input` gates it per model — off for a local server unless `LOCAL_PDF_INPUT` — and a gated-off PDF becomes a text note rather than vanishing. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing. When the workspace is in solo mode, `onboarding_interviewer`'s first user turn is prefixed with a short hint (`interview.solo_hint(role_kind)`, one static constant per role kind from the onboarding role step): the draft names only the principal, as principal, and no departments; an owner is asked about the offer, customers, pricing, cash and runway, an in-house executive about their organisation (drafted as the company — their employer), function, remit, manager, team size as context and what they are measured on, an independent about their practice, clients and pricing, and with no role given the role-neutral `SOLO_HINT` asks which they are. The hint rides in the user turn and the tool array is unchanged, so the cached system prompt and tool prefix are the same in both modes.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\n**Solo mode.** When the workspace (or the turn's session) is solo — one person using Open Executive for themselves — the Executive works for that one person, the principal, whatever their role: they may run their own business, lead a function inside a larger organisation, or work independently, and the persona reads which from the context instead of assuming it — the role lines under \"Your Principal\" in the org block, when the principal gave their role (workspace settings: kind, title, reports to, remit, measured on). Its persona swaps the team sections (\"You Are a Member of This Executive Team\", \"Choosing Who to Tell\", \"Departments & Org Coordination\") for \"You Work for One Person\", \"The People in Their World\", \"Who Hears From You\" and \"Goals and Areas\". Solo means only the principal uses Open Executive — not that they have no people: their manager, direct reports, peers, clients, investors and board are contacts. The Executive helps the principal work with them (a 1:1 or review prep, an update or budget case for their manager or board, a negotiation) but does not coordinate them, contacts them only when the principal asks and only if they are a contact, and never offers to loop the principal in. Every specialist stays relevant — HR for the principal's own reports, board and investor communications for reporting upward. Goals are grouped by *area* (the tools' `department_slug` is the area's slug). The chat loop withholds `send_department_message`, `send_company_broadcast` and `set_department_head` from its tool list, and a call to one of them anyway gets a JSON error tool_result instead of running. The mode is resolved once per turn and pinned on the session, so the persona, the org block, the tools and every tool handler agree — a switch made mid-turn applies from the next turn. Team mode is unchanged.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nOne tool writes under someone else's name, and it is fenced in code rather than the prompt. `ghostwrite_email` (**Act as me**, `orchestrator.delegation_tools`) writes an email as the person the Executive is speaking with and saves it as a draft in their own Gmail; it never sends. It lives in its own registry, never `_ALL_SKILL_TOOLS`, so reflection, research and workflow toolkits can never carry it. The chat loop adds it only on a turn `delegation.settings.pin_turn_delegation` offered it to — the principal, with it on, verified, in a conversation private to them (the web chat, a Slack or Discord DM, a verified private Telegram chat), on an attended turn — and builds that turn's handler map from both registries, so on any other turn a call to it is an unknown tool. Recipients are chosen in code, never by the model, and the text comes from the **ghostwriter** (`delegation.ghostwriter`), a tool-less call with a constant prompt plus the person's \"How I write\" profile. The ghostwriter is deliberately not a Council agent: the Council's edit routes have no principal check. See **Act as Me (Delegation)**.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). `run_workflow` runs the weekly review, and in solo mode the morning brief, only for the principal on a verified surface (`Workflow.principal_only_modes`, `create_goal`'s rule); anyone else gets an audited refusal that does not name the rule. This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nDocuments come in the other way through `read_document` (`orchestrator.document_tools`): it reads a PDF, Word, Excel, CSV, Markdown or text file by `path` — one another tool saved, such as a Gmail attachment (`get_gmail_attachment_content`) or a Drive file (`get_drive_file_download_url`) — or a company document by `filename`, with an optional PDF `pages` range. A scanned PDF is converted (`knowledge.pdf_reader`: local OCR by default; with `PDF_PROVIDER_READING=true`, the deployment's own model through its provider's PDF support, falling back to local OCR) rather than returned empty. Reads are confined to the tool download folders — the same resolve-then-contain check as `oe__read_file` — plus the company docs folder, and it is withheld on turns private to the principal (`PRIVATE_TURN_WITHHELD_TOOLS`): those come from a contact's email, whose own attachments the poller has already read into the turn, and must not steer the Executive into company documents.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.","mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo / sales<br/>board_comms / triage\"]\n Mode{{\"Team or solo<br/>(persona + tools per turn)\"}} --> Exec\n Exec -->|\"ghostwrite_email (Act as me)\"| Gw[\"ghostwriter<br/>(tool-less, not a Council agent)\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Mode compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external\n class Gw compute",- "generated_at": "2026-09-26T23:46:19Z"+ "generated_at": "2026-09-27T15:11:42Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.jsonindex 1395ca64..1fb719ce 100644--- a/packages/core/openexecutive/architecture/prebuilt/integrations.json+++ b/packages/core/openexecutive/architecture/prebuilt/integrations.json@@ -1,7 +1,7 @@{"section_id": "integrations","title": "Integrations",- "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it.\n- **Email** (`integrations.email_poller`) — Gmail poll loop over the Google Workspace MCP (it starts only once the MCP gateway is up); strips Reply-To, filters auto-replies. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway (`google_workspace__send_gmail_message`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary for the principal instead. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an email turn cannot change the People list). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying).\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with.\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: Claude (`PDF_VISION_MODEL`, a `document` block) when the deployment reaches Anthropic directly, else local OCR (pypdfium2 + RapidOCR, offline, no key) — so OpenRouter and local-model deployments convert them too. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. The allow-list (`_egress_sets`) is every team member's email plus the Executive's own address, always; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, `search_drive_files`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the `complete` tier, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees only) or a Drive file created from a URL the server fetches reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. Every `google_workspace__*` call acts as the Executive's own account. workspace-mcp takes the acting account per call (`user_google_email`) and nothing used to check it, so under domain-wide delegation a model-chosen address could open anyone's mailbox in the domain; `mcp_gateway._check_acting_account` now refuses a value naming any other address — before every other gate, with an `integration_outbound_blocked` audit row. An absent value stays allowed (the server's own account). As a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.\n\n### Your own Gmail (Act as me)\n\nA second, separate Gmail connection, for **Act as me** (see **Act as Me (Delegation)**): the principal's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; there is no send method. A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own Gmail (Act as me)**.",+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it.\n- **Email** (`integrations.email_poller`) — Gmail poll loop over the Google Workspace MCP (it starts only once the MCP gateway is up); strips Reply-To, filters auto-replies. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into. Outbound, the principal briefs and the client-rotation digest are emailed through the same gateway (`google_workspace__send_gmail_message`, from the Executive's own mailbox to the principal's address, subject `<brief title> — <date>`, the date in the user's zone) as formatted HTML — rendered from the brief's Markdown with raw HTML and images off, so text quoted from outside shows as text and opening the email loads nothing remote. Email is first when the principal prefers it, and otherwise the backup after every chat channel, tried only when Slack, Discord and Telegram are missing or fail; an in-band error from the tool counts as a failed send and the next channel is tried. An emailed brief is not a DM, so the per-Person outbound guard below does not apply — the gateway's roster egress gate does.\n\n Two senders get their own framing. Mail from one of the principal's **contacts** (a `kind=\"contact\"` People row — see Org) replaces the non-roster `[POLICY]` notice with a contact one: it names them (name and role/company), says not to reply unless the principal asks and not to tell anyone else, and asks for a summary for the principal instead. Both this turn and the forwarded-by-principal turn below are marked `Session.private_to_principal`: they can email, DM or invite only the principal, an alert they raise is private to the principal, and they are not offered the tools that reach anyone else or start work outside the turn (`schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`: broadcasts, meeting bookings, workflows, follow-ups, watches, artifacts, goal updates, skill drafts, connecting a new MCP server), and of the MCP tools only Google Workspace reads and the gated Gmail send (see MCP below). Every audit row about such mail is private to the principal (see Audit Log), the poller's two `integration_inbound` rows included (`_private_to_principal_mail`), so the audit log's other readers see none of it. The poller holds `audit.private_rows` for the whole handling of such a mail, because some rows are written before the turn binds its private session: the knowledge retrieval quotes the mail's From line, subject and opening. The rows themselves read exactly like an outside sender's: the `integration_inbound` row is the non-roster one (`accepted_non_roster`), and the notice opens with the non-roster notice's exact sentence. The poller handles each message with no session bound, so one message's private turn never marks the next message's rows. The turn stays unattributed (`person_id` None — no peer memory, no co-presence), and the gateway refuses mail to a contact on a poller turn anyway. Mail **forwarded by the principal** — the sender resolves to the principal and `_new_text_lines` reports a forwarded message — is wrapped in a `<forwarded_by_principal>` block: summarise it, draft a reply the principal could send (as text in the reply, never sent or saved as a Gmail draft), note any commitment or date, and offer to add the original sender as a contact (confirmed from the web app or the principal's Slack / Discord, since an email turn cannot change the People list). The reply still goes to the principal only. The From header is unauthenticated, so this framing grants nothing: a spoofed \"forward\" just gets the real principal a summary.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). The gates look up **team members only** — a contact's Slack, Discord or Telegram id is treated as unknown, so a contact can never talk to the bot (nor count as a co-present peer). Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying).\n\n### Checking a channel is set up\n\nSettings → Setup status (`GET /setup/status`, `api/setup_checks.py`) gives each channel a light and a plain-language fix. It tests the credentials with one free read-only call — Slack `auth.test`; Telegram `getMe`, then `getWebhookInfo` (is a webhook registered, is it this app's `/webhook/telegram`, did a delivery fail in the past day); Discord `users/@me`, only while the bot is still connecting — and reads what the lifespan left on `app.state`: the Slack socket's `is_connected()`, the Discord bot's `is_ready()` together with its gateway socket being open (discord.py stays ready while it reconnects after a drop), or the exception its task stopped with (`LoginFailure`, `PrivilegedIntentsRequired`), and the MCP gateway. Because inbound is roster-gated, a connected Slack, Discord or Telegram is amber while nobody on the roster has its id (`slack_user_id`, `discord_user_id`, `telegram_chat_id`), or when its latest `integration_inbound` row is a `Rejected: …` from the past day whose sender still isn't on the roster — the page shows the sender's id, never message text. Local login with no `TELEGRAM_WEBHOOK_SECRET` is red for Telegram, since the local-login gate turns its webhook away. Google Chat and Gmail are checked from configuration: a numeric project number and a readable service-account key; the OAuth client (or service-account key) the workspace-mcp child signs in with.\n\nA channel setting written `KEY= # note` in a `.env` file arrives as the note's text, because python-dotenv strips only a comment that follows a value. `Settings` reads such a value as unset for the Slack, Telegram, Discord and Google Chat credentials, so the line no longer switches a channel on with its own comment as the token. `TELEGRAM_WEBHOOK_SECRET` is the exception, because read as unset a junk secret would turn the webhook's check off. It is kept instead, and since Telegram can only ever send 1–256 of `A-Z a-z 0-9 _ -` (what `setWebhook` accepts), a secret outside that set — a leftover comment, a pasted `<value from Step 2>` — could only be matched by someone who guessed it: while it is set the webhook refuses every update, neither the local-login gate nor the roster tools count it as proof (`Settings.telegram_webhook_secret_valid`), and Setup status shows it red (`.env.example` shipped four such lines; the notes now sit on their own lines).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, Telegram, Slack and Google Chat. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them — under an `[Attached: <name>]` label, which the open-loop pass reads as \"not the speaker's words\" — and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\n**Scanned PDFs** are read, not reported empty. A PDF with no text layer goes through `knowledge.pdf_reader`: with `PDF_PROVIDER_READING=true` (opt-in, off by default) the deployment's own model reads it through its provider's PDF support (Anthropic natively, OpenRouter's `file-parser`, a local server only with `LOCAL_PDF_INPUT`); otherwise, and as the fallback, local OCR (pypdfium2 + RapidOCR, offline, no key) — so every deployment converts them. The label then reads `(converted from scanned pages)`, and an unreadable one says why. The index takes the text already extracted for the turn, so a scan is converted once. A file a channel delivered (everything here except `POST /chat/upload`, where the signed-in user sends it) converts at most `PDF_INBOUND_MAX_PAGES` (30) pages and draws on a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget shared by all senders, so sending scans cannot run up unbounded model spend or CPU.\n\nPer channel:\n- **Slack** — a `file_share` message (previously dropped outright for its `subtype`) is handled like any message; files download only after the roster gate and the response gate, with the bot token sent only to `https://files.slack.com/` (needs the `files:read` scope). History and peer memory record the words plus `(Attached files: …)`, never a document's text.\n- **Google Chat** — uploaded attachments download through `media.download` with the reply credentials (`chat.bot`), checked against the 20 MB cap per chunk, 5 per message; an attachment-only message is no longer dropped. The webhook authenticates Google, not the sender, so files are read only when the event's `user.email` is on the People roster (a team member); anyone else's files are named to the Executive, never downloaded. A Drive file shared into a message is left to the Drive tools, with its id.\n- **Email** — the poller (`integrations.email_attachments`) downloads up to 5 readable attachments of the message itself via `get_gmail_attachment_content` — workspace-mcp in stdio mode saves the file and answers `Saved to: <path>`, which must start its line, be the last such line and end in the answer's `Saved filename:` (the answer echoes the sender-chosen attachment name first, and a name carrying `Saved to: /…` must not redirect the read), then resolve inside the tool download folders — and appends their text to the turn (15k chars each). Only for a sender the principal knows (team, contact, principal); a stranger's files stay a list. It runs outside the model loop, so it works on private turns without adding the attachment tool to `PRIVATE_TURN_MCP_TOOLS`.\n- Anything else (a Drive PDF, a skipped attachment) — the Executive's `read_document` tool.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees against the roster (and a refusal of public / whole-domain Drive sharing). The Gmail gate also accepts only a fixed set of argument keys, so workspace-mcp's `reply_all` (recipients taken from the thread, never checked) and `forward_message_id` / `include_forwarded_attachments` (forwarding any inbox message) are refused; a reply is `thread_id` plus an explicit, roster-checked `to`. The allow-list (`_egress_sets`) is every team member's email plus the Executive's own address, always; a **contact's** email joins it only when `people_tools.contacts_reachable_now()` is true — a turn the principal started on a verified surface (web chat, their own Slack or Discord, a verified private Telegram chat), or inside `grant_contact_egress()` (the decisions approve route, when the approver is the principal). On any other turn — an inbound email, a teammate, the scheduler, a workflow, the alert review — a contact's address is refused exactly like a stranger's, so the refusal cannot reveal that it belongs to a contact (contacts are private to the principal). A turn about the principal's private mail (`Session.private_to_principal`) narrows the list to the principal's own address and the Executive's. Such a turn may call only the MCP tools in `schedule_tools.PRIVATE_TURN_MCP_TOOLS`: Google Workspace reads (`search_gmail_messages`, `get_gmail_message_content`, `get_events`, `list_calendars`, `query_freebusy`, `search_drive_files`) and the two Gmail tools this gate narrows to the principal (`send_gmail_message`, `draft_gmail_message`). It is an exact allow-list, not a server: workspace-mcp runs at the `complete` tier, where a Google Chat message to a space, a Docs, Sheets or Drive write into a file already shared with others, `manage_event` on a shared calendar (its gate checks attendees only) or a Drive file created from a URL the server fetches reaches people with no recipient check; and every other server has none at all (a Slack or Notion server, the default `fetch` server, whose URL can carry the turn's content, a server loaded at runtime). Its `search_tools` results show only the allowed tools (`workflows.tool_catalog.filter_search_results`; output it cannot parse reads as no match), and a `call_tool` naming anything else is refused with an error tool_result and an audit row private to the principal (`schedule_tools.private_turn_withholds`), a missing name included. `search_tools` and `call_tool` stay offered, so the tool list and its cached prefix do not change. The typed calendar tool (`_resolve_attendees`) and the chat DM tools (`message_person`, `send_telegram_message`, `send_discord_dm` and their person-id recovery) apply the same rule — a contact's id reads as an unknown one off the principal's turn — and a private turn may DM or invite only the principal (`PRIVATE_TURN_REFUSAL` otherwise); `message_person` never falls back to a \"Needs you\" alert for a contact, who cannot sign in to see it. The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. Every `google_workspace__*` call acts as the Executive's own account. workspace-mcp takes the acting account per call (`user_google_email`) and nothing used to check it, so under domain-wide delegation a model-chosen address could open anyone's mailbox in the domain; `mcp_gateway._check_acting_account` now refuses a value naming any other address — before every other gate, with an `integration_outbound_blocked` audit row. An absent value stays allowed (the server's own account). As a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active and the recipient is not one of the principal's contacts (a contact cannot DM the bot, and quoting the principal's conversation into their email reply's unattended turn would put it in the audit log) — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.\n\n### Your own Gmail (Act as me)\n\nA second, separate Gmail connection, for **Act as me** (see **Act as Me (Delegation)**): the principal's *own* mailbox, which `delegation.gmail.DelegateGmail` reads and drafts into over the Gmail REST API. It is never registered with the MCP gateway, so the model can reach it only through the typed `ghostwrite_email` handler — never by tool name through `call_tool`. The credential is one file per person in `DELEGATION_GOOGLE_CREDENTIALS_DIR` (default `company/delegation_google/`, `/data/delegation_google` in Docker), minted on a computer with a browser by `scripts/connect-own-gmail.py --email <you>` with the Executive's own OAuth client and the scopes `gmail.readonly` and `gmail.compose` — the same seed-it-yourself flow as the Executive's token, since the API serves no OAuth callback. It never lives in `WORKSPACE_MCP_CREDENTIALS_DIR`, where workspace-mcp picks a credential by address.\n\nEvery use re-checks with Google that the credential opens the mailbox on the person's People entry, and refuses outright when that address is the Executive's own: a shared mailbox would make everything the Executive writes look like theirs. Drafts are threaded (`In-Reply-To`, `References` of whole ids ending with the parent, `threadId`) and stamped `X-OE-Ghostwritten`; there is no send method. A Gmail rate limit, even as a 403, is an error to retry rather than a reconnect. The voice learner and the thread shown to the ghostwriter keep only each sender's own words through `email_poller.sender_new_text`, the poller's quoted-reply stripper made public. Setup status shows it as **Your own Gmail (Act as me)**.","mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop unrostered\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\n Guard[\"outbound anti-spam guard<br/>(dedup / rate cap / quiet hours)\"]\n Out[\"DM / department<br/>/ broadcast tools\"]\n Channels --> Resolve\n Resolve --> Gate\n Gate -- \"unknown sender\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\n Exec --> Guard\n Guard -- \"suppress\" --> Drop\n Guard -- \"allow\" --> Out\n Out --> Channels\n Own[(\"Principal's own Gmail<br/>(Act as me: REST, drafts only)\")]\n Exec -- \"ghostwrite_email\" --> Own\n class Channels entry\n class Resolve compute\n class Gate compute\n class Drop external\n class Exec hot\n class Attach compute\n class MCP external\n class Guard compute\n class Out compute\n class Own external",- "generated_at": "2026-09-27T13:09:21Z"+ "generated_at": "2026-09-27T15:11:42Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/rag.json b/packages/core/openexecutive/architecture/prebuilt/rag.jsonindex e42104b9..1b7cf0a4 100644--- a/packages/core/openexecutive/architecture/prebuilt/rag.json+++ b/packages/core/openexecutive/architecture/prebuilt/rag.json@@ -1,7 +1,7 @@{"section_id": "rag","title": "Knowledge & RAG",- "markdown": "Retrieval is handled by `openexecutive.knowledge.retriever.retrieve`, querying ChromaDB collections through `openexecutive.knowledge.store.ChromaDBStore`. When the caller passes `record_source`, `retrieve` also names every document its block quotes — company uploads by filename, built-in knowledge by a title made from its filename, Notion pages, research notes by date, and earlier published documents with a link to `/artifacts/<id>` — so the web chat can list what an answer looked at: the chat route's own search, and each specialist's that answered (see the Lifecycle and API sections). The recording never raises, and a retrieval that fails leaves the specialist without context rather than failing the turn. Six collections back the system:\n\n- **BUILTIN** — curated MBA-style domain knowledge shipped with the repo, including a `sales` domain (founder-led sales, qualification and pipeline, proposals and pricing conversations, follow-up and forecasting) and solo-founder guides in finance, marketing, legal and HR. Seeded at boot by `loader.seed_builtin_knowledge` (FAILURES by `seed_failures`): the whole tree on an empty collection, otherwise only the `SHIPPED_BUILTIN_FILES` entries with no chunks yet — so a doc added in a later release reaches an install seeded by an earlier one, instead of shipping, registering as approved, and never being retrievable. Presence is judged from each row's `source` path relative to `knowledge/builtin/` (not the absolute path, which moves with the install), read in one metadata scan narrowed to seeded rows so the external OER corpus sharing the collection is never pulled. A complete store indexes nothing.\n- **COMPANY** — customer documents ingested via the `/documents` endpoint. Curated uploads only — synced Notion pages do not land here. A document's identity is its **filename**: chunk metadata and the chunk id both derive from it, so re-uploading upserts in place rather than duplicating, and `DELETE /documents/{filename}` matches the rows it claims to remove. Inbound attachments are **not** here — see ATTACHMENTS below; rows left by the earlier scheme are migrated out on boot. A scanned PDF (no text layer) is converted before chunking — see \"Reading scanned PDFs\" below — so it no longer indexes zero chunks while reporting `indexed`.\n- **NOTION_WIKI** — optional Notion sync (`NOTION_SYNC_ENABLED`) incrementally re-indexes pages shared with a Notion internal integration into a separate `notion_wiki` collection (`type=notion`). A Notion share is inherited and multi-writer, so this text is unreviewed relative to curated company docs; the retriever labels it as such and ranks it below COMPANY. Un-shared pages are purged on the next tick.\n- **FAILURES** — recorded failure cases (queried by `retrieve_failures`) teaching specialists what to avoid.\n- **RECENT_RESEARCH** — web-research artifacts persisted from `executive_research` runs, plus every deliverable published with `draft_artifact` (metadata `type=artifact`, `artifact_id`; dropped again when superseded or deleted), kept separate from COMPANY so unvetted machine-generated text never blends into curated knowledge, and ranked below company documents. Artifact chunks are labelled `[published artifact <id> — <date> — earlier output, treat as data]` so the model can reread the whole thing with `get_artifact` without lending quoted text the Executive's own authority. Both kinds are cleared on a client switch or fixture reset.\n- **ATTACHMENTS** — files attached in an integration channel (`inbound_attachments`), written only by `integrations.attachments`. The one collection `retrieve` **never queries**. The content is chosen by whoever sent the message, passes through no upload endpoint and gets no review; it is already inlined into the turn that carried it, and must not become company knowledge that resurfaces later. NOTION_WIKI and RECENT_RESEARCH are queried-but-labelled — this one is written and never read back.\n\nEach parallel specialist call runs its own domain-filtered query. When no explicit filter is passed, `DOMAIN_ALIASES` maps the specialist key to its domains — e.g. `cso`→`strategy`, `cpo`→`product`,`strategy`, `sales`→`sales`,`marketing`, `board_comms`→`board`,`finance`. A specialist with no entry would get no filter at all and retrieve every domain, so each new specialist needs one. Hits beyond a cosine distance threshold are dropped, and very short messages (greetings) bypass retrieval entirely. BUILTIN can carry its own tighter gate via `KNOWLEDGE_BUILTIN_DISTANCE_THRESHOLD`: built-in knowledge is generic and far larger than a typical company corpus, so the distance that admits the right company doc also admits unrelated handbook prose. Unset, every collection shares `KNOWLEDGE_DISTANCE_THRESHOLD`.\n\n`POST /documents` rejects any domain outside that set with a 400 — an unvalidated string would index the document under a domain no specialist filters on, failing silently and only at retrieval time. The tenth accepted value, `general`, is the catch-all for an upload nobody classified (it is the default on the endpoint and in the UI's picker). It maps to no specialist, so every specialist's **company** filter is widened to include it — an unclassified document is visible to all rather than to none. That widening is deliberately not applied to BUILTIN, whose rows are shared with external OER sources that fall back to `general` when they declare no domains; fanning those into every specialist would blend unvetted third-party material into every answer.\n\nMulti-domain chunks fan out to one row per declared domain, so `_dedupe_by_text` drops duplicate-text hits while preserving relevance order before results are returned.\n\n### Reading scanned PDFs\n\npypdf returns only a PDF's saved text layer, so a scan, a phone photo saved as PDF, or a deck printed to PDF as images used to come back empty everywhere a PDF is read. `knowledge.pdf_reader.read_pdf_text` tries three readers in order and never raises:\n\n1. **Text layer** (pypdf) — used whenever it yields real text (at least ~20 visible characters per page, so a scan carrying only page numbers still falls through).\n2. **Claude** — the pages as a base64 `document` block, transcribed to Markdown by `PDF_VISION_MODEL` (default `claude-sonnet-5`), `PDF_VISION_PAGES_PER_CALL` pages per request (default 20), three requests at a time. Only when that model resolves to the **Anthropic-direct** provider: the OpenRouter / local translator drops `document` blocks, so the PDF would be silently lost.\n3. **Local OCR** — pages rendered with pypdfium2 and read by RapidOCR (ONNX, models bundled in the wheel): offline, no key, no per-page cost, on every provider. Also the fallback when step 2 errors, refuses or returns nothing. `PDF_OCR_ENABLED=false` turns it off.\n\n`PDF_VISION_MAX_PAGES` (default 100) caps the pages read, with a note saying how many were; a file a channel delivered (`inbound=True`) is capped at `PDF_INBOUND_MAX_PAGES` (30) and metered by a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget. OCR is bounded too: a page renders within a 25-megapixel budget whatever its MediaBox claims (a crafted 20000pt page would otherwise allocate gigabytes), at most two documents OCR at once, and each stops after 240 s with what it has. A PDF of more than 2,000 pages is refused before any page is parsed (the caps above bound conversion, not the text-layer pass). A Claude slice that runs into the output limit is split in half until each part fits; a single page that still does not fit keeps what was written, marked `[transcription cut off here]`, and the note says so. A result is cached in process by the file's sha256 (32 entries) so a re-read does not re-bill; a failure is not cached. `loader.read_document_text` / `extract_text_from_file_async` route a PDF through it and every other type through the sync extractor, and are what `ingest_file` (uploads, boot reconcile), the `/documents/{filename}` preview, intake uploads, chat attachments, the email poller, `oe__read_file` and the Executive's `read_document` tool use.\n\n### The SME review gate\n\nBefore the distance threshold applies, both `retrieve` and `retrieve_failures` drop **withheld** items — anything the review store reports as `pending` or `rejected` (`ReviewStore.get_withheld_filenames`). Approved items with a priority set are then sorted ahead of the rest.\n\nKnowledge shipped with the product registers as a trusted default (`approved`, NULL `reviewed_at`), so nothing is withheld until a human deliberately queues a domain for curation or rejects something. See the **SME Knowledge Review** section for the full state model. The filter matches on the `(domain, filename)` pair Chroma carries. A bare filename was ambiguous *and* caller-choosable — `POST /knowledge/builtin` takes any `(domain, filename)`, so uploading a file named after a shipped doc in another domain silently withheld that shipped doc from every specialist. Failure case studies are keyed in their own namespace, so a user-authored one cannot collide with a shipped one.\n\nThe formatted context is injected into the **user turn** (wrapped in `<relevant_knowledge>` by `BaseAgent.analyze`), never into a cached system block — per-query hits would otherwise poison the prompt cache.\n\n### Skills (Playbooks) collection\n\nSkills — called **playbooks** in the UI, where they are a tab on Workflows — are Markdown procedures with YAML frontmatter, indexed one document per skill in their own `skills` collection (name + description + when_to_use; the body is fetched by `load_skill`). Built-ins ship under `knowledge/builtin/skills/`; company skills live in `company/skills/`. Customizing a built-in (a `PUT` from the Playbooks tab; the chat tools refuse built-ins) writes a company skill of the same name flagged `customizes_builtin: true`, which **replaces** the built-in: it shadows the built-in everywhere (chat, and the workflows that follow it — see the Workflows section), and deleting it reverts. A built-in cannot be deleted, so \"delete\" **hides** it via `company/skills/.hidden.yaml`; hidden and shadowed built-ins are dropped from the index. `sync_builtin_skill_index` reconciles the built-in rows at startup, after a client-slot restore, and after a fixture reset — so a built-in added in a release reaches an already-seeded index, and a removed one leaves it.\n\n**Drafts.** The Executive's chat tools never change the library directly: `create_skill`, `update_skill` and `delete_skill` save a draft as JSON in `company/skills/.drafts/` (one per name; a newer proposal replaces the pending one). Drafts are not `*.md`, so they are never listed, indexed, searched, loaded or followed. A person approves a draft on the Playbooks tab (`POST /skill-drafts/{name}/approve`), which applies it through the ordinary skills operations, or discards it. Each save gets a fresh `id`, and approve/discard name the version the person saw: a proposal swapped in after review (say by a crafted inbound message) is never applied unseen, and approving never removes a newer draft that arrived meanwhile. This matches the draft → human-approval shape of custom workflows: a crafted inbound message can propose a playbook, but only a person can put one in effect.",+ "markdown": "Retrieval is handled by `openexecutive.knowledge.retriever.retrieve`, querying ChromaDB collections through `openexecutive.knowledge.store.ChromaDBStore`. When the caller passes `record_source`, `retrieve` also names every document its block quotes — company uploads by filename, built-in knowledge by a title made from its filename, Notion pages, research notes by date, and earlier published documents with a link to `/artifacts/<id>` — so the web chat can list what an answer looked at: the chat route's own search, and each specialist's that answered (see the Lifecycle and API sections). The recording never raises, and a retrieval that fails leaves the specialist without context rather than failing the turn. Six collections back the system:\n\n- **BUILTIN** — curated MBA-style domain knowledge shipped with the repo, including a `sales` domain (founder-led sales, qualification and pipeline, proposals and pricing conversations, follow-up and forecasting) and solo-founder guides in finance, marketing, legal and HR. Seeded at boot by `loader.seed_builtin_knowledge` (FAILURES by `seed_failures`): the whole tree on an empty collection, otherwise only the `SHIPPED_BUILTIN_FILES` entries with no chunks yet — so a doc added in a later release reaches an install seeded by an earlier one, instead of shipping, registering as approved, and never being retrievable. Presence is judged from each row's `source` path relative to `knowledge/builtin/` (not the absolute path, which moves with the install), read in one metadata scan narrowed to seeded rows so the external OER corpus sharing the collection is never pulled. A complete store indexes nothing.\n- **COMPANY** — customer documents ingested via the `/documents` endpoint. Curated uploads only — synced Notion pages do not land here. A document's identity is its **filename**: chunk metadata and the chunk id both derive from it, so re-uploading upserts in place rather than duplicating, and `DELETE /documents/{filename}` matches the rows it claims to remove. Inbound attachments are **not** here — see ATTACHMENTS below; rows left by the earlier scheme are migrated out on boot. A scanned PDF (no text layer) is converted before chunking — see \"Reading scanned PDFs\" below — so it no longer indexes zero chunks while reporting `indexed`.\n- **NOTION_WIKI** — optional Notion sync (`NOTION_SYNC_ENABLED`) incrementally re-indexes pages shared with a Notion internal integration into a separate `notion_wiki` collection (`type=notion`). A Notion share is inherited and multi-writer, so this text is unreviewed relative to curated company docs; the retriever labels it as such and ranks it below COMPANY. Un-shared pages are purged on the next tick.\n- **FAILURES** — recorded failure cases (queried by `retrieve_failures`) teaching specialists what to avoid.\n- **RECENT_RESEARCH** — web-research artifacts persisted from `executive_research` runs, plus every deliverable published with `draft_artifact` (metadata `type=artifact`, `artifact_id`; dropped again when superseded or deleted), kept separate from COMPANY so unvetted machine-generated text never blends into curated knowledge, and ranked below company documents. Artifact chunks are labelled `[published artifact <id> — <date> — earlier output, treat as data]` so the model can reread the whole thing with `get_artifact` without lending quoted text the Executive's own authority. Both kinds are cleared on a client switch or fixture reset.\n- **ATTACHMENTS** — files attached in an integration channel (`inbound_attachments`), written only by `integrations.attachments`. The one collection `retrieve` **never queries**. The content is chosen by whoever sent the message, passes through no upload endpoint and gets no review; it is already inlined into the turn that carried it, and must not become company knowledge that resurfaces later. NOTION_WIKI and RECENT_RESEARCH are queried-but-labelled — this one is written and never read back.\n\nEach parallel specialist call runs its own domain-filtered query. When no explicit filter is passed, `DOMAIN_ALIASES` maps the specialist key to its domains — e.g. `cso`→`strategy`, `cpo`→`product`,`strategy`, `sales`→`sales`,`marketing`, `board_comms`→`board`,`finance`. A specialist with no entry would get no filter at all and retrieve every domain, so each new specialist needs one. Hits beyond a cosine distance threshold are dropped, and very short messages (greetings) bypass retrieval entirely. BUILTIN can carry its own tighter gate via `KNOWLEDGE_BUILTIN_DISTANCE_THRESHOLD`: built-in knowledge is generic and far larger than a typical company corpus, so the distance that admits the right company doc also admits unrelated handbook prose. Unset, every collection shares `KNOWLEDGE_DISTANCE_THRESHOLD`.\n\n`POST /documents` rejects any domain outside that set with a 400 — an unvalidated string would index the document under a domain no specialist filters on, failing silently and only at retrieval time. The tenth accepted value, `general`, is the catch-all for an upload nobody classified (it is the default on the endpoint and in the UI's picker). It maps to no specialist, so every specialist's **company** filter is widened to include it — an unclassified document is visible to all rather than to none. That widening is deliberately not applied to BUILTIN, whose rows are shared with external OER sources that fall back to `general` when they declare no domains; fanning those into every specialist would blend unvetted third-party material into every answer.\n\nMulti-domain chunks fan out to one row per declared domain, so `_dedupe_by_text` drops duplicate-text hits while preserving relevance order before results are returned.\n\n### Reading scanned PDFs\n\npypdf returns only a PDF's saved text layer, so a scan, a phone photo saved as PDF, or a deck printed to PDF as images used to come back empty everywhere a PDF is read. `knowledge.pdf_reader.read_pdf_text` tries three readers in order and never raises:\n\n1. **Text layer** (pypdf) — used whenever it yields real text (at least ~20 visible characters per page, so a scan carrying only page numbers still falls through).\n2. **The deployment's own model, through its provider's PDF support** — opt-in, `PDF_PROVIDER_READING=true` (off by default: an upgrade never starts sending scanned PDFs off the server; this also means an Anthropic-direct deployment OCRs scans locally until it opts in) — the pages as a base64 `document` block, transcribed to Markdown by `PDF_VISION_MODEL` (unset: `DEFAULT_MODEL`, the model the deployment already runs on), `PDF_VISION_PAGES_PER_CALL` pages per request (default 20), three requests at a time. Each provider carries the block its own way: Anthropic reads it natively; on OpenRouter the translator makes it an OpenAI `file` part and the provider adds the `file-parser` plugin — engine `native` for Claude or any model the catalog lists with `file` input (OpenAI's GPT-4o and later, Gemini…), else `PDF_OPENROUTER_ENGINE` (default `mistral-ocr`, $2 per 1,000 pages); a local OpenAI-compatible server gets the `file` part only with `LOCAL_PDF_INPUT=true` (e.g. `LOCAL_BASE_URL` pointed at OpenAI's own API). `providers.registry.pdf_input_supported` decides; a model that cannot take one never receives it (the feature gate swaps a stray `document` block for a note). Turning it on sends scanned pages off the server — to the provider, and on OpenRouter possibly to its parser (Mistral OCR) — and the destination is logged once per process.\n3. **Local OCR** — pages rendered with pypdfium2 and read by RapidOCR (ONNX, models bundled in the wheel): offline, no key, no per-page cost. The default reader while step 2 is off, what a local model without PDF input gets, and the fallback on every provider when step 2 errors, refuses or returns nothing. `PDF_OCR_ENABLED=false` turns it off.\n\n`PDF_VISION_MAX_PAGES` (default 100) caps the pages read, with a note saying how many were; a file a channel delivered (`inbound=True`) is capped at `PDF_INBOUND_MAX_PAGES` (30) and metered by a rolling `PDF_INBOUND_PAGES_PER_HOUR` (300) budget. OCR is bounded too: a page renders within a 25-megapixel budget whatever its MediaBox claims (a crafted 20000pt page would otherwise allocate gigabytes), at most two documents OCR at once, and each stops after 240 s with what it has. A PDF of more than 2,000 pages is refused before any page is parsed (the caps above bound conversion, not the text-layer pass). A Claude slice that runs into the output limit is split in half until each part fits; a single page that still does not fit keeps what was written, marked `[transcription cut off here]`, and the note says so. A result is cached in process by the file's sha256 (32 entries) so a re-read does not re-bill; a failure is not cached. `loader.read_document_text` / `extract_text_from_file_async` route a PDF through it and every other type through the sync extractor, and are what `ingest_file` (uploads, boot reconcile), the `/documents/{filename}` preview, intake uploads, chat attachments, the email poller, `oe__read_file` and the Executive's `read_document` tool use.\n\n### The SME review gate\n\nBefore the distance threshold applies, both `retrieve` and `retrieve_failures` drop **withheld** items — anything the review store reports as `pending` or `rejected` (`ReviewStore.get_withheld_filenames`). Approved items with a priority set are then sorted ahead of the rest.\n\nKnowledge shipped with the product registers as a trusted default (`approved`, NULL `reviewed_at`), so nothing is withheld until a human deliberately queues a domain for curation or rejects something. See the **SME Knowledge Review** section for the full state model. The filter matches on the `(domain, filename)` pair Chroma carries. A bare filename was ambiguous *and* caller-choosable — `POST /knowledge/builtin` takes any `(domain, filename)`, so uploading a file named after a shipped doc in another domain silently withheld that shipped doc from every specialist. Failure case studies are keyed in their own namespace, so a user-authored one cannot collide with a shipped one.\n\nThe formatted context is injected into the **user turn** (wrapped in `<relevant_knowledge>` by `BaseAgent.analyze`), never into a cached system block — per-query hits would otherwise poison the prompt cache.\n\n### Skills (Playbooks) collection\n\nSkills — called **playbooks** in the UI, where they are a tab on Workflows — are Markdown procedures with YAML frontmatter, indexed one document per skill in their own `skills` collection (name + description + when_to_use; the body is fetched by `load_skill`). Built-ins ship under `knowledge/builtin/skills/`; company skills live in `company/skills/`. Customizing a built-in (a `PUT` from the Playbooks tab; the chat tools refuse built-ins) writes a company skill of the same name flagged `customizes_builtin: true`, which **replaces** the built-in: it shadows the built-in everywhere (chat, and the workflows that follow it — see the Workflows section), and deleting it reverts. A built-in cannot be deleted, so \"delete\" **hides** it via `company/skills/.hidden.yaml`; hidden and shadowed built-ins are dropped from the index. `sync_builtin_skill_index` reconciles the built-in rows at startup, after a client-slot restore, and after a fixture reset — so a built-in added in a release reaches an already-seeded index, and a removed one leaves it.\n\n**Drafts.** The Executive's chat tools never change the library directly: `create_skill`, `update_skill` and `delete_skill` save a draft as JSON in `company/skills/.drafts/` (one per name; a newer proposal replaces the pending one). Drafts are not `*.md`, so they are never listed, indexed, searched, loaded or followed. A person approves a draft on the Playbooks tab (`POST /skill-drafts/{name}/approve`), which applies it through the ordinary skills operations, or discards it. Each save gets a fresh `id`, and approve/discard name the version the person saw: a proposal swapped in after review (say by a crafted inbound message) is never applied unseen, and approving never removes a newer draft that arrived meanwhile. This matches the draft → human-approval shape of custom workflows: a crafted inbound message can propose a playbook, but only a person can put one in effect.","mermaid": "flowchart TD\n Call[\"Specialist call<br/>(domain-filtered)\"] --> Q[\"retrieve(query, domain)\"]\n Q --> Builtin[(BUILTIN)]\n Q --> Company[(COMPANY)]\n Q --> NotionWiki[(NOTION_WIKI)]\n Q --> Failures[(FAILURES)]\n Q --> Research[(RECENT_RESEARCH)]\n Attach[\"integrations.attachments\"] --> Attachments[(ATTACHMENTS<br/>never queried)]\n Builtin --> Dedupe[\"dedupe by text<br/>+ distance gate\"]\n Company --> Dedupe\n NotionWiki --> Dedupe\n Failures --> Dedupe\n Research --> Dedupe\n Dedupe --> Inject[\"Inject into USER turn<br/>(not cached)\"]\n class Call entry\n class Q compute\n class Dedupe compute\n class Builtin storage\n class Company storage\n class NotionWiki storage\n class Failures storage\n class Research storage\n class Attachments storage\n class Attach compute\n class Inject hot",- "generated_at": "2026-09-27T00:21:17Z"+ "generated_at": "2026-09-27T15:11:42Z"}diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.pyindex 44fe6349..5c883ad2 100644--- a/packages/core/openexecutive/config.py+++ b/packages/core/openexecutive/config.py@@ -287,6 +287,11 @@ class Settings(BaseSettings):local_include_usage_accounting: bool = Field(False, alias="LOCAL_INCLUDE_USAGE_ACCOUNTING")+ # Whether LOCAL_BASE_URL accepts PDFs as OpenAI `file` content parts —+ # true for OpenAI's own API (https://api.openai.com/v1), false for+ # Ollama / LM Studio / vLLM. Off, a PDF for a local model is OCR'd on+ # this server instead (knowledge/pdf_reader.py).+ local_pdf_input: bool = Field(False, alias="LOCAL_PDF_INPUT")@field_validator("local_models", mode="before")@classmethod@@ -534,19 +539,35 @@ class Settings(BaseSettings):# ---- Scanned PDFs (knowledge/pdf_reader.py) ----# A PDF with no text layer (a scan, or one printed to PDF as images) is- # converted instead of coming back empty. Deployments that reach Claude- # directly (ANTHROPIC_API_KEY, OpenRouter off) have PDF_VISION_MODEL read- # the pages; every other deployment — OpenRouter, local models — gets- # local OCR, which needs no key and makes no model call.- pdf_vision_model: str = Field("claude-sonnet-5", alias="PDF_VISION_MODEL")+ # read by a model through its own provider's PDF support: Anthropic+ # natively, OpenRouter via its file-parser (see PDF_OPENROUTER_ENGINE), a+ # local server only when LOCAL_PDF_INPUT says it takes PDFs. Otherwise —+ # or when that call fails — the server OCRs the pages locally.+ # Unset means DEFAULT_MODEL, the model the deployment already runs on.+ pdf_vision_model: str | None = Field(None, alias="PDF_VISION_MODEL")+ # OpenRouter's PDF parser for a model that cannot read files natively+ # (a native-file model always gets "native"). mistral-ocr is OpenRouter's+ # scan-grade OCR ($2 per 1,000 pages); cloudflare-ai is free Markdown.+ pdf_openrouter_engine: Literal["mistral-ocr", "cloudflare-ai", "native"] = Field(+ "mistral-ocr", alias="PDF_OPENROUTER_ENGINE"+ )# Pages read per converted PDF; the rest are skipped with a note.pdf_vision_max_pages: int = Field(100, alias="PDF_VISION_MAX_PAGES", ge=1, le=600)# Pages sent to the model per request (each request transcribes a slice).pdf_vision_pages_per_call: int = Field(20, alias="PDF_VISION_PAGES_PER_CALL", ge=1, le=100)- # Local OCR fallback. Off means a scanned PDF on a non-Claude deployment- # stays unreadable (and says so).+ # Opt-in: whether scanned PDFs may be sent to the model provider at all.+ # On, the deployment's model reads them through its provider (Anthropic+ # natively; OpenRouter, and for a model without native file input its+ # parser, e.g. Mistral OCR; a local server with LOCAL_PDF_INPUT). Off (the+ # default), they never leave this server: local OCR only. Off by default+ # because company documents are sensitive and turning it on adds data+ # egress (and, on OpenRouter, possibly a third-party processor).+ pdf_provider_reading: bool = Field(False, alias="PDF_PROVIDER_READING")+ # Local OCR: what reads scanned PDFs while PDF_PROVIDER_READING is off,+ # for a model that cannot take a PDF, and the fallback when the provider+ # fails. Off means such a PDF stays unreadable (and says so).pdf_ocr_enabled: bool = Field(True, alias="PDF_OCR_ENABLED")# Files that arrive on their own through a channel (chat, Slack, Google# Chat, email attachments) — not ones the Executive or the signed-in userdiff --git a/packages/core/openexecutive/knowledge/pdf_reader.py b/packages/core/openexecutive/knowledge/pdf_reader.pyindex 5e2f6f63..1d20dc6f 100644--- a/packages/core/openexecutive/knowledge/pdf_reader.py+++ b/packages/core/openexecutive/knowledge/pdf_reader.py@@ -6,14 +6,22 @@ relied on pypdf alone got ``""`` back and the Executive could only say itcould not read the file. ``read_pdf_text`` tries three readers in order:1. **Text layer** (pypdf) — free and exact; used whenever it yields real text.-2. **Claude** — a ``document`` content block, which gives the model every- page as an image as well as its text. Only when ``PDF_VISION_MODEL``- resolves to the Anthropic-direct provider: the OpenRouter / local- translator drops ``document`` blocks, so sending one there would silently- lose the PDF.+2. **The deployment's own model, through its provider's PDF support**+ (opt-in: ``PDF_PROVIDER_READING=true``; off by default, so scanned PDFs+ stay on the server unless an operator turns this on) — the+ pages go out as an Anthropic ``document`` block to ``PDF_VISION_MODEL``+ (default: ``DEFAULT_MODEL``), and each provider carries it its own way:+ Anthropic reads it natively; OpenRouter gets an OpenAI ``file`` part plus+ its ``file-parser`` plugin (``native`` for a model that reads files, else+ ``PDF_OPENROUTER_ENGINE``, default ``mistral-ocr``); a local server gets+ the ``file`` part only with ``LOCAL_PDF_INPUT`` (e.g. OpenAI's own API).+ ``providers.registry.pdf_input_supported`` decides; the translation lives+ in ``providers/translator.py`` and ``openrouter_provider.py``.+ The destination is logged once per process when this step is on.3. **Local OCR** — pages rendered with pypdfium2 and read by RapidOCR (ONNX,- models bundled in the wheel). Works on every provider, offline, with no- key and no per-page cost. Also the fallback when step 2 fails or refuses.+ models bundled in the wheel), offline, with no key and no per-page cost:+ the default reader while step 2 is off, for a local model without PDF+ input, and the fallback whenever step 2 fails or refuses.Callers get a ``PdfReadResult`` and never an exception: an unreadable PDFcomes back as ``method="none"`` with a ``note`` saying why, which callers@@ -35,7 +43,7 @@ from typing import Any, Literallogger = logging.getLogger(__name__)-Method = Literal["text_layer", "vision", "ocr", "none"]+Method = Literal["text_layer", "model", "ocr", "none"]# Below this many non-whitespace characters per page, the text layer is taken# to be missing: a scanned deck often carries only page numbers or a footer.@@ -59,7 +67,7 @@ _OCR_MAX_PAGE_PIXELS = 25_000_000# documents at once, each stopping (with what it has) after the time budget._OCR_CONCURRENCY = 2_OCR_TIME_BUDGET_S = 240.0-# Pages converted (Claude or OCR) for files that arrive on their own through+# Pages converted (model or OCR) for files that arrive on their own through# a channel — as opposed to one the Executive or the signed-in user asks to# read — are metered per rolling hour, so no sender can run up unbounded model# spend or CPU by sending scans. See PDF_INBOUND_MAX_PAGES / _PAGES_PER_HOUR.@@ -86,7 +94,7 @@ class PdfReadResult:@propertydef converted(self) -> bool:"""True when the text came from reading page images, not a text layer."""- return self.method in ("vision", "ocr")+ return self.method in ("model", "ocr")# ── Cache ────────────────────────────────────────────────────────────────────@@ -149,7 +157,7 @@ def _is_thin(text: str, pages: int) -> bool:return visible < _MIN_CHARS_PER_PAGE * max(pages, 1)-# ── Claude (document blocks) ─────────────────────────────────────────────────+# ── The deployment's model (a document block, through any provider) ──────────def slice_pdf(data: bytes, start: int, end: int) -> bytes:"""Pages [start, end) of ``data`` as a standalone PDF."""@@ -164,23 +172,57 @@ def slice_pdf(data: bytes, start: int, end: int) -> bytes:return out.getvalue()-def _vision_provider(model: str) -> Any | None:- """The provider for ``model`` when it is Anthropic-direct, else None.+def _pdf_model() -> str:+ """The model that reads scanned pages: PDF_VISION_MODEL, else the model+ the deployment already runs on."""+ from openexecutive.config import get_settings- Anything else (OpenRouter, a local server, or no API key at all — which- ``get_provider`` reports by raising) cannot carry a ``document`` block.- """+ settings = get_settings()+ return settings.pdf_vision_model or settings.default_model+++_announced: set[tuple[str, str]] = set()+++def _announce_destination(model: str, provider: Any) -> None:+ """Log once per process where scanned PDFs are sent, so an operator can+ see the data leave: which provider, and on OpenRouter which parser."""+ from openexecutive.providers.openrouter_provider import OpenRouterProvider++ where = type(provider).__name__+ if isinstance(provider, OpenRouterProvider):+ from openexecutive.providers.openrouter_provider import _pdf_engine+ from openexecutive.providers.registry import openrouter_slug_for_claude++ slug = openrouter_slug_for_claude(model) or model+ where = f"OpenRouter (file-parser engine {_pdf_engine(slug)})"+ key = (model, where)+ if key in _announced:+ return+ _announced.add(key)+ logger.info(+ "pdf_reader: scanned PDFs are sent to %s via %s "+ "(PDF_PROVIDER_READING is on; off keeps them on this server)",+ model, where,+ )+++def _model_provider(model: str) -> Any | None:+ """The provider to send ``model`` a PDF through, or None when that model+ cannot receive one (a local server without LOCAL_PDF_INPUT) or has no+ reachable provider at all (``get_provider`` reports that by raising)."""from openexecutive.providers import get_provider- from openexecutive.providers.anthropic_provider import AnthropicProvider+ from openexecutive.providers.registry import pdf_input_supportedtry:- provider = get_provider(model)+ if not pdf_input_supported(model):+ return None+ return get_provider(model)except Exception:return None- return provider if isinstance(provider, AnthropicProvider) else None-async def _vision_slice(+async def _model_slice(provider: Any, model: str, data: bytes, start: int, end: int) -> tuple[str, bool]:"""Transcribe pages [start, end): ``(text, cut off at max_tokens)``."""@@ -240,16 +282,17 @@ async def _transcribe(return f"{first}\n\n{second}", cut_a or cut_b-async def _read_with_vision(data: bytes, pages: int) -> tuple[str, bool] | None:- """Transcribe up to ``pages`` pages with Claude: ``(text, whether a page- was cut off)``, or None if unavailable or failed."""+async def _read_with_model(data: bytes, pages: int) -> tuple[str, bool] | None:+ """Transcribe up to ``pages`` pages with the deployment's model: ``(text,+ whether a page was cut off)``, or None if unavailable or failed."""from openexecutive.config import get_settingssettings = get_settings()- model = settings.pdf_vision_model- provider = _vision_provider(model)+ model = _pdf_model()+ provider = _model_provider(model)if provider is None:return None+ _announce_destination(model, provider)step = settings.pdf_vision_pages_per_callbounds = [(s, min(s + step, pages)) for s in range(0, pages, step)]@@ -259,12 +302,12 @@ async def _read_with_vision(data: bytes, pages: int) -> tuple[str, bool] | None:# The gate covers one request, not a split's recursion, so halves of# a cut-off slice queue like any other request.async with gate:- return await _vision_slice(provider, model, data, start, end)+ return await _model_slice(provider, model, data, start, end)try:parts = await asyncio.gather(*(_transcribe(request, s, e) for s, e in bounds))except Exception as exc:- logger.warning("pdf_reader: vision transcription failed (%s)", type(exc).__name__)+ logger.warning("pdf_reader: model transcription failed (%s)", type(exc).__name__)return Nonereturn "\n\n".join(t for t, _cut in parts), any(cut for _t, cut in parts)@@ -433,21 +476,22 @@ async def read_pdf_text()limit = granted- vision = await _read_with_vision(data, limit) if limit else None- if vision:- transcript, cut_off = vision+ use_model = limit and settings.pdf_provider_reading+ transcribed = await _read_with_model(data, limit) if use_model else None+ if transcribed:+ transcript, cut_off = transcribednote = "; ".join(n for n in (_pages_note(limit, pages),"some pages' transcription was cut off" if cut_off else "",) if n)- result = PdfReadResult(transcript, "vision", pages, note)+ result = PdfReadResult(transcript, "model", pages, note)_cache_put(key, result)return resultif not settings.pdf_ocr_enabled:- return _fallback(text, pages, "it looks scanned and scanned-PDF conversion is turned off")+ return _fallback(text, pages, "it looks scanned and local OCR is turned off")try:ocr, read = await asyncio.to_thread(_ocr_pdf, data, limit)except OcrUnavailable:diff --git a/packages/core/openexecutive/providers/feature_gate.py b/packages/core/openexecutive/providers/feature_gate.pyindex 693e6da7..9d6ac9cc 100644--- a/packages/core/openexecutive/providers/feature_gate.py+++ b/packages/core/openexecutive/providers/feature_gate.py@@ -18,7 +18,7 @@ from typing import Anyclass FeatureSpec:"""What a given model is allowed to receive.- All four flags default to True for Claude family; the registry's+ All flags default to True for Claude family; the registry's``MODEL_SPECS`` table flips them off for non-Claude models so amisconfigured caller can't bypass the gate."""@@ -27,6 +27,14 @@ class FeatureSpec:supports_thinking: bool = Truesupports_web_search: bool = Truesupports_tool_use: bool = True+ # Whether a PDF ``document`` block may be sent. Anthropic reads it+ # natively and OpenRouter parses one for any model; a self-hosted+ # OpenAI-compatible server usually cannot (LOCAL_PDF_INPUT says it can).+ supports_pdf_input: bool = True+++# What a PDF becomes for a model that cannot read one: said, never dropped.+PDF_OMITTED_NOTE = "[PDF omitted: this model can't read PDF files]"def apply_feature_gates(spec: FeatureSpec, kwargs: dict[str, Any]) -> dict[str, Any]:@@ -40,6 +48,7 @@ def apply_feature_gates(spec: FeatureSpec, kwargs: dict[str, Any]) -> dict[str,and spec.supports_thinkingand spec.supports_web_searchand spec.supports_tool_use+ and spec.supports_pdf_input):# Fast path: nothing to strip.return kwargs@@ -60,6 +69,9 @@ def apply_feature_gates(spec: FeatureSpec, kwargs: dict[str, Any]) -> dict[str,out.pop("tools", None)out.pop("tool_choice", None)+ if not spec.supports_pdf_input:+ _replace_documents(out)+return out@@ -117,3 +129,19 @@ def _strip_web_search_tools(kwargs: dict[str, Any]) -> None:]if not kwargs["tools"]:kwargs.pop("tools", None)+++def _replace_documents(kwargs: dict[str, Any]) -> None:+ """Swap every ``document`` block in the messages for a text note, so the+ model is told a PDF was there instead of the block vanishing in+ translation."""+ for message in kwargs.get("messages") or []:+ content = message.get("content") if isinstance(message, dict) else None+ if not isinstance(content, list):+ continue+ message["content"] = [+ {"type": "text", "text": PDF_OMITTED_NOTE}+ if isinstance(block, dict) and block.get("type") == "document"+ else block+ for block in content+ ]diff --git a/packages/core/openexecutive/providers/openai_compatible.py b/packages/core/openexecutive/providers/openai_compatible.pyindex 996b5653..807f4f78 100644--- a/packages/core/openexecutive/providers/openai_compatible.py+++ b/packages/core/openexecutive/providers/openai_compatible.py@@ -127,6 +127,7 @@ class OpenAICompatibleProvider:supports_thinking=False,supports_web_search=False,supports_tool_use=True,+ supports_pdf_input=False,),)return slug, spec@@ -142,6 +143,11 @@ class OpenAICompatibleProvider:# LLMProvider surface# ------------------------------------------------------------------+ def _extend_body(self, slug: str, body: dict[str, Any]) -> None:+ """Backend-specific request fields, added to the translated body in+ place. None for a plain OpenAI-compatible server: an unknown+ top-level field can 400 there (see include_usage_accounting)."""+def messages_create(self, **kwargs: Any) -> Awaitable[Any]:return self._messages_create(kwargs)@@ -155,6 +161,7 @@ class OpenAICompatibleProvider:body = to_openai_request(slug, gated, include_usage=self._include_usage_accounting)+ self._extend_body(slug, body)_announce_reasoning(slug, body)try:@@ -183,6 +190,7 @@ class OpenAICompatibleProvider:body = to_openai_request(slug, gated, include_usage=self._include_usage_accounting)+ self._extend_body(slug, body)_announce_reasoning(slug, body)body["stream"] = Truereturn _OpenAICompatibleStream(diff --git a/packages/core/openexecutive/providers/openrouter_catalog.py b/packages/core/openexecutive/providers/openrouter_catalog.pyindex 130c549a..d8af5e6f 100644--- a/packages/core/openexecutive/providers/openrouter_catalog.py+++ b/packages/core/openexecutive/providers/openrouter_catalog.py@@ -68,6 +68,13 @@ _loaded_models: list[str] | None = None# request field for them. Drives the Council "Deep reasoning" checkbox for# non-Claude models._loaded_reasoning: frozenset[str] = frozenset()+# Ids whose catalog entry lists "file" in ``architecture.input_modalities``:+# the model reads a PDF itself, so OpenRouter's file-parser can pass it+# through ("native") instead of OCRing it first.+_loaded_file_input: frozenset[str] = frozenset()+# Every id in the last fetched catalog (unfiltered), so ``accepts_files`` can+# tell "known, no file input" from "not in the catalog".+_known_ids: frozenset[str] = frozenset()_loaded_at: float | None = None@@ -87,6 +94,31 @@ def supports_reasoning(model_id: str) -> bool | None:return model_id in _loaded_reasoning+def accepts_files(model_id: str) -> bool | None:+ """Whether the loaded catalog says ``model_id`` reads files (PDFs)+ natively. ``None`` when no catalog is loaded or the slug isn't in it —+ the caller treats that as "unknown". Unlike ``supports_reasoning`` this+ looks at every catalog entry, not only the Council's filtered list: a+ PDF may be read by any model the operator names."""+ if _loaded_models is None:+ return None+ if model_id in _loaded_file_input:+ return True+ return False if model_id in _known_ids else None+++def file_input_ids(entries: Iterable[Mapping[str, Any]]) -> frozenset[str]:+ """Ids of catalog entries whose ``input_modalities`` list contains "file"."""+ out: set[str] = set()+ for entry in entries:+ model_id = entry.get("id")+ arch = entry.get("architecture")+ inputs = arch.get("input_modalities") if isinstance(arch, Mapping) else None+ if isinstance(model_id, str) and isinstance(inputs, list) and "file" in inputs:+ out.add(model_id)+ return frozenset(out)++def reasoning_capable_ids(entries: Iterable[Mapping[str, Any]]) -> frozenset[str]:"""Ids of catalog entries that list "reasoning" in ``supported_parameters``."""out: set[str] = set()@@ -230,7 +262,7 @@ async def refresh_openrouter_catalog(settings: Any) -> bool:Never raises: a failure logs a warning and leaves the previous cache(or the never-loaded state → registry fallback) untouched."""- global _loaded_models, _loaded_reasoning, _loaded_at+ global _loaded_models, _loaded_reasoning, _loaded_file_input, _known_ids, _loaded_attry:entries = await fetch_catalog(base_url=settings.openrouter_base_url,@@ -252,6 +284,10 @@ async def refresh_openrouter_catalog(settings: Any) -> bool:return False_loaded_models = models_loaded_reasoning = reasoning_capable_ids(entries) & frozenset(models)+ _loaded_file_input = file_input_ids(entries)+ _known_ids = frozenset(+ e["id"] for e in entries if isinstance(e, Mapping) and isinstance(e.get("id"), str)+ )_loaded_at = time.time()logger.info("OpenRouter catalog loaded: %d model(s) from %d catalog entries, "@@ -285,7 +321,9 @@ async def run_catalog_refresher(settings: Any) -> None:def _reset_for_tests() -> None:- global _loaded_models, _loaded_reasoning, _loaded_at+ global _loaded_models, _loaded_reasoning, _loaded_file_input, _known_ids, _loaded_at_loaded_models = None_loaded_reasoning = frozenset()+ _loaded_file_input = frozenset()+ _known_ids = frozenset()_loaded_at = Nonediff --git a/packages/core/openexecutive/providers/openrouter_provider.py b/packages/core/openexecutive/providers/openrouter_provider.pyindex 86e803a2..8551ed39 100644--- a/packages/core/openexecutive/providers/openrouter_provider.py+++ b/packages/core/openexecutive/providers/openrouter_provider.py@@ -12,6 +12,7 @@ for backward compatibility with existing imports.from __future__ import annotationsfrom collections.abc import Callable+from typing import Anyfrom openexecutive.providers.feature_gate import FeatureSpecfrom openexecutive.providers.openai_compatible import (@@ -19,6 +20,9 @@ from openexecutive.providers.openai_compatible import (_OpenAICompatibleStream,)+# Claude on OpenRouter reads PDFs natively, whatever the catalog says.+_CLAUDE_SLUG_PREFIX = "anthropic/claude-"+# Backward-compatible alias — the stream class is fully generic._OpenRouterStream = _OpenAICompatibleStream@@ -26,6 +30,18 @@ _OpenRouterStream = _OpenAICompatibleStreamclass OpenRouterProvider(OpenAICompatibleProvider):"""LLMProvider implementation backed by OpenRouter."""+ def _extend_body(self, slug: str, body: dict[str, Any]) -> None:+ """A request carrying a PDF (an OpenAI ``file`` part, from an+ Anthropic ``document`` block) names OpenRouter's file-parser engine:+ ``native`` for a model that reads files itself — Claude, or any the+ catalog lists with "file" input — so the PDF goes to it untouched;+ otherwise ``PDF_OPENROUTER_ENGINE`` (default ``mistral-ocr``, the+ engine for scans). A request with no file part is left byte-identical.+ """+ if not _has_file_part(body):+ return+ body["plugins"] = [{"id": "file-parser", "pdf": {"engine": _pdf_engine(slug)}}]+def __init__(self,*,@@ -61,3 +77,22 @@ class OpenRouterProvider(OpenAICompatibleProvider):# to real Anthropic that rejects the field outright.include_usage_accounting=True,)+++def _has_file_part(body: dict[str, Any]) -> bool:+ for message in body.get("messages") or []:+ content = message.get("content") if isinstance(message, dict) else None+ if isinstance(content, list) and any(+ isinstance(part, dict) and part.get("type") == "file" for part in content+ ):+ return True+ return False+++def _pdf_engine(slug: str) -> str:+ from openexecutive.config import get_settings+ from openexecutive.providers import openrouter_catalog++ if slug.startswith(_CLAUDE_SLUG_PREFIX) or openrouter_catalog.accepts_files(slug):+ return "native"+ return str(get_settings().pdf_openrouter_engine)diff --git a/packages/core/openexecutive/providers/registry.py b/packages/core/openexecutive/providers/registry.pyindex 6f64af5e..e43d546a 100644--- a/packages/core/openexecutive/providers/registry.py+++ b/packages/core/openexecutive/providers/registry.py@@ -15,6 +15,7 @@ the hardcoded ``OPENROUTER_MODELS`` snapshot when nothing has been loaded.from __future__ import annotationsimport re+from dataclasses import replacefrom typing import Any, Literal, TypedDictfrom fastapi import HTTPException@@ -394,8 +395,15 @@ def _local() -> OpenAICompatibleProvider:# Local models get the tools-only spec: no cache_control, thinking,# or web_search — a self-hosted OpenAI-compatible server has no# search tool and would 400 (or silently ignore) the rest.+ # PDFs only when the operator says the server takes them+ # (LOCAL_PDF_INPUT, e.g. OpenAI's own API); otherwise the gate+ # replaces a PDF with a note and pdf_reader OCRs it locally instead.+ local_spec = replace(+ _LOCAL_FEATURE_SPEC,+ supports_pdf_input=bool(getattr(settings, "local_pdf_input", False)),+ )spec_lookup: dict[str, FeatureSpec] = {- m: _LOCAL_FEATURE_SPEC for m in _local_models(settings)+ m: local_spec for m in _local_models(settings)}_local_provider = OpenAICompatibleProvider(base_url=base_url,@@ -476,6 +484,23 @@ def get_provider(model: str) -> LLMProvider:return _openrouter()+def pdf_input_supported(model: str) -> bool:+ """Whether a PDF ``document`` block sent to ``model`` reaches a reader.++ Mirrors ``get_provider``'s routing without building anything: a local+ slug reads PDFs only with LOCAL_PDF_INPUT; a Claude id reads them+ natively on Anthropic (when a key is set) or through OpenRouter; any+ other slug goes to OpenRouter, whose file-parser handles every model.+ False when the model has no reachable provider at all.+ """+ settings = get_settings()+ if model in _local_models(settings):+ return bool(getattr(settings, "local_pdf_input", False))+ if settings.openrouter_enabled:+ return True+ return _is_claude(model) and bool(settings.anthropic_api_key)++def _reset_for_tests() -> None:"""Drop cached provider singletons. Test-only — pytest fixtures call this."""global _anthropic_provider, _openrouter_provider, _local_providerdiff --git a/packages/core/openexecutive/providers/translator.py b/packages/core/openexecutive/providers/translator.pyindex 4195d9df..7b22a0c7 100644--- a/packages/core/openexecutive/providers/translator.py+++ b/packages/core/openexecutive/providers/translator.py@@ -96,6 +96,39 @@ def _typed_text_block(block: dict[str, Any]) -> dict[str, Any] | None:return _typed_text_with_cc(block.get("text", ""), block.get("cache_control"))+def _pdf_filename(title: Any) -> str:+ """A document's ``title`` as a safe wire filename: last path segment,+ printable, at most 100 characters, ending in ``.pdf`` (OpenRouter's+ parser keys on the extension). ``document.pdf`` when there is none."""+ if not isinstance(title, str):+ return "document.pdf"+ name = "".join(c for c in title.replace("\\", "/").rsplit("/", 1)[-1] if c.isprintable())+ name = name.strip()[:96]+ if not name:+ return "document.pdf"+ return name if name.lower().endswith(".pdf") else f"{name}.pdf"+++def _file_part(block: dict[str, Any]) -> dict[str, Any] | None:+ """An Anthropic base64 PDF ``document`` block as the OpenAI chat+ ``file`` content part, which OpenAI and OpenRouter both accept. Anything+ else (a URL or text source, another media type) is ``None``: there is no+ faithful OpenAI shape for it, and the caller drops it as before."""+ source = block.get("source")+ if not isinstance(source, dict) or source.get("type") != "base64":+ return None+ if source.get("media_type") != "application/pdf":+ return None+ data = source.get("data")+ if not isinstance(data, str) or not data:+ return None+ filename = _pdf_filename(block.get("title"))+ return {+ "type": "file",+ "file": {"filename": filename, "file_data": f"data:application/pdf;base64,{data}"},+ }++def _translate_system(system: Any) -> str | list[dict[str, Any]] | None:"""Translate an Anthropic ``system`` argument to the OpenRouter shape.@@ -209,6 +242,11 @@ def _user_content_to_openai(stays as a typed-block array so the cache hint survives translation toOpenRouter. Otherwise we flatten to a plain string — broader upstreamcompatibility for non-Anthropic routing and slightly smaller wire bytes.++ A base64 PDF ``document`` block becomes an OpenAI ``file`` part (see+ ``_file_part``) and forces the typed-array form, text and files in their+ original order. Whether the model may receive one at all is decided+ earlier, by ``feature_gate`` (``supports_pdf_input``)."""if isinstance(content, str):return [{"role": "user", "content": content}]@@ -219,6 +257,10 @@ def _user_content_to_openai(text_chunks: list[str] = [] # populated for the flat-string fallbacktool_messages: list[dict[str, Any]] = []preserve_typed = _any_block_has_cache_control(content)+ # Text and PDF parts in their original order, used only when a PDF is+ # present: a file part cannot ride in the flat-string form.+ ordered_parts: list[dict[str, Any]] = []+ has_file = Falsefor block in content:if not isinstance(block, dict):@@ -228,10 +270,16 @@ def _user_content_to_openai(txt = block.get("text", "")if isinstance(txt, str) and txt:text_chunks.append(txt)- if preserve_typed:- typed = _typed_text_block(block)- if typed is not None:- text_blocks.append(typed)+ typed = _typed_text_block(block)+ if preserve_typed and typed is not None:+ text_blocks.append(typed)+ if typed is not None:+ ordered_parts.append(typed if preserve_typed else {"type": "text", "text": txt})+ elif btype == "document":+ part = _file_part(block)+ if part is not None:+ ordered_parts.append(part)+ has_file = Trueelif btype == "tool_result":tool_use_id = block.get("tool_use_id")inner = block.get("content")@@ -261,7 +309,11 @@ def _user_content_to_openai()msgs: list[dict[str, Any]] = []- if preserve_typed and text_blocks:+ if has_file:+ # A PDF forces the typed-array form. Text keeps its cache marker when+ # the request carries one (the same projection as below).+ msgs.append({"role": "user", "content": ordered_parts})+ elif preserve_typed and text_blocks:msgs.append({"role": "user", "content": text_blocks})elif text_chunks:# Fall back to the flat-string form even when ``preserve_typed`` isdiff --git a/packages/core/tests/unit/test_pdf_reader.py b/packages/core/tests/unit/test_pdf_reader.pyindex e9ab4726..721daeaa 100644--- a/packages/core/tests/unit/test_pdf_reader.py+++ b/packages/core/tests/unit/test_pdf_reader.py@@ -1,6 +1,6 @@"""knowledge.pdf_reader — reading scanned / image-only PDFs.-The model is stubbed (no network): `_vision_provider` is patched to a fake+The model is stubbed (no network): `_model_provider` is patched to a fakewith `messages_create`. OCR runs for real in one test (skipped when RapidOCRis not installed) and is stubbed elsewhere so the rest stay fast."""@@ -17,6 +17,13 @@ from openexecutive.knowledge import pdf_readerfrom openexecutive.knowledge.pdf_reader import PdfReadResult, read_pdf_text[email protected](autouse=True)+def _provider_reading_on(monkeypatch):+ """Provider reading is opt-in (off by default); most tests here exercise+ that path, so they turn it on. The default is pinned by its own test."""+ monkeypatch.setenv("PDF_PROVIDER_READING", "true")++@pytest.fixture(autouse=True)def _fresh_cache():pdf_reader.clear_cache()@@ -116,7 +123,7 @@ class _FakeProvider:def _use_provider(monkeypatch: pytest.MonkeyPatch, provider: Any) -> None:- monkeypatch.setattr(pdf_reader, "_vision_provider", lambda model: provider)+ monkeypatch.setattr(pdf_reader, "_model_provider", lambda model: provider)def _stub_ocr(monkeypatch: pytest.MonkeyPatch, text: str = "--- page 1 ---\nOCR TEXT") -> list:@@ -164,7 +171,7 @@ async def test_scanned_pdf_is_transcribed_from_a_document_block(monkeypatch):result = await read_pdf_text(_blank_pdf(2), filename="scan.pdf")- assert result == PdfReadResult("Revenue 4.2M [1 to 2]", "vision", 2)+ assert result == PdfReadResult("Revenue 4.2M [1 to 2]", "model", 2)assert result.convertedassert ocr == [](call,) = provider.calls@@ -183,7 +190,7 @@ async def test_long_scan_is_sent_in_slices_and_joined_in_order(monkeypatch):result = await read_pdf_text(_blank_pdf(45), filename="scan.pdf")- assert result.method == "vision"+ assert result.method == "model"assert result.text == "part [1 to 20]\n\npart [21 to 40]\n\npart [41 to 45]"assert sorted(_pages_in(c) for c in provider.calls) == [5, 20, 20]@@ -195,7 +202,7 @@ async def test_pages_past_the_cap_are_skipped_with_a_note(monkeypatch):result = await read_pdf_text(_blank_pdf(25), filename="scan.pdf")- assert result.method == "vision"+ assert result.method == "model"assert result.pages == 25assert result.note == "only the first 10 of 25 pages were read"assert sum(_pages_in(c) for c in provider.calls) == 10@@ -233,25 +240,44 @@ async def test_a_failed_transcription_falls_back_to_ocr(monkeypatch, provider):assert provider.calls-def test_openrouter_and_missing_keys_get_no_vision_provider(monkeypatch):- """The OpenRouter / local translator drops `document` blocks, so only the- Anthropic-direct provider may be handed the PDF."""+def test_each_deployment_gets_its_own_pdf_reader(monkeypatch):+ """The PDF goes to whatever provider the model routes to — Anthropic,+ OpenRouter, or a local server that says it takes PDFs — and only a model+ with no way to receive one falls to local OCR."""from openexecutive.providers import registryfrom openexecutive.providers.anthropic_provider import AnthropicProvider+ from openexecutive.providers.openai_compatible import OpenAICompatibleProvider+ from openexecutive.providers.openrouter_provider import OpenRouterProviderregistry._reset_for_tests()try:- assert isinstance(pdf_reader._vision_provider("claude-sonnet-5"), AnthropicProvider)+ assert isinstance(pdf_reader._model_provider("claude-sonnet-5"), AnthropicProvider)registry._reset_for_tests()monkeypatch.setenv("OPENROUTER_ENABLED", "true")monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-test")- assert pdf_reader._vision_provider("claude-sonnet-5") is None- assert pdf_reader._vision_provider("openai/gpt-6-astra") is None+ assert isinstance(pdf_reader._model_provider("claude-sonnet-5"), OpenRouterProvider)+ assert isinstance(pdf_reader._model_provider("openai/gpt-6-astra"), OpenRouterProvider)++ registry._reset_for_tests()+ monkeypatch.setenv("LOCAL_MODELS_ENABLED", "true")+ monkeypatch.setenv("LOCAL_BASE_URL", "http://localhost:11434/v1")+ monkeypatch.setenv("LOCAL_MODELS", "llama3.3")+ assert pdf_reader._model_provider("llama3.3") is None+ monkeypatch.setenv("LOCAL_PDF_INPUT", "true")+ assert isinstance(pdf_reader._model_provider("llama3.3"), OpenAICompatibleProvider)finally:registry._reset_for_tests()+def test_the_pdf_model_defaults_to_the_deployments_model(monkeypatch):+ monkeypatch.delenv("PDF_VISION_MODEL", raising=False)+ monkeypatch.setenv("DEFAULT_MODEL", "openai/gpt-6-astra")+ assert pdf_reader._pdf_model() == "openai/gpt-6-astra"+ monkeypatch.setenv("PDF_VISION_MODEL", "claude-haiku-4-5")+ assert pdf_reader._pdf_model() == "claude-haiku-4-5"++async def test_ocr_not_installed_says_so(monkeypatch):_use_provider(monkeypatch, None)@@ -311,7 +337,7 @@ async def test_an_unreadable_result_is_not_cached(monkeypatch):assert (await read_pdf_text(data)).method == "none"_use_provider(monkeypatch, _FakeProvider())- assert (await read_pdf_text(data)).method == "vision"+ assert (await read_pdf_text(data)).method == "model"# ── Real OCR ─────────────────────────────────────────────────────────────────@@ -433,7 +459,7 @@ async def test_a_cut_off_slice_is_split_until_each_part_fits(monkeypatch):result = await read_pdf_text(_blank_pdf(20), filename="dense.pdf")- assert result.method == "vision"+ assert result.method == "model"assert result.note == ""assert result.text == ("part [1 to 5]\n\npart [6 to 10]\n\npart [11 to 15]\n\npart [16 to 20]"@@ -448,9 +474,55 @@ async def test_a_single_page_that_never_fits_is_kept_and_flagged(monkeypatch):result = await read_pdf_text(_blank_pdf(2), filename="dense.pdf")- assert result.method == "vision"+ assert result.method == "model"assert result.text == ("dense page [1 to 1]\n[transcription cut off here]\n\n""dense page [2 to 2]\n[transcription cut off here]")assert result.note == "some pages' transcription was cut off"+++# ── Keeping scanned PDFs on the server ───────────────────────────────────────+++async def test_provider_reading_off_keeps_scans_on_this_server(monkeypatch):+ monkeypatch.setenv("PDF_PROVIDER_READING", "false")+ provider = _FakeProvider()+ _use_provider(monkeypatch, provider)+ ocr = _stub_ocr(monkeypatch)++ result = await read_pdf_text(_blank_pdf(2), filename="scan.pdf")++ assert result.method == "ocr"+ assert provider.calls == []+ assert ocr == [2]+++async def test_provider_reading_is_off_by_default(monkeypatch):+ """An upgrade must not start sending scanned PDFs off the server."""+ monkeypatch.delenv("PDF_PROVIDER_READING", raising=False)+ provider = _FakeProvider()+ _use_provider(monkeypatch, provider)+ ocr = _stub_ocr(monkeypatch)++ result = await read_pdf_text(_blank_pdf(2), filename="scan.pdf")++ assert result.method == "ocr"+ assert provider.calls == []+ assert ocr == [2]+++async def test_where_scans_go_is_logged_once(monkeypatch):+ from unittest.mock import MagicMock++ monkeypatch.setattr(pdf_reader, "_announced", set())+ log = MagicMock()+ monkeypatch.setattr(pdf_reader, "logger", log)+ _use_provider(monkeypatch, _FakeProvider())++ await read_pdf_text(_blank_pdf(1), filename="a.pdf")+ await read_pdf_text(_blank_pdf(2), filename="b.pdf")++ lines = [c.args[0] % c.args[1:] for c in log.info.call_args_list]+ assert len([line for line in lines if "scanned PDFs are sent to" in line]) == 1+ assert "PDF_PROVIDER_READING is on" in lines[0]diff --git a/packages/core/tests/unit/test_provider_pdf_input.py b/packages/core/tests/unit/test_provider_pdf_input.pynew file mode 100644index 00000000..c3a2d759--- /dev/null+++ b/packages/core/tests/unit/test_provider_pdf_input.py@@ -0,0 +1,280 @@+"""PDFs through each provider's own file support.++An Anthropic ``document`` block is what ``knowledge.pdf_reader`` sends. On+the OpenAI-format path it used to vanish in translation; it now becomes an+OpenAI ``file`` part, OpenRouter adds its ``file-parser`` plugin, and a model+that cannot take a PDF gets a note in its place instead of silence.+"""+from __future__ import annotations++import asyncio+from typing import Any+from unittest.mock import AsyncMock, MagicMock++import httpx+import pytest++from openexecutive.providers import openrouter_catalog as catalog+from openexecutive.providers import registry+from openexecutive.providers.feature_gate import (+ PDF_OMITTED_NOTE,+ FeatureSpec,+ apply_feature_gates,+)+from openexecutive.providers.openai_compatible import OpenAICompatibleProvider+from openexecutive.providers.openrouter_provider import OpenRouterProvider+from openexecutive.providers.translator import to_openai_request++_PDF = {+ "type": "document",+ "source": {"type": "base64", "media_type": "application/pdf", "data": "JVBERi0x"},+}++[email protected](autouse=True)+def _reset() -> Any:+ catalog._reset_for_tests()+ registry._reset_for_tests()+ yield+ catalog._reset_for_tests()+ registry._reset_for_tests()+++def _user(*blocks: dict[str, Any]) -> dict[str, Any]:+ return {"model": "x", "max_tokens": 8, "messages": [{"role": "user", "content": list(blocks)}]}+++# ── Translator ───────────────────────────────────────────────────────────────+++def test_a_pdf_becomes_an_openai_file_part_in_order() -> None:+ body = to_openai_request(+ "openai/gpt-6",+ _user({"type": "text", "text": "Before"}, dict(_PDF, title="deck.pdf"),+ {"type": "text", "text": "Transcribe it."}),+ )++ assert body["messages"] == [{+ "role": "user",+ "content": [+ {"type": "text", "text": "Before"},+ {"type": "file", "file": {+ "filename": "deck.pdf", "file_data": "data:application/pdf;base64,JVBERi0x",+ }},+ {"type": "text", "text": "Transcribe it."},+ ],+ }]+++def test_without_a_pdf_the_user_turn_is_unchanged() -> None:+ body = to_openai_request("openai/gpt-6", _user({"type": "text", "text": "hi"}))++ assert body["messages"] == [{"role": "user", "content": "hi"}]+++def test_a_cache_marker_survives_next_to_a_pdf() -> None:+ cc = {"type": "ephemeral"}+ body = to_openai_request(+ "anthropic/claude-sonnet-5", _user(_PDF, {"type": "text", "text": "q", "cache_control": cc}),+ )++ content = body["messages"][0]["content"]+ assert content[0]["type"] == "file"+ assert content[1] == {"type": "text", "text": "q", "cache_control": cc}+++ "source",+ [+ {"type": "url", "url": "https://example.com/a.pdf"},+ {"type": "base64", "media_type": "text/plain", "data": "aGk="},+ ],+ ids=["url-source", "not-a-pdf"],+)+def test_a_document_with_no_faithful_openai_shape_is_left_out(source: dict[str, Any]) -> None:+ body = to_openai_request(+ "openai/gpt-6", _user({"type": "document", "source": source}, {"type": "text", "text": "q"}),+ )++ assert body["messages"] == [{"role": "user", "content": "q"}]+++# ── Feature gate ─────────────────────────────────────────────────────────────+++def test_a_model_without_pdf_input_is_told_a_pdf_was_there() -> None:+ kwargs = _user(_PDF, {"type": "text", "text": "q"})++ out = apply_feature_gates(FeatureSpec(supports_pdf_input=False), kwargs)++ assert out["messages"][0]["content"] == [+ {"type": "text", "text": PDF_OMITTED_NOTE},+ {"type": "text", "text": "q"},+ ]+ assert kwargs["messages"][0]["content"][0] is _PDF # the caller's dict is untouched+++# ── OpenRouter's file-parser plugin ──────────────────────────────────────────+++def _ok() -> MagicMock:+ fake = MagicMock()+ fake.json.return_value = {+ "id": "x",+ "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],+ }+ fake.raise_for_status = MagicMock()+ return fake+++def _sent_body(provider: OpenAICompatibleProvider, model: str, kwargs: dict[str, Any]) -> dict:+ captured: dict[str, Any] = {}++ async def fake_post(url: str, **post_kwargs: Any) -> Any:+ captured.update(post_kwargs.get("json", {}))+ return _ok()++ provider._client.post = AsyncMock(side_effect=fake_post) # type: ignore[method-assign]+ asyncio.run(provider.messages_create(**dict(kwargs, model=model)))+ return captured+++def _openrouter() -> OpenRouterProvider:+ return OpenRouterProvider(+ api_key="sk-or-test", model_resolver=registry._openrouter_model_resolver+ )+++def test_claude_on_openrouter_reads_the_pdf_natively() -> None:+ body = _sent_body(_openrouter(), "claude-sonnet-5", _user(_PDF))++ assert body["plugins"] == [{"id": "file-parser", "pdf": {"engine": "native"}}]+ assert body["messages"][-1]["content"][0]["type"] == "file"+++def test_a_catalog_file_model_reads_natively_and_others_get_the_parser(monkeypatch) -> None:+ monkeypatch.setattr(catalog, "_loaded_models", ["openai/gpt-6", "meta-llama/llama-4-scout"])+ monkeypatch.setattr(catalog, "_loaded_file_input", frozenset({"openai/gpt-6"}))+ monkeypatch.setattr(catalog, "_known_ids", frozenset({"openai/gpt-6", "meta-llama/llama-4-scout"}))++ native = _sent_body(_openrouter(), "openai/gpt-6", _user(_PDF))+ parsed = _sent_body(_openrouter(), "meta-llama/llama-4-scout", _user(_PDF))+ monkeypatch.setenv("PDF_OPENROUTER_ENGINE", "cloudflare-ai")+ configured = _sent_body(_openrouter(), "meta-llama/llama-4-scout", _user(_PDF))++ assert native["plugins"][0]["pdf"]["engine"] == "native"+ assert parsed["plugins"][0]["pdf"]["engine"] == "mistral-ocr"+ assert configured["plugins"][0]["pdf"]["engine"] == "cloudflare-ai"+++def test_no_plugin_without_a_pdf_or_on_a_local_server() -> None:+ plain = _sent_body(_openrouter(), "openai/gpt-6", _user({"type": "text", "text": "hi"}))+ local = OpenAICompatibleProvider(+ base_url="http://localhost:11434/v1",+ spec_lookup={"llama3.3": FeatureSpec(supports_pdf_input=True)},+ )+ local_body = _sent_body(local, "llama3.3", _user(_PDF))++ assert "plugins" not in plain+ assert "plugins" not in local_body+ assert local_body["messages"][-1]["content"][0]["type"] == "file"+++# ── Catalog ──────────────────────────────────────────────────────────────────+++async def test_the_catalog_records_which_models_take_files(monkeypatch) -> None:+ def entry(model_id: str, inputs: list[str]) -> dict[str, Any]:+ return {+ "id": model_id,+ "created": 1,+ "supported_parameters": ["tools"],+ "pricing": {"prompt": "0.000001", "completion": "0.000002"},+ "architecture": {"input_modalities": inputs, "output_modalities": ["text"]},+ }++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"data": [+ entry("openai/gpt-6", ["text", "image", "file"]),+ entry("meta-llama/llama-4-scout", ["text"]),+ ]})++ real = catalog.httpx.AsyncClient++ def factory(**kwargs: Any) -> httpx.AsyncClient:+ kwargs["transport"] = httpx.MockTransport(handler)+ return real(**kwargs)++ monkeypatch.setattr(catalog.httpx, "AsyncClient", factory)+ settings = MagicMock(+ openrouter_base_url="https://openrouter.example/api/v1",+ openrouter_catalog_timeout_s=5.0,+ openrouter_catalog_providers=frozenset({"openai", "meta-llama"}),+ openrouter_catalog_per_provider=5,+ )++ assert catalog.accepts_files("openai/gpt-6") is None # nothing loaded yet+ assert await catalog.refresh_openrouter_catalog(settings) is True+ assert catalog.accepts_files("openai/gpt-6") is True+ assert catalog.accepts_files("meta-llama/llama-4-scout") is False+ assert catalog.accepts_files("unknown/model") is None+++# ── Registry ─────────────────────────────────────────────────────────────────+++def test_pdf_input_follows_the_route(monkeypatch) -> None:+ assert registry.pdf_input_supported("claude-sonnet-5") is True # Anthropic direct++ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)+ monkeypatch.setenv("OPENROUTER_ENABLED", "true")+ monkeypatch.setenv("OPENROUTER_API_KEY", "sk-or-test")+ assert registry.pdf_input_supported("claude-sonnet-5") is True # via OpenRouter+ assert registry.pdf_input_supported("openai/gpt-6") is True++ monkeypatch.setenv("OPENROUTER_ENABLED", "false")+ monkeypatch.setenv("LOCAL_MODELS_ENABLED", "true")+ monkeypatch.setenv("LOCAL_BASE_URL", "http://localhost:11434/v1")+ monkeypatch.setenv("LOCAL_MODELS", "llama3.3")+ assert registry.pdf_input_supported("llama3.3") is False+ assert registry.pdf_input_supported("claude-sonnet-5") is False # no key, no OpenRouter+ monkeypatch.setenv("LOCAL_PDF_INPUT", "true")+ assert registry.pdf_input_supported("llama3.3") is True+++def test_a_local_server_without_pdf_input_gets_the_note(monkeypatch) -> None:+ monkeypatch.setenv("LOCAL_MODELS_ENABLED", "true")+ monkeypatch.setenv("LOCAL_BASE_URL", "http://localhost:11434/v1")+ monkeypatch.setenv("LOCAL_MODELS", "llama3.3")++ body = _sent_body(registry.get_provider("llama3.3"), "llama3.3", _user(_PDF))++ assert body["messages"][-1]["content"] == PDF_OMITTED_NOTE+++ ("title", "filename"),+ [+ (None, "document.pdf"),+ ("deck.pdf", "deck.pdf"),+ ("../../etc/passwd", "passwd.pdf"),+ ("C:\\Users\\x\\Board Deck.PDF", "Board Deck.PDF"),+ ("a\nb" + "x" * 300, ("ab" + "x" * 94) + ".pdf"),+ (" ", "document.pdf"),+ ],+)+def test_the_wire_filename_is_a_safe_pdf_name(title: Any, filename: str) -> None:+ block = dict(_PDF, title=title) if title is not None else _PDF+ body = to_openai_request("openai/gpt-6", _user(block))++ assert body["messages"][0]["content"][0]["file"]["filename"] == filename+++def test_an_unknown_slug_on_a_bare_server_gets_the_note_not_the_pdf() -> None:+ """The fallback spec for a slug no lookup covers assumes the least,+ PDF input included."""+ bare = OpenAICompatibleProvider(base_url="http://localhost:8000/v1")++ body = _sent_body(bare, "some-unlisted-model", _user(_PDF))++ assert body["messages"][-1]["content"] == PDF_OMITTED_NOTE