Skip to content
Python

Connectors on machines: grant handoff, GitHub and Slack on a box, subscriptions

Rohit C Prasadea021ff6aa88
diff --git a/coworker/connectors/adapters.py b/coworker/connectors/adapters.py
index 3d64d952..b823039a 100644
--- a/coworker/connectors/adapters.py
+++ b/coworker/connectors/adapters.py
@@ -31,6 +31,14 @@ _SLACK_MENTION_RE = re.compile(r"<@([UW][A-Z0-9]+)(?:\|[^>]*)?>")
# -- pure mappers --------------------------------------------------------------
+
+def _poll_cursor_path(connection_id: str):
+ """Where a box keeps its machine-events poll cursor for one connection."""
+ from ..secrets import state_dir
+
+ safe = "".join(ch for ch in connection_id if ch.isalnum() or ch in "-_")
+ return state_dir() / "poll-cursors" / f"{safe}.cursor"
+
def telegram_message_to_event(msg: Any) -> Optional[MessageEvent]:
text = getattr(msg, "text", None)
if not text:
@@ -425,6 +433,8 @@ def make_adapter(
relay_url: Optional[str] = None,
relay_hub=None,
github_token_client=None,
+ machine_unseal=None,
+ machine_poll_base: Optional[str] = None,
) -> Optional[BasePlatformAdapter]:
"""Build the adapter for a connected platform from its SecretStore profile.
@@ -443,6 +453,38 @@ def make_adapter(
return TelegramAdapter(profile["bot_token"])
if platform == "slack":
if profile.get("mode") == "relay":
+ # Machine-held Slack (machines spec §Managed events): on a box
+ # there is no cloud sign-in — inbound events drain the broker's
+ # sealed queue by machine credential instead of riding the WS.
+ # Same adapter, different transport; `machine_unseal` (the box's
+ # identity key) only exists on joined boxes, so the desktop never
+ # takes this branch.
+ if (
+ machine_unseal is not None
+ and machine_poll_base
+ and profile.get("machine_credential")
+ and profile.get("broker_user_id")
+ and profile.get("connection_id")
+ ):
+ from .machine_poll import MachinePollTransport
+ from .relay_client import SlackRelayAdapter
+
+ def _poll_transport():
+ return MachinePollTransport(
+ machine_poll_base,
+ connection_id=str(profile["connection_id"]),
+ user_id=str(profile["broker_user_id"]),
+ credential=str(profile["machine_credential"]),
+ unseal=machine_unseal,
+ cursor_path=_poll_cursor_path(str(profile["connection_id"])),
+ )
+
+ return SlackRelayAdapter(
+ machine_poll_base,
+ lambda: "", # unused: the poll transport owns its auth
+ teams=_load_slack_teams(secrets),
+ transport_factory=_poll_transport,
+ )
if not (relay_url and token_provider):
logger.warning(
"slack managed-relay configured but relay endpoint / sign-in unavailable "
@@ -460,20 +502,49 @@ def make_adapter(
if profile.get("bot_token") and profile.get("app_token"):
return SlackAdapter(profile["bot_token"], profile["app_token"])
if platform == "github" and profile.get("mode") == "relay":
- if not (relay_url and token_provider):
- logger.warning(
- "github managed-relay configured but relay endpoint / sign-in "
- "unavailable — sign in and set cloud_relay_ws_url; skipping"
- )
- return None
from .github_installs import list_installs
from .github_relay import GitHubRelayAdapter
from .relay_client import RelayHub
- hub = relay_hub or RelayHub(relay_url, token_provider)
installs = (
{iid: prof for iid, prof in list_installs(secrets)} if secrets else {}
)
+ # Machine-held GitHub (machines spec §Managed events, increment 2):
+ # events drain the sealed queue by machine credential; tokens mint on
+ # the delegated route (github_installation_token's box fallback). Own
+ # hub — the poll transport is per-connection, so it can't share
+ # Slack's. Boxes only: machine_unseal never exists on the desktop.
+ if (
+ machine_unseal is not None
+ and machine_poll_base
+ and profile.get("machine_credential")
+ and profile.get("broker_user_id")
+ and profile.get("connection_id")
+ ):
+ from .machine_poll import MachinePollTransport
+
+ def _gh_poll_transport():
+ return MachinePollTransport(
+ machine_poll_base,
+ connection_id=str(profile["connection_id"]),
+ user_id=str(profile["broker_user_id"]),
+ credential=str(profile["machine_credential"]),
+ unseal=machine_unseal,
+ cursor_path=_poll_cursor_path(str(profile["connection_id"])),
+ )
+
+ return GitHubRelayAdapter(
+ RelayHub(machine_poll_base, lambda: "", transport_factory=_gh_poll_transport),
+ installs=installs,
+ token_client=github_token_client,
+ )
+ if not (relay_url and token_provider):
+ logger.warning(
+ "github managed-relay configured but relay endpoint / sign-in "
+ "unavailable — sign in and set cloud_relay_ws_url; skipping"
+ )
+ return None
+ hub = relay_hub or RelayHub(relay_url, token_provider)
return GitHubRelayAdapter(
hub, installs=installs, token_client=github_token_client
)
diff --git a/coworker/connectors/base.py b/coworker/connectors/base.py
index e269c09e..026f04e2 100644
--- a/coworker/connectors/base.py
+++ b/coworker/connectors/base.py
@@ -95,6 +95,20 @@ class MessageEvent:
# The bot itself was @-mentioned (UX-DECISIONS §31 mention router). Computed from the RAW
# platform text at mapping time — mention tokens are rewritten for display afterwards.
mentions_me: bool = False
+ # The broker's one-responder routing (connectors-across-machines spec §3): when a
+ # session subscribed to this source at the cloud, the relay envelope names it and the
+ # box delivers straight there — no fan-out, no per-mention spawn.
+ target_session_id: Optional[str] = None
+ # The coworker the cloud's routing line names for a per-mention session in this
+ # workspace / installation (UX-049). A hint: used when that coworker exists here.
+ mention_persona: Optional[str] = None
+ # The configuration this event fired under (connectors spec §10): {config_id,
+ # event, name, spawn?}. With `spawn` the box starts a fresh session from the
+ # spec; without it the envelope also names `target_session_id`.
+ configuration: Optional[dict] = None
+ # A reply-only frame ("unknown_name"): post one line on the thread, start nothing.
+ reply_only: Optional[str] = None
+ known_names: list = field(default_factory=list)
def tagged_text(self) -> str:
"""How the message enters the super-agent thread: source + reply handle + text.
diff --git a/coworker/connectors/chat_tools.py b/coworker/connectors/chat_tools.py
new file mode 100644
index 00000000..f0b21143
--- /dev/null
+++ b/coworker/connectors/chat_tools.py
@@ -0,0 +1,291 @@
+"""Chat connector tools — Slack and Telegram posting as ordinary connector tools.
+
+Spec (connectors-across-machines §11, owner rulings 2026-09-05): posting to a chat
+platform is a catalog tool gated by the persona's `connectors:` like every other
+connector tool — a session with Slack enabled can post to Slack, and nothing else
+decides it. The generic `send_message` / `send_file` pair (built for the retiring
+super-agent personas) is being replaced by these; both coexist until §11.7 step 7.
+
+Same senders underneath (`senders.py`): stateless HTTP posts, bot token read from the
+SecretStore at call time, never in the model's context. The standing-rule target of
+`slack_post_message` (`slack:<workspace>/<channel>[:<thread_ts>]`, see
+`tool_defs._slack_thread`) is exactly the handle the inbound framing and the thread
+grant use, so a session started for a thread posts back to it without asking.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+import aisuite as ai
+
+from ..secrets import SecretStore
+from .senders import DEFAULT_FILE_SENDERS, DEFAULT_SENDERS, FileSender, Sender
+from .slack_addr import qualify
+from .tools import (
+ _MAX_FILE_BYTES,
+ _render_html_png,
+ _resolve_token,
+ _resolve_within,
+ _slack_channel_name_like,
+)
+
+
+def _meta(name: str, caps: list[str]) -> ai.ToolMetadata:
+ return ai.ToolMetadata(
+ name=name,
+ category="connector",
+ risk_level="medium",
+ capabilities=caps,
+ requires_approval=True,
+ )
+
+
+def _schema(name: str, description: str, properties: dict[str, Any], required: list[str]) -> dict[str, Any]:
+ return {
+ "type": "function",
+ "function": {
+ "name": name,
+ "description": description,
+ "parameters": {"type": "object", "properties": properties, "required": required},
+ },
+ }
+
+
+def _attach(fn: Callable[..., Any], schema: dict[str, Any], caps: list[str]) -> Callable[..., Any]:
+ name = schema["function"]["name"]
+ fn.__name__ = name
+ fn.__doc__ = schema["function"]["description"]
+ fn.__coworker_schema__ = schema
+ fn.__aisuite_tool_metadata__ = _meta(name, caps)
+ return fn
+
+
+# -- Slack workspace + channel resolution ------------------------------------------------
+
+
+def slack_workspaces(secrets: SecretStore) -> list[str]:
+ """Connected workspace ids: every managed `slack:team:<T…>` install, plus
+ `default` when a manual single-workspace bot token exists."""
+ from .config import _slack_team_profiles
+
+ out = [team_id for team_id, _p in _slack_team_profiles(secrets)]
+ if (secrets.get("slack:default") or {}).get("bot_token"):
+ out.append("default")
+ return out
+
+
+def _pick_workspace(secrets: SecretStore, workspace: str) -> tuple[Optional[str], Optional[str]]:
+ """(workspace, error). Empty → the only connected workspace; several → refuse
+ rather than guess (spec §11.8)."""
+ known = slack_workspaces(secrets)
+ if not known:
+ return None, "no Slack workspace is connected — connect Slack first"
+ wanted = (workspace or "").strip()
+ if not wanted:
+ if len(known) == 1:
+ return known[0], None
+ return None, f"several Slack workspaces are connected ({', '.join(known)}) — pass `workspace`"
+ if wanted not in known:
+ return None, f"workspace {wanted!r} is not connected (connected: {', '.join(known)})"
+ return wanted, None
+
+
+def _resolve_channel_in(secrets: SecretStore, workspace: str, channel: str) -> tuple[Optional[str], Optional[str]]:
+ """A channel id passes through; a NAME resolves within the workspace via the same
+ cached roster the GUI's channel picker uses. (channel_id, error)."""
+ from .slack_directory import list_channels
+
+ raw = (channel or "").strip()
+ if not raw:
+ return None, "channel is required"
+ if not _slack_channel_name_like(raw.lstrip("#")):
+ return raw, None
+ query = raw.lstrip("#").strip()
+ r = list_channels(secrets, workspace, query, limit=50)
+ if not r.get("ok"):
+ return None, str(r.get("error") or f"could not list channels in {workspace}")
+ hits = [c for c in (r.get("channels") or []) if str(c.get("name", "")).lower() == query.lower()]
+ if not hits:
+ return None, f"no channel named #{query} in workspace {workspace}"
+ c = hits[0]
+ if not c.get("is_member"):
+ return None, f"found #{query}, but the bot isn't a member — invite @OpenWorker to #{query} in Slack, then retry"
+ return str(c["id"]), None
+
+
+def _slack_chat_id(workspace: str, channel_id: str) -> str:
+ return channel_id if workspace == "default" else qualify(workspace, channel_id)
+
+
+# -- tools ---------------------------------------------------------------------------------
+
+
+def make_chat_tools(
+ secrets: SecretStore,
+ *,
+ roots: Optional[list] = None,
+ senders: Optional[dict[str, Sender]] = None,
+ file_senders: Optional[dict[str, FileSender]] = None,
+ render_html: Optional[Callable[[Path], bytes]] = None,
+) -> list[Callable[..., Any]]:
+ """Every chat connector's tools; `make_integration_tools` filters them down to the
+ session's enabled connectors like the rest of the catalog."""
+ senders = senders if senders is not None else DEFAULT_SENDERS
+ file_senders = file_senders if file_senders is not None else DEFAULT_FILE_SENDERS
+ render_html = render_html or _render_html_png
+ bases = [Path(r.path) for r in (roots or []) if getattr(r, "path", None)]
+
+ def slack_post_message(workspace: str = "", channel: str = "", thread_ts: str = "", text: str = "") -> dict[str, Any]:
+ if not (text or "").strip():
+ return {"error": "text is required"}
+ ws, err = _pick_workspace(secrets, workspace)
+ if err:
+ return {"error": err}
+ channel_id, err = _resolve_channel_in(secrets, ws, channel)
+ if err:
+ return {"error": err}
+ chat_id = _slack_chat_id(ws, channel_id)
+ token = _resolve_token(secrets, "slack", chat_id)
+ if not token:
+ return {"error": f"no bot token for workspace {ws} — connect it first"}
+ sender = senders.get("slack")
+ if sender is None:
+ return {"error": "slack sending is not available"}
+ from .attribution import sender_prefix
+
+ result = sender(token, chat_id, sender_prefix(secrets, chat_id) + text, (thread_ts or "").strip() or None)
+ if result.ok:
+ return {
+ "ok": True,
+ "message_id": result.message_id,
+ "workspace": ws,
+ "channel": channel_id,
+ "thread_ts": (thread_ts or "").strip() or None,
+ }
+ return {"error": result.error or "send failed"}
+
+ def slack_upload_file(
+ workspace: str = "",
+ channel: str = "",
+ thread_ts: str = "",
+ path: str = "",
+ title: str = "",
+ comment: str = "",
+ as_screenshot: bool = False,
+ ) -> dict[str, Any]:
+ ws, err = _pick_workspace(secrets, workspace)
+ if err:
+ return {"error": err}
+ channel_id, err = _resolve_channel_in(secrets, ws, channel)
+ if err:
+ return {"error": err}
+ chat_id = _slack_chat_id(ws, channel_id)
+ if not bases:
+ return {"error": "no workspace folders available to read from"}
+ resolved = _resolve_within(path, bases)
+ if resolved is None or not resolved.is_file():
+ return {"error": "path is outside the folders this session can access (or missing)"}
+ token = _resolve_token(secrets, "slack", chat_id)
+ if not token:
+ return {"error": f"no bot token for workspace {ws} — connect it first"}
+ sender = file_senders.get("slack")
+ if sender is None:
+ return {"error": "slack file upload is not available"}
+ if as_screenshot:
+ if resolved.suffix.lower() not in (".html", ".htm"):
+ return {"error": "as_screenshot only applies to .html files"}
+ try:
+ data = render_html(resolved)
+ except Exception as exc: # noqa: BLE001 — surfaced to the model as a tool error
+ return {"error": f"could not render the page: {exc}"}
+ filename = resolved.stem + ".png"
+ else:
+ if resolved.stat().st_size > _MAX_FILE_BYTES:
+ return {"error": "file is larger than 50 MB"}
+ data = resolved.read_bytes()
+ filename = resolved.name
+ note = comment or ""
+ if note:
+ from .attribution import sender_prefix
+
+ note = sender_prefix(secrets, chat_id) + note
+ result = sender(token, chat_id, (thread_ts or "").strip() or None, filename, data, title or None, note or None)
+ if result.ok:
+ return {"ok": True, "file_id": result.message_id, "workspace": ws, "channel": channel_id, "filename": filename}
+ return {"error": result.error or "file send failed"}
+
+ def telegram_send_message(chat_id: str = "", text: str = "", thread_id: str = "") -> dict[str, Any]:
+ chat = (chat_id or "").strip()
+ if not chat:
+ return {"error": "chat_id is required"}
+ if not (text or "").strip():
+ return {"error": "text is required"}
+ token = _resolve_token(secrets, "telegram", chat)
+ if not token:
+ return {"error": "no bot token for telegram — connect it first"}
+ sender = senders.get("telegram")
+ if sender is None:
+ return {"error": "telegram sending is not available"}
+ result = sender(token, chat, text, (thread_id or "").strip() or None)
+ if result.ok:
+ return {"ok": True, "message_id": result.message_id, "chat_id": chat}
+ return {"error": result.error or "send failed"}
+
+ workspace_prop = {
+ "type": "string",
+ "description": "Workspace id (T…) from the message you are answering, or 'default' for a manually connected bot. May be omitted when exactly one workspace is connected.",
+ }
+ channel_prop = {
+ "type": "string",
+ "description": "Channel id (C…/D…/G…) from the message you are answering, or a channel name like '#general' (resolved within the workspace).",
+ }
+ thread_prop = {
+ "type": "string",
+ "description": "Thread timestamp to reply in (the `thread_ts` of the message you are answering). Omit to post to the channel itself.",
+ }
+ return [
+ _attach(
+ slack_post_message,
+ _schema(
+ "slack_post_message",
+ "Post a message to a Slack channel or thread. To answer a message you received, pass the workspace, channel and thread_ts it came with — that reply is pre-approved for the thread the session was started for. Plain assistant text is not delivered anywhere.",
+ {"workspace": workspace_prop, "channel": channel_prop, "thread_ts": thread_prop, "text": {"type": "string", "description": "The message text."}},
+ ["channel", "text"],
+ ),
+ ["messaging"],
+ ),
+ _attach(
+ slack_upload_file,
+ _schema(
+ "slack_upload_file",
+ "Upload a file from the session's folders into a Slack channel or thread. Slack previews pdf/csv/images itself — send the actual file. For .html set as_screenshot=true to send a rendered PNG. Uploads always ask for approval, even in a thread where text replies are pre-approved.",
+ {
+ "workspace": workspace_prop,
+ "channel": channel_prop,
+ "thread_ts": thread_prop,
+ "path": {"type": "string", "description": "The file to send — workspace-relative, or absolute within an allowed folder."},
+ "title": {"type": "string", "description": "Display title (defaults to the filename)."},
+ "comment": {"type": "string", "description": "Short message posted with the file."},
+ "as_screenshot": {"type": "boolean", "description": "HTML only: render headless and send a PNG preview instead of the raw file."},
+ },
+ ["channel", "path"],
+ ),
+ ["messaging", "files"],
+ ),
+ _attach(
+ telegram_send_message,
+ _schema(
+ "telegram_send_message",
+ "Send a message to a Telegram chat. To answer a message you received, pass the chat_id it came with — that reply is pre-approved for the chat the session was started for.",
+ {
+ "chat_id": {"type": "string", "description": "The chat id from the message you are answering."},
+ "text": {"type": "string", "description": "The message text."},
+ "thread_id": {"type": "string", "description": "Forum topic id, when answering inside a topic."},
+ },
+ ["chat_id", "text"],
+ ),
+ ["messaging"],
+ ),
+ ]
diff --git a/coworker/connectors/github_installs.py b/coworker/connectors/github_installs.py
index 872bd0cc..191dd1cc 100644
--- a/coworker/connectors/github_installs.py
+++ b/coworker/connectors/github_installs.py
@@ -83,8 +83,16 @@ def managed_connect_install(
"repo_selection": form.get("repo_selection", ""),
"connection_id": form.get("connection_id", ""),
}
- if existing.get("allowed_users"):
- profile["allowed_users"] = list(existing["allowed_users"])
+ allowed = set(existing.get("allowed_users") or [])
+ installer = _norm(form.get("github_login"))
+ if installer:
+ # Pre-add the installer (Slack's UX-027 rule, applied here 2026-09-02):
+ # connecting the App is consent to talk to your own coworker — without
+ # this the very first @mention comes from the installer and parks
+ # (the 2026-09-01 GitHub drill's first catch).
+ allowed.add(installer)
+ if allowed:
+ profile["allowed_users"] = sorted(allowed)
if existing.get("allow_all"):
profile["allow_all"] = True
secrets.put(PREFIX + installation_id, profile)
diff --git a/coworker/connectors/github_relay.py b/coworker/connectors/github_relay.py
index 90bb05bb..8f9d4ae1 100644
--- a/coworker/connectors/github_relay.py
+++ b/coworker/connectors/github_relay.py
@@ -40,6 +40,15 @@ def split_thread(chat_id: str) -> tuple[str, Optional[int]]:
return repo, None
+# How an event kind reads in the opening line (spec §10: the lifecycle kinds).
+_KIND_LABELS = {
+ "mention": "mention",
+ "label": "label",
+ "pr_open": "PR opened",
+ "pr_merge": "PR merged",
+ "issue_open": "issue opened",
+}
+
class GitHubRelayAdapter(BasePlatformAdapter):
platform = "github"
@@ -138,7 +147,8 @@ class GitHubRelayAdapter(BasePlatformAdapter):
title = frame.get("title", "")
body = frame.get("body", "")
kind = frame.get("kind", "mention")
- header = f"[{kind} in {owner_repo}#{number}" + (f": {title}]" if title else "]")
+ label = _KIND_LABELS.get(kind, kind)
+ header = f"[{label} in {owner_repo}#{number}" + (f": {title}]" if title else "]")
event = MessageEvent(
text=f"{header} {body}".strip(),
source=SessionSource(
@@ -151,6 +161,15 @@ class GitHubRelayAdapter(BasePlatformAdapter):
team_id=installation_id, # the allow-list scope (≙ Slack team)
),
raw=frame,
+ # Every routed GitHub frame is a DIRECTED ask (the broker only
+ # forwards wave-1 triggers: @-mention or the slug label) — without
+ # this the §31 mention router never spawns a session for it.
+ mentions_me=True,
+ target_session_id=str(frame.get("target_session_id") or "") or None,
+ mention_persona=str(frame.get("mention_persona") or "") or None,
+ configuration=frame.get("configuration") if isinstance(frame.get("configuration"), dict) else None,
+ reply_only=str(frame.get("reply_only") or "") or None,
+ known_names=[str(n) for n in (frame.get("known_names") or [])],
)
await self.handle_message(event)
diff --git a/coworker/connectors/github_send.py b/coworker/connectors/github_send.py
new file mode 100644
index 00000000..3f4f3a0e
--- /dev/null
+++ b/coworker/connectors/github_send.py
@@ -0,0 +1,62 @@
+"""Outbound GitHub for the send_message tool — comment on an issue/PR thread.
+
+Found live in the machine-events drill: session replies to GitHub mentions
+had no sender at all ("unknown platform: github") — the relay adapter's
+send() existed, but the send_message tool the mention framing points the
+model at never learned GitHub. This is the sync, secrets-bound counterpart:
+same auth ladder as the read tools (manual PAT wins; managed relay mints a
+short-lived installation token — on a box, by machine credential), same
+retry-once on a stale token.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+from ..secrets import SecretStore
+
+
+def send_github_comment(secrets: SecretStore, chat_id: str, text: str) -> dict[str, Any]:
+ """POST a comment on `owner/repo#N`. Returns the send_message result shape."""
+ import httpx
+
+ from .github_relay import split_thread
+ from .integration_tools import _github_auth
+
+ owner_repo, number = split_thread(chat_id)
+ if number is None:
+ return {"error": f"no issue/PR number in {chat_id!r} (expected owner/repo#N)"}
+ owner = owner_repo.split("/")[0]
+ base = os.environ.get("GITHUB_API_URL", "https://api.github.com").rstrip("/")
+
+ def _post(force: bool):
+ headers, err = _github_auth(secrets, owner, force=force)
+ if err:
+ return None, err
+ try:
+ return (
+ httpx.post(
+ f"{base}/repos/{owner_repo}/issues/{number}/comments",
+ json={"body": text},
+ headers=headers,
+ timeout=20,
+ ),
+ None,
+ )
+ except httpx.HTTPError as exc:
+ return None, {"error": f"github unreachable: {type(exc).__name__}"}
+
+ resp, err = _post(force=False)
+ if resp is not None and resp.status_code == 401:
+ resp, err = _post(force=True) # stale cached token: re-mint once
+ if err:
+ return err
+ if resp.status_code not in (200, 201):
+ return {"error": f"github comment failed (http_{resp.status_code})"}
+ body = resp.json()
+ return {
+ "ok": True,
+ "message_id": str(body.get("id", "")),
+ "target": f"github:{chat_id}",
+ }
diff --git a/coworker/connectors/integration_tools.py b/coworker/connectors/integration_tools.py
index 0c5c6714..4c92f8e9 100644
--- a/coworker/connectors/integration_tools.py
+++ b/coworker/connectors/integration_tools.py
@@ -556,6 +556,11 @@ def make_integration_tools(
# Email needs the session roots: attachment downloads land in the primary scratch
# and outgoing attachments must resolve inside a granted directory.
tools.extend(make_email_tools(secrets, roots=roots))
+ # Chat connectors (spec §11): posting is a catalog tool, filtered below by the
+ # session's enabled connectors like everything else here.
+ from .chat_tools import make_chat_tools
+
+ tools.extend(make_chat_tools(secrets, roots=roots))
def github_search(
query: str, search_type: str = "issues", max_results: int = 10
@@ -789,14 +794,24 @@ def make_integration_tools(
writable = [r.path for r in (roots or []) if r.writable]
if not writable:
return None, {"error": "no writable session directory to clone into"}
- path = (
- _Path(str(raw)).expanduser().resolve()
- if raw
- else (writable[0] / default_name).resolve()
- )
+ listed = ", ".join(str(r) for r in writable)
+ if raw:
+ given = _Path(str(raw)).expanduser()
+ # Strict (owner ruling 2026-09-06): a relative name is never guessed
+ # against the process cwd or a root — the agent resends the absolute
+ # path github_clone handed back. The error names the roots so the
+ # retry is a one-turn fix, not a dead end.
+ if not given.is_absolute():
+ return None, {
+ "error": f"directory must be an absolute path inside a "
+ f"writable session directory ({listed}); got {raw!r}"
+ }
+ path = given.resolve()
+ else:
+ path = (writable[0] / default_name).resolve()
if not any(path.is_relative_to(root) for root in writable):
return None, {
- "error": f"{path} is outside the session's writable directories"
+ "error": f"{path} is outside the session's writable directories ({listed})"
}
return path, None
@@ -839,7 +854,7 @@ def make_integration_tools(
"repo": {"type": "string"},
"directory": {
"type": "string",
- "description": "target path inside a granted folder (default: <primary>/<repo>)",
+ "description": "absolute target path inside a granted folder (default: <primary>/<repo>)",
},
},
["owner", "repo"],
@@ -882,7 +897,7 @@ def make_integration_tools(
"github_pull",
"Fast-forward an existing clone in a session folder to the latest "
"upstream commits. Requires user approval.",
- {"directory": {"type": "string"}},
+ {"directory": {"type": "string", "description": "absolute path of the clone, as returned by github_clone"}},
["directory"],
),
approval=True,
@@ -890,6 +905,130 @@ def make_integration_tools(
)
)
+ def _repo_of(target) -> tuple[str, str, dict[str, Any] | None]:
+ """(owner, repo) from the clone's origin remote, or an error dict."""
+ remote, git_err = _run_git(["remote", "get-url", "origin"], cwd=target)
+ if git_err:
+ return "", "", {"error": f"no origin remote: {git_err}"}
+ m = re.search(r"[:/]([^/:]+)/([^/]+?)(?:\.git)?/?$", remote)
+ if not m:
+ return "", "", {"error": f"could not parse origin remote: {remote}"}
+ return m.group(1), m.group(2), None
+
+ def github_push(directory: str, branch: str = "") -> dict[str, Any]:
+ """The runtime pushes — the agent never handles a credential (machines
+ spec: tools are the boundary the sandbox will later harden). Same
+ per-invocation header auth as clone/pull: process-only, never at rest."""
+ target, err = _writable_target(directory)
+ if err:
+ return err
+ if not (target / ".git").exists():
+ return {"error": f"{target} is not a git repository"}
+ owner, _repo, rerr = _repo_of(target)
+ if rerr:
+ return rerr
+ if not branch:
+ branch, git_err = _run_git(
+ ["rev-parse", "--abbrev-ref", "HEAD"], cwd=target
+ )
+ if git_err or branch == "HEAD":
+ return {"error": "could not determine the current branch — pass `branch`"}
+ _out, git_err = _run_git(
+ [
+ *_github_git_auth_args(secrets, owner),
+ "-C",
+ str(target),
+ "push",
+ "--set-upstream",
+ "origin",
+ branch,
+ ]
+ )
+ if git_err:
+ return {"error": f"push failed: {git_err}"}
+ head, _ = _run_git(["rev-parse", "--short", "HEAD"], cwd=target)
+ return {"ok": True, "branch": branch, "head": head}
+
+ github_push.__name__ = "github_push"
+ tools.append(
+ _attach(
+ github_push,
+ _schema(
+ "github_push",
+ "Push the clone's current (or named) branch to GitHub — first "
+ "publish and every follow-up push to an open PR's branch alike. "
+ "The runtime authenticates with a short-lived token that is "
+ "never written to disk. Requires user approval.",
+ {
+ "directory": {"type": "string", "description": "absolute path of the clone, as returned by github_clone"},
+ "branch": {
+ "type": "string",
+ "description": "branch to push (default: the current branch)",
+ },
+ },
+ ["directory"],
+ ),
+ approval=True,
+ caps=["github", "write"],
+ )
+ )
+
+ def github_open_pr(
+ directory: str, title: str, body: str = "", base: str = "main", head: str = ""
+ ) -> dict[str, Any]:
+ target, err = _writable_target(directory)
+ if err:
+ return err
+ owner, repo, rerr = _repo_of(target)
+ if rerr:
+ return rerr
+ if not head:
+ head, git_err = _run_git(["rev-parse", "--abbrev-ref", "HEAD"], cwd=target)
+ if git_err or head == "HEAD":
+ return {"error": "could not determine the current branch — pass `head`"}
+ out = _github_call(
+ secrets,
+ "POST",
+ f"/repos/{owner}/{repo}/pulls",
+ install=owner,
+ json={"title": title, "body": body, "base": base, "head": head},
+ )
+ if out.get("error"):
+ return out
+ created = out.get("data") if isinstance(out.get("data"), dict) else {}
+ return {
+ "ok": True,
+ "number": created.get("number"),
+ "url": created.get("html_url"),
+ "head": head,
+ "base": base,
+ }
+
+ github_open_pr.__name__ = "github_open_pr"
+ tools.append(
+ _attach(
+ github_open_pr,
+ _schema(
+ "github_open_pr",
+ "Open a pull request for a pushed branch (push first with "
+ "github_push). Requires user approval.",
+ {
+ "directory": {"type": "string", "description": "absolute path of the clone, as returned by github_clone"},
+ "title": {"type": "string"},
+ "body": {"type": "string"},
+ "base": {"type": "string", "description": "target branch (default main)"},
+ "head": {
+ "type": "string",
+ "description": "source branch (default: the clone's current branch)",
+ },
+ },
+ ["directory", "title"],
+ ),
+ approval=True,
+ caps=["github", "write"],
+ )
+ )
+
_ACCOUNT_PROP = {
"type": "string",
"description": "Mailbox email to use; omit for the default account.",
diff --git a/coworker/connectors/machine_poll.py b/coworker/connectors/machine_poll.py
new file mode 100644
index 00000000..b5b35cc8
--- /dev/null
+++ b/coworker/connectors/machine_poll.py
@@ -0,0 +1,163 @@
+"""Machine event polling — the box's inbound transport for managed Slack.
+
+A machine-held connection's events queue at the broker, sealed to this
+machine's pinned key (machines spec §Managed events). This transport drains
+that queue and hands the decoded frames to the SAME RelayHub / adapter
+pipeline the desktop's WebSocket transport feeds — downstream code cannot
+tell which transport delivered a message.
+
+Auth is the machine credential minted at delegation (bearer), plus the
+opaque user/connection ids stamped into the profile. The broker answers a
+uniform 401 for anything revoked or wrong; polling then backs off and keeps
+trying quietly — a re-handoff (fresh credential) arrives as a profile
+rewrite and a gateway refresh, which rebuilds this transport.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+from collections import deque
+from typing import Any, Callable, Optional
+
+logger = logging.getLogger("coworker.connectors")
+
+_UNAUTHORIZED_BACKOFF = 60.0 # revoked/rotated credential: stay quiet
+_ERROR_BACKOFF = 15.0 # broker unreachable / 5xx: transient, retry soon
+
+
+class MachinePollTransport:
+ """RelayTransport over short-polling (open/recv/close, frame = dict).
+
+ `recv()` never signals a dropped connection (there is none to drop) — it
+ polls forever until `close()`, so the RelayHub's reconnect machinery
+ stays idle. Errors are handled here with backoff.
+ """
+
+ def __init__(
+ self,
+ base_url: str,
+ *,
+ connection_id: str,
+ user_id: str,
+ credential: str,
+ unseal: Callable[[str], bytes],
+ interval: float = 3.0,
+ cursor_path: Optional[Any] = None,
+ ) -> None:
+ self._url = base_url.rstrip("/") + "/v1/machine/events/poll"
+ self._connection_id = connection_id
+ self._user_id = user_id
+ self._credential = credential
+ self._unseal = unseal
+ self._interval = interval
+ # The cursor persists (spec §10 drill finding 2026-09-04): the broker
+ # keeps ~15 min of sealed events, so a restart with a fresh cursor
+ # replayed a PR-opened event into a duplicate session.
+ self._cursor_path = cursor_path
+ self._cursor = self._load_cursor()
+ self._buffer: deque[dict] = deque()
+ self._closed = asyncio.Event()
+ self._client = None
+ self._polls = 0 # observable for tests
+
+ async def open(self) -> None:
+ import httpx
+
+ self._client = httpx.AsyncClient(timeout=10)
+
+ async def _sleep(self, seconds: float) -> None:
+ """Interruptible sleep: close() ends it immediately."""
+ try:
+ await asyncio.wait_for(self._closed.wait(), timeout=seconds)
+ except asyncio.TimeoutError:
+ pass
+
+ async def _poll_once(self) -> Optional[list[dict[str, Any]]]:
+ """One poll round-trip: the sealed events, or None on any refusal
+ (already logged and backed off by the caller's returned delay)."""
+ import httpx
+
+ try:
+ resp = await self._client.post(
+ self._url,
+ json={
+ "connection_id": self._connection_id,
+ "user_id": self._user_id,
+ "cursor": self._cursor,
+ },
+ headers={"Authorization": f"Bearer {self._credential}"},
+ )
+ except httpx.HTTPError as exc:
+ logger.warning("machine event poll unreachable: %s", type(exc).__name__)
+ await self._sleep(_ERROR_BACKOFF)
+ return None
+ if resp.status_code == 401:
+ # Revoked or rotated credential — a re-handoff replaces this
+ # transport; until then, stay quiet rather than hammering.
+ logger.warning("machine event poll unauthorized — delegation revoked?")
+ await self._sleep(_UNAUTHORIZED_BACKOFF)
+ return None
+ if resp.status_code != 200:
+ await self._sleep(_ERROR_BACKOFF)
+ return None
+ body = resp.json()
+ new_cursor = str(body.get("cursor") or self._cursor)
+ if new_cursor != self._cursor:
+ self._cursor = new_cursor
+ self._save_cursor()
+ return list(body.get("events") or [])
+
+ def _load_cursor(self) -> str:
+ if not self._cursor_path:
+ return ""
+ try:
+ from pathlib import Path
+
+ return Path(self._cursor_path).read_text(encoding="utf-8").strip()
+ except OSError:
+ return ""
+
+ def _save_cursor(self) -> None:
+ if not self._cursor_path:
+ return
+ try:
+ from pathlib import Path
+
+ path = Path(self._cursor_path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(self._cursor, encoding="utf-8")
+ except OSError:
+ logger.warning("could not persist the poll cursor at %s", self._cursor_path)
+
+ async def recv(self) -> Optional[dict]:
+ while not self._closed.is_set():
+ if self._buffer:
+ return self._buffer.popleft()
+ if self._polls:
+ await self._sleep(self._interval)
+ if self._closed.is_set():
+ break
+ self._polls += 1
+ events = await self._poll_once()
+ for item in events or []:
+ try:
+ frame = json.loads(self._unseal(str(item.get("sealed_b64", ""))))
+ # Broad on purpose: unseal is an opaque callable whose crypto
+ # errors (InvalidTag etc.) we must not let kill the loop.
+ except Exception as exc:
+ logger.warning("machine event unseal failed: %s", type(exc).__name__)
+ continue
+ if isinstance(frame, dict):
+ self._buffer.append(frame)
+ return None
+
+ async def close(self) -> None:
+ self._closed.set()
+ if self._client is not None:
+ try:
+ await self._client.aclose()
+ except Exception:
+ pass
+ self._client = None
diff --git a/coworker/connectors/origin.py b/coworker/connectors/origin.py
new file mode 100644
index 00000000..f7967d1c
--- /dev/null
+++ b/coworker/connectors/origin.py
@@ -0,0 +1,132 @@
+"""The origin block — where an inbound message came from and how to answer it.
+
+Spec (connectors-across-machines §11.3, 2026-09-05): every message a box delivers
+to a session (mention spawn, subscription delivery, tag, configured event) opens
+with one structured block built from the inbound source: platform, workspace,
+channel, thread, sender, and the EXACT reply call — named by the platform's own
+connector tool, marked pre-approved when the session holds the thread grant. The
+opaque `platform:chat_id[:thread]` handle stays internal (thread map, grants) and
+no longer appears in model-facing text.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+from .base import SessionSource
+from .slack_addr import split
+
+PLATFORM_LABELS = {
+ "slack": "Slack",
+ "github": "GitHub",
+ "telegram": "Telegram",
+ "discord": "Discord",
+ "teams": "Teams",
+}
+
+
+def platform_label(platform: str) -> str:
+ return PLATFORM_LABELS.get(platform, (platform or "chat").capitalize())
+
+
+def _q(value: Optional[str]) -> str:
+ return '"' + str(value or "").replace('"', '\\"') + '"'
+
+
+def _github_parts(chat_id: str) -> tuple[str, str, str]:
+ """`owner/repo#N` → (owner, repo, N); a bare repo has no number."""
+ repo_part, _, number = (chat_id or "").partition("#")
+ owner, _, repo = repo_part.partition("/")
+ return owner, repo, number
+
+
+def reply_call(src: SessionSource, thread: Optional[str] = None, frame: Optional[dict[str, Any]] = None) -> str:
+ """The tool call that answers this message, spelled out with its arguments."""
+ p = src.platform
+ if p == "slack":
+ team, channel = split(src.chat_id or "")
+ team = src.team_id or team
+ args = [f"workspace={_q(team or 'default')}", f"channel={_q(channel)}"]
+ if thread:
+ args.append(f"thread_ts={_q(thread)}")
+ return f"slack_post_message({', '.join(args)}, text=…)"
+ if p == "telegram":
+ args = [f"chat_id={_q(src.chat_id)}"]
+ if thread and thread != "1":
+ args.append(f"thread_id={_q(thread)}")
+ return f"telegram_send_message({', '.join(args)}, text=…)"
+ if p == "github":
+ owner, repo, number = _github_parts(src.chat_id or "")
+ return f"github_reply(owner={_q(owner)}, repo={_q(repo)}, number={number or '…'}, body=…)"
+ # Platforms without a connector tool keep the generic reply for now.
+ target = f"{p}:{src.chat_id}" + (f":{thread}" if thread else "")
+ return f"send_message(target={_q(target)}, text=…)"
+
+
+def also_call(src: SessionSource, frame: Optional[dict[str, Any]] = None) -> Optional[str]:
+ """A second tool the same grant covers: reviewing, on a GitHub pull request."""
+ if src.platform != "github":
+ return None
+ f = frame or {}
+ if not (f.get("is_pr") or str(f.get("kind") or "").startswith("pr_")):
+ return None
+ owner, repo, number = _github_parts(src.chat_id or "")
+ return f"github_review(owner={_q(owner)}, repo={_q(repo)}, pull_number={number or '…'}, event=…, body=…)"
+
+
+def where_line(src: SessionSource, thread: Optional[str] = None, frame: Optional[dict[str, Any]] = None) -> str:
+ """`From Slack · workspace T… · #team (C…) · thread 1788….` — one line, ids kept
+ so the model can copy them into the reply call."""
+ p = src.platform
+ label = platform_label(p)
+ if p == "slack":
+ team, channel = split(src.chat_id or "")
+ team = src.team_id or team
+ parts = [f"From {label}", f"workspace {team or 'default'}"]
+ if src.chat_type == "dm":
+ parts.append(f"DM ({channel})")
+ else:
+ name = src.chat_name or ""
+ parts.append(f"#{name.lstrip('#')} ({channel})" if name and name != channel else f"channel {channel}")
+ if thread:
+ parts.append(f"thread {thread}")
+ return " · ".join(parts)
+ if p == "telegram":
+ parts = [f"From {label}", f"chat {src.chat_id}" + (f" ({src.chat_name})" if src.chat_name and src.chat_name != src.chat_id else "")]
+ if thread and thread != "1":
+ parts.append(f"topic {thread}")
+ return " · ".join(parts)
+ if p == "github":
+ owner, repo, number = _github_parts(src.chat_id or "")
+ f = frame or {}
+ noun = "pull request" if (f.get("is_pr") or str(f.get("kind") or "").startswith("pr_")) else "issue"
+ parts = [f"From {label}", f"{owner}/{repo}"]
+ if number:
+ parts.append(f"{noun} #{number}" + (f' "{f.get("title")}"' if f.get("title") else ""))
+ return " · ".join(parts)
+ where = src.chat_name or src.chat_id or ""
+ return f"From {label} · {where}" + (f" · thread {thread}" if thread else "")
+
+
+def origin_block(
+ src: SessionSource,
+ *,
+ thread: Optional[str] = None,
+ frame: Optional[dict[str, Any]] = None,
+ pre_approved: bool = True,
+ judgement_only: bool = False,
+) -> str:
+ """The block that prefixes a delivered message. `pre_approved`: the session holds
+ the thread grant (every spawn/tag/configured delivery). `judgement_only`: an
+ untagged channel message — answering is optional and asks for approval."""
+ who = src.user_name or src.user_id or "?"
+ who_line = f"Sent by {who}" + (f" ({src.user_id})" if src.user_id and src.user_id != who else "")
+ call = reply_call(src, thread, frame)
+ also = also_call(src, frame)
+ if judgement_only:
+ answer = f"To answer (only if it clearly concerns your job): {call} — this asks for approval."
+ elif pre_approved:
+ answer = f"To answer: {call} — pre-approved for this thread" + (f"; {also} likewise." if also else ".")
+ else:
+ answer = f"To answer: {call} — this asks for approval."
+ return "\n".join([where_line(src, thread, frame), who_line, answer])
diff --git a/coworker/connectors/parked.py b/coworker/connectors/parked.py
index 49e98dd3..926d93ae 100644
--- a/coworker/connectors/parked.py
+++ b/coworker/connectors/parked.py
@@ -32,6 +32,8 @@ class ParkedMessage:
chat_type: str = "channel" # "channel" | "group" | "dm"
thread_id: Optional[str] = None
team_id: Optional[str] = None # workspace id (managed relay); None for socket mode
+ # A direct @-mention of the bot (drives the §31 mention router on re-delivery).
+ mentions_me: bool = False
ts: float = field(default_factory=time.time)
id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
diff --git a/coworker/connectors/relay_client.py b/coworker/connectors/relay_client.py
index f1e7bf1c..bf862995 100644
--- a/coworker/connectors/relay_client.py
+++ b/coworker/connectors/relay_client.py
@@ -91,6 +91,7 @@ class RelayHub:
self._connections = 0 # total successful opens; reconnects == connections-1
self._connected = False # the desktop↔relay socket is open RIGHT NOW
self._dispatched = 0 # frames dispatched (observable for tests)
+ self._tasks: set[asyncio.Task] = set() # in-flight frame handlers
self.last_error: str = "" # last connect/reconnect failure ("" once healthy)
self._progress = asyncio.Event()
@@ -125,6 +126,15 @@ class RelayHub:
self._task = asyncio.create_task(self._run())
return True
+ async def _dispatch(self, handler, frame: dict) -> None:
+ try:
+ await handler(frame)
+ except Exception:
+ logger.exception("relay frame dispatch failed")
+ finally:
+ self._dispatched += 1
+ self._progress.set()
+
async def _run(self) -> None:
"""Read frames; on a dropped connection, reconnect (fresh transport) —
the relay's own watchdog analogue on the desktop side."""
@@ -137,12 +147,16 @@ class RelayHub:
if frame is not None:
handler = self._handlers.get(frame.get("provider") or "slack")
if handler is not None:
- try:
- await handler(frame)
- except Exception:
- logger.exception("relay frame dispatch failed")
- self._dispatched += 1
- self._progress.set()
+ # Each frame runs as its own task: a frame that starts a
+ # session turn (minutes) must not hold the next frame
+ # back (drill finding 2026-09-04: a merge sat behind a
+ # review). Follow-ups to a busy session steer into it.
+ task = asyncio.create_task(self._dispatch(handler, frame))
+ self._tasks.add(task)
+ task.add_done_callback(self._tasks.discard)
+ else:
+ self._dispatched += 1
+ self._progress.set()
continue
# Connection closed → reconnect unless we're shutting down.
self._connected = False
@@ -317,16 +331,26 @@ class SlackRelayAdapter(BasePlatformAdapter):
async def _on_event(self, frame: dict) -> None:
await self._dispatch_slack_event(
- frame.get("team_id", ""), frame.get("event") or {}
+ frame.get("team_id", ""),
+ frame.get("event") or {},
+ target_session_id=str(frame.get("target_session_id") or ""),
+ mention_persona=str(frame.get("mention_persona") or ""),
)
- async def _dispatch_slack_event(self, team_id: str, event: dict) -> None:
+ async def _dispatch_slack_event(
+ self, team_id: str, event: dict, *, target_session_id: str = "", mention_persona: str = ""
+ ) -> None:
"""Map a raw Slack event → MessageEvent, resolve display names via the
- per-team bot token, team-qualify the reply handle, and dispatch."""
+ per-team bot token, team-qualify the reply handle, and dispatch.
+ `target_session_id` = the broker's subscribed responder, when any."""
self.last_event_at = time.time()
mapped = slack_event_to_event(event, self._bot_user_id(team_id))
if mapped is None:
return
+ if target_session_id:
+ mapped.target_session_id = target_session_id
+ if mention_persona:
+ mapped.mention_persona = mention_persona
channel = mapped.source.chat_id # bare channel id before qualification
# Resolve friendly names with THIS workspace's bot token (cached per team),
# mirroring the Socket-Mode adapter — so cards read "@OpenWorker"/"Rohit"/"#ocw-test"
diff --git a/coworker/connectors/setup.py b/coworker/connectors/setup.py
index 57d5476d..0b53eeff 100644
--- a/coworker/connectors/setup.py
+++ b/coworker/connectors/setup.py
@@ -7,7 +7,7 @@ public bot identity captured at connect time.
from __future__ import annotations
-from typing import Any
+from typing import Any, Optional
from ..secrets import SecretStore
from .catalog_copy import about_for, access_for
@@ -418,6 +418,118 @@ def managed_connect_connector(
return {"ok": True, "account": profile.get("account") or None}
+def store_managed_grant(
+ secrets: SecretStore, connector: str, form: dict[str, str], profile: dict[str, Any]
+) -> dict[str, Any]:
+ """Store a managed OAuth grant into `secrets`, routing to the connector's
+ storage family (multi-account gmail/gcal, multi-portal hubspot, or the
+ generic path). One dispatch for both destinations: the local store on a
+ plain connect, an EphemeralSecretStore when the grant is being staged for
+ another machine (machines spec §Remote OAuth) — so the two paths can never
+ drift. Slack (relay install) and GitHub (cloud runtime) have their own
+ branches in the callback and never come through here."""
+ if connector == "gmail":
+ from . import gmail_accounts
+
+ return gmail_accounts.managed_connect_account(secrets, profile)
+ if connector == "google_calendar":
+ from . import gcal_accounts
+
+ return gcal_accounts.managed_connect_account(secrets, profile)
+ if connector == "hubspot" and form.get("hub_id"):
+ from . import hubspot_portals
+
+ profile = {**profile, "hub_id": form.get("hub_id", "")}
+ if form.get("sandbox"):
+ profile["sandbox"] = True
+ return hubspot_portals.managed_connect_portal(secrets, profile)
+ return managed_connect_connector(secrets, connector, profile)
+
+
+def store_managed_grant_bundle(
+ secrets: SecretStore,
+ connector: str,
+ form: dict[str, Any],
+ grant: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ """Turn a broker OAuth callback (`form` = the callback's fields) into this
+ connector's profile records in `secrets`, stamped with the delegation
+ (`grant` = {"user_id", "machine_credential"} when the grant is machine-
+ held). ONE routine for every destination — the desktop staging a grant
+ for another machine (EphemeralSecretStore, then sealed), and a box
+ landing a browser-sealed grant into its own store (machines spec §Cloud-
+ dashboard connect-direct) — so the families cannot drift:
+ - GitHub: one profile per installation the callback returned + pointer;
+ - Slack: the per-workspace bot token + pointer;
+ - everything else: the connector's storage family (multi-account, portal,
+ or generic)."""
+ import json as _json
+
+ from .. import cloud
+ from .github_installs import managed_connect_install
+
+ form = {k: str(v) for k, v in (form or {}).items()}
+ grant = grant or {}
+ connection_id = form.get("connection_id", "")
+ if connector == "github":
+ if not form.get("installation_id"):
+ return {"ok": False, "error": "no installation"}
+ try:
+ rows = _json.loads(form.get("installations") or "[]")
+ except ValueError:
+ rows = []
+ if not rows:
+ rows = [
+ {
+ "installation_id": form.get("installation_id", ""),
+ "account_login": form.get("account_login", ""),
+ "account_type": form.get("account_type", ""),
+ "repo_selection": form.get("repo_selection", ""),
+ }
+ ]
+ out: dict[str, Any] = {"ok": False, "error": "no installations"}
+ for row in rows:
+ out = managed_connect_install(
+ secrets,
+ {
+ **row,
+ "github_login": form.get("github_login", ""),
+ "connection_id": connection_id,
+ },
+ )
+ if not out.get("ok"):
+ return out
+ elif connector == "slack" and form.get("team_id"):
+ out = managed_connect_slack_install(secrets, form)
+ if not out.get("ok"):
+ return out
+ else:
+ if not form.get("access_token"):
+ return {"ok": False, "error": "missing fields"}
+ profile = cloud.managed_profile_from_callback(form)
+ if grant.get("user_id"):
+ profile["broker_user_id"] = grant["user_id"]
+ if grant.get("machine_credential"):
+ profile["machine_credential"] = grant["machine_credential"]
+ return store_managed_grant(secrets, connector, form, profile)
+ if connector in ("slack", "github") and grant:
+ # Stamp the delegation into every profile of the connector (pointer
+ # included) — the pointer feeds the box's poll adapter (slack) and the
+ # delegated token mint (github).
+ for key in connector_profile_keys(secrets, connector):
+ prof = dict(secrets.get(key) or {})
+ if not prof:
+ continue
+ if connection_id:
+ prof["connection_id"] = connection_id
+ if grant.get("user_id"):
+ prof["broker_user_id"] = grant["user_id"]
+ if grant.get("machine_credential"):
+ prof["machine_credential"] = grant["machine_credential"]
+ secrets.put(key, prof)
+ return out
+
+
def managed_connect_slack_install(
secrets: SecretStore, form: dict[str, Any]
) -> dict[str, Any]:
@@ -522,3 +634,97 @@ def disconnect_connector(secrets: SecretStore, name: str) -> dict[str, Any]:
dropped_accounts = mcp_oauth.sign_out(name, secrets) or dropped_accounts
mcp_config.delete_global_server(name)
return {"ok": secrets.delete(f"{name}:default") or dropped_accounts}
+
+
+def connector_profile_keys(secrets: SecretStore, name: str) -> list[str]:
+ """Every stored profile key belonging to one connector — the unit a grant
+ handoff moves to a machine. Mirrors disconnect_connector's enumeration."""
+ keys: list[str] = []
+ from . import accounts as _accounts
+
+ if _accounts.is_account_connector(name):
+ keys += [
+ _accounts.prefix(name) + account_id
+ for account_id, _profile in _accounts.list_accounts(secrets, name)
+ ]
+ if name == "gmail":
+ from . import gmail_accounts
+
+ keys += [
+ gmail_accounts.PREFIX + email
+ for email, _profile in gmail_accounts.list_accounts(secrets)
+ ]
+ if name == "google_calendar":
+ from . import gcal_accounts
+
+ keys += [
+ gcal_accounts.PREFIX + email
+ for email, _profile in gcal_accounts.list_accounts(secrets)
+ ]
+ if name == "hubspot":
+ from . import hubspot_portals
+
+ keys += [
+ hubspot_portals.PREFIX + hub_id
+ for hub_id, _profile in hubspot_portals.list_portals(secrets)
+ ]
+ if name == "slack":
+ # Managed relay: one bot-token profile per workspace.
+ keys += sorted(
+ row["profile"]
+ for row in secrets.status()
+ if str(row.get("profile", "")).startswith("slack:team:")
+ )
+ if name == "github":
+ # Managed App relay: one metadata profile per installation — routing
+ # only, no secrets (tokens mint on demand).
+ keys += sorted(
+ row["profile"]
+ for row in secrets.status()
+ if str(row.get("profile", "")).startswith("github:install:")
+ )
+ if secrets.get(f"{name}:default") is not None:
+ keys.append(f"{name}:default")
+ return keys
+
+
+def connector_handoff_info(secrets: SecretStore, name: str) -> dict[str, Any]:
+ """Whether this connector's grant can MOVE to a machine, and which profile
+ keys the move carries. One grant, one holder (spec §Remote OAuth): the
+ handoff deploys these sealed, then the desktop forgets its copy.
+
+ Not portable: MCP-backed connects (their OAuth + server registration are
+ local by construction). Relay-mode Slack and managed GitHub ARE portable
+ since machine events (spec §Managed events + increment 2): Slack's bot
+ tokens move sealed and its inbound rides the sealed queue; a GitHub
+ handoff moves NO secrets at all — installation routing metadata plus the
+ machine credential, which the box uses both to drain events and to mint
+ 1-hour installation tokens on the delegated route."""
+ d = get_descriptor(name)
+ if d is None:
+ return {"ok": False, "error": "unknown connector"}
+ default = secrets.get(f"{name}:default") or {}
+ if default.get("mode") == "mcp":
+ return {"ok": True, "portable": False, "reason": "mcp_local", "profiles": []}
+ # Managed (broker-refreshed) grants move via DELEGATION (spec §Remote
+ # OAuth): the handoff marks each connection machine-held at the broker,
+ # and the machine renews by possession on the delegated route. That
+ # needs the connection_id the broker issued — a managed profile without
+ # one (pre-connection-tracking era) can't be delegated and stays gated.
+ # The slack/github pointer profiles are managed METADATA only — mode +
+ # delegation stamps, no grant — so they don't gate.
+ keys = connector_profile_keys(secrets, name)
+ managed = [
+ k
+ for k in keys
+ if (secrets.get(k) or {}).get("managed")
+ and not (name in ("slack", "github") and k == f"{name}:default")
+ ]
+ if any(not (secrets.get(k) or {}).get("connection_id") for k in managed):
+ return {"ok": True, "portable": False, "reason": "refresh_binding", "profiles": []}
+ return {
+ "ok": True,
+ "portable": bool(keys),
+ "profiles": keys,
+ "needs_delegation": bool(managed),
+ }
diff --git a/coworker/connectors/tool_defs.py b/coworker/connectors/tool_defs.py
index d0a7a860..3e38372e 100644
--- a/coworker/connectors/tool_defs.py
+++ b/coworker/connectors/tool_defs.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Any, Optional
+from typing import Any, Callable, Optional
from ..secrets import SecretStore
@@ -22,9 +22,73 @@ class ConnectorToolDef:
# single-argument targets are declarable in v1 (no wildcards, no composite targets), and
# only write tools should declare one — reads never gate, so a rule would be meaningless.
target_arg: Optional[str] = None
+ # The composite alternative (spec §10.7 (b), 2026-09-05): a function that derives the
+ # rule target from several arguments — a GitHub thread is `owner` + `repo` + a number,
+ # and the target it yields is the same `github:owner/repo#N` handle the thread grant
+ # pins for `send_message`, so one grant covers replying AND reviewing on that thread.
+ # Returns None when the call does not fully name its target.
+ target_fn: Optional[Callable[[dict[str, Any]], Optional[str]]] = None
+
+
+def _github_thread(number_arg: str) -> Callable[[dict[str, Any]], Optional[str]]:
+ def target(arguments: dict[str, Any]) -> Optional[str]:
+ owner = str(arguments.get("owner") or "").strip()
+ repo = str(arguments.get("repo") or "").strip()
+ number = str(arguments.get(number_arg) or "").strip()
+ if not (owner and repo and number.isdigit()):
+ return None
+ return f"github:{owner}/{repo}#{number}"
+
+ return target
+
+
+def _slack_thread(arguments: dict[str, Any]) -> Optional[str]:
+ """`slack:<workspace>/<channel>[:<thread_ts>]` — the SAME handle the inbound
+ framing and the thread grant use (slack_addr: a bare channel for the manual
+ single-workspace install, team-qualified for managed relays)."""
+ workspace = str(arguments.get("workspace") or "").strip()
+ channel = str(arguments.get("channel") or "").strip()
+ thread = str(arguments.get("thread_ts") or "").strip()
+ if not channel:
+ return None
+ chat = f"{workspace}/{channel}" if workspace and workspace != "default" else channel
+ return f"slack:{chat}" + (f":{thread}" if thread else "")
+
+
+def _telegram_chat(arguments: dict[str, Any]) -> Optional[str]:
+ chat_id = str(arguments.get("chat_id") or "").strip()
+ thread = str(arguments.get("thread_id") or "").strip()
+ if not chat_id:
+ return None
+ return f"telegram:{chat_id}" + (f":{thread}" if thread else "")
TOOL_DEFS: tuple[ConnectorToolDef, ...] = (
+ # Chat connectors (spec §11, 2026-09-05): posting is a connector tool like any
+ # other, gated by `connectors:` — no separate "messaging" capability.
+ ConnectorToolDef(
+ "slack",
+ "slack_post_message",
+ "Post message",
+ "write",
+ "Post a message to a channel or thread in a connected workspace.",
+ target_fn=_slack_thread,
+ ),
+ ConnectorToolDef(
+ "slack",
+ "slack_upload_file",
+ "Upload file",
+ "write",
+ "Upload a file from the session's folders into a channel or thread.",
+ ),
+ ConnectorToolDef(
+ "telegram",
+ "telegram_send_message",
+ "Send message",
+ "write",
+ "Send a message to a Telegram chat.",
+ target_fn=_telegram_chat,
+ ),
ConnectorToolDef(
"browser",
# Egress, not a read: the URL is model-chosen, so the request itself can carry
@@ -115,6 +179,7 @@ TOOL_DEFS: tuple[ConnectorToolDef, ...] = (
"Reply on issue/PR",
"write",
"Comment on an issue or pull request.",
+ target_fn=_github_thread("number"),
),
ConnectorToolDef(
"github",
@@ -122,6 +187,7 @@ TOOL_DEFS: tuple[ConnectorToolDef, ...] = (
"Review a PR",
"write",
"Submit a pull-request review (approve / request changes / comment).",
+ target_fn=_github_thread("pull_number"),
),
ConnectorToolDef(
"github",
@@ -146,6 +212,22 @@ TOOL_DEFS: tuple[ConnectorToolDef, ...] = (
"write",
"Fast-forward an existing clone to the latest commits.",
),
+ ConnectorToolDef(
+ "github",
+ # The runtime pushes; the agent never handles a credential (machines
+ # spec §Managed events — tools are the future sandbox boundary).
+ "github_push",
+ "Push a branch",
+ "write",
+ "Push the clone's branch to GitHub with a short-lived token.",
+ ),
+ ConnectorToolDef(
+ "github",
+ "github_open_pr",
+ "Open a pull request",
+ "write",
+ "Open a PR for a pushed branch.",
+ ),
ConnectorToolDef(
"email",
"email_list_folders",
@@ -1109,14 +1191,37 @@ for _def in TOOL_DEFS:
# which tools can EVER carry a standing rule: exec/destructive tools must never appear here.
TARGET_ARGS: dict[str, str] = {d.name: d.target_arg for d in TOOL_DEFS if d.target_arg}
TARGET_ARGS["send_message"] = "target"
+# Composite targets (several arguments → one handle); together with TARGET_ARGS this is
+# the whole set of rule-eligible tools.
+TARGET_FNS: dict[str, Callable[[dict[str, Any]], Optional[str]]] = {
+ d.name: d.target_fn for d in TOOL_DEFS if d.target_fn
+}
def target_arg_for(tool_name: str) -> Optional[str]:
"""The argument that names this tool's standing-rule target, or None if the tool
- isn't eligible for standing rules."""
+ isn't eligible for standing rules by a single argument."""
return TARGET_ARGS.get(tool_name)
+def rule_eligible(tool_name: str) -> bool:
+ """Whether a standing rule can ever name this tool (single-arg or composite target)."""
+ return tool_name in TARGET_ARGS or tool_name in TARGET_FNS
+
+
+def standing_target_for(tool_name: str, arguments: dict[str, Any]) -> Optional[str]:
+ """The exact target this call names for a standing rule, or None when the tool is
+ not rule-eligible or the call does not name one."""
+ fn = TARGET_FNS.get(tool_name)
+ if fn is not None:
+ return fn(arguments or {})
+ arg = TARGET_ARGS.get(tool_name)
+ if arg is None:
+ return None
+ value = str((arguments or {}).get(arg) or "").strip()
+ return value or None
+
+
def connector_for_tool(tool_name: str) -> str | None:
return TOOL_TO_CONNECTOR.get(tool_name)
diff --git a/coworker/connectors/tools.py b/coworker/connectors/tools.py
index 8b2f4ce4..d2f6fc35 100644
--- a/coworker/connectors/tools.py
+++ b/coworker/connectors/tools.py
@@ -144,6 +144,14 @@ def make_send_message_tool(
platform, chat_id, thread_id = _parse_or_coerce(target)
except ValueError as exc:
return {"error": str(exc)}
+ # GitHub replies are issue/PR comments: no bot token exists (the App
+ # mints per-call — on a box, by machine credential), so it bypasses
+ # the token/sender machinery below (drill finding: this path simply
+ # didn't exist, on any deployment).
+ if platform == "github":
+ from .github_send import send_github_comment
+
+ return send_github_comment(secrets, chat_id, text)
sender = senders.get(platform)
if sender is None:
return {"error": f"unknown platform: {platform}"}
diff --git a/coworker/subscription_sync.py b/coworker/subscription_sync.py
new file mode 100644
index 00000000..92cbbbe2
--- /dev/null
+++ b/coworker/subscription_sync.py
@@ -0,0 +1,199 @@
+"""Register channel subscriptions at the cloud before writing them locally.
+
+Connectors-across-machines spec §3.3: for managed inbound connectors (Slack in
+relay mode, GitHub) the broker's subscription row is the truth — ONE session
+across all of the user's machines answers a source. The local
+``SubscriptionStore`` is the on-box mirror. So a subscribe goes to the broker
+first; only an accepted claim is written locally, and a clash comes back as
+``held`` so the UI can offer the move.
+
+Two doors, picked by what this process holds:
+- a joined box: the connector profile carries the machine credential minted at
+ delegation → ``POST /v1/machine/subscriptions`` (the broker takes the
+ machine id from the credential's holder);
+- the signed-in desktop: the cloud session token → ``POST /v1/subscriptions``
+ as machine ``desktop``.
+Neither (Socket-Mode Slack, Telegram, signed out) → nothing to register; the
+subscription is local-only, exactly as before.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Optional
+
+import httpx
+
+from .cloud import fresh_access_token
+from .config import Config
+from .secrets import SecretStore
+
+logger = logging.getLogger("coworker.subscriptions")
+
+MANAGED_INBOUND = ("slack", "github")
+_TIMEOUT = 15
+
+
+def _door(secrets: SecretStore, config: Config, connector: str) -> Optional[dict[str, Any]]:
+ """How to reach the broker for this connector, or None (local-only)."""
+ if connector not in MANAGED_INBOUND:
+ return None
+ profile = secrets.get(f"{connector}:default") or {}
+ if profile.get("mode") != "relay":
+ return None
+ base = (config.cloud_base_url or "").rstrip("/")
+ if not base:
+ return None
+ if (
+ profile.get("machine_credential")
+ and profile.get("broker_user_id")
+ and profile.get("connection_id")
+ ):
+ return {
+ "kind": "machine",
+ "url": base + "/v1/machine/subscriptions",
+ "headers": {"Authorization": f"Bearer {profile['machine_credential']}"},
+ "ids": {
+ "user_id": str(profile["broker_user_id"]),
+ "connection_id": str(profile["connection_id"]),
+ },
+ }
+ token = fresh_access_token(secrets, config)
+ if token:
+ return {
+ "kind": "user",
+ "url": base + "/v1/subscriptions",
+ "headers": {"Authorization": f"Bearer {token}"},
+ "ids": {},
+ }
+ return None
+
+
+def _connector_of(source: str) -> str:
+ return source.split(":", 1)[0] if ":" in source else ""
+
+
+def register(
+ secrets: SecretStore,
+ config: Config,
+ *,
+ source: str,
+ session_id: str,
+ title: str = "",
+ move: bool = False,
+) -> dict[str, Any]:
+ """Claim `source` for `session_id` at the broker.
+
+ Returns ``{"ok": True, "registered": bool}`` (False = local-only, nothing
+ to register), ``{"ok": False, "error": "held", "held_by", "also",
+ "move_allowed"}`` on a clash, or ``{"ok": False, "error": <text>}`` when the
+ broker refused or could not be reached (the local write must NOT happen)."""
+ door = _door(secrets, config, _connector_of(source))
+ if door is None:
+ return {"ok": True, "registered": False}
+ body = {
+ **door["ids"],
+ "source": source,
+ "session_id": session_id,
+ "title": title[:200],
+ "move": bool(move),
+ }
+ try:
+ resp = httpx.post(door["url"], json=body, headers=door["headers"], timeout=_TIMEOUT)
+ except httpx.HTTPError as exc:
+ logger.warning("subscription register unreachable: %s", type(exc).__name__)
+ return {"ok": False, "error": "The cloud could not be reached — try again in a moment."}
+ if resp.status_code == 404:
+ # A broker without the subscriptions routes yet (or a connection it no
+ # longer knows): behave as before the cloud table existed — local-only.
+ return {"ok": True, "registered": False}
+ if resp.status_code == 409:
+ detail = (resp.json() or {}).get("detail") or {}
+ return {
+ "ok": False,
+ "error": "held",
+ "held_by": detail.get("held_by") or {},
+ "also": detail.get("also") or [],
+ "move_allowed": bool(detail.get("move_allowed", True)),
+ }
+ if resp.status_code != 200:
+ try:
+ detail = (resp.json() or {}).get("detail")
+ except ValueError:
+ detail = ""
+ return {"ok": False, "error": str(detail or f"cloud refused (http {resp.status_code})")}
+ data = resp.json() or {}
+ return {
+ "ok": True,
+ "registered": True,
+ "moved_from": data.get("moved_from") or [],
+ }
+
+
+def _post(door: dict[str, Any], path: str, body: dict[str, Any]) -> None:
+ try:
+ httpx.post(
+ door["url"] + path, json={**door["ids"], **body}, headers=door["headers"], timeout=_TIMEOUT
+ )
+ except httpx.HTTPError as exc: # best effort: the next reconcile catches up
+ logger.info("subscription %s not reported: %s", path or "remove", type(exc).__name__)
+
+
+def remove(secrets: SecretStore, config: Config, *, source: str, session_id: str) -> None:
+ """Best-effort release of a row this session held (a stale box cannot
+ release a session that took over — the broker checks)."""
+ door = _door(secrets, config, _connector_of(source))
+ if door is not None:
+ _post(door, "/remove", {"source": source, "session_id": session_id})
+
+
+def report_orphan(secrets: SecretStore, config: Config, *, source: str) -> None:
+ """The broker named a session this box no longer has: the row stops
+ capturing events and the glance page shows it as gone."""
+ door = _door(secrets, config, _connector_of(source))
+ if door is not None and door["kind"] == "machine":
+ _post(door, "/orphan", {"source": source})
+ elif door is not None:
+ _post(door, "/remove", {"source": source})
+
+
+# --- mirror refresh (spec §3.3 follow-up, UX-049 4b) ---------------------------
+
+
+def _get(door: dict[str, Any], path: str) -> Optional[dict[str, Any]]:
+ try:
+ resp = httpx.get(door["url"] + path, params=door["ids"], headers=door["headers"], timeout=_TIMEOUT)
+ except httpx.HTTPError as exc:
+ logger.info("mirror refresh unreachable: %s", type(exc).__name__)
+ return None
+ if resp.status_code != 200:
+ return None
+ try:
+ return resp.json() or {}
+ except ValueError:
+ return None
+
+
+def pull(secrets: SecretStore, config: Config) -> dict[str, Any]:
+ """What the broker holds for this box: its subscription rows and the
+ owner's People lists, per managed inbound connector. Only a joined box
+ (machine credential) pulls; the desktop's truth is its own store plus
+ the user-authed views. Returns
+ ``{"subscriptions": [rows for THIS machine], "elsewhere": [rows on other
+ machines], "people": {connector: [rows]}}`` — empty when nothing to pull."""
+ out: dict[str, Any] = {"subscriptions": [], "elsewhere": [], "people": {}}
+ for connector in MANAGED_INBOUND:
+ door = _door(secrets, config, connector)
+ if door is None or door["kind"] != "machine":
+ continue
+ subs = _get(door, "")
+ if subs is not None:
+ mine = str(subs.get("machine_id") or "")
+ for row in subs.get("subscriptions") or []:
+ if row.get("connector") != connector:
+ continue
+ (out["subscriptions"] if mine and row.get("machine_id") == mine else out["elsewhere"]).append(row)
+ ppl = _get({**door, "url": door["url"].replace("/subscriptions", "/people")}, "")
+ if ppl is not None:
+ out["people"][connector] = [r for r in ppl.get("people") or [] if r.get("connector") == connector]
+ return out
diff --git a/coworker/subscriptions.py b/coworker/subscriptions.py
index f8b5d33a..db800bc2 100644
--- a/coworker/subscriptions.py
+++ b/coworker/subscriptions.py
@@ -23,7 +23,7 @@ import threading
from collections import deque
from dataclasses import asdict, dataclass, field
from pathlib import Path
-from typing import Optional
+from typing import Callable, Optional
@dataclass
@@ -218,22 +218,31 @@ def subscription_tools(
*,
default_platform: str = "slack",
routing_targets: Optional[list[str]] = None,
+ register: Optional[Callable[[str, str], dict]] = None,
+ release: Optional[Callable[[str, str], None]] = None,
) -> list:
"""The channel-subscription tools for a messaging persona's session: subscribe / unsubscribe /
list / catch up. The agent obtains a channel by asking the user (ask_user) or from a channel
- message it's reacting to."""
+ message it's reacting to. `register(session_id, addr)` / `release(session_id, addr)` are the
+ manager's cloud hooks (spec §3.3): the same one-responder rule and the same "held by" answer
+ the app's UI gets — an agent never silently splits a channel with another session."""
def subscribe_channel(channel: str) -> dict:
"""Subscribe THIS session to a messaging channel so you receive its messages (a steer while
you work, or a fresh turn when idle). Ask the user which channel (ask_user) if you don't
already have one. `channel` may be a Slack `#channel` mention, a `platform:chat_id` address,
- or a channel id."""
+ or a channel id. If another session already answers that channel you get `held_by` back —
+ tell the user; only they can move it (in the app)."""
addr = resolve_channel(channel, default_platform=default_platform)
if not addr or ":" not in addr:
return {
"ok": False,
"error": f"could not resolve a channel from {channel!r}",
}
+ if register is not None:
+ verdict = register(session_id, addr)
+ if not verdict.get("ok"):
+ return {"ok": False, "channel": addr, **verdict}
store.subscribe(session_id, addr)
warn = None
if routing_targets and addr in routing_targets:
@@ -248,6 +257,8 @@ def subscription_tools(
"""Stop THIS session from listening to a channel."""
addr = resolve_channel(channel, default_platform=default_platform)
removed = store.unsubscribe(session_id, addr)
+ if removed and release is not None:
+ release(session_id, addr)
return {"ok": True, "unsubscribed": addr, "was_subscribed": removed}
def list_subscriptions() -> dict:
diff --git a/coworker/tools/connreq.py b/coworker/tools/connreq.py
new file mode 100644
index 00000000..8cfb410e
--- /dev/null
+++ b/coworker/tools/connreq.py
@@ -0,0 +1,62 @@
+"""`request_connector` and `grant_connector` — connector access is a human decision.
+
+Spec (connectors-across-machines §11.6, owner-ruled 2026-09-05):
+
+- `request_connector(connector, reason)`: any connector-capable coworker may ask the
+ human to connect a service it could use ("connecting GitHub lets me keep the board
+ and the repo in step"). The card offers Connect / Not now; declining is a normal
+ outcome and the coworker says what it could not do.
+- `grant_connector(worker, connector, reason)`: a lead asks the human to give one of
+ its workers a connector, later than the staffing card. Approval flips the worker's
+ per-session connection within the worker persona's declared ceiling.
+
+Both are engine-intercepted like `request_tool`: the user's out-of-band decision IS the
+consent, so they never go through the permission path. These bodies only run when no
+requester is wired (a surface that cannot prompt).
+"""
+
+from __future__ import annotations
+
+from aisuite import ToolMetadata, tool
+
+
+def request_connector_tool() -> object:
+ def request_connector(connector: str, reason: str) -> dict:
+ """Ask the user to connect a service you could use but that is not connected
+ (e.g. `github`, `slack`, `linear`). Use it when a connection would let you do
+ the job properly — keeping a tracker in step, posting where the team reads —
+ not for a convenience. `reason` is ONE sentence: what the connection lets you
+ do. The user may decline; then carry on without it and say plainly what you
+ could not do. Never ask twice for the same connector in one session."""
+ return {"approved": False, "error": "connector requests aren't available in this surface"}
+
+ return tool(
+ request_connector,
+ metadata=ToolMetadata(
+ category="system",
+ risk_level="low",
+ capabilities=["request_connector"],
+ description="Ask the user to connect a service (GitHub, Slack, Linear, …) you could use.",
+ ),
+ )
+
+
+def grant_connector_tool() -> object:
+ def grant_connector(worker: str, connector: str, reason: str) -> dict:
+ """Ask the user to give one of your workers access to a connector it does not
+ have yet — `worker` is the callname from the staffing roster (e.g. "nia"),
+ `connector` the service id (e.g. "github"). Workers start with no connectors;
+ ask only when the item genuinely needs it (pushing a branch, filing an issue)
+ and say so in `reason` (one sentence). The user decides; if declined, route
+ the external step through yourself or the user."""
+ return {"approved": False, "error": "connector grants aren't available in this surface"}
+
+ return tool(
+ grant_connector,
+ metadata=ToolMetadata(
+ category="team",
+ risk_level="medium",
+ capabilities=["team"],
+ description="Ask the user to grant one of your workers a connector.",
+ ),
+ )
diff --git a/tests/test_accounts.py b/tests/test_accounts.py
index 4443d8c1..389f11e0 100644
--- a/tests/test_accounts.py
+++ b/tests/test_accounts.py
@@ -176,3 +176,43 @@ def test_generic_account_routes(acme, secrets, tmp_path, monkeypatch):
out = client.post("/v1/connectors/linear/accounts/x/default").json()
assert not out["ok"] and "not a multi-account" in out["error"]
+
+# -- grant handoff (spec §Remote OAuth): profile-key enumeration + portability --
+
+
+def test_connector_profile_keys_and_handoff_info(acme, secrets):
+ from coworker.connectors.setup import (
+ connector_handoff_info,
+ connector_profile_keys,
+ )
+
+ # Nothing stored → nothing to move.
+ assert connector_profile_keys(secrets, "acmeapp") == []
+ assert connector_handoff_info(secrets, "acmeapp")["portable"] is False
+
+ # Two accounts + the default pointer = the full move unit.
+ connect_connector(secrets, "acmeapp", {"api_key": "k1", "project_id": "11"}, validate=False)
+ connect_connector(secrets, "acmeapp", {"api_key": "k2", "project_id": "22"}, validate=False)
+ keys = connector_profile_keys(secrets, "acmeapp")
+ assert set(keys) == {"acmeapp:account:11", "acmeapp:account:22", "acmeapp:default"}
+ info = connector_handoff_info(secrets, "acmeapp")
+ assert info["portable"] is True and set(info["profiles"]) == set(keys)
+
+ # A managed grant WITH a broker connection_id moves via delegation
+ # (needs_delegation tells the GUI to run the delegate step first).
+ profile = secrets.get("acmeapp:account:11")
+ profile["managed"] = True
+ profile["connection_id"] = "conn_abc"
+ secrets.put("acmeapp:account:11", profile)
+ delegable = connector_handoff_info(secrets, "acmeapp")
+ assert delegable["portable"] is True and delegable["needs_delegation"] is True
+
+ # A managed grant WITHOUT a connection_id (pre-tracking era) cannot be
+ # delegated and stays gated.
+ profile.pop("connection_id")
+ secrets.put("acmeapp:account:11", profile)
+ gated = connector_handoff_info(secrets, "acmeapp")
+ assert gated["portable"] is False and gated["reason"] == "refresh_binding"
+
+ # Unknown connector is an error, not an empty success.
+ assert connector_handoff_info(secrets, "nope")["ok"] is False
diff --git a/tests/test_chat_tools.py b/tests/test_chat_tools.py
new file mode 100644
index 00000000..111c3a3c
--- /dev/null
+++ b/tests/test_chat_tools.py
@@ -0,0 +1,211 @@
+"""Chat connector tools (connectors-across-machines spec §11, 2026-09-05): Slack and
+Telegram posting as ordinary connector tools gated by `connectors:`, the origin block
+that names the reply call, and the thread grant that pre-approves it. No network."""
+
+from __future__ import annotations
+
+import pytest
+
+from coworker.connectors.base import SendResult, SessionSource
+from coworker.connectors.chat_tools import make_chat_tools, slack_workspaces
+from coworker.connectors.origin import origin_block, reply_call, where_line
+from coworker.connectors.tool_defs import rule_eligible, standing_target_for
+from coworker.permissions import PermissionEngine, standing_rule_candidate
+from coworker.secrets import SecretStore
+
+
+class _Meta:
+ def __init__(self, category="connector", requires_approval=True):
+ self.category = category
+ self.requires_approval = requires_approval
+
+
+def _tools(secrets, record):
+ def sender(token, chat_id, text, thread_id=None):
+ record.append({"token": token, "chat_id": chat_id, "text": text, "thread_id": thread_id})
+ return SendResult(True, message_id="99")
+
+ return {t.__name__: t for t in make_chat_tools(secrets, senders={"slack": sender, "telegram": sender})}
+
+
+# -- catalog + standing-rule targets ---------------------------------------------------
+
+
+def test_chat_tools_are_catalog_entries_with_composite_targets():
+ assert rule_eligible("slack_post_message") and rule_eligible("telegram_send_message")
+ assert not rule_eligible("slack_upload_file") # uploads are never covered by a thread grant
+ assert standing_target_for("slack_post_message", {"workspace": "T1", "channel": "C1", "thread_ts": "1.2"}) == "slack:T1/C1:1.2"
+ assert standing_target_for("slack_post_message", {"workspace": "default", "channel": "C1"}) == "slack:C1"
+ assert standing_target_for("slack_post_message", {"channel": "C1", "thread_ts": "1.2"}) == "slack:C1:1.2"
+ assert standing_target_for("slack_post_message", {"workspace": "T1"}) is None
+ assert standing_target_for("telegram_send_message", {"chat_id": "123"}) == "telegram:123"
+ assert standing_target_for("telegram_send_message", {"chat_id": "123", "thread_id": "7"}) == "telegram:123:7"
+ meta = _Meta()
+ assert standing_rule_candidate("slack_post_message", {"workspace": "T1", "channel": "C1", "thread_ts": "1.2", "text": "x"}, meta) == "slack:T1/C1:1.2"
+
+
+def test_thread_grant_matches_the_platform_tool_on_that_thread_only(tmp_path):
+ e = PermissionEngine(workspace_root=tmp_path, task_rules={"slack_post_message": {"slack:T1/C1:1.2"}})
+ meta = _Meta()
+ hit = e.evaluate("slack_post_message", {"workspace": "T1", "channel": "C1", "thread_ts": "1.2", "text": "hi"}, meta)
+ assert hit.allowed and hit.rule == "slack_post_message → slack:T1/C1:1.2"
+ # The channel itself (no thread), another thread, another workspace: all ask.
+ for args in (
+ {"workspace": "T1", "channel": "C1", "text": "hi"},
+ {"workspace": "T1", "channel": "C1", "thread_ts": "9.9", "text": "hi"},
+ {"workspace": "T2", "channel": "C1", "thread_ts": "1.2", "text": "hi"},
+ ):
+ d = e.evaluate("slack_post_message", args, meta)
+ assert not d.allowed and d.needs_user, args
+ # Uploads never ride the text grant.
+ up = e.evaluate("slack_upload_file", {"workspace": "T1", "channel": "C1", "thread_ts": "1.2", "path": "a.pdf"}, meta)
+ assert not up.allowed
+
+
+# -- the tools ---------------------------------------------------------------------------
+
+
+def test_slack_post_message_uses_the_workspace_token_and_threads(tmp_path):
+ secrets = SecretStore(tmp_path / "s.json")
+ secrets.put("slack:team:T1", {"bot_token": "xoxb-t1"})
+ record: list = []
+ tools = _tools(secrets, record)
+ out = tools["slack_post_message"](workspace="T1", channel="C1", thread_ts="1.2", text="hello")
+ assert out == {"ok": True, "message_id": "99", "workspace": "T1", "channel": "C1", "thread_ts": "1.2"}
+ assert record == [{"token": "xoxb-t1", "chat_id": "T1/C1", "text": "hello", "thread_id": "1.2"}]
+ # A single connected workspace may be left implicit.
+ out = tools["slack_post_message"](channel="C2", text="top level")
+ assert out["ok"] and record[-1]["chat_id"] == "T1/C2" and record[-1]["thread_id"] is None
+ # Metadata: a connector write that gates.
+ t = tools["slack_post_message"]
+ assert t.__aisuite_tool_metadata__.category == "connector" and t.__aisuite_tool_metadata__.requires_approval is True
+ assert t.__coworker_schema__["function"]["parameters"]["required"] == ["channel", "text"]
+
+
+def test_slack_post_message_refuses_to_guess_between_workspaces(tmp_path):
+ secrets = SecretStore(tmp_path / "s.json")
+ secrets.put("slack:team:T1", {"bot_token": "xoxb-t1"})
+ secrets.put("slack:default", {"bot_token": "xoxb-manual", "mode": "socket"})
+ assert sorted(slack_workspaces(secrets)) == ["T1", "default"]
+ record: list = []
+ tools = _tools(secrets, record)
+ err = tools["slack_post_message"](channel="C1", text="x")["error"]
+ assert "several Slack workspaces" in err and "T1" in err and record == []
+ # Named explicitly: the manual install posts with a bare channel id + its own token.
+ out = tools["slack_post_message"](workspace="default", channel="C1", text="x")
+ assert out["ok"] and record[-1] == {"token": "xoxb-manual", "chat_id": "C1", "text": "x", "thread_id": None}
+ assert "not connected" in tools["slack_post_message"](workspace="T9", channel="C1", text="x")["error"]
+ assert "no Slack workspace" in _tools(SecretStore(tmp_path / "empty.json"), [])["slack_post_message"](channel="C1", text="x")["error"]
+
+
+def test_slack_channel_name_resolves_within_the_workspace(tmp_path, monkeypatch):
+ secrets = SecretStore(tmp_path / "s.json")
+ secrets.put("slack:team:T1", {"bot_token": "xoxb-t1"})
+ seen: list = []
+
+ def fake_list(secrets_, team_id, query="", limit=25, **_kw):
+ seen.append((team_id, query))
+ return {"ok": True, "channels": [{"id": "C77", "name": "general", "is_member": True}, {"id": "C78", "name": "generalities", "is_member": False}]}
+
+ monkeypatch.setattr("coworker.connectors.slack_directory.list_channels", fake_list)
+ record: list = []
+ tools = _tools(secrets, record)
+ assert tools["slack_post_message"](workspace="T1", channel="#general", text="hi")["channel"] == "C77"
+ assert seen == [("T1", "general")] and record[-1]["chat_id"] == "T1/C77"
+ assert "no channel named #nope" in tools["slack_post_message"](workspace="T1", channel="nope", text="hi")["error"]
+
+
+def test_telegram_send_message(tmp_path):
+ secrets = SecretStore(tmp_path / "s.json")
+ record: list = []
+ tools = _tools(secrets, record)
+ assert "connect it first" in tools["telegram_send_message"](chat_id="123", text="x")["error"]
+ secrets.put("telegram:default", {"bot_token": "T0K"})
+ out = tools["telegram_send_message"](chat_id="123", text="hello", thread_id="7")
+ assert out == {"ok": True, "message_id": "99", "chat_id": "123"}
+ assert record == [{"token": "T0K", "chat_id": "123", "text": "hello", "thread_id": "7"}]
+ assert "chat_id is required" in tools["telegram_send_message"](text="x")["error"]
+
+
+# -- assembly: the connector gate is the only gate -------------------------------------
+
+
+class _StubProvider:
+ def complete(self, **_kw): # pragma: no cover
+ from coworker.providers import AssistantTurn
+
+ return AssistantTurn()
+
+ def capabilities(self, _model): # pragma: no cover
+ from coworker.providers.base import ModelCapabilities
+
+ return ModelCapabilities()
+
+ def stream(self, **_kw): # pragma: no cover
+ from coworker.providers.base import StreamChunk
+
+ yield StreamChunk(turn=self.complete())
+
+
+def _engine(agent, secrets, tmp_path):
+ from coworker.agent import build_engine
+
+ return build_engine(agent=agent, workspace=tmp_path, provider=_StubProvider(), secrets=secrets)
+
+
+def test_slack_in_connectors_is_the_whole_condition(tmp_path):
+ from coworker.agents.base import Agent
+
+ secrets = SecretStore(tmp_path / "s.json")
+ secrets.put("slack:default", {"bot_token": "xoxb", "app_token": "xapp", "mode": "socket"})
+ lead = Agent(name="lead", title="Lead", system_prompt="x", connectors=("github", "slack"))
+ names = _engine(lead, secrets, tmp_path).registry.names()
+ assert {"slack_post_message", "slack_upload_file", "send_message", "send_file"} <= set(names)
+ assert "telegram_send_message" not in names # telegram isn't connected
+ # The old `messaging` trait decides nothing: GitHub-only stays chat-less…
+ reviewer = Agent(name="rev", title="Reviewer", system_prompt="x", connectors=("github",), messaging=True)
+ names = _engine(reviewer, secrets, tmp_path).registry.names()
+ assert "slack_post_message" not in names and "send_message" not in names
+ # …and `connectors: true` (every connected connector) gets the chat tools.
+ general = Agent(name="gen", title="General", system_prompt="x", connectors=True)
+ assert "slack_post_message" in _engine(general, secrets, tmp_path).registry.names()
+
+
+def test_manifest_can_chat_is_derived_from_connectors():
+ from coworker.personas.loading import capability_set
+ from coworker.personas.manifest import parse_manifest
+
+ m = parse_manifest("---\nid: a\nname: A\nconnectors: [github, slack]\nmessaging: false\n---\nprompt")
+ assert m.can_chat is True and m.to_agent().messaging is True and "messaging" in capability_set(m)
+ m = parse_manifest("---\nid: b\nname: B\nconnectors: [github]\nmessaging: true\n---\nprompt")
+ assert m.can_chat is False and m.to_agent().messaging is False and "messaging" not in capability_set(m)
+
+
+# -- the origin block -------------------------------------------------------------------
+
+
+def test_origin_block_slack_thread():
+ src = SessionSource(platform="slack", chat_id="T07/C0B", user_id="U1", user_name="Rohit", chat_name="team", chat_type="channel", team_id="T07")
+ block = origin_block(src, thread="1788.5")
+ assert block.splitlines() == [
+ "From Slack · workspace T07 · #team (C0B) · thread 1788.5",
+ "Sent by Rohit (U1)",
+ 'To answer: slack_post_message(workspace="T07", channel="C0B", thread_ts="1788.5", text=…) — pre-approved for this thread.',
+ ]
+ dm = SessionSource(platform="slack", chat_id="D9", user_id="U1", user_name="U1", chat_type="dm")
+ assert where_line(dm) == "From Slack · workspace default · DM (D9)"
+ judged = origin_block(src, thread="1788.5", judgement_only=True)
+ assert judged.endswith("— this asks for approval.") and "only if it clearly concerns your job" in judged
+
+
+def test_origin_block_telegram_and_github():
+ tg = SessionSource(platform="telegram", chat_id="123", user_id="7", user_name="Ann", chat_name="Ann", chat_type="dm")
+ assert reply_call(tg) == 'telegram_send_message(chat_id="123", text=…)'
+ assert where_line(tg, "1") == "From Telegram · chat 123 (Ann)" # the General topic is not a topic
+ gh = SessionSource(platform="github", chat_id="acme/site#42", user_id="octocat", user_name="octocat", chat_name="acme/site#42", chat_type="channel")
+ assert where_line(gh, frame={"kind": "pr_open", "title": "Add retry"}) == 'From GitHub · acme/site · pull request #42 "Add retry"'
+ assert where_line(gh, frame={"kind": "issue_open"}) == "From GitHub · acme/site · issue #42"
+ assert reply_call(gh) == 'github_reply(owner="acme", repo="site", number=42, body=…)'
+ block = origin_block(gh, frame={"is_pr": True})
+ assert block.endswith('body=…) — pre-approved for this thread; github_review(owner="acme", repo="site", pull_number=42, event=…, body=…) likewise.')
+ assert "github_review" not in origin_block(gh, frame={"kind": "issue_open"})
diff --git a/tests/test_configured_spawn.py b/tests/test_configured_spawn.py
new file mode 100644
index 00000000..48a01770
--- /dev/null
+++ b/tests/test_configured_spawn.py
@@ -0,0 +1,326 @@
+"""Configurations on the box (connectors-across-machines spec §10.4): a spawn spec
+starts a session (coworker, model, checkout, skills, instructions); a reply-only
+frame posts one line; a configured event to an existing session carries its own
+framing; titles are unique per machine; the picker learns which rows are leads."""
+
+from __future__ import annotations
+
+import asyncio
+import subprocess
+from pathlib import Path
+
+from coworker.connectors.base import MessageEvent, SessionSource
+from coworker.server.manager import SessionManager, configured_opening
+from tests.test_subscriptions import ScriptedProvider
+
+
+def _github_event(*, kind="pr_open", number="42", configuration=None, reply_only=None, known_names=(), name="", sender="octocat", repo="acme/site"):
+ frame = {
+ "provider": "github", "installation_id": "101", "owner_repo": repo, "number": number,
+ "kind": kind, "name": name, "event": "pull_request", "sender": sender,
+ "title": "Add retry loop", "body": "Retries the worker fetch.",
+ "url": f"https://github.com/{repo}/pull/{number}", "head_ref": "feat/retry", "base_ref": "main",
+ }
+ ev = MessageEvent(
+ text=f"[PR opened in {repo}#{number}: Add retry loop] Retries the worker fetch.",
+ source=SessionSource(platform="github", chat_id=f"{repo}#{number}", user_id=sender, user_name=sender, chat_name=f"{repo}#{number}", chat_type="channel", team_id="101"),
+ raw=frame,
+ mentions_me=True,
+ configuration=configuration,
+ reply_only=reply_only,
+ known_names=list(known_names),
+ )
+ return ev
+
+
+def _connect_github(mgr):
+ mgr.secrets.put("github:default", {"token": "ghp_test", "enabled": True})
+
+
+class FakeGateway:
+ def __init__(self):
+ self.sent: list[tuple[str, str]] = []
+
+ async def deliver(self, target, text):
+ self.sent.append((target, text))
+ return type("R", (), {"ok": True})()
+
+
+def _mgr(tmp_path, monkeypatch):
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))
+ mgr = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ _connect_github(mgr)
+ return mgr
+
+
+def test_reply_only_posts_one_line_and_starts_nothing(tmp_path, monkeypatch):
+ mgr = _mgr(tmp_path, monkeypatch)
+ mgr.gateway = FakeGateway() # must NOT be used for GitHub (its send needs a desktop session)
+ posted: list[tuple[str, str]] = []
+ monkeypatch.setattr(
+ "coworker.connectors.github_send.send_github_comment",
+ lambda secrets, chat_id, text: posted.append((chat_id, text)) or {"ok": True},
+ )
+ delivered: list = []
+
+ async def fake_deliver(session_id, message, *, source=None):
+ delivered.append(session_id)
+
+ monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)
+ before = {r["session_id"] for r in mgr.list_sessions()}
+ ev = _github_event(kind="mention", name="reviwer", reply_only="unknown_name", known_names=["reviewer", "sec-lead"])
+ asyncio.run(mgr._dispatch_inbound(ev))
+ assert delivered == []
+ assert {r["session_id"] for r in mgr.list_sessions()} == before
+ assert mgr.gateway.sent == []
+ (chat_id, text) = posted[0]
+ assert chat_id == "acme/site#42"
+ assert "`reviwer`" in text and "`reviewer`" in text and "`sec-lead`" in text
+
+
+def test_spawn_starts_a_session_from_the_spec(tmp_path, monkeypatch):
+ mgr = _mgr(tmp_path, monkeypatch)
+ delivered: list[tuple[str, str]] = []
+
+ async def fake_deliver(session_id, message, *, source=None):
+ delivered.append((session_id, message))
+
+ monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)
+ cfg = {
+ "config_id": "cfg1", "event": "pr_open", "name": "",
+ "spawn": {"kind": "new", "machine_id": "m-a", "persona": "cowork", "models": ["ollama:qwen3-coder:30b"],
+ "base_dir": "", "worktree": True, "skills": ["semgrep-review"], "instructions": "Correctness first, then security."},
+ }
+ asyncio.run(mgr._dispatch_inbound(_github_event(configuration=cfg)))
+ assert len(delivered) == 1
+ sid, opening = delivered[0]
+ assert "A pull request was opened on GitHub in acme/site#42: Add retry loop (by octocat)." in opening
+ # The origin block names the exact reply call (spec §11.3); the opaque handle is gone.
+ assert "From GitHub · acme/site · pull request #42" in opening
+ assert 'github_reply(owner="acme", repo="site", number=42, body=…) — pre-approved for this thread; github_review(owner="acme", repo="site", pull_number=42' in opening
+ assert "github:acme/site#42" not in opening and "data to review" in opening
+ row = next(r for r in mgr.list_sessions() if r["session_id"] == sid)
+ assert row["agent"] == "cowork" and row["origin"] == "github" and row["title"].startswith("PR #42")
+ assert row["model"] == "ollama:qwen3-coder:30b" # the spec's first entry (cowork has no list)
+ rec = mgr.session_store.load(sid)
+ assert rec.spawn["config_id"] == "cfg1" and rec.spawn["instructions"] == "Correctness first, then security."
+ # Spec §11.5 defaults: auto-approve + send approvals to the Inbox; the reviewer may
+ # judge this session's calls with nobody attending (the human opted in).
+ assert rec.mode == "auto-approve" and rec.spawn["approval_mode"] == "auto-approve"
+ assert mgr.unattended.is_unattended(sid) is True and mgr.reviewer_opted(sid) is True
+ assert mgr.get_engine(sid).is_attended() is True
+ assert rec.spawn["worktree"] == "" and rec.spawn["clone"] == "" # no base directory
+ # Session-only: the instructions join the standing rules for this session, no other.
+ assert "For this session: Correctness first" in mgr._user_rules_for(sid)
+ other = mgr.get_engine("plain", agent="cowork")
+ mgr.save("plain", other)
+ assert "Correctness first" not in mgr._user_rules_for("plain")
+ # Skills listed in the spec are enabled for the session; the thread is owned.
+ assert mgr.session_skills.get(sid) == {"semgrep-review": True}
+ assert mgr.mention_sessions.get("github:acme/site#42") == sid
+ # The thread grant covers replying and reviewing on THIS pull request, and it
+ # survives a rebuild (re-derived from the thread map, not from the live engine).
+ for tool in ("send_message", "github_reply", "github_review"):
+ assert mgr.get_engine(sid).permissions.task_rules[tool] == {"github:acme/site#42"}, tool
+ mgr._engines.pop(sid)
+ assert mgr.get_engine(sid).permissions.task_rules["github_review"] == {"github:acme/site#42"}
+ # A per-turn save never clears the spawn record.
+ mgr.save(sid, mgr.get_engine(sid))
+ assert mgr.session_store.load(sid).spawn["config_id"] == "cfg1"
+
+
+def _git(*args, cwd=None):
+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
+
+
+def _local_origin(tmp_path) -> Path:
+ """A bare acme/site.git with main and a PR #42 head, served over file://."""
+ origin = tmp_path / "origin" / "acme" / "site.git"
+ origin.parent.mkdir(parents=True)
+ _git("init", "--bare", "-b", "main", str(origin))
+ src = tmp_path / "seed"
+ _git("clone", "-q", str(origin), str(src))
+ _git("-C", str(src), "config", "user.email", "t@t")
+ _git("-C", str(src), "config", "user.name", "t")
+ (src / "README.md").write_text("main\n")
+ _git("-C", str(src), "add", ".")
+ _git("-C", str(src), "commit", "-qm", "main")
+ _git("-C", str(src), "push", "-q", "origin", "main")
+ _git("-C", str(src), "checkout", "-qb", "feat/retry")
+ (src / "worker.ts").write_text("retry()\n")
+ _git("-C", str(src), "add", ".")
+ _git("-C", str(src), "commit", "-qm", "pr")
+ _git("-C", str(src), "push", "-q", "origin", "feat/retry:refs/pull/42/head")
+ return tmp_path / "origin"
+
+
+def test_spawn_checks_out_a_worktree_and_archive_removes_it(tmp_path, monkeypatch):
+ origin = _local_origin(tmp_path)
+ monkeypatch.setenv("GITHUB_GIT_URL", f"file://{origin}")
+ monkeypatch.delenv("OPENWORKER_BASE_DIR", raising=False)
+ mgr = _mgr(tmp_path, monkeypatch)
+ delivered: list[tuple[str, str]] = []
+
+ async def fake_deliver(session_id, message, *, source=None):
+ delivered.append((session_id, message))
+
+ monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)
+ base = tmp_path / "work"
+ cfg = {"config_id": "cfg2", "event": "pr_open", "spawn": {"kind": "new", "persona": "cowork", "models": [], "base_dir": str(base), "worktree": True}}
+ asyncio.run(mgr._dispatch_inbound(_github_event(configuration=cfg)))
+ sid, opening = delivered[0]
+ rec = mgr.session_store.load(sid)
+ clone, wt = base / "site" / "main", base / "site" / "pr-42"
+ assert rec.spawn["clone"] == str(clone) and rec.spawn["worktree"] == str(wt)
+ assert Path(rec.workspace).resolve() == wt.resolve()
+ assert (wt / "worker.ts").exists() and not (clone / "worker.ts").exists() # the PR head, not main
+ assert f"checkout of the code under review: {wt}" in opening
+ # No token at rest in the clone.
+ assert "AUTHORIZATION" not in (clone / ".git" / "config").read_text()
+ # Archive: the worktree goes, the clone stays.
+ assert mgr.set_session_flags(sid, archived=True)["ok"] is True
+ assert not wt.exists() and (clone / ".git").exists()
+ assert "pr-42" not in _git("-C", str(clone), "worktree", "list")
+
+
+def test_spawn_without_a_worktree_works_in_the_clone(tmp_path, monkeypatch):
+ origin = _local_origin(tmp_path)
+ monkeypatch.setenv("GITHUB_GIT_URL", f"file://{origin}")
+ monkeypatch.delenv("OPENWORKER_BASE_DIR", raising=False)
+ mgr = _mgr(tmp_path, monkeypatch)
+
+ async def fake_deliver(session_id, message, *, source=None):
+ pass
+
+ monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)
+ base = tmp_path / "work"
+ cfg = {"config_id": "cfg3", "event": "issue_open", "spawn": {"kind": "new", "persona": "cowork", "base_dir": str(base), "worktree": False}}
+ asyncio.run(mgr._dispatch_inbound(_github_event(kind="issue_open", number="9", configuration=cfg)))
+ rec = next(mgr.session_store.load(r["session_id"]) for r in mgr.list_sessions() if r["origin"] == "github")
+ assert Path(rec.workspace).resolve() == (base / "site" / "main").resolve()
+ assert rec.spawn["worktree"] == ""
+ # Deleting it keeps the clone (nothing to remove).
+ mgr.delete_session(rec.session_id)
+ assert (base / "site" / "main" / ".git").exists()
+
+
+def test_checkout_outside_the_base_dir_is_refused(tmp_path, monkeypatch):
+ monkeypatch.setenv("OPENWORKER_BASE_DIR", str(tmp_path / "allowed"))
+ (tmp_path / "allowed").mkdir()
+ mgr = _mgr(tmp_path, monkeypatch)
+ recorded: list = []
+ monkeypatch.setattr(mgr.unrouted, "record", lambda *a, **k: recorded.append((a, k)))
+ cfg = {"config_id": "cfg4", "event": "pr_open", "spawn": {"kind": "new", "persona": "cowork", "base_dir": str(tmp_path / "elsewhere"), "worktree": True}}
+ asyncio.run(mgr._dispatch_inbound(_github_event(configuration=cfg)))
+ assert recorded and "checkout failed" in recorded[0][1]["reason"]
+
+
+def test_configured_event_to_an_existing_session_carries_its_framing(tmp_path, monkeypatch):
+ mgr = _mgr(tmp_path, monkeypatch)
+ delivered: list[tuple[str, str]] = []
+
+ async def fake_deliver(session_id, message, *, source=None):
+ delivered.append((session_id, message))
+
+ monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)
+ mgr.save("sec-lead", mgr.get_engine("sec-lead", agent="cowork"))
+ ev = _github_event(kind="pr_merge", configuration={"config_id": "c", "event": "pr_merge", "name": ""})
+ ev.target_session_id = "sec-lead"
+ asyncio.run(mgr._dispatch_inbound(ev))
+ assert [s for s, _ in delivered] == ["sec-lead"]
+ assert "A pull request was merged on GitHub in acme/site#42" in delivered[0][1]
+ # The promised pre-approval is real: the thread is granted to the existing session —
+ # replying AND reviewing on that one pull request, nothing wider.
+ rules = mgr.get_engine("sec-lead").permissions.task_rules
+ for tool in ("send_message", "github_reply", "github_review"):
+ assert rules.get(tool) == {"github:acme/site#42"}, tool
+
+
+def test_titles_are_unique_per_machine_and_rows_flag_leads(tmp_path, monkeypatch):
+ mgr = _mgr(tmp_path, monkeypatch)
+ mgr.save("a", mgr.get_engine("a", agent="cowork"))
+ mgr.save("b", mgr.get_engine("b", agent="cowork"))
+ assert mgr.rename_session("a", "Reviewer")["ok"] is True
+ dup = mgr.rename_session("b", "Reviewer")
+ assert dup["ok"] is False and "already named" in dup["error"]
+ assert mgr.rename_session("a", "Reviewer")["ok"] is True # renaming to its own title is fine
+ rows = {r["session_id"]: r for r in mgr.list_sessions()}
+ assert rows["a"]["lead"] is False
+ mgr.session_store.save(type(mgr.session_store.load("a"))(session_id="lead", workspace=str(tmp_path), model="m", mode="interactive", agent="swe-lead"))
+ assert {r["session_id"]: r for r in mgr.list_sessions()}["lead"]["lead"] is True
+
+
+def test_configured_opening_reads_plainly():
+ ev = _github_event(kind="issue_open", number="9", configuration={"config_id": "c", "event": "issue_open"})
+ text = configured_opening(ev, "github:acme/site#9", "")
+ assert text.startswith("An issue was opened on GitHub in acme/site#9: Add retry loop (by octocat).")
+ assert "Your session folder" not in text
+
+
+def test_named_mention_on_a_pr_checks_out_the_pr_head(tmp_path, monkeypatch):
+ origin = _local_origin(tmp_path)
+ monkeypatch.setenv("GITHUB_GIT_URL", f"file://{origin}")
+ monkeypatch.delenv("OPENWORKER_BASE_DIR", raising=False)
+ mgr = _mgr(tmp_path, monkeypatch)
+
+ async def fake_deliver(session_id, message, *, source=None):
+ pass
+
+ monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)
+ base = tmp_path / "work"
+ cfg = {"config_id": "cfg5", "event": "named_mention", "name": "reviewer", "spawn": {"kind": "new", "persona": "cowork", "base_dir": str(base), "worktree": True}}
+ ev = _github_event(kind="mention", name="reviewer", configuration=cfg)
+ ev.raw["is_pr"] = True
+ asyncio.run(mgr._dispatch_inbound(ev))
+ rec = next(mgr.session_store.load(r["session_id"]) for r in mgr.list_sessions() if r["origin"] == "github")
+ assert rec.spawn["worktree"] == str(base / "site" / "pr-42")
+ assert (base / "site" / "pr-42" / "worker.ts").exists() # the PR head, not main
+ assert rec.title.startswith("PR mention #42")
+
+
+def test_configured_event_to_a_gated_session_is_parked_not_swallowed(tmp_path, monkeypatch):
+ mgr = _mgr(tmp_path, monkeypatch)
+ delivered: list = []
+
+ async def fake_deliver(session_id, message, *, source=None):
+ delivered.append(session_id)
+
+ monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)
+ monkeypatch.setattr(mgr, "_inbound_connector_allowed", lambda sid, platform: False)
+ recorded: list = []
+ monkeypatch.setattr(mgr.unrouted, "record", lambda *a, **k: recorded.append(k.get("reason", "")))
+ mgr.save("lead", mgr.get_engine("lead", agent="cowork"))
+ ev = _github_event(kind="pr_merge", configuration={"config_id": "c", "event": "pr_merge", "name": ""})
+ ev.target_session_id = "lead"
+ asyncio.run(mgr._dispatch_inbound(ev))
+ assert delivered == [] and recorded and "off for the target session" in recorded[0]
+
+
+def test_swe_lead_is_reachable_on_github_and_slack():
+ from pathlib import Path
+
+ from coworker.personas.manifest import parse_manifest
+
+ m = parse_manifest((Path(__file__).resolve().parents[1] / "coworker/personas/builtin/swe-lead/manifest.md").read_text())
+ assert set(m.connectors) == {"github", "slack"}
+
+
+def test_spawn_applies_the_configured_approval_mode_and_inbox_dial(tmp_path, monkeypatch):
+ mgr = _mgr(tmp_path, monkeypatch)
+
+ async def fake_deliver(session_id, message, *, source=None):
+ pass
+
+ monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)
+ cfg = {"config_id": "cfg9", "event": "pr_open", "name": "", "spawn": {"kind": "new", "persona": "cowork", "models": [], "approval_mode": "interactive", "unattended": False}}
+ asyncio.run(mgr._dispatch_inbound(_github_event(configuration=cfg)))
+ sid = next(r["session_id"] for r in mgr.list_sessions() if r["title"].startswith("PR #42"))
+ rec = mgr.session_store.load(sid)
+ assert rec.mode == "interactive" and mgr.unattended.is_unattended(sid) is False
+ assert mgr.reviewer_opted(sid) is False and mgr.get_engine(sid).is_attended is None
+ # Bypass is the user's call (owner ruling): stored and applied as given; legacy "auto" too.
+ cfg = {"config_id": "cfg10", "event": "pr_open", "name": "", "spawn": {"kind": "new", "persona": "cowork", "models": [], "approval_mode": "auto"}}
+ asyncio.run(mgr._dispatch_inbound(_github_event(number="43", configuration=cfg)))
+ sid = next(r["session_id"] for r in mgr.list_sessions() if r["title"].startswith("PR #43"))
+ assert mgr.session_store.load(sid).mode == "bypass-approvals"
+
diff --git a/tests/test_github_installs.py b/tests/test_github_installs.py
index 907dd2e6..f2cc8377 100644
--- a/tests/test_github_installs.py
+++ b/tests/test_github_installs.py
@@ -44,7 +44,7 @@ def client(tmp_path, monkeypatch):
def _install_form(installation_id: str, *, login="octocat", account="acme") -> dict:
"""The broker's loopback POST — deliberately NO token fields (§4)."""
state = f"github-{installation_id}"
- cloud._pending_managed_states[state] = cloud._now()
+ cloud._pending_managed_states[state] = {"created": cloud._now(), "machine_id": "", "machine_name": ""}
return {
"connector": "github",
"installation_id": installation_id,
@@ -140,6 +140,29 @@ def test_disconnect_last_installation_never_resurrects_manual_pat(client, monkey
# --- allow-list: per-installation scope (the per-workspace pattern) -----------
+def test_managed_install_pre_adds_the_installer(tmp_path, monkeypatch):
+ """Connecting the App is consent to talk to your own coworker: the installing
+ login is on the allow-list from the first frame (Slack's UX-027 rule)."""
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))
+ secrets = SecretStore()
+ github_installs.managed_connect_install(secrets, _install_form("101", login="rohit"))
+ assert secrets.get("github:install:101")["allowed_users"] == ["rohit"]
+ settings = load_settings(secrets)["github"]
+
+ class Src:
+ platform = "github"
+ team_id = "101"
+ user_id = "rohit"
+
+ assert is_authorized(settings, Src()) is True
+ # A reinstall by someone else keeps the earlier list and adds the new installer.
+ github_installs.managed_connect_install(secrets, _install_form("101", login="teammate"))
+ assert secrets.get("github:install:101")["allowed_users"] == ["rohit", "teammate"]
+ # No login on the form (older broker) → no phantom entry.
+ github_installs.managed_connect_install(secrets, _install_form("202", login=""))
+ assert "allowed_users" not in secrets.get("github:install:202")
+
+
def test_github_settings_carry_per_installation_allowlists(tmp_path, monkeypatch):
monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))
secrets = SecretStore()
@@ -589,10 +612,22 @@ def test_clone_refuses_paths_outside_granted_roots(tmp_path, monkeypatch, _origi
monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))
monkeypatch.setenv("GITHUB_GIT_URL", f"file://{_origin['base']}")
secrets = SecretStore()
- _granted, tools = _clone_tools(secrets, tmp_path)
+ granted, tools = _clone_tools(secrets, tmp_path)
out = tools["github_clone"]("acme", "site", directory=str(tmp_path / "elsewhere"))
assert "outside the session's writable directories" in out["error"]
+ assert str(granted) in out["error"] # the roots are named so the agent can correct itself
+ # Strict: a relative name is never resolved against the cwd or a root.
+ for tool, args in (
+ ("github_clone", ("acme", "site")),
+ ("github_pull", ()),
+ ("github_push", ()),
+ ("github_open_pr", ()),
+ ):
+ kw = {"directory": "site"} if tool != "github_open_pr" else {"directory": "site", "title": "t"}
+ out = tools[tool](*args, **kw)
+ assert "must be an absolute path" in out["error"] and str(granted) in out["error"], tool
+ assert not (granted / "site").exists()
assert not (tmp_path / "elsewhere").exists()
# and with no writable root at all → a clear error, no filesystem writes
@@ -614,3 +649,57 @@ def test_clone_refuses_non_empty_target(tmp_path, monkeypatch, _origin):
out = tools["github_clone"]("acme", "site")
assert "not empty" in out["error"]
assert (granted / "site" / "keep.txt").read_text() == "existing work"
+
+
+def test_push_and_open_pr_tools(tmp_path, monkeypatch, _origin):
+ """The runtime pushes and opens the PR — the agent never handles a
+ credential (machines spec: tools are the future sandbox boundary). Push
+ publishes a feature branch to origin; open_pr posts the API call with the
+ clone's parsed owner/repo and branch."""
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))
+ monkeypatch.setenv("GITHUB_GIT_URL", f"file://{_origin['base']}")
+ secrets = SecretStore()
+ github_installs.managed_connect_install(secrets, _install_form("101"))
+ monkeypatch.setattr(
+ cloud, "github_installation_token", lambda s, c, iid, *, force=False: "ghs_live"
+ )
+ granted, tools = _clone_tools(secrets, tmp_path)
+
+ assert tools["github_clone"]("acme", "site").get("ok") is True
+ clone = granted / "site"
+ _git(["checkout", "-b", "feature/scaffold"], cwd=clone)
+ (clone / "src.ts").write_text("export {}\n")
+ _git(["add", "."], cwd=clone)
+ _git(["commit", "-m", "scaffold"], cwd=clone)
+
+ out = tools["github_push"](str(clone))
+ assert out == {"ok": True, "branch": "feature/scaffold", "head": out["head"]}
+ # The branch really landed on the 'GitHub' side.
+ import subprocess
+
+ bare = _origin["base"] / "acme" / "site.git"
+ branches = subprocess.run(
+ ["git", "branch"], cwd=bare, capture_output=True, text=True
+ ).stdout
+ assert "feature/scaffold" in branches
+
+ from coworker.connectors import integration_tools as it
+
+ seen = {}
+
+ def fake_call(_secrets, method, path, *, install="", **kw):
+ seen.update({"method": method, "path": path, "install": install, **kw})
+ # The runtime's HTTP envelope: the created PR sits under `data`.
+ return {"ok": True, "data": {"number": 7, "html_url": "https://github.com/acme/site/pull/7"}}
+
+ monkeypatch.setattr(it, "_github_call", fake_call)
+ pr = tools["github_open_pr"](str(clone), "Add scaffolding", body="initial")
+ assert pr["ok"] is True and pr["number"] == 7
+ assert pr["url"].endswith("/pull/7")
+ assert seen["path"] == "/repos/acme/site/pulls"
+ assert seen["json"] == {
+ "title": "Add scaffolding",
+ "body": "initial",
+ "base": "main",
+ "head": "feature/scaffold",
+ }
diff --git a/tests/test_hubspot_portals.py b/tests/test_hubspot_portals.py
index 19a836b3..281e8986 100644
--- a/tests/test_hubspot_portals.py
+++ b/tests/test_hubspot_portals.py
@@ -203,7 +203,7 @@ def client(tmp_path, monkeypatch):
def test_managed_callback_lands_in_portal_profile(client):
import coworker.cloud as cloud
- cloud._pending_managed_states["s"] = cloud._now()
+ cloud._pending_managed_states["s"] = {"created": cloud._now(), "machine_id": "", "machine_name": ""}
resp = client.post(
"/oauth/callback",
data={
diff --git a/tests/test_machine_poll.py b/tests/test_machine_poll.py
new file mode 100644
index 00000000..43c7b2df
--- /dev/null
+++ b/tests/test_machine_poll.py
@@ -0,0 +1,540 @@
+"""Machine-held Slack inbound (machines spec §Managed events): the poll
+transport that drains the broker's sealed queue, its wiring into the relay
+adapter, and the delegation stamping that arms it."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+
+import pytest
+from fastapi.testclient import TestClient
+
+from coworker.connectors.machine_poll import MachinePollTransport
+from coworker.remote.identity import load_or_create, seal_b64
+from coworker.server import SessionManager, create_app
+
+
+def _transport(tmp_path, events_batches, interval=0.0):
+ """A transport whose poll rounds are canned; unseal = a real box identity."""
+ identity = load_or_create(tmp_path / "box-id")
+ t = MachinePollTransport(
+ "https://broker.test",
+ connection_id="conn_1",
+ user_id="usr_1",
+ credential="mc_t",
+ unseal=identity.unseal_b64,
+ interval=interval,
+ )
+ batches = list(events_batches)
+
+ async def _fake_poll_once():
+ return batches.pop(0) if batches else []
+
+ t._poll_once = _fake_poll_once
+ return t, identity
+
+
+def _sealed(identity, frame: dict) -> dict:
+ return {
+ "event_key": "k",
+ "sealed_b64": seal_b64(identity.seal_public_key_b64, json.dumps(frame).encode()),
+ }
+
+
+async def test_transport_unseals_and_orders_frames(tmp_path):
+ identity = load_or_create(tmp_path / "box-id")
+ one = _sealed(identity, {"provider": "slack", "n": 1})
+ two = _sealed(identity, {"provider": "slack", "n": 2})
+ t, _ = _transport(tmp_path, [[one, two]])
+ await t.open()
+ assert (await t.recv())["n"] == 1
+ assert (await t.recv())["n"] == 2
+ await t.close()
+
+
+async def test_transport_skips_garbage_keeps_going(tmp_path):
+ identity = load_or_create(tmp_path / "box-id")
+ good = _sealed(identity, {"provider": "slack", "n": 1})
+ t, _ = _transport(
+ tmp_path, [[{"event_key": "bad", "sealed_b64": "not-a-blob"}, good]]
+ )
+ await t.open()
+ # The garbage blob is logged and dropped; the good frame still arrives.
+ assert (await t.recv())["n"] == 1
+ await t.close()
+
+
+async def test_transport_close_ends_recv(tmp_path):
+ t, _ = _transport(tmp_path, [], interval=30.0)
+ await t.open()
+ task = asyncio.create_task(t.recv())
+ await asyncio.sleep(0.05)
+ await t.close()
+ assert await asyncio.wait_for(task, timeout=1.0) is None
+
+
+async def test_hub_dispatches_polled_frames(tmp_path):
+ """The RelayHub can't tell this transport from the desktop WebSocket —
+ frames fan out to the registered provider handler exactly the same."""
+ from coworker.connectors.relay_client import RelayHub
+
+ identity = load_or_create(tmp_path / "box-id")
+ frame = {"provider": "slack", "kind": "event", "text": "hi"}
+ t, _ = _transport(tmp_path, [[_sealed(identity, frame)]], interval=5.0)
+ hub = RelayHub("unused://", lambda: "", transport_factory=lambda: t)
+ seen: list[dict] = []
+
+ async def handler(f):
+ seen.append(f)
+
+ hub.register("slack", handler)
+ assert await hub.start()
+ await hub.wait_dispatched(1)
+ await hub.stop()
+ assert seen and seen[0]["text"] == "hi"
+
+
+def test_make_adapter_prefers_poll_transport_on_boxes(tmp_path):
+ from coworker.connectors import make_adapter
+ from coworker.connectors.relay_client import SlackRelayAdapter
+ from coworker.secrets import EphemeralSecretStore
+
+ secrets = EphemeralSecretStore()
+ profile = {
+ "mode": "relay",
+ "managed": True,
+ "connection_id": "conn_1",
+ "broker_user_id": "usr_1",
+ "machine_credential": "mc_t",
+ }
+ identity = load_or_create(tmp_path / "box-id")
+ adapter = make_adapter(
+ "slack",
+ profile,
+ secrets=secrets,
+ machine_unseal=identity.unseal_b64,
+ machine_poll_base="https://broker.test",
+ )
+ assert isinstance(adapter, SlackRelayAdapter)
+ transport = adapter._hub._transport_factory()
+ assert isinstance(transport, MachinePollTransport)
+ # Desktop (no unseal): the stamped profile alone never takes this branch.
+ assert (
+ make_adapter("slack", profile, secrets=secrets, machine_poll_base="x") is None
+ )
+
+
+# --- delegation stamping (the sidecar side that arms the transport) -----------
+
+
+def client(tmp_path, monkeypatch):
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "state"))
+ manager = SessionManager(workspace=tmp_path)
+ app = create_app(manager)
+ with TestClient(app) as c:
+ c.manager = manager
+ yield c
+
+
+def test_slack_delegate_dedupes_and_stamps_pointer(client, monkeypatch):
+ """Every Slack workspace shares ONE broker connection: the handoff must
+ delegate once (a second call would rotate the credential) and stamp the
+ grant into each team profile AND the pointer the poll adapter reads."""
+ from coworker import cloud
+
+ secrets = client.manager.secrets
+ secrets.put(
+ "slack:default", {"type": "oauth", "managed": True, "mode": "relay", "enabled": True}
+ )
+ for team in ("T1", "T2"):
+ secrets.put(
+ f"slack:team:{team}",
+ {
+ "type": "oauth",
+ "managed": True,
+ "bot_token": f"xoxb-{team}",
+ "team_id": team,
+ "connection_id": "conn_slack",
+ },
+ )
+ calls: list[tuple[str, str]] = []
+
+ def fake_delegate(_s, _c, connection_id, *, seal_pubkey="", machine_id=""):
+ calls.append((connection_id, seal_pubkey))
+ return {"user_id": "usr_1", "machine_credential": "mc_minted"}
+
+ monkeypatch.setattr(cloud, "delegate_connection", fake_delegate)
+ r = client.post(
+ "/v1/connectors/slack/delegate", json={"seal_pubkey": "SEALPUB"}
+ )
+ assert r.status_code == 200, r.text
+ assert r.json()["ok"] is True
+ assert calls == [("conn_slack", "SEALPUB")] # deduped: one call, key passed
+ for team in ("T1", "T2"):
+ prof = secrets.get(f"slack:team:{team}")
+ assert prof["broker_user_id"] == "usr_1"
+ assert prof["machine_credential"] == "mc_minted"
+ pointer = secrets.get("slack:default")
+ assert pointer["connection_id"] == "conn_slack"
+ assert pointer["broker_user_id"] == "usr_1"
+ assert pointer["machine_credential"] == "mc_minted"
+
+
+def test_slack_relay_handoff_is_portable_now(client):
+ """Machine events lifted the cloud-runtime gate: relay Slack moves, its
+ unit = every team profile + the pointer, delegation required."""
+ from coworker.connectors.setup import connector_handoff_info
+
+ secrets = client.manager.secrets
+ secrets.put(
+ "slack:default", {"type": "oauth", "managed": True, "mode": "relay", "enabled": True}
+ )
+ secrets.put(
+ "slack:team:T1",
+ {
+ "type": "oauth",
+ "managed": True,
+ "bot_token": "xoxb-1",
+ "team_id": "T1",
+ "connection_id": "conn_slack",
+ },
+ )
+ info = connector_handoff_info(secrets, "slack")
+ assert info["portable"] is True
+ assert info["needs_delegation"] is True
+ assert set(info["profiles"]) == {"slack:team:T1", "slack:default"}
+
+
+def test_revoke_connector_connections_by_name(client, monkeypatch):
+ """The drill finding: a machine-scope disconnect of a managed grant needs
+ the DESKTOP to revoke at the broker (the box has no session) — by
+ connector NAME, since the desktop forgot the profiles at handoff."""
+ from coworker import cloud
+
+ client.manager.secrets.put(
+ cloud.CLOUD_AUTH_PROFILE, {"access_token": "sess", "expires": 9999999999}
+ )
+ calls: list[str] = []
+
+ class _Resp:
+ def __init__(self, status_code, body=None):
+ self.status_code = status_code
+ self._body = body or {}
+
+ def json(self):
+ return self._body
+
+ def fake_get(url, headers=None, timeout=None):
+ return _Resp(
+ 200,
+ {
+ "connections": [
+ {"connection_id": "conn_slack", "connector": "slack", "status": "connected"},
+ {"connection_id": "conn_dead", "connector": "slack", "status": "disconnected"},
+ {"connection_id": "conn_other", "connector": "notion", "status": "connected"},
+ ]
+ },
+ )
+
+ def fake_post(url, headers=None, timeout=None):
+ calls.append(url)
+ return _Resp(200, {"ok": True})
+
+ monkeypatch.setattr(cloud.httpx, "get", fake_get)
+ monkeypatch.setattr(cloud.httpx, "post", fake_post)
+ r = client.post("/v1/cloud/connections/slack/revoke")
+ assert r.status_code == 200
+ assert r.json() == {"ok": True, "revoked": 1}
+ # Only the LIVE slack connection was disconnected — never other
+ # connectors, never already-dead rows.
+ assert len(calls) == 1 and calls[0].endswith("/v1/connections/conn_slack/disconnect")
+
+
+# --- increment 2: GitHub on the same spine ------------------------------------
+
+
+def _seed_github_install(secrets, installation_id="9001"):
+ from coworker.connectors.github_installs import managed_connect_install
+
+ return managed_connect_install(
+ secrets,
+ {
+ "installation_id": installation_id,
+ "account_login": "quillvoice",
+ "account_type": "Organization",
+ "github_login": "rohit",
+ "repo_selection": "selected",
+ "connection_id": "conn_gh",
+ },
+ )
+
+
+def test_github_handoff_is_portable_metadata_only(client):
+ """A GitHub handoff moves NO secrets: installation routing metadata plus
+ the pointer — tokens mint on demand via the machine credential."""
+ from coworker.connectors.setup import connector_handoff_info
+
+ secrets = client.manager.secrets
+ _seed_github_install(secrets)
+ info = connector_handoff_info(secrets, "github")
+ assert info["portable"] is True
+ assert info["needs_delegation"] is True
+ assert set(info["profiles"]) == {"github:install:9001", "github:default"}
+
+
+def test_github_delegate_stamps_pointer(client, monkeypatch):
+ from coworker import cloud
+
+ secrets = client.manager.secrets
+ _seed_github_install(secrets)
+ monkeypatch.setattr(
+ cloud,
+ "delegate_connection",
+ lambda *a, **k: {"user_id": "usr_1", "machine_credential": "mc_gh"},
+ )
+ r = client.post("/v1/connectors/github/delegate", json={"seal_pubkey": "PUB"})
+ assert r.status_code == 200 and r.json()["ok"], r.text
+ pointer = secrets.get("github:default")
+ assert pointer["connection_id"] == "conn_gh"
+ assert pointer["machine_credential"] == "mc_gh"
+ assert secrets.get("github:install:9001")["machine_credential"] == "mc_gh"
+
+
+def test_github_token_mints_by_credential_without_session(monkeypatch, tmp_path):
+ """The box fallback: no cloud session → mint on the delegated route with
+ the pointer's stamps, bearer = machine credential."""
+ from coworker import cloud
+ from coworker.config import Config
+ from coworker.secrets import EphemeralSecretStore
+
+ secrets = EphemeralSecretStore()
+ secrets.put(
+ "github:default",
+ {
+ "mode": "relay",
+ "managed": True,
+ "connection_id": "conn_gh",
+ "broker_user_id": "usr_1",
+ "machine_credential": "mc_gh",
+ },
+ )
+ seen = {}
+
+ class _Resp:
+ status_code = 200
+
+ @staticmethod
+ def json():
+ return {"token": "ghs_BOX", "expires_at": ""}
+
+ def fake_post(url, json=None, headers=None, timeout=None):
+ seen.update({"url": url, "json": json, "auth": headers["Authorization"]})
+ return _Resp()
+
+ monkeypatch.setattr(cloud.httpx, "post", fake_post)
+ cloud._GITHUB_TOKEN_CACHE.clear()
+ token = cloud.github_installation_token(secrets, Config(), "9001", force=True)
+ assert token == "ghs_BOX"
+ assert seen["url"].endswith("/v1/machine/github/mint")
+ assert seen["json"]["connection_id"] == "conn_gh"
+ assert seen["auth"] == "Bearer mc_gh"
+ cloud._GITHUB_TOKEN_CACHE.clear()
+
+
+def test_make_adapter_github_poll_transport_on_boxes(tmp_path):
+ from coworker.connectors import make_adapter
+ from coworker.connectors.github_relay import GitHubRelayAdapter
+ from coworker.secrets import EphemeralSecretStore
+
+ secrets = EphemeralSecretStore()
+ _ = secrets # installs empty is fine
+ profile = {
+ "mode": "relay",
+ "managed": True,
+ "connection_id": "conn_gh",
+ "broker_user_id": "usr_1",
+ "machine_credential": "mc_gh",
+ }
+ identity = load_or_create(tmp_path / "box-id")
+ adapter = make_adapter(
+ "github",
+ profile,
+ secrets=secrets,
+ machine_unseal=identity.unseal_b64,
+ machine_poll_base="https://broker.test",
+ )
+ assert isinstance(adapter, GitHubRelayAdapter)
+ assert isinstance(adapter._hub._transport_factory(), MachinePollTransport)
+ # Desktop shape unchanged: without unseal, relay needs url+sign-in.
+ assert make_adapter("github", profile, secrets=secrets) is None
+
+
+async def test_github_frame_is_a_mention_for_the_router(tmp_path):
+ """Drill finding: every routed GitHub frame is a directed ask (the broker
+ only forwards wave-1 triggers), so the adapter must flag mentions_me —
+ without it the mention router never spawns a session for GitHub."""
+ from coworker.connectors.github_relay import GitHubRelayAdapter
+ from coworker.connectors.relay_client import RelayHub
+
+ adapter = GitHubRelayAdapter(RelayHub("unused://", lambda: ""), installs={})
+ seen = []
+
+ async def capture(event):
+ seen.append(event)
+
+ adapter.handle_message = capture
+ await adapter._on_event(
+ {
+ "provider": "github",
+ "kind": "mention",
+ "installation_id": "9001",
+ "owner_repo": "o/r",
+ "number": 1,
+ "sender": "rohit",
+ "body": "@openworker-agent do the thing",
+ }
+ )
+ assert seen and seen[0].mentions_me is True
+
+
+def test_parked_message_preserves_mention_flag(tmp_path):
+ """Park → allow_deliver must not lose the mention bit (the re-injected
+ event takes the §31 mention route)."""
+ from coworker.connectors.parked import ParkedStore
+
+ store = ParkedStore(tmp_path / "parked.json")
+ item = store.park(
+ platform="github",
+ chat_id="o/r#1",
+ user_id="rohit",
+ text="[mention] hi",
+ team_id="9001",
+ mentions_me=True,
+ )
+ assert store.pop(item.id).mentions_me is True
+
+
+def test_send_message_github_posts_issue_comment(monkeypatch):
+ """Drill finding: send_message had NO github path ("unknown platform").
+ Now it comments on the issue/PR thread, minting via the same auth ladder
+ as the read tools — which on a box is the machine credential."""
+ from coworker.connectors.tools import make_send_message_tool
+ from coworker.secrets import EphemeralSecretStore
+
+ secrets = EphemeralSecretStore()
+ secrets.put(
+ "github:default",
+ {
+ "mode": "relay",
+ "managed": True,
+ "connection_id": "conn_gh",
+ "broker_user_id": "usr_1",
+ "machine_credential": "mc_gh",
+ },
+ )
+ secrets.put(
+ "github:install:9001",
+ {"managed": True, "installation_id": "9001", "account_login": "rohitcpbot"},
+ )
+ from coworker import cloud
+
+ monkeypatch.setattr(
+ cloud, "github_installation_token", lambda *a, **k: "ghs_MINTED"
+ )
+ seen = {}
+
+ class _Resp:
+ status_code = 201
+
+ @staticmethod
+ def json():
+ return {"id": 4242}
+
+ def fake_post(url, json=None, headers=None, timeout=None):
+ seen.update({"url": url, "auth": headers.get("Authorization", "")})
+ return _Resp()
+
+ import httpx as _httpx
+
+ monkeypatch.setattr(_httpx, "post", fake_post)
+
+ tool = make_send_message_tool(secrets)
+ out = tool("github:rohitcpbot/dailypuzzle#2", "All set — connected and listening.")
+ assert out == {
+ "ok": True,
+ "message_id": "4242",
+ "target": "github:rohitcpbot/dailypuzzle#2",
+ }
+ assert seen["url"].endswith("/repos/rohitcpbot/dailypuzzle/issues/2/comments")
+ assert seen["auth"] == "Bearer ghs_MINTED"
+
+
+
+async def test_github_frame_carries_the_broker_target_session():
+ """Connectors-across-machines spec §3: a subscribed repo's events name
+ the responder; the adapter passes it through untouched."""
+ from coworker.connectors.github_relay import GitHubRelayAdapter
+ from coworker.connectors.relay_client import RelayHub
+
+ adapter = GitHubRelayAdapter(RelayHub("unused://", lambda: ""), installs={})
+ seen = []
+
+ async def capture(event):
+ seen.append(event)
+
+ adapter.handle_message = capture
+ base = {"provider": "github", "kind": "mention", "installation_id": "9001",
+ "owner_repo": "o/r", "number": 1, "sender": "rohit", "body": "@ow hi"}
+ await adapter._on_event({**base, "target_session_id": "lead-1"})
+ await adapter._on_event(base)
+ assert [e.target_session_id for e in seen] == ["lead-1", None]
+
+
+def test_cursor_persists_across_transports(tmp_path):
+ """A restart must not replay the broker's ~15 min of queued events (drill
+ finding 2026-09-04: a duplicate PR session): the cursor is kept on disk."""
+ from coworker.connectors.machine_poll import MachinePollTransport
+
+ path = tmp_path / "poll-cursors" / "conn.cursor"
+ t = MachinePollTransport("http://x", connection_id="c", user_id="u", credential="mc", unseal=lambda b: b"", cursor_path=path)
+ assert t._cursor == ""
+ t._cursor = "1788574089744#81997fbe"
+ t._save_cursor()
+ t2 = MachinePollTransport("http://x", connection_id="c", user_id="u", credential="mc", unseal=lambda b: b"", cursor_path=path)
+ assert t2._cursor == "1788574089744#81997fbe"
+
+
+async def test_hub_does_not_block_on_a_slow_handler(tmp_path):
+ """Two frames; the first handler takes a while. The second must be handled
+ before the first finishes (a review turn must not hold a merge back)."""
+ from coworker.connectors.relay_client import RelayHub
+
+ identity = load_or_create(tmp_path / "box-id")
+ f1 = {"provider": "slack", "kind": "event", "text": "slow"}
+ f2 = {"provider": "slack", "kind": "event", "text": "fast"}
+ t, _ = _transport(tmp_path, [[_sealed(identity, f1), _sealed(identity, f2)]], interval=5.0)
+ hub = RelayHub("unused://", lambda: "", transport_factory=lambda: t)
+ order: list[str] = []
+ gate = asyncio.Event()
+
+ async def handler(f):
+ if f["text"] == "slow":
+ await gate.wait()
+ order.append(f["text"])
+
+ hub.register("slack", handler)
+ assert await hub.start()
+ await hub.wait_dispatched(1) # "fast" completes while "slow" is still parked
+ assert order == ["fast"]
+ gate.set()
+ await hub.wait_dispatched(2)
+ await hub.stop()
+ assert order == ["fast", "slow"]
diff --git a/tests/test_mention_router.py b/tests/test_mention_router.py
index fed63b56..280bcbb6 100644
--- a/tests/test_mention_router.py
+++ b/tests/test_mention_router.py
@@ -131,10 +131,35 @@ def test_mention_spawns_visible_session_with_thread_grant(tmp_path, monkeypatch)
# The opening turn carries the reply contract and went to the new session.
got_sid, opening, source = captured[-1]
assert got_sid == sid
- assert target in opening and "pre-approved" in opening
+ # The origin block (spec §11.3): ids the model copies into the reply call, no handle.
+ assert "From Slack · workspace default · #general (C1) · thread 1700000010.000100" in opening
+ assert 'slack_post_message(workspace="default", channel="C1", thread_ts="1700000010.000100", text=…) — pre-approved' in opening
+ assert target not in opening
+ assert "mentioned on Slack in #general" in opening and "Slack-appropriate" in opening
+ # The grant covers the platform's own reply tool as well (spec §11.4).
+ assert target in mgr._engines[sid].permissions.task_rules["slack_post_message"]
assert source["connector"] == "slack" and source["kind"] == "channel"
+def test_mention_opening_is_framed_for_the_platform():
+ """GitHub mentions must not be told they own a Slack thread (2026-09-01 drill)."""
+ from coworker.server.manager import mention_opening
+
+ gh_src = SessionSource(platform="github", chat_id="acme/api#12", user_id="rohit", user_name="rohit", chat_name="acme/api#12", chat_type="channel")
+ gh = mention_opening(gh_src, "@bot fix this")
+ assert gh.startswith("🔔 You were mentioned on GitHub in acme/api#12 by rohit")
+ assert "You own this GitHub issue/PR thread" in gh
+ assert 'github_reply(owner="acme", repo="api", number=12, body=…) — pre-approved' in gh and "GitHub-appropriate" in gh
+ assert "Slack" not in gh
+ sl_src = SessionSource(platform="slack", chat_id="C1", user_id="U1", user_name="U1", chat_name="general", chat_type="channel")
+ sl = mention_opening(sl_src, "hi", "1.2", "- U2: earlier")
+ assert "You own this Slack thread" in sl and sl.endswith("Recent channel context:\n- U2: earlier")
+ assert 'slack_post_message(workspace="default", channel="C1", thread_ts="1.2", text=…)' in sl
+ # Unknown platform degrades to a capitalised name, never a crash.
+ mx = mention_opening(SessionSource(platform="matrix", chat_id="!r", user_id="u", user_name="u", chat_name="!r"), "t")
+ assert "mentioned on Matrix in" in mx and 'send_message(target="matrix:!r", text=…)' in mx
+
+
def test_followup_tag_steers_same_session(tmp_path, monkeypatch):
mgr = _mgr(tmp_path)
captured = _capture_deliveries(mgr, monkeypatch)
@@ -177,19 +202,28 @@ def test_distinct_thread_spawns_distinct_session(tmp_path, monkeypatch):
def test_subscribed_coworker_overrides_router(tmp_path, monkeypatch):
mgr = _mgr(tmp_path)
captured = _capture_deliveries(mgr, monkeypatch)
+ mgr.save("sA", mgr.get_engine("sA")) # the connected coworker exists
mgr.subscriptions.subscribe("sA", "slack:C1")
asyncio.run(mgr._dispatch_inbound(_mention_event()))
- # Delivered to the connected coworker with must-respond framing + the thread target…
+ # Delivered to the connected coworker with must-respond framing + the reply call…
assert len(captured) == 1
sid, message, _ = captured[0]
assert sid == "sA"
assert "must" in message and "respond" in message
- assert "slack:C1:1700000010.000100" in message
+ assert 'slack_post_message(workspace="default", channel="C1", thread_ts="1700000010.000100", text=…) — pre-approved' in message
# …and the router spawned nothing.
assert mgr.mention_sessions.all() == []
- assert mgr.list_sessions() == []
+ assert [s["session_id"] for s in mgr.list_sessions()] == ["sA"]
+ # The tag granted the thread to the subscribed session (spec §11.4 — drill 5
+ # finding: a subscribed session that got tagged had to ask to reply), and the
+ # grant survives a rebuild because it is persisted with the session's grants.
+ target = "slack:C1:1700000010.000100"
+ assert target in mgr._engines["sA"].permissions.task_rules["slack_post_message"]
+ assert target in mgr._engines["sA"].permissions.task_rules["send_message"]
+ mgr._engines.pop("sA")
+ assert target in mgr.get_engine("sA").permissions.task_rules["slack_post_message"]
def test_grant_reseeds_on_engine_rebuild(tmp_path, monkeypatch):
@@ -202,6 +236,8 @@ def test_grant_reseeds_on_engine_rebuild(tmp_path, monkeypatch):
mgr._engines.pop(sid) # simulate restart/rebuild
engine = mgr.get_engine(sid)
assert target in engine.permissions.task_rules["send_message"]
+ # A Slack thread grants the reply only — the GitHub tools stay out of it.
+ assert "github_reply" not in engine.permissions.task_rules
def test_deleted_session_releases_thread_and_respawns(tmp_path, monkeypatch):
diff --git a/tests/test_slack_relay.py b/tests/test_slack_relay.py
index 5c17fba2..acef7061 100644
--- a/tests/test_slack_relay.py
+++ b/tests/test_slack_relay.py
@@ -434,3 +434,38 @@ def test_make_adapter_loads_per_team_tokens():
relay_url="wss://relay/ws",
)
assert adapter._bot_token("T9") == "xoxb-9"
+
+
+async def test_relay_carries_the_broker_target_session():
+ frame = {**_event_frame("T1", "C1", "U_ALICE"), "target_session_id": "sess-42"}
+ adapter = _adapter([frame, _event_frame("T1", "C1", "U_ALICE", ts="2.0")])
+ events: list[MessageEvent] = []
+
+ async def handler(e):
+ events.append(e)
+
+ adapter.set_message_handler(handler)
+ assert await adapter.connect() is True
+ try:
+ await adapter.wait_dispatched(2)
+ finally:
+ await adapter.disconnect()
+ assert events[0].target_session_id == "sess-42"
+ assert events[1].target_session_id is None
+
+
+async def test_relay_carries_the_routed_coworker():
+ frame = {**_event_frame("T1", "C1", "U_ALICE"), "mention_persona": "triage-lead"}
+ adapter = _adapter([frame])
+ events: list[MessageEvent] = []
+
+ async def handler(e):
+ events.append(e)
+
+ adapter.set_message_handler(handler)
+ assert await adapter.connect() is True
+ try:
+ await adapter.wait_dispatched(1)
+ finally:
+ await adapter.disconnect()
+ assert events[0].mention_persona == "triage-lead"
diff --git a/tests/test_slack_workspaces.py b/tests/test_slack_workspaces.py
index 89aaf66e..5f83807a 100644
--- a/tests/test_slack_workspaces.py
+++ b/tests/test_slack_workspaces.py
@@ -27,7 +27,7 @@ def client(tmp_path, monkeypatch):
def _install_form(team_id: str) -> dict:
state = f"slack-{team_id}"
- cloud._pending_managed_states[state] = cloud._now()
+ cloud._pending_managed_states[state] = {"created": cloud._now(), "machine_id": "", "machine_name": ""}
return {
"connector": "slack",
"team_id": team_id,
diff --git a/tests/test_subscription_sync.py b/tests/test_subscription_sync.py
new file mode 100644
index 00000000..aea60109
--- /dev/null
+++ b/tests/test_subscription_sync.py
@@ -0,0 +1,143 @@
+"""Cloud-first subscriptions (connectors-across-machines spec §3.3): which door
+the box / desktop uses, and how the broker's answers map to the route's."""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+
+from coworker import subscription_sync as sync
+from coworker.config import Config
+from coworker.secrets import SecretStore
+
+
+class _Resp:
+ def __init__(self, status, body):
+ self.status_code = status
+ self._body = body
+
+ def json(self):
+ return self._body
+
+
+def cfg():
+ return Config(cloud_base_url="https://api.test")
+
+
+def _capture(monkeypatch, status=200, body=None, raise_error=False):
+ calls = []
+
+ def fake_post(url, json=None, headers=None, timeout=None):
+ calls.append({"url": url, "json": json, "headers": headers})
+ if raise_error:
+ raise httpx.ConnectError("down")
+ return _Resp(status, body if body is not None else {"ok": True, "moved_from": []})
+
+ monkeypatch.setattr(sync.httpx, "post", fake_post)
+ return calls
+
+
+def test_box_registers_by_machine_credential(tmp_path, monkeypatch, cfg):
+ secrets = SecretStore(tmp_path / "s.json")
+ secrets.put("slack:default", {
+ "mode": "relay", "machine_credential": "mc_abc", "broker_user_id": "u1",
+ "connection_id": "conn1",
+ })
+ calls = _capture(monkeypatch)
+ out = sync.register(secrets, cfg, source="slack:T1/C1", session_id="s1", title="Ops")
+ assert out == {"ok": True, "registered": True, "moved_from": []}
+ (call,) = calls
+ assert call["url"] == "https://api.test/v1/machine/subscriptions"
+ assert call["headers"] == {"Authorization": "Bearer mc_abc"}
+ assert call["json"] == {"user_id": "u1", "connection_id": "conn1", "source": "slack:T1/C1",
+ "session_id": "s1", "title": "Ops", "move": False}
+
+
+def test_desktop_registers_by_session_token(tmp_path, monkeypatch, cfg):
+ secrets = SecretStore(tmp_path / "s.json")
+ secrets.put("github:default", {"mode": "relay"})
+ monkeypatch.setattr(sync, "fresh_access_token", lambda s, c: "jwt-1")
+ calls = _capture(monkeypatch)
+ out = sync.register(secrets, cfg, source="github:acme/site", session_id="s1", move=True)
+ assert out["ok"] and out["registered"]
+ (call,) = calls
+ assert call["url"] == "https://api.test/v1/subscriptions"
+ assert call["headers"] == {"Authorization": "Bearer jwt-1"}
+ assert call["json"]["move"] is True and "user_id" not in call["json"]
+
+
+def test_local_only_when_nothing_to_register(tmp_path, monkeypatch, cfg):
+ secrets = SecretStore(tmp_path / "s.json")
+ calls = _capture(monkeypatch)
+ # Socket-Mode Slack: the broker has no relay for it.
+ secrets.put("slack:default", {"bot_token": "xoxb", "app_token": "xapp"})
+ assert sync.register(secrets, cfg, source="slack:C1", session_id="s") == {"ok": True, "registered": False}
+ # Telegram is not a managed inbound connector at all.
+ assert sync.register(secrets, cfg, source="telegram:123", session_id="s") == {"ok": True, "registered": False}
+ # Relay mode but signed out on the desktop: local-only, honest.
+ secrets.put("slack:default", {"mode": "relay"})
+ monkeypatch.setattr(sync, "fresh_access_token", lambda s, c: None)
+ assert sync.register(secrets, cfg, source="slack:C1", session_id="s") == {"ok": True, "registered": False}
+ assert calls == []
+
+
+def test_held_and_failures_map_to_route_answers(tmp_path, monkeypatch, cfg):
+ secrets = SecretStore(tmp_path / "s.json")
+ secrets.put("slack:default", {"mode": "relay", "machine_credential": "mc", "broker_user_id": "u", "connection_id": "c"})
+ held = {"detail": {"error": "held", "held_by": {"session_id": "other", "title": "Lead", "machine_id": "m-a"},
+ "also": [], "move_allowed": False}}
+ _capture(monkeypatch, status=409, body=held)
+ out = sync.register(secrets, cfg, source="slack:C1", session_id="s")
+ assert out["ok"] is False and out["error"] == "held"
+ assert out["held_by"]["title"] == "Lead" and out["move_allowed"] is False
+ # An older broker without the route: local-only, exactly as before.
+ _capture(monkeypatch, status=404, body={"detail": "Not Found"})
+ assert sync.register(secrets, cfg, source="slack:C1", session_id="s") == {"ok": True, "registered": False}
+ _capture(monkeypatch, status=401, body={"detail": "unauthorized"})
+ out = sync.register(secrets, cfg, source="slack:C1", session_id="s")
+ assert out["ok"] is False and out["error"] == "unauthorized"
+ _capture(monkeypatch, raise_error=True)
+ out = sync.register(secrets, cfg, source="slack:C1", session_id="s")
+ assert out["ok"] is False and "could not be reached" in out["error"]
+
+
+def test_remove_and_orphan_are_best_effort(tmp_path, monkeypatch, cfg):
+ secrets = SecretStore(tmp_path / "s.json")
+ secrets.put("slack:default", {"mode": "relay", "machine_credential": "mc", "broker_user_id": "u", "connection_id": "c"})
+ calls = _capture(monkeypatch)
+ sync.remove(secrets, cfg, source="slack:C1", session_id="s")
+ sync.report_orphan(secrets, cfg, source="slack:C1")
+ assert [c["url"].rsplit("/", 1)[1] for c in calls] == ["remove", "orphan"]
+ assert calls[0]["json"]["session_id"] == "s"
+ _capture(monkeypatch, raise_error=True)
+ sync.remove(secrets, cfg, source="slack:C1", session_id="s") # never raises
+
+
+# --- mirror refresh (UX-049 4b) ---------------------------------------------------
+
+
+def test_pull_partitions_rows_by_this_machine(tmp_path, monkeypatch, cfg):
+ secrets = SecretStore(tmp_path / "s.json")
+ secrets.put("slack:default", {"mode": "relay", "machine_credential": "mc", "broker_user_id": "u", "connection_id": "c"})
+ calls = []
+
+ def fake_get(url, params=None, headers=None, timeout=None):
+ calls.append(url)
+ if url.endswith("/machine/subscriptions"):
+ return _Resp(200, {"machine_id": "m-a", "subscriptions": [
+ {"connector": "slack", "source": "slack:C1", "machine_id": "m-a", "session_id": "s1"},
+ {"connector": "slack", "source": "slack:C2", "machine_id": "m-b", "session_id": "s9"},
+ {"connector": "github", "source": "github:o/r", "machine_id": "m-a", "session_id": "s1"},
+ ]})
+ return _Resp(200, {"people": [{"connector": "slack", "scope": "T1", "member": "U_BOB", "name": "Bob"}]})
+
+ monkeypatch.setattr(sync.httpx, "get", fake_get)
+ out = sync.pull(secrets, cfg)
+ assert [r["source"] for r in out["subscriptions"]] == ["slack:C1"]
+ assert [r["source"] for r in out["elsewhere"]] == ["slack:C2"]
+ assert out["people"]["slack"][0]["member"] == "U_BOB"
+ assert sorted(u.rsplit("/", 1)[1] for u in calls) == ["people", "subscriptions"]
+ # A desktop (no machine credential) pulls nothing.
+ secrets.put("slack:default", {"mode": "relay"})
+ assert sync.pull(secrets, cfg) == {"subscriptions": [], "elsewhere": [], "people": {}}
diff --git a/tests/test_subscriptions.py b/tests/test_subscriptions.py
index d5b4964e..f9ad7df1 100644
--- a/tests/test_subscriptions.py
+++ b/tests/test_subscriptions.py
@@ -1,6 +1,7 @@
"""Channel subscriptions: the store, the agent tools, and the gateway fan-out dispatch."""
import asyncio
+import json
import pytest
@@ -328,3 +329,220 @@ def test_refresh_gateway_replaces_listeners(tmp_path):
asyncio.run(mgr.refresh_gateway())
assert mgr.gateway is not None and mgr.gateway is not first
asyncio.run(mgr.aclose())
+
+
+# --- cloud-first subscribe + one-responder delivery (spec §3.3) -----------------
+
+
+def test_subscribe_route_registers_at_the_cloud_first(tmp_path, monkeypatch):
+ from fastapi.testclient import TestClient
+ from coworker import subscription_sync
+ from coworker.server import create_app
+
+ mgr = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ client = TestClient(create_app(mgr))
+ seen = []
+
+ def fake_register(secrets, config, *, source, session_id, title="", move=False):
+ seen.append((source, session_id, move))
+ if source == "slack:CHELD" and not move:
+ return {"ok": False, "error": "held", "move_allowed": True,
+ "held_by": {"session_id": "other", "title": "Lead", "machine_id": "m-a"}, "also": []}
+ return {"ok": True, "registered": True, "moved_from": [{"session_id": "other", "source": source}] if move else []}
+
+ monkeypatch.setattr(subscription_sync, "register", fake_register)
+ r = client.post("/v1/subscriptions", json={"session_id": "s1", "channel": "slack:CHELD"}).json()
+ assert r["ok"] is False and r["error"] == "held" and r["held_by"]["title"] == "Lead"
+ assert mgr.subscriptions.for_session("s1") == [] # nothing written locally
+ r = client.post("/v1/subscriptions", json={"session_id": "s1", "channel": "slack:CHELD", "move": True}).json()
+ assert r["ok"] is True and r["registered"] is True
+ assert [x.channel for x in mgr.subscriptions.for_session("s1")] == ["slack:CHELD"]
+ assert seen == [("slack:CHELD", "s1", False), ("slack:CHELD", "s1", True)]
+ # A move retires the previous holder's local mirror when it lived here.
+ mgr.subscriptions.subscribe("other", "slack:C2")
+ client.post("/v1/subscriptions", json={"session_id": "s1", "channel": "slack:C2", "move": True})
+ assert mgr.subscriptions.for_session("other") == []
+ # Unsubscribe releases the row at the cloud.
+ released = []
+ monkeypatch.setattr(subscription_sync, "remove", lambda s, c, *, source, session_id: released.append((source, session_id)))
+ client.post("/v1/subscriptions/remove", json={"session_id": "s1", "channel": "slack:C2"})
+ assert released == [("slack:C2", "s1")]
+
+
+def test_agent_subscribe_tool_obeys_the_cloud(tmp_path, monkeypatch):
+ from coworker import subscription_sync
+
+ mgr = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ monkeypatch.setattr(
+ subscription_sync, "register",
+ lambda *a, **k: {"ok": False, "error": "held", "held_by": {"title": "Lead"}, "also": [], "move_allowed": True},
+ )
+ sub, *_ = subscription_tools(
+ mgr.subscriptions, "sX", mgr.channel_buffer,
+ register=lambda sid, addr: mgr.subscribe_session(sid, addr),
+ )
+ out = sub("slack:C1")
+ assert out["ok"] is False and out["held_by"]["title"] == "Lead"
+ assert mgr.subscriptions.for_session("sX") == []
+
+
+def test_targeted_event_goes_only_to_the_named_session(tmp_path, monkeypatch):
+ mgr = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ _connect_slack(mgr)
+ delivered: list[tuple[str, str]] = []
+
+ async def fake_deliver(session_id, message, *, source=None):
+ delivered.append((session_id, message))
+
+ monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)
+ # Two local subscribers plus the cloud's named responder (a third session).
+ mgr.subscriptions.subscribe("sA", "slack:C1")
+ mgr.subscriptions.subscribe("sB", "slack:C1")
+ for sid in ("sA", "sB", "sT"):
+ mgr.get_engine(sid)
+ mgr.save(sid, mgr.get_engine(sid))
+ ev = _event("deploy failed", chat_type="channel")
+ ev.target_session_id = "sT"
+ asyncio.run(mgr._dispatch_inbound(ev))
+ assert [sid for sid, _ in delivered] == ["sT"]
+ assert "NOT mentioned" in delivered[0][1]
+ # A mention to the target gets the must-respond framing, still only there.
+ delivered.clear()
+ ev = _event("<@UBOT> help", chat_type="channel")
+ ev.target_session_id = "sT"
+ ev.mentions_me = True
+ asyncio.run(mgr._dispatch_inbound(ev))
+ assert [sid for sid, _ in delivered] == ["sT"] and "must respond" in delivered[0][1]
+
+
+def test_unknown_target_is_reported_and_falls_through(tmp_path, monkeypatch):
+ mgr = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ _connect_slack(mgr)
+ delivered: list[str] = []
+
+ async def fake_deliver(session_id, message, *, source=None):
+ delivered.append(session_id)
+
+ monkeypatch.setattr(mgr, "deliver_to_session", fake_deliver)
+ orphaned: list[str] = []
+ monkeypatch.setattr(mgr, "_report_orphan_subscription", lambda channel: orphaned.append(channel))
+ mgr.subscriptions.subscribe("sA", "slack:C1")
+ ev = _event("hello", chat_type="channel")
+ ev.target_session_id = "no-such-session"
+ asyncio.run(mgr._dispatch_inbound(ev))
+ assert orphaned == ["slack:C1"]
+ assert delivered == ["sA"] # today's fan-out, unchanged
+
+
+# --- mirror refresh + box-to-box handoff (UX-049 4b) --------------------------------
+
+
+def test_refresh_mirrors_applies_broker_view(tmp_path, monkeypatch):
+ from coworker import subscription_sync
+
+ mgr = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ mgr.secrets.put("slack:team:T1", {"managed": True, "bot_token": "xoxb", "allowed_users": ["U_OLD"]})
+ for sid in ("s1", "s2"):
+ mgr.get_engine(sid)
+ mgr.save(sid, mgr.get_engine(sid))
+ mgr.subscriptions.subscribe("s2", "slack:C2") # moved away at the cloud
+ orphaned: list[str] = []
+ monkeypatch.setattr(mgr, "_report_orphan_subscription", lambda channel: orphaned.append(channel))
+ monkeypatch.setattr(subscription_sync, "pull", lambda s, c: {
+ "subscriptions": [
+ {"source": "slack:C1", "session_id": "s1"},
+ {"source": "slack:C3", "session_id": "gone"},
+ ],
+ "elsewhere": [{"source": "slack:C2", "session_id": "x", "machine_id": "m-b"}],
+ "people": {"slack": [{"scope": "T1", "member": "U_BOB", "name": "Bob"}, {"scope": "T1", "member": "U_AMY", "name": ""}]},
+ })
+ counts = asyncio.run(mgr.refresh_subscription_mirrors())
+ assert counts == {"added": 1, "removed": 1, "orphans": 1, "people": 2}
+ assert [s.channel for s in mgr.subscriptions.for_session("s1")] == ["slack:C1"]
+ assert mgr.subscriptions.for_session("s2") == []
+ assert orphaned == ["slack:C3"]
+ assert mgr.secrets.get("slack:team:T1")["allowed_users"] == ["U_AMY", "U_BOB"]
+
+
+def test_handoff_sealed_stamps_grant_and_seals_to_target(tmp_path):
+ from fastapi.testclient import TestClient
+ from coworker.remote.identity import load_or_create
+ from coworker.server import create_app
+
+ mgr = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ mgr.secrets.put("slack:default", {"mode": "relay", "connection_id": "conn_1", "broker_user_id": "u_src", "machine_credential": "mc_src"})
+ mgr.secrets.put("slack:team:T1", {"managed": True, "connection_id": "conn_1", "bot_token": "xoxb-1", "team_id": "T1"})
+ client = TestClient(create_app(mgr))
+ target = load_or_create(tmp_path / "target-id")
+ r = client.post("/v1/connectors/slack/handoff-sealed", json={}).json()
+ assert r["ok"] is False and "seal_pubkey" in r["error"]
+ r = client.post("/v1/connectors/slack/handoff-sealed", json={"seal_pubkey": target.seal_public_key_b64}).json()
+ assert r["ok"] is False and "grant" in r["error"]
+ r = client.post(
+ "/v1/connectors/slack/handoff-sealed",
+ json={"seal_pubkey": target.seal_public_key_b64, "grant": {"user_id": "u_src", "machine_credential": "mc_target"}},
+ ).json()
+ assert r["ok"] is True and r["profiles"] == ["slack:default", "slack:team:T1"]
+ opened = json.loads(target.unseal_b64(r["sealed_b64"]))["profiles"]
+ assert opened["slack:team:T1"]["bot_token"] == "xoxb-1"
+ assert opened["slack:team:T1"]["machine_credential"] == "mc_target"
+ assert opened["slack:default"]["machine_credential"] == "mc_target"
+ # The source keeps its own credential — Enable is a copy.
+ assert mgr.secrets.get("slack:default")["machine_credential"] == "mc_src"
+ assert "xoxb-1" not in r["sealed_b64"]
+
+
+def test_desktop_broker_views_pass_through(tmp_path, monkeypatch):
+ from fastapi.testclient import TestClient
+ from coworker import cloud
+ from coworker.server import create_app
+
+ mgr = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ client = TestClient(create_app(mgr))
+ seen = []
+
+ def fake_request(secrets, config, method, path, body=None):
+ seen.append((method, path, body))
+ if path.startswith("/v1/people"):
+ return 200, {"people": [{"member": "U_BOB"}]}
+ if path.startswith("/v1/connections/c1/holders/"):
+ return 404, {"detail": "unknown connection or holder"}
+ return 0, {"error": "cloud unreachable"}
+
+ monkeypatch.setattr(cloud, "broker_request", fake_request)
+ assert client.get("/v1/cloud/people?connector=slack&scope=T1").json()["people"][0]["member"] == "U_BOB"
+ assert client.delete("/v1/cloud/connections/c1/holders/m-a").status_code == 404
+ assert client.get("/v1/cloud/subscriptions?connector=slack").status_code == 502
+ assert client.post("/v1/cloud/connections/c1/default-machine", json={"machine_id": "m-a"}).status_code == 502
+ assert seen[0] == ("GET", "/v1/people?connector=slack&scope=T1", None)
+ assert seen[3] == ("POST", "/v1/connections/c1/default-machine", {"machine_id": "m-a"})
+
+
+def test_mention_spawn_uses_the_routed_coworker_when_present(tmp_path, monkeypatch):
+ mgr = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ _connect_slack(mgr)
+ ids = [p.id for p in mgr.personas.list()] if hasattr(mgr.personas, "list") else []
+ other = next((i for i in ids if i != mgr.personas.default_id()), None)
+ spawned: list[str] = []
+
+ def fake_get_engine(sid, agent=None, **kw):
+ spawned.append(agent)
+ return None # spawn records "could not spawn" and stops — enough to see the choice
+
+ monkeypatch.setattr(mgr, "get_engine", fake_get_engine)
+ ev = _event("<@UBOT> hi", chat_type="channel")
+ ev.mentions_me = True
+ ev.mention_persona = other or "no-such-coworker"
+ asyncio.run(mgr._dispatch_inbound(ev))
+ assert spawned[-1] == (other or mgr.personas.default_id())
+ ev2 = _event("<@UBOT> again", chat_type="channel", chat_id="C9")
+ ev2.mentions_me = True
+ ev2.mention_persona = "no-such-coworker"
+ asyncio.run(mgr._dispatch_inbound(ev2))
+ assert spawned[-1] == mgr.personas.default_id() # missing coworker → the machine default
+
+
+def test_relay_people_may_approve_too(tmp_path):
+ mgr = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ mgr.secrets.put("slack:team:T1", {"managed": True, "mode": "relay", "slack_user_id": "U_ME", "allowed_users": ["U_BOB"]})
+ assert mgr.slack_approval_owner_ids("T1") == {"U_ME", "U_BOB"}