AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
chore(deps): bump workspace-mcp to 2.1.0 (#529)
Rufuse97ca0577cb0
diff --git a/docker/Dockerfile b/docker/Dockerfileindex 9ceec8e6..c387dbf7 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -129,7 +129,7 @@ RUN uv pip install --system "fastembed==0.8.1" \# Google Workspace MCP server, run co-located as a stdio child of the MCP gateway# (see docker/workspace-mcp-launch.sh + packages/core/mcp_servers.json.example).# Installed into its OWN venv — NOT the system env — so its deps (fastmcp etc.)-# can't collide with the API's. Pinned to 1.29.0: it has the+# can't collide with the API's. Pinned to 2.1.0: it has the# `--tool-tier {core,extended,complete}` flag the launcher uses (1.3.0 did NOT —# it only had `--tools`, so `--tool-tier complete` errored and the child died),# and its fastmcp (4.x) works with modern pydantic (no pin needed).@@ -140,7 +140,7 @@ RUN uv pip install --system "fastembed==0.8.1" \# gateway's egress gates key on (_GATED_GMAIL_TOOLS / _GATED_CALENDAR_TOOLS /# Drive share gate in orchestrator/mcp_gateway.py). Bump together with those gates.RUN uv venv /opt/workspace-mcp \- && uv pip install --python /opt/workspace-mcp/bin/python "workspace-mcp==1.29.0" \+ && uv pip install --python /opt/workspace-mcp/bin/python "workspace-mcp==2.1.0" \&& /opt/workspace-mcp/bin/workspace-mcp --tool-tier complete --help >/dev/null 2>&1COPY docker/workspace-mcp-launch.sh /usr/local/bin/workspace-mcp-launch.shRUN chmod +x /usr/local/bin/workspace-mcp-launch.shdiff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex d3fc563d..96eecf82 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -8335,7 +8335,7 @@ integrations:and block 0 carries a Connected Systems section built from them(prompts/connected_systems.render_connected_systems) with the Google toolnames pinned by service (GOOGLE_TOOL_MANIFEST, checked against- workspace-mcp 1.29.0 — re-check on a bump). extensible-mcp's+ workspace-mcp 2.1.0 — re-check on a bump). extensible-mcp'sDiscoveredToolsFilter runs only tools one of the session's searchesreturned and keeps them for the session's life, so the lifespan runsMCPGateway.prime_pinned_tools() once in the background when@@ -8373,7 +8373,7 @@ integrations:single-tenant model (one install = one company = one exec Google account), sothe server is inherently one-per-install; co-locating means a new install needsonly the API+UI apps. workspace-mcp is baked into the API image in its own- venv (docker/Dockerfile: `uv pip install workspace-mcp==1.29.0` at /opt/+ venv (docker/Dockerfile: `uv pip install workspace-mcp==2.1.0` at /opt/workspace-mcp — it has the --tool-tier flag and a fastmcp that workswith modern pydantic) and launched bydocker/workspace-mcp-launch.sh, referenced as the `command` of thediff --git a/packages/core/openexecutive/architecture/prebuilt/caching.json b/packages/core/openexecutive/architecture/prebuilt/caching.jsonindex 44bd0e95..a2a46244 100644--- a/packages/core/openexecutive/architecture/prebuilt/caching.json+++ b/packages/core/openexecutive/architecture/prebuilt/caching.json@@ -1,7 +1,7 @@{"section_id": "caching","title": "Prompt Caching",- "markdown": "The Executive system prompt is partitioned for Anthropic prompt caching by `openexecutive.prompts.cache_manager.build_system_blocks`. It emits at most two `cache_control` blocks, consolidated down from four to stay within Anthropic's 4-block API limit alongside the tool definitions and the agent loop's intra-turn marker.\n\n- **Block 0 — persona + knowledge (1h TTL, always present):** the executive persona constant — `EXECUTIVE_PERSONA_PROMPT` for a team, `EXECUTIVE_PERSONA_SOLO_PROMPT` in solo mode — or an admin override, which wins as-is in either mode, with the `{VOICE_PERSONA}` substitution, then the admin's Council **additional instructions** for the Executive (`persona_instructions`, wrapped in `<additional_instructions>`; blank leaves the block byte-identical, and like the override it changes only on save), conditional `WEB_SEARCH_ADDENDUM` / `MCP_ADDENDUM`, the constant `TOOL_BUILDING_ADDENDUM` (when to build a tool with `run_script`, check `list_saved_tools` first, keep what will be needed again, and talk about it without saying \"script\"; present with a gateway unless `CHAT_SCRIPTS=false`, a setting, so constant per deployment), the identity addendum (exec name/email, impersonation guard), the *Connected Systems* section (whose Google part is derived from `WORKSPACE_MCP_TOOLS` and `WORKSPACE_MCP_TOOL_TIER` — process-constant settings, so it is as cacheable as the rest), the constant `DELEGATION_ADDENDUM` while anyone on the install has Act as me on, the timezone addendum, and `KNOWLEDGE_INDEX_SUMMARY`. The timezone addendum names the user's zone, read fresh on every build from the workspace settings (`memory.workspace_settings.get_user_timezone`: the workspace's zone, else `USER_TIMEZONE`, else UTC). Every component is a constant or changes only when an admin or the user changes a setting, so the TTL is long. Setting a new time zone changes the addendum, so the 1h block misses once on that change and is warm again from the next turn — accepted, since a stale zone would mis-schedule follow-ups. Act as me works the same way: its addendum is keyed on the install-level setting (`delegation.settings.block0_delegation_on`), never on the turn or the speaker, so switching it on or off misses the 1h block once; off, block 0 is byte-identical to an install without the feature.\n The *Connected Systems* section (`prompts.connected_systems.render_connected_systems`) tells the model what is connected so it never has to discover it: Google Workspace on or off (on only when `google_workspace` is among the servers the running gateway started with, `MCPGateway.server_names`, so a gateway that failed to start never reads as connected; and *needs reconnecting* instead of connected while the server is in `MCPGateway.needs_reconnect` — set when a Google tool answers with an authorization failure such as `invalid_grant` (`mcp_gateway.grant_failure`), cleared by the next answer that is not one or by `mark_reconnected` — so the model stops promising mail it cannot read; the set changing re-renders block 0 and costs one cache miss), and when on, how to act from its own account plus the pinned Google tool names by service (`GOOGLE_TOOL_MANIFEST`: Gmail, Calendar, Drive, Docs, Sheets, as workspace-mcp 1.29.0 names them) to call directly; any other configured MCP servers by name (`_comment` keys skipped); Slack / Discord / Telegram / Google Chat on or off from their settings (names only, never a token); Notion knowledge sync; a Confluence knowledge sync line only when that sync is on (a setting, so constant per deployment); and one constant Act as me line that points at `DELEGATION_ADDENDUM`, so switching Act as me still changes block 0 by that addendum alone. The \"never ask which address to send from\" guidance lives here now, shown only while Google is connected; the identity addendum keeps the name, address and impersonation guard. Every input is fixed per process and the output is sorted, so block 0 stays warm; it is appended even under a persona override. It replaces what the model used to learn from `search_tools`, an uncached proxy whose results were gone by the next turn.\n- **Block 1 — company + org (5m TTL, only if non-empty):** `company_profile.to_prompt_block()` plus `render_org_block(mode=…)` — for a team: departments, heads, principals, charters and the People roster; in solo: the principal's own line, their role lines when set (a static lead-in marking the role private to the principal, then kind in plain words, title, reports to, remit, measured on — from the role pinned for the turn: the workspace settings, or a session's `principal_role` override), and their goals grouped by area. The role is set once per install and changes only when the principal edits it, so it is as stable as the rest of the block. Shorter TTL so org edits propagate quickly. The principal's contacts are private to them, so `build_system_blocks(include_contacts=...)` adds the `## Contacts` section, after the team or solo block, only on the principal's own verified turn (`executive._contacts_in_prompt`). That gives block 1 exactly two stable variants per mode — with and without contacts — and never anything per-request; every other turn's block is byte-identical to an install with no contacts.\n\n## Solo mode: one prefix per mode\n\nSolo mode — one person using Open Executive for themselves — changes three cached parts, all resolved **once per turn** by `pin_turn_workspace_mode(session)` (the session's override, else the workspace setting) so they always agree: the block-0 persona, the block-1 org block, and the tool list, which drops `send_company_broadcast`, `send_department_message` and `set_department_head` *before* the sort, so it stays sorted and keeps its 1h marker on the last tool. The resolved mode is pinned on the session for the rest of the turn, so the tool handlers use it too and a switch made mid-turn applies from the next turn. Every part is a constant or stable per install, so each mode keeps its own warm cache and switching modes misses once.\n\nThe two personas share most of their text. `prompts/executive_persona.py` holds plain string literals — a shared head, body and tail plus team or solo sections — concatenated at import and never formatted, so both prompts are constants. The team prompt is byte-for-byte what it was before the split; a test pins its sha256.\n\nTool schemas are static: nothing in a definition depends on company data — `create_goal` takes its area as free text rather than an enum of the current departments, which would change the cached tool prefix every time an area was added, and `record_decision_outcome` takes a plain decision id. The solo persona is still one constant: its goal and decision-outcome lines (`_SOLO_CREATE_GOAL`, `_SOLO_DECISION_OUTCOME`) are literals concatenated at import, and the team persona is byte-identical (a test pins its sha256). The scheduler's proactive-trigger run (a Session marked `unattended`) is sent the list without `schedule_tools.UNATTENDED_WITHHELD_TOOLS`, so it has a stable tool prefix of its own, as each mode does. So does a turn private to the principal (`Session.private_to_principal`: mail from one of their contacts, or mail they forwarded): it is sent the list without `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, dropped before the sort, so private turns in a mode share one sorted prefix with its marker on the last tool. Act as me adds tools rather than dropping any: on a turn `delegation.settings.pin_turn_delegation` offered it to (the principal's own verified, attended turn in a private conversation, with it on), `ghostwrite_email`, the mailbox and calendar reads (`search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply`, `my_email_read_before`, `my_calendar`, and `save_my_email_attachment`, which copies a file out of it), `remind_me` and `propose_actions` join the pool together before the sort, so those turns share one more sorted prefix and every other turn's list is byte-identical to before. The offer never depends on the Gmail connection, so a lapsed token never flips the prefix. `recall_history` (Always in the loop) joins the same way, before the sort, on a turn whose speaker may read their own notes; its offer reads only their switch and the surface, never the notes themselves. The chat note-taker runs after the turn, outside the cached prompt. Tool definitions are sorted by name so their serialized order is stable across requests; the `web_search` server tool is appended after the sorted list so it never receives a `cache_control` marker. The last client tool carries the third marker (1h TTL).\n\n## Tools opened on demand\n\nThe less common tools are not in the list at all. `orchestrator.tool_groups` puts them in named groups — calendar, people, goals, watch_and_alerts, workflows, documents, messaging, skills — and `tool_groups.split` takes them out of the turn's offered tools after every filter above (mode, unattended, private turn) and before the sort, adding two small tools in their place: `open_tools(group)`, whose description names each offered group and its tools, and `use_tool(name, input)`. When the model opens a group, the loop answers with that group's tools (name, description, input schema) as a **tool result**. It never adds them to the list: the list is the start of the cached prefix, so a list that grew mid-turn would miss the cache for the tools, both system blocks and the whole history. The list is the same on every call of every turn, and a group's descriptions are paid for only on a turn that opens it. That took the direct list from about 19,500 tokens to about 6,500, re-sent on every model call.\n\n`open_tools`'s description and its results name only the tools the turn offers (`tool_groups.open_tools_tool`), so a private turn never sees a withheld tool's name. The description depends only on that set, which is fixed for each kind of turn, so each still has one stable list. A `use_tool` call is rewritten into the tool's own call, same id, before dispatch (`tool_groups.unwrap`); the model's assistant block stays as it was sent, so the result pairs with the id it used. The rewritten call meets the same guards, handler, progress events and audit rows as a direct call. `use_tool` takes only names in `tool_groups.DEFERRED`; anything else, or an input that is not an object, gets an error tool result. The everyday tools (`consult_specialist`, `propose_form_values`, people and memory lookups, follow-ups, the MCP meta-tools) stay direct.\n\n## The intra-turn marker\n\nThe fourth and final breakpoint belongs to the tool-use loop. After each iteration appends its `tool_result` blocks, `executive._apply_loop_cache_marker` moves a single ephemeral marker onto the **newest non-empty tool result**. Without it the loop caches only the static tools+system prefix, so every iteration re-sends the whole accumulated transcript at full input price — the runtime signature is `cache_read_input_tokens` pinned flat while the prompt grows iteration over iteration.\n\nThe marker **moves rather than accumulates**: each pass first sweeps every `tool_result` clean, then re-marks the newest one. A marker left in place per iteration would reach `max_iterations` breakpoints and blow the 4-block limit. Sweeping first also makes the helper idempotent — there is no bookkeeping index to drift.\n\nOn the loop's **first call** there is no tool result yet, so the same slot marks the **message being answered** instead (`executive._mark_turn_message`, 5m): the question plus this turn's context (facts, memory, knowledge excerpts). Without it the first call sends that context uncached and the second call writes the same tokens to the cache, so it is paid twice; with it the first call writes it once and later calls read it back. The marker sits on a copy of the message, never the caller's dict, and comes off (`_clear_turn_marker`) as soon as the loop marker lands on a tool result, so a request never carries both.\n\n## The history marker\n\nOnce a conversation has history, the agent loop also marks the **newest non-empty history turn** (normally the previous reply) with a **1h** breakpoint (`executive._apply_history_cache_marker`), so the next message reads the whole conversation back from cache and writes only what is new: the last exchange, this turn's context and its tool calls. History turns are rebuilt from plain text, so the previous turn's loop entries, which ended inside that turn's retrieved context and tool results, never match; without this marker every message re-wrote the whole conversation into the cache. 1h because people reply in minutes, not seconds.\n\nThe history marker takes the company block's slot: block 1 stays in the prefix, covered by the history marker, and dropping its 5m marker keeps the TTLs in the order the API requires, longer before shorter. On a first message (no history) block 1 keeps its 5m marker as before. `_build_messages` itself never marks history, so the committee revision call, which reuses those messages, keeps the plain layout. `Session.get_recent_history` moves its window's start in steps of 10 turns (keeping 20 to 30), so a long conversation's first history message, and the cached prefix with it, stays put between steps instead of shifting every turn. On the OpenRouter path the translator keeps assistant turns as typed text parts whenever a request carries the history marker (`translator._request_caches_assistant_text`), so the marker reaches Anthropic and every reply has the same shape whether or not it is the one marked. A rolling marker on every history turn used to claim a latent fifth breakpoint, which Anthropic rejects outright.\n\n**The breakpoint budget, in full:** last client tool (1h) + persona+knowledge (1h) + company+org (5m, first message only) or history (1h) + the turn's message on the first call, then the newest tool result (5m) = at most 4, longer TTLs first.\n\nRAG context is **never** placed in a cached system block — retrieved hits vary per query and would poison the cache. It is injected into the **user turn** instead. The chat surfaces (web chat, Telegram, Discord, Google Chat) cap it at `KNOWLEDGE_CHAT_MAX_CHARS` (default 6,000 characters, 0 = no cap): `retriever._fit_to_budget` keeps the closest chunks across every collection until the cap, because each excerpt is re-sent on every call of the turn.\n\nSpecialist calls follow the same rule. Each specialist caches only its static domain prompt (`BaseAgent.analyze`, one ephemeral block); everything per call — retrieved knowledge, failure cases, past decisions, department memory, the company's stage (`<company_stage>`) and, in solo mode, the principal's role (`<principal_role>`) — goes in the specialist's user turn, so the cached domain prompt is byte-identical across companies and profile edits.\n\nThe ghostwriter's call (Act as me) carries no cache markers: its system prompt is the constant `GHOSTWRITER_PROMPT` plus that person's voice block — short, and sent only when a draft is written — and the thread and the intent go in its user turn.\n\n## Tool-result bound\n\n`TOOL_RESULT_MAX_CHARS` (default 20,000 characters, about 5,000 tokens) caps a single tool result before it enters the prompt, applied at the one point every result reaches the model rather than at each producer — so it also covers specialist output, tool errors and the unknown-tool fallback, while non-model consumers (the `propose_form_values` JSON parse, the audit trail) still read the full text. A turn's results also share one reading budget, `TOOL_RESULTS_TURN_MAX_CHARS` (default 40,000 characters; 0 turns it off): once the turn's results reach it, each further result shows its first 3,000 characters and its marker says, in place of the advice to ask again more narrowly (that re-read would be cut too), that the question has read as much as it can, so the model answers from what it has and says what it could not read, and it never edits or rewrites anything from that cut result, so a partial read never becomes a lossy write. The read it needs to edit may be the one that was cut, so each question gets one full re-read (`executive._TurnReadingBudget`): repeating a cut call with exactly the same input is answered with the result the turn already has, under the per-result cap, and the marker says so while that re-read is left. The tool never runs again, because the budget cuts any tool's result and a repeated write would happen twice. After it is used, the marker says to offer the edit as its own request, which starts with a fresh budget. A turn therefore reads at most the budget plus one more result (`executive._turn_result_limit`). A specialist's answer is the analysis itself, not a read, so it neither counts nor is cut. A built tool's (`run_script`) result counts but is never cut below the per-result cap: it lists the writes that already ran, and a short cut would hide some and get them repeated. Tool discovery (`open_tools`, `search_tools`) is treated the same way, since its result is the schema the next call needs. The per-result cap is a circuit breaker, not a routine clipper: ordinary tool output (a status, an email thread, a specialist's analysis) stays under it. A long document read does not, and the marker asks for a narrower request, such as a page range or a section, because a result stays in the prompt for every remaining call of the turn. A cut result carries an explicit marker naming the tool and stating that the result is incomplete — truncating silently is worse than not truncating, because the model reads the cut text as the whole answer.\n\n**The invariant:** never put dynamic content in a `cache_control` block. A single mutating value breaks the cache and drives roughly a 10x cost increase.",+ "markdown": "The Executive system prompt is partitioned for Anthropic prompt caching by `openexecutive.prompts.cache_manager.build_system_blocks`. It emits at most two `cache_control` blocks, consolidated down from four to stay within Anthropic's 4-block API limit alongside the tool definitions and the agent loop's intra-turn marker.\n\n- **Block 0 — persona + knowledge (1h TTL, always present):** the executive persona constant — `EXECUTIVE_PERSONA_PROMPT` for a team, `EXECUTIVE_PERSONA_SOLO_PROMPT` in solo mode — or an admin override, which wins as-is in either mode, with the `{VOICE_PERSONA}` substitution, then the admin's Council **additional instructions** for the Executive (`persona_instructions`, wrapped in `<additional_instructions>`; blank leaves the block byte-identical, and like the override it changes only on save), conditional `WEB_SEARCH_ADDENDUM` / `MCP_ADDENDUM`, the constant `TOOL_BUILDING_ADDENDUM` (when to build a tool with `run_script`, check `list_saved_tools` first, keep what will be needed again, and talk about it without saying \"script\"; present with a gateway unless `CHAT_SCRIPTS=false`, a setting, so constant per deployment), the identity addendum (exec name/email, impersonation guard), the *Connected Systems* section (whose Google part is derived from `WORKSPACE_MCP_TOOLS` and `WORKSPACE_MCP_TOOL_TIER` — process-constant settings, so it is as cacheable as the rest), the constant `DELEGATION_ADDENDUM` while anyone on the install has Act as me on, the timezone addendum, and `KNOWLEDGE_INDEX_SUMMARY`. The timezone addendum names the user's zone, read fresh on every build from the workspace settings (`memory.workspace_settings.get_user_timezone`: the workspace's zone, else `USER_TIMEZONE`, else UTC). Every component is a constant or changes only when an admin or the user changes a setting, so the TTL is long. Setting a new time zone changes the addendum, so the 1h block misses once on that change and is warm again from the next turn — accepted, since a stale zone would mis-schedule follow-ups. Act as me works the same way: its addendum is keyed on the install-level setting (`delegation.settings.block0_delegation_on`), never on the turn or the speaker, so switching it on or off misses the 1h block once; off, block 0 is byte-identical to an install without the feature.\n The *Connected Systems* section (`prompts.connected_systems.render_connected_systems`) tells the model what is connected so it never has to discover it: Google Workspace on or off (on only when `google_workspace` is among the servers the running gateway started with, `MCPGateway.server_names`, so a gateway that failed to start never reads as connected; and *needs reconnecting* instead of connected while the server is in `MCPGateway.needs_reconnect` — set when a Google tool answers with an authorization failure such as `invalid_grant` (`mcp_gateway.grant_failure`), cleared by the next answer that is not one or by `mark_reconnected` — so the model stops promising mail it cannot read; the set changing re-renders block 0 and costs one cache miss), and when on, how to act from its own account plus the pinned Google tool names by service (`GOOGLE_TOOL_MANIFEST`: Gmail, Calendar, Drive, Docs, Sheets, as workspace-mcp 2.1.0 names them) to call directly; any other configured MCP servers by name (`_comment` keys skipped); Slack / Discord / Telegram / Google Chat on or off from their settings (names only, never a token); Notion knowledge sync; a Confluence knowledge sync line only when that sync is on (a setting, so constant per deployment); and one constant Act as me line that points at `DELEGATION_ADDENDUM`, so switching Act as me still changes block 0 by that addendum alone. The \"never ask which address to send from\" guidance lives here now, shown only while Google is connected; the identity addendum keeps the name, address and impersonation guard. Every input is fixed per process and the output is sorted, so block 0 stays warm; it is appended even under a persona override. It replaces what the model used to learn from `search_tools`, an uncached proxy whose results were gone by the next turn.\n- **Block 1 — company + org (5m TTL, only if non-empty):** `company_profile.to_prompt_block()` plus `render_org_block(mode=…)` — for a team: departments, heads, principals, charters and the People roster; in solo: the principal's own line, their role lines when set (a static lead-in marking the role private to the principal, then kind in plain words, title, reports to, remit, measured on — from the role pinned for the turn: the workspace settings, or a session's `principal_role` override), and their goals grouped by area. The role is set once per install and changes only when the principal edits it, so it is as stable as the rest of the block. Shorter TTL so org edits propagate quickly. The principal's contacts are private to them, so `build_system_blocks(include_contacts=...)` adds the `## Contacts` section, after the team or solo block, only on the principal's own verified turn (`executive._contacts_in_prompt`). That gives block 1 exactly two stable variants per mode — with and without contacts — and never anything per-request; every other turn's block is byte-identical to an install with no contacts.\n\n## Solo mode: one prefix per mode\n\nSolo mode — one person using Open Executive for themselves — changes three cached parts, all resolved **once per turn** by `pin_turn_workspace_mode(session)` (the session's override, else the workspace setting) so they always agree: the block-0 persona, the block-1 org block, and the tool list, which drops `send_company_broadcast`, `send_department_message` and `set_department_head` *before* the sort, so it stays sorted and keeps its 1h marker on the last tool. The resolved mode is pinned on the session for the rest of the turn, so the tool handlers use it too and a switch made mid-turn applies from the next turn. Every part is a constant or stable per install, so each mode keeps its own warm cache and switching modes misses once.\n\nThe two personas share most of their text. `prompts/executive_persona.py` holds plain string literals — a shared head, body and tail plus team or solo sections — concatenated at import and never formatted, so both prompts are constants. The team prompt is byte-for-byte what it was before the split; a test pins its sha256.\n\nTool schemas are static: nothing in a definition depends on company data — `create_goal` takes its area as free text rather than an enum of the current departments, which would change the cached tool prefix every time an area was added, and `record_decision_outcome` takes a plain decision id. The solo persona is still one constant: its goal and decision-outcome lines (`_SOLO_CREATE_GOAL`, `_SOLO_DECISION_OUTCOME`) are literals concatenated at import, and the team persona is byte-identical (a test pins its sha256). The scheduler's proactive-trigger run (a Session marked `unattended`) is sent the list without `schedule_tools.UNATTENDED_WITHHELD_TOOLS`, so it has a stable tool prefix of its own, as each mode does. So does a turn private to the principal (`Session.private_to_principal`: mail from one of their contacts, or mail they forwarded): it is sent the list without `schedule_tools.PRIVATE_TURN_WITHHELD_TOOLS`, dropped before the sort, so private turns in a mode share one sorted prefix with its marker on the last tool. Act as me adds tools rather than dropping any: on a turn `delegation.settings.pin_turn_delegation` offered it to (the principal's own verified, attended turn in a private conversation, with it on), `ghostwrite_email`, the mailbox and calendar reads (`search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply`, `my_email_read_before`, `my_calendar`, and `save_my_email_attachment`, which copies a file out of it), `remind_me` and `propose_actions` join the pool together before the sort, so those turns share one more sorted prefix and every other turn's list is byte-identical to before. The offer never depends on the Gmail connection, so a lapsed token never flips the prefix. `recall_history` (Always in the loop) joins the same way, before the sort, on a turn whose speaker may read their own notes; its offer reads only their switch and the surface, never the notes themselves. The chat note-taker runs after the turn, outside the cached prompt. Tool definitions are sorted by name so their serialized order is stable across requests; the `web_search` server tool is appended after the sorted list so it never receives a `cache_control` marker. The last client tool carries the third marker (1h TTL).\n\n## Tools opened on demand\n\nThe less common tools are not in the list at all. `orchestrator.tool_groups` puts them in named groups — calendar, people, goals, watch_and_alerts, workflows, documents, messaging, skills — and `tool_groups.split` takes them out of the turn's offered tools after every filter above (mode, unattended, private turn) and before the sort, adding two small tools in their place: `open_tools(group)`, whose description names each offered group and its tools, and `use_tool(name, input)`. When the model opens a group, the loop answers with that group's tools (name, description, input schema) as a **tool result**. It never adds them to the list: the list is the start of the cached prefix, so a list that grew mid-turn would miss the cache for the tools, both system blocks and the whole history. The list is the same on every call of every turn, and a group's descriptions are paid for only on a turn that opens it. That took the direct list from about 19,500 tokens to about 6,500, re-sent on every model call.\n\n`open_tools`'s description and its results name only the tools the turn offers (`tool_groups.open_tools_tool`), so a private turn never sees a withheld tool's name. The description depends only on that set, which is fixed for each kind of turn, so each still has one stable list. A `use_tool` call is rewritten into the tool's own call, same id, before dispatch (`tool_groups.unwrap`); the model's assistant block stays as it was sent, so the result pairs with the id it used. The rewritten call meets the same guards, handler, progress events and audit rows as a direct call. `use_tool` takes only names in `tool_groups.DEFERRED`; anything else, or an input that is not an object, gets an error tool result. The everyday tools (`consult_specialist`, `propose_form_values`, people and memory lookups, follow-ups, the MCP meta-tools) stay direct.\n\n## The intra-turn marker\n\nThe fourth and final breakpoint belongs to the tool-use loop. After each iteration appends its `tool_result` blocks, `executive._apply_loop_cache_marker` moves a single ephemeral marker onto the **newest non-empty tool result**. Without it the loop caches only the static tools+system prefix, so every iteration re-sends the whole accumulated transcript at full input price — the runtime signature is `cache_read_input_tokens` pinned flat while the prompt grows iteration over iteration.\n\nThe marker **moves rather than accumulates**: each pass first sweeps every `tool_result` clean, then re-marks the newest one. A marker left in place per iteration would reach `max_iterations` breakpoints and blow the 4-block limit. Sweeping first also makes the helper idempotent — there is no bookkeeping index to drift.\n\nOn the loop's **first call** there is no tool result yet, so the same slot marks the **message being answered** instead (`executive._mark_turn_message`, 5m): the question plus this turn's context (facts, memory, knowledge excerpts). Without it the first call sends that context uncached and the second call writes the same tokens to the cache, so it is paid twice; with it the first call writes it once and later calls read it back. The marker sits on a copy of the message, never the caller's dict, and comes off (`_clear_turn_marker`) as soon as the loop marker lands on a tool result, so a request never carries both.\n\n## The history marker\n\nOnce a conversation has history, the agent loop also marks the **newest non-empty history turn** (normally the previous reply) with a **1h** breakpoint (`executive._apply_history_cache_marker`), so the next message reads the whole conversation back from cache and writes only what is new: the last exchange, this turn's context and its tool calls. History turns are rebuilt from plain text, so the previous turn's loop entries, which ended inside that turn's retrieved context and tool results, never match; without this marker every message re-wrote the whole conversation into the cache. 1h because people reply in minutes, not seconds.\n\nThe history marker takes the company block's slot: block 1 stays in the prefix, covered by the history marker, and dropping its 5m marker keeps the TTLs in the order the API requires, longer before shorter. On a first message (no history) block 1 keeps its 5m marker as before. `_build_messages` itself never marks history, so the committee revision call, which reuses those messages, keeps the plain layout. `Session.get_recent_history` moves its window's start in steps of 10 turns (keeping 20 to 30), so a long conversation's first history message, and the cached prefix with it, stays put between steps instead of shifting every turn. On the OpenRouter path the translator keeps assistant turns as typed text parts whenever a request carries the history marker (`translator._request_caches_assistant_text`), so the marker reaches Anthropic and every reply has the same shape whether or not it is the one marked. A rolling marker on every history turn used to claim a latent fifth breakpoint, which Anthropic rejects outright.\n\n**The breakpoint budget, in full:** last client tool (1h) + persona+knowledge (1h) + company+org (5m, first message only) or history (1h) + the turn's message on the first call, then the newest tool result (5m) = at most 4, longer TTLs first.\n\nRAG context is **never** placed in a cached system block — retrieved hits vary per query and would poison the cache. It is injected into the **user turn** instead. The chat surfaces (web chat, Telegram, Discord, Google Chat) cap it at `KNOWLEDGE_CHAT_MAX_CHARS` (default 6,000 characters, 0 = no cap): `retriever._fit_to_budget` keeps the closest chunks across every collection until the cap, because each excerpt is re-sent on every call of the turn.\n\nSpecialist calls follow the same rule. Each specialist caches only its static domain prompt (`BaseAgent.analyze`, one ephemeral block); everything per call — retrieved knowledge, failure cases, past decisions, department memory, the company's stage (`<company_stage>`) and, in solo mode, the principal's role (`<principal_role>`) — goes in the specialist's user turn, so the cached domain prompt is byte-identical across companies and profile edits.\n\nThe ghostwriter's call (Act as me) carries no cache markers: its system prompt is the constant `GHOSTWRITER_PROMPT` plus that person's voice block — short, and sent only when a draft is written — and the thread and the intent go in its user turn.\n\n## Tool-result bound\n\n`TOOL_RESULT_MAX_CHARS` (default 20,000 characters, about 5,000 tokens) caps a single tool result before it enters the prompt, applied at the one point every result reaches the model rather than at each producer — so it also covers specialist output, tool errors and the unknown-tool fallback, while non-model consumers (the `propose_form_values` JSON parse, the audit trail) still read the full text. A turn's results also share one reading budget, `TOOL_RESULTS_TURN_MAX_CHARS` (default 40,000 characters; 0 turns it off): once the turn's results reach it, each further result shows its first 3,000 characters and its marker says, in place of the advice to ask again more narrowly (that re-read would be cut too), that the question has read as much as it can, so the model answers from what it has and says what it could not read, and it never edits or rewrites anything from that cut result, so a partial read never becomes a lossy write. The read it needs to edit may be the one that was cut, so each question gets one full re-read (`executive._TurnReadingBudget`): repeating a cut call with exactly the same input is answered with the result the turn already has, under the per-result cap, and the marker says so while that re-read is left. The tool never runs again, because the budget cuts any tool's result and a repeated write would happen twice. After it is used, the marker says to offer the edit as its own request, which starts with a fresh budget. A turn therefore reads at most the budget plus one more result (`executive._turn_result_limit`). A specialist's answer is the analysis itself, not a read, so it neither counts nor is cut. A built tool's (`run_script`) result counts but is never cut below the per-result cap: it lists the writes that already ran, and a short cut would hide some and get them repeated. Tool discovery (`open_tools`, `search_tools`) is treated the same way, since its result is the schema the next call needs. The per-result cap is a circuit breaker, not a routine clipper: ordinary tool output (a status, an email thread, a specialist's analysis) stays under it. A long document read does not, and the marker asks for a narrower request, such as a page range or a section, because a result stays in the prompt for every remaining call of the turn. A cut result carries an explicit marker naming the tool and stating that the result is incomplete — truncating silently is worse than not truncating, because the model reads the cut text as the whole answer.\n\n**The invariant:** never put dynamic content in a `cache_control` block. A single mutating value breaks the cache and drives roughly a 10x cost increase.","mermaid": "flowchart TD\n Tools[\"Tool defs (sorted by name)<br/>less common ones behind open_tools<br/>last one: cache_control 1h\"] --> B0\n Mode{{\"effective_workspace_mode<br/>(team or solo, once per turn)\"}} --> Tools\n Mode --> B0\n Mode --> B1\n Deleg{{\"Act as me on?<br/>(install-level, not per turn)\"}} --> B0\n Offer{{\"ghostwrite_email offered?<br/>(pinned once per turn)\"}} --> Tools\n B0[\"Block 0: persona (team or solo) + knowledge<br/>cache_control 1h\"] --> B1\n B1[\"Block 1: company + org (team or solo render)<br/>cache_control 5m on a first message\"] --> Limit{{\"≤ 4 cache_control blocks\"}}\n Loop[\"Newest tool_result<br/>cache_control 5m (moves each iteration)\"] --> Limit\n Hist[\"Newest history turn<br/>cache_control 1h (replaces block 1 marker)\"] --> Limit\n Limit --> Turn[\"User turn\"]\n RAG[\"RAG hits<br/>(vary per query)\"] --> Turn\n Turn --> API[\"Anthropic API\"]\n class B0 cache\n class B1 cache\n class RAG hot\n class Turn hot\n class Tools compute\n class Mode compute\n class Loop cache\n class API external\n class Deleg compute\n class Offer compute","generated_at": "2026-10-14T13:07:16Z"}diff --git a/packages/core/openexecutive/memory/drive_reads.py b/packages/core/openexecutive/memory/drive_reads.pyindex 1a55a356..c36e6fd4 100644--- a/packages/core/openexecutive/memory/drive_reads.py+++ b/packages/core/openexecutive/memory/drive_reads.py@@ -81,7 +81,8 @@ CREATE INDEX IF NOT EXISTS idx_session_drive_searchesON session_drive_searches(session_id, person_id, query);"""-# workspace-mcp 1.29.0 output shapes (gdrive/drive_tools.py).+# workspace-mcp output shapes (gdrive/drive_tools.py), as of 2.1.0. Since 2.0+# a search Drive did not finish ends in a WARNING line, which matches no item._EMPTY_SEARCH_PREFIX = "No files found for '"_SEARCH_HEADER_RE = re.compile(r"^Found \d+ files for ")# workspace-mcp interpolates the file's name and type unescaped, so a namediff --git a/packages/core/openexecutive/orchestrator/mail_file_save.py b/packages/core/openexecutive/orchestrator/mail_file_save.pyindex 3298ecd1..4415f944 100644--- a/packages/core/openexecutive/orchestrator/mail_file_save.py+++ b/packages/core/openexecutive/orchestrator/mail_file_save.py@@ -58,7 +58,7 @@ _NAME_BAD = re.compile(r'[\x00-\x1f\x7f"*:<>?/\\|#%]')_MIME_RE = re.compile(r"^[A-Za-z0-9.+_-]+/[A-Za-z0-9.+_-]+$")_GOOGLE_ID_RE = re.compile(r"^[A-Za-z0-9_-]{10,200}$")_GOOGLE_LINK_PREFIXES = ("https://drive.google.com/", "https://docs.google.com/")-# workspace-mcp's create_drive_file / create_drive_folder answer (1.29.0):+# workspace-mcp's create_drive_file / create_drive_folder answer (1.29.0, unchanged in 2.1.0):# "Successfully created file '<name>' (ID: <id>) in folder '<folder>' for# <email>. Link: <link>". The name comes first and may hold anything, so the# greedy match takes the last "' (ID: " — the real one.diff --git a/packages/core/openexecutive/orchestrator/mcp_gateway.py b/packages/core/openexecutive/orchestrator/mcp_gateway.pyindex 056c651f..b336daad 100644--- a/packages/core/openexecutive/orchestrator/mcp_gateway.py+++ b/packages/core/openexecutive/orchestrator/mcp_gateway.py@@ -111,7 +111,7 @@ _FORWARDED_ENV_VARS = (# Outbound Gmail tools whose arguments may carry recipients. Any tool name# matching one of these (after the `google_workspace__` namespace prefix) is-# subject to the recipient allow-list. Names track workspace-mcp 1.29.0: the+# subject to the recipient allow-list. Names track workspace-mcp 2.1.0: the# send/reply/forward surface is a single `send_gmail_message` (reply is that# tool with thread_id/quoting; forward is its `forward_message_id` arg, which# `_GMAIL_ALLOWED_ARG_KEYS` refuses), and `draft_gmail_message` replaced@@ -555,7 +555,8 @@ _GMAIL_RECIPIENT_FIELDS = ("to", "cc", "bcc")# is rejected by default. Add new keys here only after confirming they cannot# carry an unvalidated address.#-# Deliberately NOT allowed (workspace-mcp 1.29.0 send_gmail_message args):+# Deliberately NOT allowed (workspace-mcp send_gmail_message args, and since+# 2.1.0 draft_gmail_message's too):# - reply_all: workspace-mcp derives To/Cc from the thread itself, so the# recipients never pass through the roster check below.# - forward_message_id / include_forwarded_attachments: forward any inboxdiff --git a/packages/core/openexecutive/prompts/connected_systems.py b/packages/core/openexecutive/prompts/connected_systems.pyindex 02dc5f94..eb2c0374 100644--- a/packages/core/openexecutive/prompts/connected_systems.py+++ b/packages/core/openexecutive/prompts/connected_systems.py@@ -27,7 +27,7 @@ GOOGLE_SERVER = "google_workspace"_SERVER_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}")# The Google Workspace tools the Executive reaches for on most turns, by-# service, as workspace-mcp 1.29.0 (pinned in docker/Dockerfile) names them.+# service, as workspace-mcp 2.1.0 (pinned in docker/Dockerfile) names them.# A new workspace-mcp can rename tools: re-check this list when bumping the# pin. Apps Script tools stay out, since the gateway refuses them. Listing a# name here never widens access: every call still runs the gateway's gates@@ -85,7 +85,7 @@ GOOGLE_SERVICE_OF: dict[str, str] = {}# Pinned tools that workspace-mcp's `core` tier does NOT include, read from-# `core/tool_tiers.yaml` in the pinned 1.29.0. Tiers are cumulative, so+# `core/tool_tiers.yaml` in the pinned 2.1.0. Tiers are cumulative, so# `extended` and `complete` carry all 24 and only `core` needs subtracting.# Re-check when bumping the pin, exactly as for the manifest above.GOOGLE_TOOLS_ABOVE_CORE: frozenset[str] = frozenset({