AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
"""Who has Act as me on, and whether this turn may use it.
One row per person in ``delegation_settings``: a person turns it on for
themselves (``PUT /delegation``), and nobody turns it on for anyone else.
Absent, unreadable or off all mean off.
**Who may have it.** ``can_delegate`` is the single rule: the principal, and
a team member (not a contact, not archived) once the owner has let team
members use it (``team_members_enabled``: the ``DELEGATION_TEAM_MEMBERS``
install setting makes the owner's switch available, and the owner's switch in
``delegation_team`` turns it on). Each still turns it on for themselves.
Everything else here is keyed by person. What a teammate's mailbox touches is
private to *that* person, not to the principal: audit rows carry
``private_to_person`` (``audit.rows_for_person``), a reply card is its
approver's alone (``DecisionClassSpec.approver_only``), and a conversation
that read their mail is theirs alone (``session_store.mark_mail_private``).
**Per turn.** ``pin_turn_delegation`` runs at the start of every chat turn
(``Executive.stream_chat`` and the committee path), next to the workspace-mode
pin, and records a ``TurnDelegation``: whether the speaker has it on, whether
``ghostwrite_email`` is offered this turn, and — set by the tool — whether the
turn has touched the speaker's mailbox (every audit row the turn writes after
that is private). The pin is held in a context variable for the turn's task as
well as on the session, so two turns running at once on one session (a second
browser tab) each read their own. It is offered only when all of these hold:
- the speaker may have it (``can_delegate``) and turned it on;
- the speaker is on a surface that verified it is them
(``people_tools.is_principal_on_verified_surface`` for the principal,
``teammate_on_verified_surface`` for a team member), and a web turn also
carried a signed-in caller (``x-caller-email``) or runs under local login.
A request with no caller header is not a sign-in and never gets it. Whoever
holds ``BACKEND_SHARED_SECRET`` is trusted as the UI proxy that stamps that
header, as on every principal-only route;
- the conversation is private to the speaker: the web chat, a Slack or
Discord DM, or a verified private Telegram chat — never a shared channel or
thread, where a draft's preview or the matching threads would be posted for
everyone and other people's messages sit in the model's context;
- the turn is not unattended and not private to the principal (the email
poller's turns), so inbound text can never reach it.
The Gmail connection is deliberately NOT part of the offer: the handler checks
it on every call and says how to fix it, and the tool list (a cached prefix)
does not flip when a token lapses.
**The system prompt.** ``block0_delegation_on`` is the install-level flag the
cached persona block keys its constant ``DELEGATION_ADDENDUM`` on — whether
anyone here may have it and has it on — so it changes only when a setting
does, never per turn or per speaker.
"""
from __future__ import annotations
import contextvars
import logging
import re
import sqlite3
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any
from openexecutive.delegation.schema import SETTINGS_TABLE, TEAM_TABLE, ensure_schema
from openexecutive.utils.deployment import is_local_login as local_login
if TYPE_CHECKING:
from openexecutive.people.models import Person
logger = logging.getLogger(__name__)
@dataclass
class DelegationOverride:
"""Evals and tests only: run a turn as if ``person`` had Act as me set to
``enabled``, against ``gmail`` — a fake mailbox, never a real one. With an
override the surface checks are skipped (an eval has no web sign-in), so
the tool is offered only when a fake mailbox is supplied."""
enabled: bool
gmail: Any = None
person: Person | None = None
@dataclass
class TurnDelegation:
"""Act as me for the turn in progress (``Session.turn_delegation``)."""
enabled: bool = False
offered: bool = False
# The turn is its speaker's alone: every audit row it writes is private
# (``people_tools``) and it teaches no memory. Set before a read of their
# mailbox or notes, and from the start of every turn in a conversation
# that once read them (``_carry_kept_private``).
touched_mail: bool = False
# This turn itself read their mailbox or notes (set before the read, with
# ``touched_mail``): nothing that opens a link, runs a script or workflow,
# or posts to everyone runs for the rest of it (``delegation.lockdown``).
# Never carried into the next turn: what the mail said reaches a later
# turn only as the Executive's own reply, which the person has read.
read_mail: bool = False
# What the safety check made of the mail this turn read
# (``outside_content.check_mail_read``), which decides how much of the
# lockdown applies under Balanced (``delegation.lockdown.mail_lock_holds``):
# ``mail_vetted`` once every mail read so far was checked, ``mail_held``
# once one was flagged or too big to check. A read not yet checked
# leaves ``mail_vetted`` false, so the whole lockdown holds.
mail_vetted: bool = False
mail_held: bool = False
# Who sent the mail this turn read, address to display name
# (``mail_read_tools``): a new contact's address may be one of them, when
# its name or address matches the contact's, never one the mail's text
# only mentions (``delegation.lockdown.speaker_named_contact``).
mail_senders: dict[str, str] = field(default_factory=dict)
# Threads a search this turn listed whose newest message's sender the mail
# service authenticated, thread id to that address (``mail_read_tools``):
# the Executive's own mail among them skips the safety check
# (``outside_content.check_mail_read``).
mail_verified: dict[str, str] = field(default_factory=dict)
# Drafts made this turn, against the per-turn cap.
drafts: int = 0
# Searches and thread reads of their mailbox this turn, against the
# per-turn caps (``orchestrator.mail_read_tools``).
searches: int = 0
threads_read: int = 0
attachments_read: int = 0
# Files copied from their mail to the Executive's Drive or OneDrive
# (``save_my_email_attachment``).
files_saved: int = 0
# Reminders set this turn (orchestrator.reminder_tools).
reminders: int = 0
# Approval cards left this turn (orchestrator.action_card_tools).
action_cards: int = 0
# The speaker's own words this turn (``executive._speaker_text``): a new
# contact may take an address they typed, and a draft's address they
# didn't type is named back to them. Pinned here because the turn's
# message joins the session history only once the turn ends.
speaker_text: str = ""
person_id: int | None = None
# The session this pin was made for, so a pin left in a task's context
# never answers for another session.
session_id: str | None = None
# The pin for the turn this task is running. Concurrent turns on one session
# run in separate tasks, so each reads its own even though the session object
# (and its ``turn_delegation`` attribute) is shared.
_TURN: contextvars.ContextVar[TurnDelegation | None] = contextvars.ContextVar(
"delegation_turn", default=None
)
def can_delegate(person: Person | None) -> bool:
"""Whether ``person`` may turn Act as me on for themselves: a non-archived
team member who is the principal, or any other one once the owner has let
team members use it (``team_members_enabled``). Never a contact."""
if not (
person is not None
and person.id is not None
and not person.archived
and person.kind == "team"
):
return False
return bool(person.is_principal) or team_members_enabled()
def team_members_available() -> bool:
"""Whether this install lets the owner turn it on for team members
(``DELEGATION_TEAM_MEMBERS``). Never raises."""
try:
from openexecutive.config import get_settings
return bool(get_settings().delegation_team_members)
except Exception:
logger.warning("delegation: couldn't read the team-members setting — treating it as off", exc_info=True)
return False
def team_members_switch(*, db_path: Path | None = None) -> bool:
"""The owner's "Let team members use Act as me", as stored. Never raises:
a missing file, table or row, or any read error, is off (logged)."""
path = _resolve_db_path(db_path)
if not path.exists():
return False
try:
conn = sqlite3.connect(str(path))
try:
row = conn.execute(f"SELECT enabled FROM {TEAM_TABLE} WHERE id = 1").fetchone() # noqa: S608 — constant table name
finally:
conn.close()
except sqlite3.OperationalError as exc:
if "no such table" not in str(exc):
logger.warning("delegation: could not read the team switch (%s) — treating it as off", exc)
return False
except Exception:
logger.warning("delegation: could not read the team switch — treating it as off", exc_info=True)
return False
return bool(row is not None and row[0])
def team_members_enabled(*, db_path: Path | None = None) -> bool:
"""Whether team members may have it: the install allows it and the owner
turned it on. Never raises."""
return team_members_available() and team_members_switch(db_path=db_path)
def set_team_members(enabled: bool, *, updated_by: str, db_path: Path | None = None) -> None:
"""Store the owner's switch. Callers authorize first (the route)."""
now = datetime.now(UTC).isoformat()
conn = sqlite3.connect(str(_resolve_db_path(db_path)))
try:
ensure_schema(conn)
conn.execute(
f"INSERT INTO {TEAM_TABLE} (id, enabled, updated_at, updated_by) " # noqa: S608 — constant table name
"VALUES (1, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET "
"enabled = excluded.enabled, updated_at = excluded.updated_at, "
"updated_by = excluded.updated_by",
(1 if enabled else 0, now, updated_by),
)
conn.commit()
finally:
conn.close()
def enabled_person_ids(*, db_path: Path | None = None) -> list[int]:
"""Everyone whose own switch is on, whether or not they may still have
it. Never raises: an unreadable table is nobody (logged)."""
path = _resolve_db_path(db_path)
if not path.exists():
return []
try:
conn = sqlite3.connect(str(path))
try:
rows = conn.execute(
f"SELECT person_id FROM {SETTINGS_TABLE} WHERE enabled = 1 ORDER BY person_id" # noqa: S608 — constant table name
).fetchall()
finally:
conn.close()
except sqlite3.OperationalError as exc:
if "no such table" not in str(exc):
logger.warning("delegation: could not read who has it on (%s)", exc)
return []
except Exception:
logger.warning("delegation: could not read who has it on", exc_info=True)
return []
return [int(r[0]) for r in rows]
def _resolve_db_path(db_path: Path | None) -> Path:
if db_path is not None:
return db_path
from openexecutive.memory import episodic
return Path(episodic.DB_PATH)
def is_enabled(person_id: int | None, *, db_path: Path | None = None) -> bool:
"""Whether ``person_id`` turned it on. Never raises: a missing file, table
or row, or any read error, is off (logged)."""
if person_id is None:
return False
path = _resolve_db_path(db_path)
if not path.exists():
return False
try:
conn = sqlite3.connect(str(path))
try:
row = conn.execute(
f"SELECT enabled FROM {SETTINGS_TABLE} WHERE person_id = ?", # noqa: S608 — constant table name
(person_id,),
).fetchone()
finally:
conn.close()
except sqlite3.OperationalError as exc:
if "no such table" not in str(exc):
logger.warning("delegation: could not read the setting (%s) — treating it as off", exc)
return False
except Exception:
logger.warning("delegation: could not read the setting — treating it as off", exc_info=True)
return False
return bool(row is not None and row[0])
def set_enabled(
person_id: int, enabled: bool, *, updated_by: str, db_path: Path | None = None
) -> None:
"""Store ``person_id``'s setting. Callers authorize first (the route)."""
now = datetime.now(UTC).isoformat()
conn = sqlite3.connect(str(_resolve_db_path(db_path)))
try:
ensure_schema(conn)
conn.execute(
f"INSERT INTO {SETTINGS_TABLE} (person_id, enabled, updated_at, updated_by) " # noqa: S608 — constant table name
"VALUES (?, ?, ?, ?) ON CONFLICT(person_id) DO UPDATE SET "
"enabled = excluded.enabled, updated_at = excluded.updated_at, "
"updated_by = excluded.updated_by",
(person_id, 1 if enabled else 0, now, updated_by),
)
conn.commit()
finally:
conn.close()
# Right now's read of the principal's sent mail goes with it when they
# turn it off, and is read again soon after they turn it on.
from openexecutive.briefing import waiting_on
waiting_on.reset_cache()
def _principal() -> Person | None:
try:
from openexecutive.people.store import find_principal_person
return find_principal_person()
except Exception:
logger.warning("delegation: principal lookup failed — treating it as off", exc_info=True)
return None
def enabled_for_install() -> bool:
"""Whether anyone on this install may have it and has it on. Never
raises."""
principal = _principal()
if can_delegate(principal) and is_enabled(principal.id if principal else None):
return True
if not team_members_enabled():
return False
try:
from openexecutive.people.store import get_person
return any(can_delegate(get_person(pid)) for pid in enabled_person_ids())
except Exception:
logger.warning("delegation: team lookup failed — treating it as off", exc_info=True)
return False
def block0_delegation_on(session: Any) -> bool:
"""The flag the cached persona block keys ``DELEGATION_ADDENDUM`` on: the
session's override when it carries one, else ``enabled_for_install``."""
override = getattr(session, "delegation_override", None)
if isinstance(override, DelegationOverride):
return override.enabled
return enabled_for_install()
def _speaker(session: Any) -> Person | None:
person_id = getattr(session, "caller_person_id", None)
if not isinstance(person_id, int):
return None
try:
from openexecutive.people.store import get_person
return get_person(person_id)
except Exception:
logger.warning("delegation: speaker lookup failed — not offering it", exc_info=True)
return None
# Slack and Discord sessions for a direct message (the adapters' session ids).
_DM_SESSION_PREFIXES = {"slack": "slack:dm:", "discord": "discord:dm:"}
def private_conversation(session: Any) -> bool:
"""Whether only the speaker (and the Executive) can read this
conversation: the web chat, a Slack or Discord DM, a Telegram chat
(``is_principal_on_verified_surface`` already accepts only a private one),
or one a channel adapter marked so (``Session.private_chat``) for a
sender it verified (``Session.speaker_verified``).
Also the morning brief's rule for reading what is private to the
principal from a chat turn (``workflows.morning_brief``). A web chat
shared with teammates (``Session.shared_chat``) is read by all of them,
so it isn't."""
if getattr(session, "from_web_chat", False) is True:
return getattr(session, "shared_chat", False) is not True
if getattr(session, "private_chat", False) is True:
# Whose conversation it is matters to callers that ask nothing else
# (``correction_tools._scheduled_by``).
return getattr(session, "speaker_verified", False) is True
channel = str(getattr(session, "origin_channel", "") or "")
if channel == "telegram":
return True
prefix = _DM_SESSION_PREFIXES.get(channel)
session_id = str(getattr(session, "session_id", "") or "")
return prefix is not None and session_id.startswith(prefix)
def speaker_surface_ok(session: Any, person: Person | None) -> bool:
"""Whether ``session``'s turn comes from ``person`` themselves, verified,
in a conversation private to them — the surface half of the offer, which
``ghostwrite_email`` checks again on every call. Never raises."""
if not can_delegate(person):
return False
try:
from openexecutive.orchestrator.people_tools import (
is_principal_on_verified_surface,
teammate_on_verified_surface,
)
if person is not None and person.is_principal:
if not is_principal_on_verified_surface(session):
return False
else:
teammate = teammate_on_verified_surface(session)
if teammate is None or person is None or teammate.id != person.id:
return False
except Exception:
logger.warning("delegation: surface check failed — not offering it", exc_info=True)
return False
if not private_conversation(session):
return False
if getattr(session, "from_web_chat", False) is True:
return getattr(session, "web_caller_signed_in", False) is True or local_login()
return True
def _offered(session: Any, person: Person | None, enabled: bool) -> bool:
if not enabled:
return False
if getattr(session, "unattended", False) is True:
return False
if getattr(session, "private_to_principal", False) is True:
return False
# Another AI app asking over the MCP server: nobody is here to approve.
if getattr(session, "from_mcp_client", False) is True:
return False
# A host origin's turn (Session.from_host) only reads and advises.
if getattr(session, "from_host", False) is True:
return False
override = getattr(session, "delegation_override", None)
if isinstance(override, DelegationOverride):
return override.gmail is not None
return speaker_surface_ok(session, person)
def pin_turn_delegation(session: Any, speaker_text: str) -> TurnDelegation:
"""Resolve Act as me for a NEW turn and pin it on the session.
Read fresh every turn — never the previous turn's pin — so turning it off
applies from the very next message. Never raises: anything that cannot be
read leaves it off for the turn."""
override = getattr(session, "delegation_override", None)
person: Person | None
if isinstance(override, DelegationOverride):
person = override.person
enabled = bool(override.enabled)
else:
person = _speaker(session)
enabled = can_delegate(person) and is_enabled(person.id if person else None)
pinned = TurnDelegation(
enabled=enabled,
offered=_offered(session, person, enabled),
speaker_text=speaker_text,
person_id=person.id if person is not None else None,
session_id=getattr(session, "session_id", None),
)
if not isinstance(override, DelegationOverride):
_carry_kept_private(pinned)
session.turn_delegation = pinned
_TURN.set(pinned)
return pinned
def history_len(session: Any) -> int | None:
"""How many history messages ``session`` holds now, or None when that
can't be told (stored as when the conversation read mail,
``session_store.mail_read_at``)."""
history = getattr(session, "conversation_history", None)
return len(history) if isinstance(history, list) else None
def _carry_kept_private(pinned: TurnDelegation) -> None:
"""A conversation that once read someone's mail (``mark_mail_private``)
stays theirs on every later turn: its rows are private to them and it
teaches no memory, however it is answered (``touched_mail``). Nobody else
drafts in it. The turn's own lockdown is not carried (``read_mail``):
history keeps only the speaker's words and the Executive's replies, never
the mail a tool returned, and a later message is the person asking again
after reading that reply. Fails closed: a flag that can't be read counts
as set."""
if not pinned.session_id:
return
from openexecutive.memory import session_store
try:
kept = session_store.session_mail_private(pinned.session_id)
owner = session_store.get_session_owner(pinned.session_id)[1] if kept else None
except Exception:
logger.warning("delegation: couldn't read whether the conversation is private — treating it as private", exc_info=True)
kept, owner = True, None
if not kept:
return
pinned.touched_mail = True
if owner is not None and owner != pinned.person_id:
pinned.enabled = pinned.offered = False
pinned.person_id = owner
def turn_delegation(session: Any) -> TurnDelegation | None:
"""The pinned state for ``session``'s current turn, or None: this task's
own pin when it was made for ``session``, else the one on the session."""
pinned = _TURN.get()
if (
isinstance(pinned, TurnDelegation)
and session is not None
and pinned.session_id == getattr(session, "session_id", None)
):
return pinned
stored = getattr(session, "turn_delegation", None)
return stored if isinstance(stored, TurnDelegation) else None
# Tag blocks the adapters add around the speaker's words (e.g. the
# ``<outbound_reply_context>`` backstory hydrated into a Slack or Discord DM).
_INJECTED_BLOCK = re.compile(r"<([a-z_]+)\b[^>]*>.*?</\1\s*>", re.DOTALL)
_ADDRESS = re.compile(r"[\w.+\-]+@[\w\-]+(?:\.[\w\-]+)+")
# How an attachment shows up in the speaker's text: the label before a
# document's inlined text (``integrations.attachments``), or a note naming the
# file ("(Attached files: …)" from the web upload route, "(Skipped …)",
# "(Could not …)"). None has an end mark, and a filename is chosen by whoever
# sent the file — so a message that carries any of them can't be split into
# the speaker's words and the attachment's. Matched anywhere: a stray match
# only costs the typed addresses, never admits one.
_ATTACHMENT_MARK = re.compile(r"\[Attached: |\((?:Attached|Skipped|Could not)\b")
def own_words(speaker_text: str) -> str | None:
"""What the speaker typed this turn: ``speaker_text`` without any tag
block an adapter added (quoted backstory is not something they typed), or
None when the message carries an attachment (its text, or a note naming
the file), whose words can't be told apart from theirs."""
from openexecutive.integrations.inbound_hydration import strip_outbound_reply_context
# The hydrated reply backstory is removed by its exact, anchored shape
# first: text quoted inside it can carry a look-alike closing tag
# ("</outbound_reply_context >") that would end the generic match below
# early and pass the rest off as the speaker's words.
text = strip_outbound_reply_context(speaker_text or "")
if _ATTACHMENT_MARK.search(text):
return None
return _INJECTED_BLOCK.sub(" ", text)
def typed_addresses(speaker_text: str) -> set[str]:
"""Email addresses the speaker typed this turn (``own_words``). None at
all when the message carries an attachment, so they give the address in a
message of its own (or add the person as a contact)."""
words = own_words(speaker_text)
if words is None:
return set()
return {m.group(0).lower() for m in _ADDRESS.finditer(words)}
def turn_read_delegate_mail(session: Any = None) -> bool:
"""Whether the current turn has itself read the speaker's mailbox or
notes, which locks it down (``delegation.lockdown``). ``session``
defaults to the bound one."""
if session is None:
from openexecutive.orchestrator.schedule_tools import current_session
session = current_session.get()
pinned = turn_delegation(session)
return pinned is not None and pinned.read_mail
def turn_touched_delegate_mail(session: Any = None) -> bool:
"""Whether the current turn is its speaker's alone: it read their
mailbox, or runs in a conversation that did (private rows, no memory).
``session`` defaults to the bound one."""
if session is None:
from openexecutive.orchestrator.schedule_tools import current_session
session = current_session.get()
pinned = turn_delegation(session)
return pinned is not None and pinned.touched_mail