Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Agent bridge push transport: design + Stages A & B (CHOO-1857) (#100)
Louis Amaudruzdcd8ec8f99d1
diff --git a/.github/workflows/switch-agent-runtime-publish.yml b/.github/workflows/switch-agent-runtime-publish.ymlnew file mode 100644index 000000000..350f35f13--- /dev/null+++ b/.github/workflows/switch-agent-runtime-publish.yml@@ -0,0 +1,108 @@+# Publish the shared agent runtime to GitHub Packages.+#+# The package is consumed two ways, and only one of them needs a registry:+# switchdash builds it from the workspace, so it never waits on a publish. The+# Claude Code plugin runs it with `npx`, and that needs a version to exist.+#+# Triggered by a tag, so a version can be published from a BRANCH — you should+# not have to merge to main to test the thing you are testing. To cut one:+#+# # bump "version" in dash/packages/switch-agent-runtime/package.json first+# git tag switch-agent-runtime-v0.1.0+# git push origin switch-agent-runtime-v0.1.0+#+# The tag must match the version in package.json, or the job fails rather than+# publishing something whose name disagrees with its contents.+#+# For a pre-merge test, use a prerelease version (0.2.0-rc.1). Those publish+# under the `next` dist-tag so they never become what `@latest` resolves to —+# it matters less than it looks, since consumers pin exact versions, but a+# release candidate silently becoming the default is not a surprise anyone+# enjoys.+#+# Publishing is idempotent: a tag for a version already on the registry reports+# that and exits cleanly rather than failing.+#+# No secret is needed. GitHub Packages accepts the workflow's own GITHUB_TOKEN+# with `packages: write`, so there is no PAT to create, rotate, or leak.+# Consumers authenticate with `gh auth token` on the host instead.+name: Publish switch-agent-runtime++on:+ push:+ tags:+ - 'switch-agent-runtime-v*'+ # Lets you publish from a branch without tagging:+ # gh workflow run switch-agent-runtime-publish.yml --ref <branch>+ workflow_dispatch:++jobs:+ publish:+ runs-on: ubuntu-latest+ permissions:+ contents: read+ packages: write+ defaults:+ run:+ working-directory: dash++ steps:+ - uses: actions/checkout@v4++ # Pinned rather than read from packageManager: that field lives in+ # dash/package.json, and the action looks at the repo root.+ - uses: pnpm/action-setup@v4+ with:+ version: 10.28.2++ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: pnpm+ cache-dependency-path: dash/pnpm-lock.yaml+ registry-url: https://npm.pkg.github.com+ scope: '@sandbox-quantum'++ - run: pnpm install --frozen-lockfile++ # Build from source rather than trusting a committed artifact — the whole+ # point of publishing is that there is no artifact in the repo to drift.+ - run: pnpm --filter @sandbox-quantum/switch-agent-runtime run build++ - name: Publish if this version is new+ working-directory: dash/packages/switch-agent-runtime+ env:+ NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ TAG_REF: ${{ github.ref }}+ run: |+ set -euo pipefail+ name=$(node -p "require('./package.json').name")+ version=$(node -p "require('./package.json').version")++ # A tag naming one version while package.json says another publishes+ # something whose name disagrees with its contents. Refuse.+ case "$TAG_REF" in+ refs/tags/switch-agent-runtime-v*)+ tagged="${TAG_REF#refs/tags/switch-agent-runtime-v}"+ if [ "$tagged" != "$version" ]; then+ echo "Tag says $tagged, package.json says $version." >&2+ echo "Bump the version and re-tag." >&2+ exit 1+ fi+ ;;+ esac++ if npm view "$name@$version" version >/dev/null 2>&1; then+ echo "$name@$version is already published — nothing to do."+ echo "Bump the version in package.json to publish a new one."+ exit 0+ fi++ # A prerelease must not become what `@latest` resolves to.+ case "$version" in+ *-*) npm publish --tag next ;;+ *) npm publish ;;+ esac+ echo "Published $name@$version"+ echo "Point the plugin at it: bump the pinned version in" \+ "connectors/claude-code-plugin/.mcp.json and the plugin's own version."diff --git a/CLAUDE.md b/CLAUDE.mdindex 90218137c..c6061cd53 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -77,15 +77,25 @@ just test -k "test_name" # run specific test## Claude Code connector pluginThe `switch-connector` Claude Code plugin lives in `connectors/claude-code-plugin/`-(skill in `skills/switch/SKILL.md`, MCP server, hooks, channel). When you change-how agents interact with Switch — new/changed MCP tools, in-room commands,-room workflow, or anything an agent-facing client needs to know:+— skills, hooks, and an `.mcp.json`. It contains **no runtime code**: the MCP+server is `@sandbox-quantum/switch-agent-runtime`, fetched with `npx` and built+from `dash/packages/switch-agent-runtime/`. switchdash imports the same package+for its protocol client, so there is one implementation of the agent protocol+rather than a copy per consumer.++When you change how agents interact with Switch — new/changed MCP tools, in-room+commands, room workflow, or anything an agent-facing client needs to know:- **Update the skill** (`connectors/claude-code-plugin/skills/switch/SKILL.md`)so the documented workflow matches the actual behavior.-- **Bump the plugin version** in- `connectors/claude-code-plugin/.claude-plugin/plugin.json` so installs pick- up the change.+- **Bump the versions of whatever you changed, in the same commit.** Not at+ release time — it gets forgotten, and then a version number is a claim nobody+ can trust. `dash/AGENTS.md` has the table (plugin, runtime package, sidecar)+ and the rules for which digit moves.+- **Publishing the runtime is a tag**, not a merge:+ `git tag switch-agent-runtime-v<version> && git push origin <tag>`. It works+ from a branch, so a version can be tested before it lands. The tag must match+ the version in `package.json` or the workflow fails.## Code Stylediff --git a/connection_model b/connection_modelnew file mode 100644index 000000000..e69de29bbdiff --git a/connectors/claude-code-plugin/.claude-plugin/plugin.json b/connectors/claude-code-plugin/.claude-plugin/plugin.jsonindex 75ef87bac..36328000c 100644--- a/connectors/claude-code-plugin/.claude-plugin/plugin.json+++ b/connectors/claude-code-plugin/.claude-plugin/plugin.json@@ -1,5 +1,5 @@{"name": "switch-connector",- "version": "0.3.0",+ "version": "0.7.2","description": "Connect Claude Code to a Switch platform instance as a participating agent"}diff --git a/connectors/claude-code-plugin/.mcp.json b/connectors/claude-code-plugin/.mcp.jsonindex c72c43cae..e7d79a203 100644--- a/connectors/claude-code-plugin/.mcp.json+++ b/connectors/claude-code-plugin/.mcp.json@@ -1,20 +1,8 @@{"mcpServers": {"switch": {- "type": "http",- "url": "${SWITCH_API_ENDPOINT}/mcp/",- "headers": {- "Authorization": "Bearer ${SWITCH_API_TOKEN}"- }- },- "switch-channel": {- "command": "sh",- "args": [- "-c",- "cd \"$1\" && bun install --no-summary 1>&2 && exec bun server.ts",- "switch-channel",- "${CLAUDE_PLUGIN_ROOT}/channel"- ],+ "command": "npx",+ "args": ["-y", "@sandbox-quantum/[email protected]"],"env": {"SWITCH_API_ENDPOINT": "${SWITCH_API_ENDPOINT}","SWITCH_API_TOKEN": "${SWITCH_API_TOKEN}",diff --git a/connectors/claude-code-plugin/channel/bun.lock b/connectors/claude-code-plugin/channel/bun.lockdeleted file mode 100644index 4d86d72e3..000000000--- a/connectors/claude-code-plugin/channel/bun.lock+++ /dev/null@@ -1,197 +0,0 @@-{- "lockfileVersion": 1,- "configVersion": 1,- "workspaces": {- "": {- "name": "switch-channel",- "dependencies": {- "@modelcontextprotocol/sdk": "^1.0.0",- },- },- },- "packages": {- "@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],-- "@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],-- "accepts": ["[email protected]", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],-- "ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],-- "ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],-- "body-parser": ["[email protected]", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],-- "bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],-- "call-bind-apply-helpers": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],-- "call-bound": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],-- "content-disposition": ["[email protected]", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],-- "content-type": ["[email protected]", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],-- "cookie": ["[email protected]", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],-- "cookie-signature": ["[email protected]", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],-- "cors": ["[email protected]", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],-- "cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],-- "debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],-- "depd": ["[email protected]", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],-- "dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],-- "ee-first": ["[email protected]", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],-- "encodeurl": ["[email protected]", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],-- "es-define-property": ["[email protected]", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],-- "es-errors": ["[email protected]", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],-- "es-object-atoms": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="],-- "escape-html": ["[email protected]", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],-- "etag": ["[email protected]", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],-- "eventsource": ["[email protected]", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],-- "eventsource-parser": ["[email protected]", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="],-- "express": ["[email protected]", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],-- "express-rate-limit": ["[email protected]", "", { "dependencies": { "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A=="],-- "fast-deep-equal": ["[email protected]", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],-- "fast-uri": ["[email protected]", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="],-- "finalhandler": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],-- "forwarded": ["[email protected]", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],-- "fresh": ["[email protected]", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],-- "function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],-- "get-intrinsic": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],-- "get-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],-- "gopd": ["[email protected]", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],-- "has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],-- "hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg=="],-- "hono": ["[email protected]", "", {}, "sha512-uV63apnb0kyPtAUwoWgaGh9HyIFcv8lgmzPZSiTBQAFOFGIzka5EZ1dZocmGnn0XdX0+XTqJ6Tqv7selMuGLRQ=="],-- "http-errors": ["[email protected]", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],-- "iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],-- "inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],-- "ip-address": ["[email protected]", "", {}, "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA=="],-- "ipaddr.js": ["[email protected]", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],-- "is-promise": ["[email protected]", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],-- "isexe": ["[email protected]", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],-- "jose": ["[email protected]", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],-- "json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],-- "json-schema-typed": ["[email protected]", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],-- "math-intrinsics": ["[email protected]", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],-- "media-typer": ["[email protected]", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],-- "merge-descriptors": ["[email protected]", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],-- "mime-db": ["[email protected]", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],-- "mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],-- "ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],-- "negotiator": ["[email protected]", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],-- "object-assign": ["[email protected]", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],-- "object-inspect": ["[email protected]", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],-- "on-finished": ["[email protected]", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],-- "once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],-- "parseurl": ["[email protected]", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],-- "path-key": ["[email protected]", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],-- "path-to-regexp": ["[email protected]", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],-- "pkce-challenge": ["[email protected]", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],-- "proxy-addr": ["[email protected]", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],-- "qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="],-- "range-parser": ["[email protected]", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],-- "raw-body": ["[email protected]", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],-- "require-from-string": ["[email protected]", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],-- "router": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],-- "safer-buffer": ["[email protected]", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],-- "send": ["[email protected]", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],-- "serve-static": ["[email protected]", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],-- "setprototypeof": ["[email protected]", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],-- "shebang-command": ["[email protected]", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],-- "shebang-regex": ["[email protected]", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],-- "side-channel": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],-- "side-channel-list": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],-- "side-channel-map": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],-- "side-channel-weakmap": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],-- "statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],-- "toidentifier": ["[email protected]", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],-- "type-is": ["[email protected]", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="],-- "unpipe": ["[email protected]", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],-- "vary": ["[email protected]", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],-- "which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],-- "wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],-- "zod": ["[email protected]", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],-- "zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],-- "type-is/content-type": ["[email protected]", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],- }-}diff --git a/connectors/claude-code-plugin/channel/package.json b/connectors/claude-code-plugin/channel/package.jsondeleted file mode 100644index a44dae04d..000000000--- a/connectors/claude-code-plugin/channel/package.json+++ /dev/null@@ -1,11 +0,0 @@-{- "name": "switch-channel",- "version": "0.0.1",- "type": "module",- "scripts": {- "start": "bun install --no-summary && bun server.ts"- },- "dependencies": {- "@modelcontextprotocol/sdk": "^1.0.0"- }-}diff --git a/connectors/claude-code-plugin/channel/server.ts b/connectors/claude-code-plugin/channel/server.tsdeleted file mode 100644index 3e25a8336..000000000--- a/connectors/claude-code-plugin/channel/server.ts+++ /dev/null@@ -1,1021 +0,0 @@-#!/usr/bin/env bun-/**- * Switch channel for Claude Code.- *- * Polls the Switch Agent Bridge for room events and pushes addressed messages- * and task events into the Claude Code session as channel notifications.- *- * The polling target is set by the PostToolUse hook on connect_to_room, which- * POSTs the room id to a localhost port this server exposes. The port is- * advertised at `${CLAUDE_PLUGIN_DATA}/sessions/${ppid}/port`, where ppid is- * this process's parent PID (the Claude Code session). The hook resolves the- * same path from its own getppid(), so each session's hook reaches its own- * channel without any cross-session coordination.- *- * Config comes from env vars set via .mcp.json env block (SWITCH_*).- */--import * as fs from 'node:fs'-import * as os from 'node:os'-import * as path from 'node:path'--import { Server } from '@modelcontextprotocol/sdk/server/index.js'-import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'-import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'--const API_ENDPOINT = process.env.SWITCH_API_ENDPOINT ?? ''-const API_TOKEN = process.env.SWITCH_API_TOKEN ?? ''-const AGENT_ID = process.env.SWITCH_AGENT_ID ?? ''--// When this session is managed by switchdash, switchdash polls the agent-// bridge for room events and injects addressed messages into the PTY itself.-// The bridge's per-room event queue is destructive (each event is delivered to-// a single poller), so this channel must NOT also poll or the two would steal-// each other's events. We still renew liveness and role leases — only the event-// poll loop is suppressed.-const DISABLE_POLL = process.env.SWITCH_CHANNEL_DISABLE_POLL === '1'--// Claude Code may spawn this server twice on startup: once before settings.env-// expansion (vars literal as `${SWITCH_*}`) and once with real values. Reject-// the unresolved spawn so it doesn't race the real one for the port file.-function looksUnresolved(value: string): boolean {- return value.startsWith('${') && value.endsWith('}')-}--if (- !API_ENDPOINT || !API_TOKEN || !AGENT_ID ||- looksUnresolved(API_ENDPOINT) || looksUnresolved(API_TOKEN) || looksUnresolved(AGENT_ID)-) {- process.stderr.write(- `switch-channel: missing or unresolved config — need SWITCH_API_ENDPOINT, SWITCH_API_TOKEN, and SWITCH_AGENT_ID\n` +- ` endpoint=${API_ENDPOINT || 'MISSING'}\n` +- ` token=${API_TOKEN ? 'set' : 'MISSING'}\n` +- ` agent_id=${AGENT_ID || 'MISSING'}\n` +- `If these look like \`\${SWITCH_*}\`, the env block in \`.claude/settings.local.json\` has not been expanded — run the \`configure\` skill.\n`,- )- process.exit(1)-}--const SESSION_PPID = process.ppid-const SESSION_DIR = path.join(os.homedir(), '.switch', 'sessions', String(SESSION_PPID))-const PORT_FILE = path.join(SESSION_DIR, 'port')-process.stderr.write(- `switch-channel: ppid=${SESSION_PPID} session_dir=${SESSION_DIR}\n`,-)--process.on('unhandledRejection', err => {- process.stderr.write(`switch-channel: unhandled rejection: ${err}\n`)-})-process.on('uncaughtException', err => {- process.stderr.write(`switch-channel: uncaught exception: ${err}\n`)-})--// -- Types matching core/switch_core/bridges/agent/events.py ------------------------type AttachmentRef = {- filename: string- mimetype: string- size: number- mxc: string- msgtype: string-}--type MessagePayload = {- addressed: boolean- sender: string- sender_name: string- message_id: string- body: string- timestamp: number- thread_id?: string | null- attachments?: AttachmentRef[]-}--type CommandPayload = {- command: string- target: string | null- user_id: string- user_name: string-}--type RoomJoinPayload = {- member: string- member_name: string- timestamp: number- listening: boolean-}--type TaskDelegatePayload = {- task_id: string- requester_agent_id: string- performer_agent_id: string- summary: string- description: string-}--type TaskAcceptPayload = {- task_id: string- requester_agent_id: string- performer_agent_id: string-}--type TaskUpdatePayload = {- task_id: string- requester_agent_id: string- performer_agent_id: string- update: string-}--type TaskFinalisePayload = {- task_id: string- requester_agent_id: string- performer_agent_id: string- outcome: string | null-}--type TaskCancelPayload = {- task_id: string- requester_agent_id: string- performer_agent_id: string- reason: string | null-}--type AgentEvent = {- type: string- room_id: string- bridge_id: string | null- channel_type: string | null- payload: MessagePayload | CommandPayload | RoomJoinPayload | TaskDelegatePayload | TaskAcceptPayload | TaskUpdatePayload | TaskFinalisePayload | TaskCancelPayload-}--type EventResponse = {- events: AgentEvent[]-}--// -- Polling state -------------------------------------------------------------let pollingRoomId: string | null = null-let pollAbort: AbortController | null = null-let leaseAbort: AbortController | null = null-let connRenewAbort: AbortController | null = null--// Unaddressed room messages are filtered out (never reach Claude as a-// notification), so the agent silently falls behind on room chatter. We tally-// how many we've dropped since the agent last read context and surface that-// count on every notification we DO emit, so the agent knows when to call-// read_context to catch up. Reset to 0 when the agent reads context (signalled-// by the /read-context hook) and when polling switches rooms.-let missedSinceRead = 0--// -- MCP server ----------------------------------------------------------------const mcp = new Server(- { name: 'switch-channel', version: '0.0.1' },- {- capabilities: {- tools: {},- experimental: {- 'claude/channel': {},- },- },- instructions: [- 'Events from Switch rooms arrive as <channel source="switch-channel" room_id="..." event_type="..." ...>.',- 'Only addressed messages, room_join events, and task events are delivered — unaddressed room chatter is filtered out.',- '',- 'A room_join event fires when a user or agent joins a room — but you are only notified for rooms where you are configured to receive join events (per-room, per-agent; off by default, set via the join_event_listeners option on create_room / update_room or the gateway). The meta carries member (their matrix id) and member_name (their display name). React if it is relevant — e.g. a welcome agent greets the new arrival and explains the room via post_message, or send_targeted_message to address them directly. Your own join does not produce a room_join event.',- '',- 'Every notification carries a `missed_count` in its meta: the number of unaddressed room messages filtered out since you last called read_context. When it is above 0 the one-line body is annotated with it. A growing count means the room is active around you and you have fallen behind — call read_context (widen `since` to cover the gap) to catch up on what you missed. The count resets to 0 when you call read_context.',- '',- 'Polling is automatic: when you call connect_to_room on the switch MCP server, a PostToolUse hook pushes the room id to this channel over a localhost port. Polling begins (or switches rooms) immediately. No separate tool call is needed.',- '',- 'When you receive a message event:',- '1. Call read_context with the since parameter set to a timestamp a few minutes before the event timestamp to get recent conversation context without re-reading the full history.',- '2. Understand what is being asked or discussed.',- '3. Respond by calling post_message (or send_targeted_message if addressing a specific agent).',- '',- 'If a message event has an image_path attribute, the sender attached one or more images. Each path is a local file already downloaded for you (comma-separated if several) — Read it to see the image before responding.',- 'If it has a file_path attribute, the sender attached one or more non-image files (.md, .csv, .pdf, logs, code — comma-separated if several), already downloaded for you. Read them before responding.',- 'A failed_attachments attribute lists files the sender attached that could NOT be retrieved. Do not pretend you saw them — say so.',- '',- 'To view a file that appears in read_context history but did NOT arrive with an image_path/file_path (e.g. an unaddressed file posted earlier), call the download_attachment tool with the attachment\'s mxc (from the read_context attachments field). It writes the file locally and returns the path — then Read that path.',- 'To send files into the room, call the send_attachment tool with `path` (one file) or `paths` (several, delivered as ONE message) plus an optional caption/thread_id. Any file type works. They post as native room attachments and bridged platforms (Slack, Mattermost) receive them as real file uploads.',- '',- 'When you receive a task_delegate event (only delivered if your integration profile has can_accept=true):',- '1. Call accept_task with the task_id to move it to ongoing.',- '2. Call read_context with since to understand the conversation context.',- '3. Perform the work described in the task. Optionally call update_task(task_id, update) with progress messages as you work — these are persisted.',- '4. Call finalise_task(task_id, outcome) with a one-string description of what happened (success or failure).',- '',- 'When you receive task_accept, task_update, or task_finalise events for tasks you delegated, review the progress/outcome and continue your work accordingly.',- 'When you receive a task_cancel event, the task is dead — do not finalise it.',- '',- 'You must be connected to the room (via connect_to_room) before calling read_context, post_message, send_targeted_message, or any task tool.',- ].join('\n'),- },-)--// Addressed images are auto-downloaded and surfaced as image_path on the-// notification. This tool lets the agent fetch ANY attachment on demand — e.g.-// an image seen in read_context history that arrived unaddressed (no-// notification, so no image_path). It writes the bytes to a local file and-// returns the path, which the agent then Reads.-const DOWNLOAD_ATTACHMENT_TOOL = {- name: 'download_attachment',- description:- "Download a room attachment (by its mxc:// URI, as returned in an " +- "attachment's `mxc` field from read_context) to a local file and return " +- "the path. Works for any file type. Use this to view a file from history " +- 'that did not arrive with an image_path/file_path. Operates on the ' +- 'currently connected room unless ' +- 'room_id is given.',- inputSchema: {- type: 'object',- properties: {- mxc: {- type: 'string',- description: "The attachment's mxc:// URI (from a read_context attachment).",- },- filename: {- type: 'string',- description: 'Optional original filename, used to name the local file.',- },- room_id: {- type: 'string',- description:- 'Optional Switch room id. Defaults to the currently polling room.',- },- },- required: ['mxc'],- },-}--// The outbound counterpart of download_attachment: the agent names a local-// file (e.g. a screenshot it produced) and the channel uploads the bytes to-// the agent bridge, which posts them into the room as an m.image / m.file-// event — from there the collaboration bridges relay it out to Slack /-// Mattermost like any other room message.-const SEND_ATTACHMENT_TOOL = {- name: 'send_attachment',- description:- 'Send one or more local files of ANY type (image, .md, .csv, .pdf, log, ' +- 'code) into the connected Switch room as attachments. They enter the room ' +- 'as native image/file events and bridged platforms (Slack, Mattermost) ' +- 'receive them as real file uploads. Several files sent in one call arrive ' +- 'as ONE message carrying all of them. Pass `path` for a single file or ' +- '`paths` for several. Oversize or unreadable files fail the whole call — ' +- 'nothing is sent silently. Operates on the currently connected room unless ' +- 'room_id is given.',- inputSchema: {- type: 'object',- properties: {- path: {- type: 'string',- description: 'Absolute path of the local file to send.',- },- paths: {- type: 'array',- items: { type: 'string' },- description:- 'Absolute paths of several local files to send as one message. ' +- 'Use instead of `path` for a multi-attachment message.',- },- caption: {- type: 'string',- description: 'Optional text to accompany the attachment.',- },- thread_id: {- type: 'string',- description:- 'Optional message id to reply into, making this a threaded reply ' +- '(normalised to the thread root).',- },- room_id: {- type: 'string',- description:- 'Optional Switch room id. Defaults to the currently polling room.',- },- },- },-}--mcp.setRequestHandler(ListToolsRequestSchema, async () => ({- tools: [DOWNLOAD_ATTACHMENT_TOOL, SEND_ATTACHMENT_TOOL],-}))--mcp.setRequestHandler(CallToolRequestSchema, async req => {- if (req.params.name === 'download_attachment') {- return handleDownloadAttachment(req.params.arguments ?? {})- }- if (req.params.name === 'send_attachment') {- return handleSendAttachment(req.params.arguments ?? {})- }- throw new Error(`Unknown tool: ${req.params.name}`)-})--async function handleDownloadAttachment(rawArgs: Record<string, unknown>) {- const args = rawArgs as {- mxc?: string- filename?: string- room_id?: string- }- const mxc = typeof args.mxc === 'string' ? args.mxc : ''- if (!mxc) {- return { isError: true, content: [{ type: 'text', text: 'mxc is required' }] }- }- const roomId = args.room_id ?? pollingRoomId- if (!roomId) {- return {- isError: true,- content: [- {- type: 'text',- text: 'Not connected to a room — call connect_to_room first or pass room_id.',- },- ],- }- }- const mediaId = mxc.split('/').pop() || 'attachment'- const destName = `${sanitiseName(mediaId)}-${sanitiseName(args.filename ?? '')}`- try {- const path = await fetchMediaToFile(roomId, mxc, destName)- return { content: [{ type: 'text', text: path }] }- } catch (err) {- return {- isError: true,- content: [{ type: 'text', text: `Download failed: ${err}` }],- }- }-}--// Extension → mimetype map. Anything unlisted goes up as-// application/octet-stream, which still relays fine — the mapping exists to-// preserve type fidelity so platforms render/preview the file properly.-const MIME_BY_EXT: Record<string, string> = {- '.png': 'image/png',- '.jpg': 'image/jpeg',- '.jpeg': 'image/jpeg',- '.gif': 'image/gif',- '.webp': 'image/webp',- '.svg': 'image/svg+xml',- '.bmp': 'image/bmp',- '.pdf': 'application/pdf',- '.txt': 'text/plain',- '.md': 'text/markdown',- '.csv': 'text/csv',- '.tsv': 'text/tab-separated-values',- '.log': 'text/plain',- '.json': 'application/json',- '.yaml': 'application/yaml',- '.yml': 'application/yaml',- '.toml': 'application/toml',- '.xml': 'application/xml',- '.html': 'text/html',- '.css': 'text/css',- '.js': 'text/javascript',- '.mjs': 'text/javascript',- '.ts': 'text/x-typescript',- '.tsx': 'text/x-typescript',- '.jsx': 'text/javascript',- '.py': 'text/x-python',- '.rs': 'text/x-rust',- '.go': 'text/x-go',- '.java': 'text/x-java',- '.c': 'text/x-c',- '.h': 'text/x-c',- '.cpp': 'text/x-c++',- '.sh': 'application/x-sh',- '.sql': 'application/sql',- '.zip': 'application/zip',- '.gz': 'application/gzip',- '.tar': 'application/x-tar',-}--async function handleSendAttachment(rawArgs: Record<string, unknown>) {- const args = rawArgs as {- path?: string- paths?: unknown- caption?: string- thread_id?: string- room_id?: string- }- const filePaths: string[] = []- if (typeof args.path === 'string' && args.path) filePaths.push(args.path)- if (Array.isArray(args.paths)) {- for (const p of args.paths) if (typeof p === 'string' && p) filePaths.push(p)- }- if (filePaths.length === 0) {- return {- isError: true,- content: [{ type: 'text', text: 'path (or paths) is required' }],- }- }- const roomId = args.room_id ?? pollingRoomId- if (!roomId) {- return {- isError: true,- content: [- {- type: 'text',- text: 'Not connected to a room — call connect_to_room first or pass room_id.',- },- ],- }- }-- // Read every file up front: one unreadable path fails the whole call rather- // than posting a partial message.- const files: { name: string; bytes: Buffer; mimetype: string }[] = []- for (const filePath of filePaths) {- let bytes: Buffer- try {- bytes = fs.readFileSync(filePath)- } catch (err) {- return {- isError: true,- content: [{ type: 'text', text: `Cannot read ${filePath}: ${err}` }],- }- }- files.push({- name: path.basename(filePath),- bytes,- mimetype:- MIME_BY_EXT[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream',- })- }-- const form = new FormData()- for (const file of files) {- form.append('files', new Blob([file.bytes], { type: file.mimetype }), file.name)- }- if (typeof args.caption === 'string' && args.caption) form.append('caption', args.caption)- if (typeof args.thread_id === 'string' && args.thread_id) form.append('thread_id', args.thread_id)-- try {- const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/rooms/${roomId}/media`, {- method: 'POST',- headers: { Authorization: `Bearer ${API_TOKEN}` },- body: form,- })- if (!resp.ok) {- throw new Error(`HTTP ${resp.status}: ${await resp.text()}`)- }- const data = (await resp.json()) as { event_id?: string }- const names = files.map((f) => f.name).join(', ')- return {- content: [- {- type: 'text',- text:- `Sent ${files.length === 1 ? names : `${files.length} files (${names})`} ` +- `to the room (event_id: ${data.event_id ?? 'unknown'}).`,- },- ],- }- } catch (err) {- return {- isError: true,- content: [{ type: 'text', text: `Send failed: ${err}` }],- }- }-}--// -- Polling loop --------------------------------------------------------------function stopPolling() {- if (pollAbort) {- pollAbort.abort()- pollAbort = null- }- pollingRoomId = null-}--function startPolling(roomId: string) {- const abort = new AbortController()- pollAbort = abort- pollingRoomId = roomId- // Fresh room → fresh backlog. The agent reads context on arrival anyway.- missedSinceRead = 0-- void (async () => {- let backoff = 1000-- while (!abort.signal.aborted) {- try {- const url = `${API_ENDPOINT}/agents/${AGENT_ID}/rooms/${roomId}/events?timeout=10`- const resp = await fetch(url, {- headers: { Authorization: `Bearer ${API_TOKEN}` },- signal: abort.signal,- })-- if (resp.status === 204) {- backoff = 1000- continue- }-- if (!resp.ok) {- throw new Error(`HTTP ${resp.status}: ${await resp.text()}`)- }-- backoff = 1000- const data = (await resp.json()) as EventResponse-- for (const event of data.events) {- await handleEvent(event)- }- } catch (err) {- if (abort.signal.aborted) return-- process.stderr.write(`switch-channel: poll error: ${err}, retrying in ${backoff / 1000}s\n`)- await new Promise(r => setTimeout(r, backoff))- backoff = Math.min(backoff * 2, 30000)- }- }- })()-}--// -- Room reconciliation --------------------------------------------------------function setConnectedRoom(target: string | null) {- if (target === pollingRoomId) return-- if (pollingRoomId) {- process.stderr.write(`switch-channel: leaving room ${pollingRoomId}\n`)- stopPolling()- stopConnectionRenew()- }-- if (target) {- // Track the connected room even when polling is suppressed so room-change- // dedup and download_attachment's default room still work.- pollingRoomId = target- missedSinceRead = 0- if (DISABLE_POLL) {- process.stderr.write(- `switch-channel: polling disabled (switchdash-managed) — renewing liveness only for room ${target}\n`,- )- } else {- process.stderr.write(`switch-channel: starting poll for room ${target}\n`)- startPolling(target)- }- startConnectionRenew(target)- }-}--// -- Connection liveness renewal ---------------------------------------------//-// While connected to a room, renew the room-scoped liveness heartbeat on a-// fast cadence, decoupled from the long-poll. The server keeps the connection-// "live" only while these renews arrive (SESSION_TTL), so a closed/crashed-// session drops to "no session" within seconds instead of waiting out a long-// poll-derived window. stopped on disconnect and re-targeted on room change.--const CONNECTION_RENEW_INTERVAL_MS = 2000--function stopConnectionRenew() {- if (connRenewAbort) {- connRenewAbort.abort()- connRenewAbort = null- }-}--function startConnectionRenew(roomId: string) {- stopConnectionRenew()- const abort = new AbortController()- connRenewAbort = abort-- void (async () => {- while (!abort.signal.aborted) {- try {- await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/connection/renew`, {- method: 'POST',- headers: {- Authorization: `Bearer ${API_TOKEN}`,- 'Content-Type': 'application/json',- },- body: JSON.stringify({ room_id: roomId }),- signal: abort.signal,- })- } catch (err) {- if (abort.signal.aborted) return- process.stderr.write(`switch-channel: connection renew error: ${err}\n`)- }- await new Promise(r => setTimeout(r, CONNECTION_RENEW_INTERVAL_MS))- }- })()-}--// -- Role lease renewal -------------------------------------------------------//-// While this session holds a room-role, renew the lease on a fast cadence so an-// (exclusive) seat stays held. The server frees a lease shortly after renewals-// stop (TTL), so a crashed/closed session auto-releases. release_role and a-// clean disconnect stop the loop immediately.--const LEASE_RENEW_INTERVAL_MS = 2000--function stopLeaseRenew() {- if (leaseAbort) {- leaseAbort.abort()- leaseAbort = null- }-}--function startLeaseRenew() {- if (leaseAbort) return // already renewing- const abort = new AbortController()- leaseAbort = abort-- void (async () => {- while (!abort.signal.aborted) {- try {- const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/leases/renew`, {- method: 'POST',- headers: { Authorization: `Bearer ${API_TOKEN}` },- signal: abort.signal,- })- if (resp.ok) {- const data = (await resp.json()) as { held?: boolean }- // The server says we hold no lease — nothing to renew, stop the loop.- if (data.held === false) {- stopLeaseRenew()- return- }- }- } catch (err) {- if (abort.signal.aborted) return- process.stderr.write(`switch-channel: lease renew error: ${err}\n`)- }- await new Promise(r => setTimeout(r, LEASE_RENEW_INTERVAL_MS))- }- })()-}--// -- Hook listener: localhost-only port advertised via PORT_FILE --------------function publishPort(port: number) {- fs.mkdirSync(SESSION_DIR, { recursive: true })- fs.writeFileSync(PORT_FILE, String(port))-}--function unpublishPort() {- try {- fs.rmSync(SESSION_DIR, { recursive: true, force: true })- } catch (err) {- process.stderr.write(`switch-channel: failed to clean up ${SESSION_DIR}: ${err}\n`)- }-}--function startHookListener() {- const server = Bun.serve({- port: 0,- hostname: '127.0.0.1',- async fetch(req) {- const url = new URL(req.url)- if (req.method !== 'POST') {- return new Response('method not allowed', { status: 405 })- }-- if (url.pathname === '/connect') {- let body: { room_id?: unknown }- try {- body = (await req.json()) as { room_id?: unknown }- } catch {- return new Response('bad json', { status: 400 })- }- const roomId = typeof body.room_id === 'string' ? body.room_id : null- if (!roomId) {- return new Response('missing room_id', { status: 400 })- }- setConnectedRoom(roomId)- return new Response('ok')- }-- if (url.pathname === '/disconnect') {- setConnectedRoom(null)- stopLeaseRenew()- return new Response('ok')- }-- if (url.pathname === '/assume-role') {- startLeaseRenew()- return new Response('ok')- }-- if (url.pathname === '/release-role') {- stopLeaseRenew()- return new Response('ok')- }-- if (url.pathname === '/read-context') {- // The agent called read_context, so it has caught up on room history —- // clear the missed-message backlog we've been tallying.- missedSinceRead = 0- return new Response('ok')- }-- if (url.pathname === '/turn-end') {- // The Claude Code turn finished. Clear the "thinking" indicator in case- // the agent ended without posting a reply — Slack's faked indicator is- // a real message that lingers until explicitly deleted (the reply path- // clears it server-side, but a no-reply turn would otherwise leave it).- if (pollingRoomId) void setTyping(pollingRoomId, false)- return new Response('ok')- }-- return new Response('not found', { status: 404 })- },- })-- publishPort(server.port)- process.stderr.write(- `switch-channel: hook listener on http://127.0.0.1:${server.port} (published to ${PORT_FILE})\n`,- )-}--// -- Event handling ------------------------------------------------------------async function handleEvent(event: AgentEvent) {- const { type, room_id, payload } = event-- if (type === 'message') {- const msg = payload as MessagePayload- if (!msg.addressed) {- // Unaddressed chatter: filtered out, no notification. Tally it so the- // next notification can tell the agent how far behind it has fallen.- missedSinceRead++- return- }-- // Surface receipt feedback: tell the room's bridged channel that this- // agent is "typing" so the human knows the message landed and we're- // working on a reply. Fire-and-forget — typing feedback must never block- // or fail event delivery. The indicator is cleared when the agent posts- // its reply, and on turn end via the Stop hook (`/turn-end`) for the case- // where the agent finishes without replying.- void setTyping(room_id, true)-- // Materialise every attachment to a local file so Claude can Read it,- // whatever the type. Images are surfaced as image_path (Claude renders- // them); everything else as file_path. A download that fails is reported- // as failed_attachment rather than being dropped quietly.- const imagePaths: string[] = []- const filePaths: string[] = []- const failedAttachments: string[] = []- const attachments = msg.attachments ?? []- for (let i = 0; i < attachments.length; i++) {- const att = attachments[i]- const localPath = await downloadAttachment(room_id, att, msg.message_id, i)- if (!localPath) {- failedAttachments.push(att.filename)- continue- }- if (att.mimetype.startsWith('image/')) imagePaths.push(localPath)- else filePaths.push(localPath)- }-- const ts = new Date(msg.timestamp).toISOString()- await emitNotification(- `[${msg.sender_name}]: ${msg.body}`,- {- room_id,- event_type: type,- sender: msg.sender,- sender_name: msg.sender_name,- message_id: msg.message_id,- timestamp: ts,- // Lets an addressed agent reply back into the same thread.- ...(msg.thread_id ? { thread_id: msg.thread_id } : {}),- ...(imagePaths.length ? { image_path: imagePaths.join(',') } : {}),- ...(filePaths.length ? { file_path: filePaths.join(',') } : {}),- ...(failedAttachments.length- ? { failed_attachments: failedAttachments.join(',') }- : {}),- },- )- return- }-- if (type === 'command') {- const cmd = payload as CommandPayload- await emitNotification(- `Command: ${cmd.command}${cmd.target ? ` target=${cmd.target}` : ''}`,- {- room_id,- event_type: type,- user_id: cmd.user_id,- user_name: cmd.user_name,- },- )- return- }-- if (type === 'room_join') {- const join = payload as RoomJoinPayload- // This agent is opted out of join events in this room — deliver nothing.- if (!join.listening) {- return- }- await emitNotification(- `${join.member_name} joined the room`,- {- room_id,- event_type: type,- member: join.member,- member_name: join.member_name,- timestamp: new Date(join.timestamp).toISOString(),- },- )- return- }-- if (type === 'task_delegate') {- const task = payload as TaskDelegatePayload- await emitNotification(- `Task delegated: ${task.summary} — ${task.description}`,- {- room_id,- event_type: type,- task_id: task.task_id,- requester_agent_id: task.requester_agent_id,- performer_agent_id: task.performer_agent_id,- summary: task.summary,- },- )- return- }-- if (type === 'task_accept') {- const task = payload as TaskAcceptPayload- await emitNotification(- `Task accepted by ${task.performer_agent_id}`,- {- room_id,- event_type: type,- task_id: task.task_id,- requester_agent_id: task.requester_agent_id,- performer_agent_id: task.performer_agent_id,- },- )- return- }-- if (type === 'task_update') {- const task = payload as TaskUpdatePayload- await emitNotification(- `Task update: ${task.update}`,- {- room_id,- event_type: type,- task_id: task.task_id,- requester_agent_id: task.requester_agent_id,- performer_agent_id: task.performer_agent_id,- },- )- return- }-- if (type === 'task_finalise') {- const task = payload as TaskFinalisePayload- await emitNotification(- `Task finalised: ${task.outcome ?? '(no outcome provided)'}`,- {- room_id,- event_type: type,- task_id: task.task_id,- requester_agent_id: task.requester_agent_id,- performer_agent_id: task.performer_agent_id,- },- )- return- }-- if (type === 'task_cancel') {- const task = payload as TaskCancelPayload- await emitNotification(- `Task cancelled${task.reason ? `: ${task.reason}` : ''}`,- {- room_id,- event_type: type,- task_id: task.task_id,- requester_agent_id: task.requester_agent_id,- performer_agent_id: task.performer_agent_id,- },- )- return- }-- process.stderr.write(`switch-channel: unknown event type: ${type}\n`)-}--const MEDIA_DIR = path.join(SESSION_DIR, 'media')--// Download an inbound attachment from the agent bridge to a local file so-// Claude can Read it. The bridge proxies the bytes out of the Matrix media-// repo (the channel holds only the bridge API token, not Matrix creds).-// Returns the local path, or null on failure (logged, never throws).-function sanitiseName(name: string): string {- return name.replace(/[^a-zA-Z0-9._-]/g, '_') || 'attachment'-}--// Fetch an attachment's bytes from the agent bridge (which proxies the Matrix-// media repo) and write them to a local file under MEDIA_DIR. Throws on error.-async function fetchMediaToFile(- roomId: string,- mxc: string,- destName: string,-): Promise<string> {- const url =- `${API_ENDPOINT}/agents/${AGENT_ID}/rooms/${roomId}/media` +- `?mxc=${encodeURIComponent(mxc)}`- const resp = await fetch(url, {- headers: { Authorization: `Bearer ${API_TOKEN}` },- })- if (!resp.ok) {- throw new Error(`HTTP ${resp.status}: ${await resp.text()}`)- }- const bytes = Buffer.from(await resp.arrayBuffer())- fs.mkdirSync(MEDIA_DIR, { recursive: true })- const dest = path.join(MEDIA_DIR, destName)- fs.writeFileSync(dest, bytes)- return dest-}--// Notification path: best-effort download (failures are logged, never thrown,-// so they can't break event delivery). Returns the local path or null.-async function downloadAttachment(- roomId: string,- att: AttachmentRef,- messageId: string,- index: number,-): Promise<string | null> {- try {- const destName = `${messageId.replace(/[^a-zA-Z0-9]/g, '_')}-${index}-${sanitiseName(att.filename)}`- return await fetchMediaToFile(roomId, att.mxc, destName)- } catch (err) {- process.stderr.write(`switch-channel: attachment download error: ${err}\n`)- return null- }-}--async function setTyping(roomId: string, isTyping: boolean) {- try {- const url = `${API_ENDPOINT}/agents/${AGENT_ID}/typing`- const resp = await fetch(url, {- method: 'POST',- headers: {- Authorization: `Bearer ${API_TOKEN}`,- 'Content-Type': 'application/json',- },- body: JSON.stringify({ room_id: roomId, is_typing: isTyping }),- })- if (!resp.ok) {- process.stderr.write(- `switch-channel: set typing failed: HTTP ${resp.status}: ${await resp.text()}\n`,- )- }- } catch (err) {- process.stderr.write(`switch-channel: set typing error: ${err}\n`)- }-}--async function emitNotification(content: string, meta: Record<string, string>) {- // Surface the unaddressed-message backlog on every notification. meta values- // are strings; missed_count is always present (0 when caught up). When it's- // non-zero, annotate the one-line body so the agent sees it without having- // to inspect meta, and knows to widen read_context's `since` to catch up.- const missed = missedSinceRead- const enriched = { ...meta, missed_count: String(missed) }- const body =- missed > 0- ? `${content}\n⚠️ ${missed} unread room message${missed === 1 ? '' : 's'} since your last read_context — call read_context (widen \`since\`) to catch up on what you missed.`- : content- await mcp.notification({- method: 'notifications/claude/channel',- params: { content: body, meta: enriched },- }).catch(err => {- process.stderr.write(`switch-channel: failed to deliver event to Claude: ${err}\n`)- })-}--// -- Connect and start ---------------------------------------------------------const transport = new StdioServerTransport()--transport.onclose = () => {- stopPolling()- stopConnectionRenew()- stopLeaseRenew()- unpublishPort()- process.exit(0)-}--// Wipe any stale port file left by a crashed previous bun for the same ppid.-// Safe: the previous process for this ppid is gone (we are it now); a live-// sibling would be a different ppid.-unpublishPort()--await mcp.connect(transport)--startHookListener()--process.stderr.write(`switch-channel: running (agent_id=${AGENT_ID})\n`)diff --git a/connectors/claude-code-plugin/skills/configure/SKILL.md b/connectors/claude-code-plugin/skills/configure/SKILL.mdindex 3e0bfe1f9..4e3a2cafb 100644--- a/connectors/claude-code-plugin/skills/configure/SKILL.md+++ b/connectors/claude-code-plugin/skills/configure/SKILL.md@@ -7,7 +7,7 @@ description: Set up the Switch connector — register this Claude Code instanceThis skill registers the current Claude Code instance as a Switch agent andwrites the resulting credentials into Claude Code settings so the `switch`-MCP server and `switch-channel` background process can connect.+local Switch runtime can connect.## How the plugin reads config@@ -24,6 +24,82 @@ choosing project-local vs. user-global settings, the user decides whetherthis Switch identity is tied to one repo or shared across all of them.This skill walks through registration and writes that block.+Separately from the agent's identity, the runtime itself is fetched from a+private registry, which needs its own one-time setup — Step 0.++## Step 0 — Registry access for the runtime++The plugin's MCP server is fetched with+`npx @sandbox-quantum/switch-agent-runtime`. That package is published to+**GitHub Packages** and is private, so npm needs to know which registry+serves the `@sandbox-quantum` scope and how to authenticate. Without both,+`npx` fails — and it fails **misleadingly**: a private package you are not+authorised for returns **404**, not 403, because registries do not admit that+private packages exist. "Package not found" almost always means "not logged+in" here.++Sessions launched by switchdash get this handed to them and need nothing.+This step is for **standalone Claude Code**, where nothing is injecting it.++First check whether it is already set up:++```bash+npm config get @sandbox-quantum:registry+```++If that prints `https://npm.pkg.github.com`, skip to Step 1.++Otherwise it needs the GitHub CLI, authenticated **and holding the+`read:packages` scope**:++```bash+gh auth status+```++If `gh` is missing or logged out, stop and tell the user to install it and run+`gh auth login` — everything below depends on it, and guessing a token is not+something to attempt.++Then look at the `Token scopes:` line. **`gh auth login` does not request+`read:packages`** — the default scopes are `gist`, `read:org`, `repo` and+`workflow`. A perfectly healthy login therefore produces a token the registry+refuses:++```+npm error 403 Permission permission_denied: The token provided does not match expected scopes.+```++If `read:packages` is absent, have the user add it:++```bash+gh auth refresh -h github.com -s read:packages+```++That opens a device-code prompt in a browser. If they cannot complete it (a+headless box, for instance), the alternative is a classic PAT with+`read:packages`, used in place of `gh auth token` below.++Then, with the user's agreement (this writes to their `~/.npmrc`):++```bash+npm config set @sandbox-quantum:registry https://npm.pkg.github.com+npm config set //npm.pkg.github.com/:_authToken "$(gh auth token)"+```++Verify it resolves before moving on, so a failure surfaces here rather than as+a broken MCP server later:++```bash+npm view @sandbox-quantum/switch-agent-runtime version+```++Two things to tell the user plainly rather than leave them to discover:++- This writes a **real token into `~/.npmrc`** (mode 0600). It is how npm+ authenticates to any private registry, but it is a credential at rest.+- It **expires when `gh` rotates its token**, and the symptom is the same+ misleading 404. Re-running the two `npm config set` lines fixes it.+## Step 1 — Check existing configRead both possible settings files to see whether the plugin is already@@ -386,7 +462,7 @@ Report to the user:- Which settings file was written.- That they need to **restart Claude Code** (or reload the session) forthe new `env` block to take effect — the `switch` MCP server and- `switch-channel` process only read environment variables at startup,+ Switch runtime only reads environment variables at startup,so an active session won't see the new values.Do **not** print the API token. It's now in the settings file; the userdiff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.mdindex 461249f65..eec2afcbc 100644--- a/connectors/claude-code-plugin/skills/switch/SKILL.md+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md@@ -11,6 +11,10 @@ message bus.## How to participate+All Switch tools are served by a local runtime running beside you, which+holds this session's push connection. Tool calls and events therefore travel+the same connection — you never talk to the Switch server directly.+1. **List your rooms** — call `list_rooms` to see which rooms you areassigned to.2. **Connect to a room** — call@@ -23,11 +27,12 @@ message bus.package carries its own `instructions` field — read those carefully,they tell you how to use that specific resource. The `linked_rooms`array advertises related rooms — see "Linked rooms" below.-3. **Polling starts automatically.** Once `connect_to_room` succeeds, a- plugin hook signals the channel process to begin polling that room.- Events arrive as `<channel>` notifications within a couple of seconds —- no separate tool call is needed. Switching rooms (calling- `connect_to_room` with a new `room_id`) re-targets polling automatically.+3. **Delivery starts automatically.** Once `connect_to_room` succeeds, a+ plugin hook tells the channel process which room you are in, and it+ claims that room on its push connection to Switch. Events arrive as+ `<channel>` notifications as they happen — no separate tool call is+ needed. Switching rooms (calling `connect_to_room` with a new+ `room_id`) re-targets delivery automatically.4. **Read context** — call `read_context` to see the conversation history.Always read before contributing. It returns the timeline **grouped intothreads**: a list of `{root, replies: [...]}` ordered by latest activity@@ -165,8 +170,13 @@ outstanding work.## Reactive event handlingAfter `connect_to_room` succeeds, events arrive as `<channel>`-notifications automatically — polling is started by a plugin hook, you-don't need to call any extra tool. **Only messages addressed to you,+notifications automatically — the channel process holds a push connection+to Switch and a plugin hook points it at your room, so you don't need to+call any extra tool. If the connection drops it reconnects and resumes+from where it stopped, so a brief network blip costs nothing. If events+were dropped and cannot be replayed you receive a **`gap` notification** —+when that happens, call `read_context` before responding rather than+assuming you have the full picture. **Only messages addressed to you,room-join events you are configured to receive, and task events aredelivered as notifications** — unaddressed room chatter (other agentstalking to each other, broadcast updates, the user discussing thingsdiff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.pyindex bd3b89893..7ce244b57 100644--- a/core/switch_core/bridges/agent/api/handlers.py+++ b/core/switch_core/bridges/agent/api/handlers.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport hashlibimport loggingfrom datetime import UTC, datetime-from typing import Annotated, Any+from typing import Annotated, Any, castfrom fastapi import (APIRouter,@@ -16,7 +16,7 @@ from fastapi import ()from pydantic import ValidationErrorfrom sqlalchemy.ext.asyncio import AsyncSession-from starlette.responses import Response+from starlette.responses import Response, StreamingResponsefrom switch_core.bridges.agent.api.schemas import (AcceptTaskRequest,@@ -24,7 +24,9 @@ from switch_core.bridges.agent.api.schemas import (AgentListResponse,BulkRegisterResult,CancelTaskRequest,+ ConnectionBeatRequest,ConnectionRenewRequest,+ ConnectionSubscribeRequest,CreateModerationRoomRequest,CreateModerationRoomResponse,DelegateTaskRequest,@@ -75,7 +77,17 @@ from switch_core.bridges.agent.dependencies import (get_protocol,get_session,)+from switch_core.bridges.agent.protocol.connections import (+ PROTOCOL_VERSION,+ ConnectionError_,+ DeliveryFilter,+ NoStreamAttachedError,+ RoomOccupiedError,+ Scope,+ UnknownConnectionError,+)from switch_core.bridges.agent.protocol.service import AgentExistsError, ProtocolService+from switch_core.bridges.agent.protocol.stream import event_streamfrom switch_core.db.models import Agent, Taskfrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.feature_flag_store import FeatureFlagStore@@ -612,13 +624,236 @@ async def poll_events(agent: Annotated[Agent, Depends(get_agent_from_scope)],protocol: Annotated[ProtocolService, Depends(get_protocol)],timeout: Annotated[float, Query()] = 10,+ accept: Annotated[str | None, Header()] = None,+ connection_id: Annotated[str | None, Query()] = None,+ scope: Annotated[str, Query()] = "single",+ event_filter: Annotated[str, Query(alias="filter")] = "all",+ start_from: Annotated[str, Query()] = "head",+ spawn_capable: Annotated[bool, Query()] = False,+ protocol_version: Annotated[int, Query(alias="protocol")] = PROTOCOL_VERSION,+ rooms: Annotated[str | None, Query()] = None,+ last_event_id: Annotated[str | None, Header(alias="last-event-id")] = None,) -> EventResponse | Response:+ """Deliver the agent's events, as a push stream or a long poll.++ `Accept: text/event-stream` opens a connection and streams: catch-up from+ the client's cursor, then live delivery. Anything else falls back to the+ long poll, which is served from the same buffer so the two cannot diverge+ while both exist.+ """+ if accept and "text/event-stream" in accept:+ return await _open_event_stream(+ agent=agent,+ protocol=protocol,+ connection_id=connection_id,+ scope=scope,+ event_filter=event_filter,+ start_from=start_from,+ spawn_capable=spawn_capable,+ protocol_version=protocol_version,+ rooms=rooms,+ last_event_id=last_event_id,+ )+events = await protocol.poll_events(agent.id, timeout=timeout)if not events:return Response(status_code=204)return EventResponse(events=events)+def _resolve_start_cursor(+ protocol: ProtocolService,+ agent_id: str,+ start_from: str,+ last_event_id: str | None,+) -> int:+ """Where a stream begins.++ `Last-Event-ID` wins when present: a reconnecting SSE client sends it+ automatically and it is the most accurate statement of what it processed.+ """+ raw = last_event_id or start_from+ if raw in ("", "head"):+ return protocol.event_buffer.head(agent_id)+ try:+ return max(int(raw), 0)+ except ValueError as exc:+ raise HTTPException(+ status_code=400,+ detail=f"start_from must be 'head' or a sequence number, got {raw!r}",+ ) from exc+++async def _open_event_stream(+ *,+ agent: Agent,+ protocol: ProtocolService,+ connection_id: str | None,+ scope: str,+ event_filter: str,+ start_from: str,+ spawn_capable: bool,+ protocol_version: int,+ rooms: str | None,+ last_event_id: str | None,+) -> StreamingResponse:+ if not connection_id:+ raise HTTPException(+ status_code=400,+ detail="connection_id is required to open an event stream; generate a "+ "UUID and reuse it when reconnecting so the connection survives the "+ "drop",+ )+ if scope not in ("single", "all"):+ raise HTTPException(+ status_code=400, detail=f"scope must be 'single' or 'all', got {scope!r}"+ )+ if event_filter not in ("all", "addressed"):+ raise HTTPException(+ status_code=400,+ detail=f"filter must be 'all' or 'addressed', got {event_filter!r}",+ )++ cursor = _resolve_start_cursor(protocol, agent.id, start_from, last_event_id)++ try:+ conn = protocol.connections.open(+ agent_id=agent.id,+ connection_id=connection_id,+ scope=cast(Scope, scope),+ delivery_filter=cast(DeliveryFilter, event_filter),+ spawn_capable=spawn_capable,+ cursor=cursor,+ protocol_version=protocol_version,+ )+ except ConnectionError_ as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc++ # Rooms are claimed before the stream starts, not after it opens. A client+ # reconnecting already knows which room it was in; making it re-subscribe+ # afterwards would race the catch-up, and buffered events for that room+ # would be skipped as "not covered" and the cursor advanced past them —+ # losing exactly the events resume exists to recover.+ for room_id in [r for r in (rooms or "").split(",") if r]:+ try:+ await protocol.require_room_member(agent.id, room_id)+ # Declaring a room on the URL takes it over; a tool call does not.+ #+ # The client doing the delivering owns the slot. Naming a room here+ # is a supervisor asserting ownership of a session it manages and+ # is about to feed — a stream it opens must work, or the session it+ # restored is silent. A `connect_to_room` claim is cooperative and+ # yields to whoever is already covering the room.+ #+ # Without this, a session started before its supervisor learned to+ # share connections keeps the slot, and the supervisor's restored+ # stream 409s and retries forever.+ protocol.connections.claim_room(conn, room_id, takeover=True)+ except (ValueError, PermissionError) as exc:+ protocol.connections.close(conn.id, "invalid room subscription")+ raise HTTPException(status_code=403, detail=str(exc)) from exc+ except ConnectionError_ as exc:+ protocol.connections.close(conn.id, "room already claimed")+ raise HTTPException(status_code=409, detail=str(exc)) from exc++ return StreamingResponse(+ event_stream(+ conn=conn,+ registry=protocol.connections,+ buffer=protocol.event_buffer,+ ),+ media_type="text/event-stream",+ headers={+ "Cache-Control": "no-cache",+ "Connection": "keep-alive",+ # Proxies that buffer would defeat the point of a push channel.+ "X-Accel-Buffering": "no",+ },+ )++[email protected]("/{agent_id}/connection/beat")+async def connection_beat(+ agent_id: str,+ req: ConnectionBeatRequest,+ agent: Annotated[Agent, Depends(get_agent_from_scope)],+ protocol: Annotated[ProtocolService, Depends(get_protocol)],+) -> dict[str, Any]:+ """The single per-connection heartbeat.++ Proves the client is alive and reports its cursor. Rejected when the+ connection is unknown, dead, or has no stream attached — an agent that can+ still make calls but is receiving nothing must be told, not left believing+ it is connected.+ """+ try:+ conn = protocol.connections.beat(agent.id, req.connection_id, req.cursor)+ except NoStreamAttachedError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except UnknownConnectionError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc++ protocol.event_buffer.confirm(agent.id, conn.id, req.cursor)+ return {"ok": True, "rooms": sorted(conn.rooms), "cursor": conn.cursor}++[email protected]("/{agent_id}/connection/subscribe")+async def connection_subscribe(+ agent_id: str,+ req: ConnectionSubscribeRequest,+ agent: Annotated[Agent, Depends(get_agent_from_scope)],+ protocol: Annotated[ProtocolService, Depends(get_protocol)],+) -> dict[str, Any]:+ """Claim a room on an open connection.++ Membership is checked here, so a connection can only cover rooms the agent+ already belongs to: subscribing is not joining. On a `single`-scope+ connection this also drops whichever room it held before, which is how+ "one room at a time" stops being a convention and becomes a guarantee.+ """+ try:+ conn = protocol.connections.require(agent.id, req.connection_id)+ except UnknownConnectionError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc++ try:+ await protocol.require_room_member(agent.id, req.room_id)+ except ValueError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ except PermissionError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from exc++ try:+ evicted = protocol.connections.claim_room(+ conn, req.room_id, takeover=req.takeover+ )+ except RoomOccupiedError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc++ return {+ "ok": True,+ "rooms": sorted(conn.rooms),+ "evicted_connection_id": evicted.id if evicted else None,+ }++[email protected]("/{agent_id}/connection/unsubscribe")+async def connection_unsubscribe(+ agent_id: str,+ req: ConnectionSubscribeRequest,+ agent: Annotated[Agent, Depends(get_agent_from_scope)],+ protocol: Annotated[ProtocolService, Depends(get_protocol)],+) -> dict[str, Any]:+ """Release a room, returning coverage to any all-scope connection."""+ try:+ conn = protocol.connections.require(agent.id, req.connection_id)+ except UnknownConnectionError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc++ protocol.connections.release_room(conn, req.room_id)+ return {"ok": True, "rooms": sorted(conn.rooms)}++@router.get("/{agent_id}/notifications", response_model=None)async def poll_notifications(agent_id: str,diff --git a/core/switch_core/bridges/agent/api/operations.py b/core/switch_core/bridges/agent/api/operations.pynew file mode 100644index 000000000..a20e5eaba--- /dev/null+++ b/core/switch_core/bridges/agent/api/operations.py@@ -0,0 +1,174 @@+"""HTTP front door for the agent operations (CHOO-1857 / CHOO-490).++`POST /agents/{agent_id}/ops/{operation}` with the operation's arguments as the+JSON body. Operation names are exactly the MCP tool names — one vocabulary, so+a local runtime translating between the two is `POST /ops/${toolName}` and+nothing more.++Both front doors are built from the **same** registry: this one dispatches into+it, and the MCP server registers its tools from it. Parity is therefore+structural — an operation is reachable through both doors the moment it exists,+and neither can quietly fall behind the other.++What is deliberately NOT here: media upload/download (multipart and binary, so+HTTP semantics matter), the event stream, connection lifecycle, mediation, and+registration. Those are not agent tools.+"""++from __future__ import annotations++import inspect+import logging+from typing import Annotated, Any++from fastapi import APIRouter, Depends, Header, HTTPException++from switch_core.bridges.agent.auth import get_agent_from_scope+from switch_core.bridges.agent.dependencies import get_protocol+from switch_core.bridges.agent.operations import all_operations, get_operation+from switch_core.bridges.agent.operations.callctx import (+ CallContext,+ reset_call_context,+ set_call_context,+)+from switch_core.bridges.agent.protocol.connections import UnknownConnectionError+from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.db.models import Agent++logger = logging.getLogger(__name__)+++class UnknownOperationError(Exception):+ def __init__(self, name: str, known: list[str]) -> None:+ super().__init__(+ f"unknown operation {name!r}; expected one of: {', '.join(sorted(known))}"+ )+ self.name = name+++class BadArgumentsError(Exception):+ """The body did not match the operation's parameters."""+++def list_operations() -> dict[str, dict[str, Any]]:+ """Every operation, with its parameters.++ Read straight off the registry both doors are built from, so this is the+ authoritative list — for clients and for the protocol documentation.+ """+ return {+ op.name: {+ "description": op.description,+ "input_schema": op.input_schema,+ }+ for op in all_operations().values()+ }+++async def call_operation(+ *,+ operation: str,+ arguments: dict[str, Any],+ agent_id: str,+ connection_id: str | None,+) -> Any:+ """Run one operation on behalf of an agent.++ `connection_id` becomes the caller's session key, so an operation that+ depends on the caller's room binding — `connect_to_room`, `post_message`,+ `assume_role` — resolves it from the connection rather than from an MCP+ transport session. That is what makes the two doors interchangeable.+ """+ op = get_operation(operation)+ if op is None:+ raise UnknownOperationError(operation, list(all_operations()))++ fn = op.fn+ signature = inspect.signature(fn)+ accepted = set(signature.parameters)++ unexpected = set(arguments) - accepted+ if unexpected:+ raise BadArgumentsError(+ f"{operation} does not accept: {', '.join(sorted(unexpected))}"+ )++ call_args: dict[str, Any] = dict(arguments)++ missing = [+ name+ for name, param in signature.parameters.items()+ if name not in call_args and param.default is inspect.Parameter.empty+ ]+ if missing:+ raise BadArgumentsError(f"{operation} requires: {', '.join(missing)}")++ token = set_call_context(CallContext(agent_id=agent_id, session_key=connection_id))+ try:+ result = fn(**call_args)+ if inspect.isawaitable(result):+ result = await result+ return result+ finally:+ reset_call_context(token)+++# ── HTTP router ──────────────────────────────────────────────────────────────+++router = APIRouter(prefix="/agents", tags=["operations"])++[email protected]("/{agent_id}/ops")+async def get_operations(+ agent_id: str,+ agent: Annotated[Agent, Depends(get_agent_from_scope)],+) -> dict[str, Any]:+ """List every operation and its parameters, straight from the registry."""+ return {"operations": list_operations()}++[email protected]("/{agent_id}/ops/{operation}")+async def post_operation(+ agent_id: str,+ operation: str,+ agent: Annotated[Agent, Depends(get_agent_from_scope)],+ protocol: Annotated[ProtocolService, Depends(get_protocol)],+ body: dict[str, Any] | None = None,+ connection_id: Annotated[str | None, Header(alias="x-switch-connection-id")] = None,+) -> dict[str, Any]:+ """Run one operation. The body is the operation's arguments.++ `X-Switch-Connection-Id` ties the call to an open connection, which is how+ an operation that depends on the caller's room binding resolves it. It is+ derived here from the header rather than trusted from the body, and the+ connection is checked against the calling agent.+ """+ if connection_id is not None:+ # Derived, never taken on trust: a connection id belonging to another+ # agent, or to one that has already died, is refused rather than+ # silently treated as no connection at all.+ try:+ protocol.connections.require(agent.id, connection_id)+ except UnknownConnectionError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc++ try:+ result = await call_operation(+ operation=operation,+ arguments=body or {},+ agent_id=agent.id,+ connection_id=connection_id,+ )+ except UnknownOperationError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ except BadArgumentsError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except PermissionError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from exc+ except ValueError as exc:+ # Operations raise ValueError for "you asked for something that is not+ # there or not allowed yet" - surfaced rather than swallowed.+ raise HTTPException(status_code=400, detail=str(exc)) from exc++ return {"result": result}diff --git a/core/switch_core/bridges/agent/api/schemas.py b/core/switch_core/bridges/agent/api/schemas.pyindex 1e7a7b1c3..06b486fa0 100644--- a/core/switch_core/bridges/agent/api/schemas.py+++ b/core/switch_core/bridges/agent/api/schemas.py@@ -107,6 +107,28 @@ class ConnectionRenewRequest(BaseModel):room_id: str+class ConnectionSubscribeRequest(BaseModel):+ """Claim (or release) a room on an open connection (CHOO-1857)."""++ connection_id: str+ room_id: str+ # Evict whichever connection currently holds the room. Off by default: the+ # usual cause of a collision is a stale process, and rejecting surfaces it.+ takeover: bool = False+++class ConnectionBeatRequest(BaseModel):+ """The single client tick that keeps a connection alive (CHOO-1857).++ Replaces /connection/renew, /watch/heartbeat and /leases/renew: it proves+ the client is alive *and* consuming, and reports how far it has read so the+ event buffer knows what has been seen.+ """++ connection_id: str+ cursor: int = 0++class StatusRequest(BaseModel):room_id: strpresence: Literal["online", "offline"] | None = Nonediff --git a/core/switch_core/bridges/agent/app.py b/core/switch_core/bridges/agent/app.pyindex 87cfdb9f3..8a6c452cf 100644--- a/core/switch_core/bridges/agent/app.py+++ b/core/switch_core/bridges/agent/app.py@@ -7,11 +7,13 @@ from fastapi.exceptions import RequestValidationErrorfrom fastapi.responses import JSONResponsefrom switch_core.bridges.agent.api.handlers import router as api_router+from switch_core.bridges.agent.api.operations import router as operations_routerfrom switch_core.bridges.agent.auth import BearerAuthMiddlewarefrom switch_core.bridges.agent.deeplink import router as deeplink_routerfrom switch_core.bridges.agent.dependencies import init_dependenciesfrom switch_core.bridges.agent.mcp import create_mcp_app-from switch_core.bridges.agent.protocol.event_queue import EventQueue+from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.request_tracker import RequestTrackerfrom switch_core.bridges.collaboration.lifecycle_service import (@@ -41,7 +43,7 @@ def create_agent_bridge_app(room_service: RoomService,client_lifecycle: ClientLifecycleService,collab_lifecycle: CollaborationBridgeLifecycleService,- event_queue: EventQueue,+ event_buffer: EventBuffer,task_store: TaskStore,request_tracker: RequestTracker,resource_request_tracker: ResourceRequestTracker,@@ -51,7 +53,15 @@ def create_agent_bridge_app(bridge_store: CollaborationBridgeStore,session_factory: object,config: SwitchConfig,+ connections: ConnectionRegistry | None = None,) -> tuple[FastAPI, ProtocolService]:+ # One registry for the whole process: the live connection set is the source+ # of truth for reachability, so every service must see the same one. The+ # caller may supply it — main.py does, because the Matrix agent clients are+ # wired before this app is built and read presence from the same registry.+ if connections is None:+ connections = ConnectionRegistry()+init_dependencies(agent_store=agent_store,agent_session_store=agent_session_store,@@ -59,7 +69,8 @@ def create_agent_bridge_app(room_service=room_service,client_lifecycle=client_lifecycle,collab_lifecycle=collab_lifecycle,- event_queue=event_queue,+ event_buffer=event_buffer,+ connections=connections,task_store=task_store,request_tracker=request_tracker,resource_request_tracker=resource_request_tracker,@@ -78,7 +89,8 @@ def create_agent_bridge_app(room_service=room_service,client_lifecycle=client_lifecycle,collab_lifecycle=collab_lifecycle,- event_queue=event_queue,+ event_buffer=event_buffer,+ connections=connections,task_store=task_store,request_tracker=request_tracker,resource_request_tracker=resource_request_tracker,@@ -121,6 +133,7 @@ def create_agent_bridge_app(return JSONResponse(status_code=422, content={"detail": exc.errors()})app.include_router(api_router, prefix="/agents", tags=["api"])+ app.include_router(operations_router)app.include_router(deeplink_router, tags=["deeplink"])app.state.config = configdiff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.pyindex 8725b5be6..9f088e246 100644--- a/core/switch_core/bridges/agent/commands.py+++ b/core/switch_core/bridges/agent/commands.py@@ -278,7 +278,11 @@ async def _dispatch_control_command(if level == "session_dependent":async with client.session_factory() as session:statuses = await compute_agent_statuses(- session, [agent], meta.room_id, client._agent_session_store+ session,+ [agent],+ meta.room_id,+ client._agent_session_store,+ client._connections,)runtime = await AgentRuntimeStateStore().get(session, agent.id, meta.room_id@@ -289,7 +293,7 @@ async def _dispatch_control_command(# command args so the controller can fold it into the reconnect# prompt.role = await client._room_role_store.agent_room_role(- session, meta.room_id, agent.id+ session, meta.room_id, agent.id, client._connections.live_agent_ids())live = statuses.get(agent.id) == AgentStatus.LIVEcaps = (runtime.control_capabilities or {}) if runtime else {}@@ -309,7 +313,7 @@ async def _dispatch_control_command(# switchdash when we know its deeplink.body = f"{ack} ([Open in SwitchDash]({deeplink}))" if deeplink else ackawait _reply(client, room, event, body)- client._event_queue.enqueue(+ client._event_buffer.enqueue(client.agent.id,meta.room_id,AgentEvent(@@ -697,7 +701,11 @@ async def _cmd_status(await _reply(client, room, event, "No agents in this room.")returnstatuses = await compute_agent_statuses(- session, agents, meta.room_id, client._agent_session_store+ session,+ agents,+ meta.room_id,+ client._agent_session_store,+ client._connections,)runtime_rows = await AgentRuntimeStateStore().get_by_room(session, meta.room_id)runtime_states = {row.agent_id: row.state for row in runtime_rows}@@ -730,7 +738,7 @@ async def _cmd_roles(await _reply(client, room, event, "No roles defined in this room.")returnholders = await client._room_role_store.live_holders_for_room(- session, meta.room_id+ session, meta.room_id, client._connections.live_agent_ids())holder_names: dict[str, str] = {}for holder_id in {h for ids in holders.values() for h in ids}:diff --git a/core/switch_core/bridges/agent/dependencies.py b/core/switch_core/bridges/agent/dependencies.pyindex 46bbbdd55..217a12473 100644--- a/core/switch_core/bridges/agent/dependencies.py+++ b/core/switch_core/bridges/agent/dependencies.py@@ -5,7 +5,8 @@ from typing import Anyfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.bridges.agent.protocol.event_queue import EventQueue+from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.request_tracker import RequestTrackerfrom switch_core.bridges.collaboration.lifecycle_service import (@@ -35,7 +36,8 @@ def init_dependencies(room_service: RoomService,client_lifecycle: ClientLifecycleService,collab_lifecycle: CollaborationBridgeLifecycleService,- event_queue: EventQueue,+ event_buffer: EventBuffer,+ connections: ConnectionRegistry,task_store: TaskStore,request_tracker: RequestTracker,resource_request_tracker: ResourceRequestTracker,@@ -52,7 +54,8 @@ def init_dependencies(_state["room_service"] = room_service_state["client_lifecycle"] = client_lifecycle_state["collab_lifecycle"] = collab_lifecycle- _state["event_queue"] = event_queue+ _state["event_buffer"] = event_buffer+ _state["connections"] = connections_state["task_store"] = task_store_state["request_tracker"] = request_tracker_state["resource_request_tracker"] = resource_request_tracker@@ -70,7 +73,8 @@ def init_dependencies(room_service=room_service,client_lifecycle=client_lifecycle,collab_lifecycle=collab_lifecycle,- event_queue=event_queue,+ event_buffer=event_buffer,+ connections=connections,task_store=task_store,request_tracker=request_tracker,resource_request_tracker=resource_request_tracker,@@ -104,8 +108,8 @@ def get_client_lifecycle() -> ClientLifecycleService:return _state["client_lifecycle"] # type: ignore[no-any-return]-def get_event_queue() -> EventQueue:- return _state["event_queue"] # type: ignore[no-any-return]+def get_event_buffer() -> EventBuffer:+ return _state["event_buffer"] # type: ignore[no-any-return]def get_task_store() -> TaskStore:diff --git a/core/switch_core/bridges/agent/mcp/server.py b/core/switch_core/bridges/agent/mcp/server.pyindex 77ca37709..2b2ef6db6 100644--- a/core/switch_core/bridges/agent/mcp/server.py+++ b/core/switch_core/bridges/agent/mcp/server.py@@ -1,18 +1,34 @@+"""MCP front door onto the agent operations (CHOO-1857 / CHOO-490).++This module owns no operations. It registers every operation from the registry+as an MCP tool and serves them over streamable HTTP at `/mcp`, so the MCP+surface is exactly the operation surface — automatically, with nothing to keep+in step by hand.++Switch hosting an MCP server is the legacy path: the supported direction is a+local runtime that serves the tool surface next to the agent and translates+each call onto its own connection. Because operations live in the registry+rather than here, retiring this door is removing a file, not a refactor.+"""+from __future__ import annotationsimport loggingfrom typing import TYPE_CHECKING, Any-from fastmcp import Context, FastMCP+from fastmcp import FastMCPfrom fastmcp.server.dependencies import get_http_request-from fastmcp.server.middleware import PingMiddleware+from fastmcp.server.middleware import Middleware, MiddlewareContext, PingMiddlewarefrom starlette.types import ASGIApp-from switch_core.bridges.agent.api.handlers import parse_timestamp_msfrom switch_core.bridges.agent.auth import BearerAuthMiddleware, OIDCTokenValidator-from switch_core.bridges.agent.protocol.instructions import build_room_instructions-from switch_core.bridges.agent.protocol.types import IntegrationProfile-from switch_core.db.models import CollaborationBridge+from switch_core.bridges.agent.operations import all_operations+from switch_core.bridges.agent.operations.callctx import (+ CallContext,+ reset_call_context,+ set_call_context,+)+from switch_core.bridges.agent.operations.context import init_operations_protocolif TYPE_CHECKING:from switch_core.bridges.agent.protocol.service import ProtocolService@@ -22,1641 +38,55 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-_protocol: ProtocolService | None = None-def init_mcp_protocol(protocol: ProtocolService) -> None:- global _protocol- _protocol = protocol-+ """Give the operations layer its protocol service.-def _get_protocol() -> ProtocolService:- assert _protocol is not None, "MCP protocol not initialized"- return _protocol---def _get_agent_id() -> str:- """Resolve the calling agent from the authenticated HTTP request scope.-- BearerAuthMiddleware sets `scope["agent_id"]` for every authenticated MCP- request; fastmcp's `get_http_request()` exposes that scope inside the tool- handler.+ Kept under the old name because callers wire it at startup; the state it+ sets now belongs to the operations layer, not to this door."""- request = get_http_request()- agent_id = request.scope.get("agent_id")- if not isinstance(agent_id, str):- raise ValueError("No agent_id in request — authentication failed")- return agent_id+ init_operations_protocol(protocol)-async def _require_connected_room(ctx: Context) -> str:- """Return the room_id this MCP session is bound to.+class CallContextMiddleware(Middleware):+ """Establish who is calling before an operation runs.- Raises if the session has not called connect_to_room.+ Operations resolve the caller from the call context and nothing else, so+ each front door is responsible for binding it. Here that means the agent+ from the authenticated request scope and the MCP transport session as the+ key that owns the room binding."""- transport_session_id = ctx.session_id- if not transport_session_id:- raise ValueError("Not connected to a room. Call connect_to_room first.")- protocol = _get_protocol()- async with protocol.session_factory() as db:- result = await protocol.agent_session_store.get_connected_room(- db, transport_session_id- )- if result is None:- raise ValueError("Not connected to a room. Call connect_to_room first.")- _, room_id = result- return room_id--mcp = FastMCP("Switch")---async def list_rooms(- ctx: Context, include_archived: bool = False-) -> list[dict[str, Any]]:- """List rooms this agent is assigned to.-- Args:- include_archived: When false (default), archived rooms are omitted so- the active list stays uncluttered. Set true to also include- archived rooms (each carries `archived: true`).-- Returns:- List of {room_id, name, description, connected, archived} dicts.- `connected` is true for the room this session is currently connected- to (if any); `archived` is true for archived rooms.- """- agent_id = _get_agent_id()+ async def on_call_tool(self, context: MiddlewareContext, call_next): # type: ignore[no-untyped-def]+ request = get_http_request()+ agent_id = request.scope.get("agent_id")+ if not isinstance(agent_id, str):+ raise ValueError("No agent_id in request — authentication failed")- protocol = _get_protocol()- connected_room_id: str | None = None- if ctx.session_id:- async with protocol.session_factory() as db:- row = await protocol.agent_session_store.get_connected_room(- db, ctx.session_id+ fastmcp_context = context.fastmcp_context+ token = set_call_context(+ CallContext(+ agent_id=agent_id,+ session_key=(+ fastmcp_context.session_id if fastmcp_context is not None else None+ ),)- if row is not None:- _, connected_room_id = row- rooms = await protocol.list_rooms(agent_id, include_archived=include_archived)-- return [- {- "room_id": r.id,- "name": r.name,- "description": r.description,- "connected": r.id == connected_room_id,- "archived": r.archived,- }- for r in rooms- ]---async def connect_to_room(- room_id: str,- ctx: Context,- include_general_instructions: bool = True,-) -> dict[str, Any]:- """Connect this session to a room. The agent must be assigned to the room.-- Args:- room_id: The Switch room id (UUID string) to connect to. Get valid- ids from list_rooms. This is the Switch room id, not the Matrix- room id. Calling again switches the active room for this session.- include_general_instructions: When true (default) the `instructions`- field carries the full room-onboarding text (interaction modes,- task protocol, agent statuses, room setup) followed by any- room-specific instructions. Set false if your host already- injects the general Switch usage instructions out-of-band (e.g.- via a Claude Code skill); the general sections are then omitted- but room-specific instructions configured at room creation are- still returned.-- Returns:- {agent_id, room_id, name, description, participants, instructions,- reference_types, references, documents, packages, linked_rooms,- roles}.- Each reference, document, and package carries its own `instructions`- field — agent-facing guidance for that resource — alongside a short- `description`. `roles` lists the room's assumable roles, each- `{name, exclusive, instructions_preview, held_by, assumable_by_me}` —- `held_by` is the list of agent names currently holding it (live lease;- empty if free, and a shared role may list several), so you can see- which roles are taken and by whom before calling- `assume_role`. `linked_rooms` lists directed pointers from this room- to other Switch rooms: each entry has `target_room_id`,- `target_room_name`, `target_room_description`, `label` (free-text- relationship hint set by the operator) and `access` —- either ``"member"`` (you can `connect_to_room(target_room_id)`) or- ``"not_member"`` (you have NOT been assigned to that room; the- connect call WILL fail — ask the operator to add you first).- """- agent_id = _get_agent_id()- protocol = _get_protocol()-- try:- room = await protocol.require_room_member(agent_id, room_id)- except ValueError as e:- raise ValueError(str(e)) from e- except PermissionError as e:- raise ValueError(str(e)) from e-- participants = await protocol.list_participants(room_id)-- async with protocol.session_factory() as session:- agent = await protocol.agent_store.get(session, agent_id)- room_model = await protocol.room_store.get(session, room.id)- if agent is None or room_model is None:- raise ValueError("Agent or room not found")- bridge: CollaborationBridge | None = None- if room_model.bridge_id:- bridge = await session.get(CollaborationBridge, room_model.bridge_id)-- profile = IntegrationProfile(**agent.integration_profile)- instructions = build_room_instructions(- agent,- room_model,- profile,- participants,- bridge,- include_general=include_general_instructions,- )- resources = await protocol.list_room_resources(room.id)- linked_rooms = await _decorate_linked_rooms(- protocol, agent_id, resources["linked_rooms"]- )- roles = await protocol.list_room_roles(agent_id, room.id)-- if not ctx.session_id:- raise ValueError("MCP session has no session id; cannot connect to room")- # session_passive agents have no poll loop, so the row exists only to- # bind the MCP transport to a room — lifecycle="explicit". always_on and- # session_addressable agents also receive heartbeat upserts; we mark the- # row "heartbeat" so the poll path's on-conflict update doesn't need to- # special-case it.- lifecycle = (- "explicit" if profile.connection_model == "session_passive" else "heartbeat"- )- async with protocol.session_factory() as db:- await protocol.agent_session_store.set_connected_room(- db,- agent_id=agent_id,- room_id=room.id,- transport_session_id=ctx.session_id,- lifecycle=lifecycle,)- await db.commit()-- return {- "agent_id": agent_id,- "room_id": room.id,- "name": room.name,- "description": room.description,- "participants": [- {- "id": p.id,- "name": p.name,- "type": p.type,- "agent_type": p.agent_type,- "can_delegate": p.can_delegate,- "can_accept": p.can_accept,- "status": p.status.value if p.status is not None else None,- "room_role": p.room_role,- "alias": p.alias,- }- for p in participants- ],- "instructions": instructions,- "reference_types": resources["reference_types"],- "references": resources["references"],- "documents": resources["documents"],- "packages": resources["packages"],- "linked_rooms": linked_rooms,- "roles": roles,- }---async def _decorate_linked_rooms(- protocol: ProtocolService,- agent_id: str,- linked_rooms: list[dict[str, Any]],-) -> list[dict[str, Any]]:- """Annotate each linked-room entry with an explicit ``access`` field —- ``"member"`` if the calling agent is assigned to the target room,- ``"not_member"`` otherwise. For ``not_member`` rows, also include a- human-readable ``access_note`` warning that ``connect_to_room`` will- fail until the agent is added by an operator."""- if not linked_rooms:- return []- async with protocol.session_factory() as session:- agent_rooms = await protocol.room_store.get_rooms_for_agent(session, agent_id)- member_ids = {r.id for r in agent_rooms}- out: list[dict[str, Any]] = []- for entry in linked_rooms:- is_member = entry["target_room_id"] in member_ids- decorated = {- **entry,- "access": "member" if is_member else "not_member",- }- if not is_member:- decorated["access_note"] = (- "You are NOT assigned to this room. connect_to_room will fail; "- "ask the room operator to add you before trying."- )- out.append(decorated)- return out---async def list_references(ctx: Context) -> dict[str, Any]:- """List references, documents, and packages attached to this session's- connected room.-- Returns:- {reference_types, references, documents, packages} — same shape as- the equivalent fields in `connect_to_room`. Use this to refresh- after attachments change mid-session.-- External references carry their `value` inline (URLs / IDs); fetch the- underlying content using your own tools as described in- `reference_types[<type>].instructions`.-- Internal documents are advertised by id + description + instructions- only; call `load_internal_documents` to fetch their content.-- Packages bundle other refs and documents and have their own- `instructions`; their `references` and `documents` arrays mirror the- same shape as the top-level fields.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- protocol = _get_protocol()- await protocol.require_room_member(agent_id, room_id)- return await protocol.list_room_resources(room_id)---async def list_linked_rooms(ctx: Context) -> list[dict[str, Any]]:- """List the rooms linked from this session's connected room.-- Returns the directed outbound links from the current room — each link- points at another Switch room and carries a free-text ``label`` set by- the room's operator (e.g. "support", "parent project", "related- workstream"). Pointers grant NO implicit access: the ``access`` field- tells you whether you (the calling agent) can act on the target —- ``"member"`` means ``connect_to_room(target_room_id)`` will work,- ``"not_member"`` means you are not assigned to that room and the call- WILL fail until an operator adds you. ``not_member`` entries also- carry an ``access_note`` spelling that out.-- Returns:- List of {target_room_id, target_room_name, target_room_description,- label, access, access_note?} dicts.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- protocol = _get_protocol()- await protocol.require_room_member(agent_id, room_id)- resources = await protocol.list_room_resources(room_id)- return await _decorate_linked_rooms(protocol, agent_id, resources["linked_rooms"])---async def load_internal_documents(ids: list[str], ctx: Context) -> list[dict[str, Any]]:- """Load the content of internal documents attached to the connected room.-- Args:- ids: List of document ids to load (from `documents[*].id` in the- connect payload or `list_references`).-- Returns:- List of {id, description, content} entries in the same order as- the requested ids. Raises an error if any id is not attached to the- current room.-- The load goes through the Switch resource manager as a Matrix event- round-trip, mirroring how tool and LLM mediation works.- """- import uuid-- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- protocol = _get_protocol()- await protocol.require_room_member(agent_id, room_id)- request_id = str(uuid.uuid4())- return await protocol.request_document_load(- agent_id=agent_id,- room_id=room_id,- document_ids=ids,- request_id=request_id,- timeout=30.0,- )---_ROOM_DOCUMENT_MAX_CONTENT_BYTES = 1_048_576---async def create_room_document(- name: str,- description: str,- instructions: str,- content: str,- ctx: Context,-) -> dict[str, str]:- """Create a new internal document scoped to the connected room.-- The document lives only in this room, is visible to all participants,- and never appears in the global resources library. Only you (the creating- agent) can later update or delete it via `update_room_document` /- `delete_room_document`. Other room members can read it via- `load_internal_documents`, and human users can delete it from the room UI.-- Args:- name: Short identifier for the document. Must be unique within this room.- description: One-line summary (shown in pickers and listings).- instructions: Agent-facing notes on when/how to use this document.- content: Full text content (max 1 MiB).-- Returns:- ``{"document_id": "..."}`` once the resource manager confirms creation.- """- import uuid-- if len(content.encode("utf-8")) > _ROOM_DOCUMENT_MAX_CONTENT_BYTES:- raise ValueError(f"content exceeds {_ROOM_DOCUMENT_MAX_CONTENT_BYTES} bytes")- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- protocol = _get_protocol()- await protocol.require_room_member(agent_id, room_id)- request_id = str(uuid.uuid4())- document_id = await protocol.request_room_document_create(- agent_id=agent_id,- room_id=room_id,- name=name,- description=description,- instructions=instructions,- content=content,- request_id=request_id,- timeout=30.0,- )- return {"document_id": document_id}---async def update_room_document(- document_id: str,- ctx: Context,- name: str | None = None,- description: str | None = None,- instructions: str | None = None,- content: str | None = None,-) -> dict[str, str]:- """Update a room-scoped document you created in the connected room.-- Only the agent that created the document can update it. Pass only the- fields you want to change; omit (or set to None) the others.- """- import uuid-- if (- content is not None- and len(content.encode("utf-8")) > _ROOM_DOCUMENT_MAX_CONTENT_BYTES- ):- raise ValueError(f"content exceeds {_ROOM_DOCUMENT_MAX_CONTENT_BYTES} bytes")- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- protocol = _get_protocol()- await protocol.require_room_member(agent_id, room_id)- request_id = str(uuid.uuid4())- await protocol.request_room_document_update(- agent_id=agent_id,- room_id=room_id,- document_id=document_id,- name=name,- description=description,- instructions=instructions,- content=content,- request_id=request_id,- timeout=30.0,- )- return {"document_id": document_id, "status": "ok"}---async def delete_room_document(document_id: str, ctx: Context) -> dict[str, str]:- """Delete a room-scoped document you created in the connected room.-- Only the agent that created the document can delete it via MCP. Users- can also delete from the room UI as an admin escape hatch.- """- import uuid-- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- protocol = _get_protocol()- await protocol.require_room_member(agent_id, room_id)- request_id = str(uuid.uuid4())- await protocol.request_room_document_delete(- agent_id=agent_id,- room_id=room_id,- document_id=document_id,- request_id=request_id,- timeout=30.0,- )- return {"document_id": document_id, "status": "ok"}---async def read_context(- ctx: Context,- limit: int = 50,- since: str | None = None,- before: str | None = None,-) -> list[dict[str, Any]]:- """Get the conversation timeline for the connected room, grouped into threads.-- Returns a list of thread groups ordered by latest activity (most-recently- active LAST, so the tail is the freshest), each shaped as::-- {"root": <message>, "replies": [<message>, ...]}-- where <message> is {"id", "sender", "sender_name", "body", "timestamp",- "attachments"}. Top-level messages are roots with an empty `replies` list;- replies are oldest-first within a thread. Use a root's (or any message's)- `id` as the `thread_id` argument to post_message / send_targeted_message to- reply into that thread.-- `attachments` is a (usually empty) list of files on the message, each- {"filename", "mimetype", "size", "mxc", "msgtype"}. Any file type can- appear, and a message may carry several. To actually view one, pass its- `mxc` to the channel's `download_attachment` tool, which fetches it to a- local file you can read.-- Args:- limit: Maximum number of messages to scan (default 50), grouped into- threads before returning.- since: ISO-8601 timestamp string (e.g. "2026-05-20T20:55:00Z"). Only- messages at or after this time are returned. Use this when an event- arrives to fetch just the recent context — pass a timestamp a few- minutes before the event ts. None = no lower bound.- before: ISO-8601 timestamp string. Only messages strictly before this- time are returned. Combine with `since` to page through history.- None = no upper bound.-- The room is implicit (the session's currently connected room). Reads- fail if you have not called connect_to_room first.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)-- protocol = _get_protocol()- since_ms = parse_timestamp_ms(since) if since else None- before_ms = parse_timestamp_ms(before) if before else None-- return await protocol.read_context(- agent_id, room_id, limit=limit, since_ms=since_ms, before_ms=before_ms- )---async def list_participants(ctx: Context) -> list[dict[str, Any]]:- """List agents and users in the connected room.-- Args:- (none) — operates on the session's currently connected room. Call- connect_to_room first.-- Returns:- List of {id, name, type} dicts for each participant.- """- _get_agent_id()- room_id = await _require_connected_room(ctx)-- protocol = _get_protocol()- participants = await protocol.list_participants(room_id)-- return [- {- "id": p.id,- "name": p.name,- "type": p.type,- "status": p.status.value if p.status is not None else None,- "alias": p.alias,- }- for p in participants- ]---async def post_message(- body: str, ctx: Context, thread_id: str | None = None-) -> dict[str, str]:- """Send a message to the connected room (broadcast, no specific recipient).-- Args:- body: The message text to send. Plain string — do not wrap in JSON or- prefix with `@name` (use send_targeted_message for addressed- messages). The room is implicit: messages go to the room this- session is currently connected to via connect_to_room, so there- is no `room_id` parameter.- thread_id: Optional. The `id` of a message to reply into, making this a- threaded reply. Pass any message id from the thread (a root or a- reply) — it is normalised to the thread root. Omit for a top-level- message. Get ids from read_context or from a notification's- thread_id.-- Returns:- {"event_id": "<matrix event id>"} for the posted message.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)-- protocol = _get_protocol()- event_id = await protocol.send_message(agent_id, room_id, body, thread_id=thread_id)- return {"event_id": event_id}---async def send_targeted_message(- body: str,- ctx: Context,- target_names: list[str] | None = None,- target_roles: list[str] | None = None,- thread_id: str | None = None,-) -> dict[str, Any]:- """Send a message addressed to specific agents/users and/or roles.-- Prepends `@name` for each name target and `@role` for each role target so- they receive it as an addressed event. Other participants still see the- message as room context. Use when you need specific participants to act,- but the work is informal (a question, nudge, or handoff that doesn't need- task tracking).-- Args:- body: The message text. Plain string — do not pre-add `@` prefixes;- this tool adds them for each target.- target_names: Agent or user names (the `name` field from- list_participants, not ids) to address. Prepended as `@name`.- target_roles: Role names (from list_roles) to address. Each is- prepended as `@role` and fans out to every live holder of that- role — the single holder for an exclusive role, all current- holders for a shared one. Use this to reach "whoever holds the- manager role" without naming the agent.- thread_id: Optional. The `id` of a message to reply into, making this a- threaded reply. Pass any message id from the thread — it is- normalised to the thread root. Omit for a top-level message.-- At least one of target_names / target_roles is required.-- Returns:- {"event_id": "<matrix event id>", "target_statuses": {name: status}}.- `target_statuses` reports each addressed *agent*'s reachability at send- time — for a role target, that is each of its live holders: `live`- (will receive immediately), `awaiting_manual_poll` (must read context- to see it), `no_session`/`disconnected` (not reachable; may not see the- message until they reconnect). User targets are omitted — their- reachability is the collaboration bridge's concern. A role with no live- holder contributes no entries.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)-- protocol = _get_protocol()- result = await protocol.send_targeted_message(- agent_id,- room_id,- target_names or [],- body,- thread_id=thread_id,- target_roles=target_roles or [],- )- return {- "event_id": result.event_id,- "target_statuses": {n: s.value for n, s in result.target_statuses.items()},- }---# ── Task Protocol ───────────────────────────────────────────────────────────---async def delegate_task(- performer_agent_id: str, summary: str, description: str, ctx: Context-) -> dict[str, str]:- """Delegate a task to a performer agent. Requires can_delegate capability.-- Args:- performer_agent_id: The id of the agent to assign the task to. Must- be a participant in the connected room. Use list_participants to- find ids (the `id` field, not `name`).- summary: Short one-line title for the task (shown in lists/headers).- description: Full instructions: what to do, inputs, expected output,- constraints. The performer reads this when accepting.-- Returns:- {"task_id": "<id>", "status": "pending", "target_status": "<status>"}.- `target_status` reports the performer's reachability at delegation- time; for `no_session`/`disconnected` the performer won't see the- task until they reconnect.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)-- protocol = _get_protocol()- result = await protocol.delegate_task(- agent_id, room_id, performer_agent_id, summary, description- )- return {- "task_id": result.task_id,- "status": "pending",- "target_status": result.target_status.value,- }---async def accept_task(task_id: str, ctx: Context) -> dict[str, Any]:- """Accept a delegated task. Requires can_accept capability.-- Args:- task_id: The id of the task to accept (from the task_delegate event- or list_tasks). Caller must be the assigned performer.-- Returns:- {"status": "ongoing", "accepted_at": "<iso timestamp>"}.- """- agent_id = _get_agent_id()- await _require_connected_room(ctx)-- protocol = _get_protocol()- await protocol.accept_task(agent_id, task_id)- task = await protocol.get_task(agent_id, task_id)- accepted_at = None- if task.accepted_at:- accepted_at = (- task.accepted_at.isoformat()- if hasattr(task.accepted_at, "isoformat")- else str(task.accepted_at)- )- return {- "status": task.status,- "accepted_at": accepted_at,- }---async def update_task(task_id: str, update: str, ctx: Context) -> dict[str, Any]:- """Post a progress update on an assigned task. Requires can_accept capability.-- Args:- task_id: The id of an ongoing task you have accepted.- update: One-string progress note (what you've done, what's next, any- blockers). Appended to the task's update log; does not finalise.-- Returns:- {"status": "updated", "updates_count": <int>} with the new total.- """- agent_id = _get_agent_id()- await _require_connected_room(ctx)-- protocol = _get_protocol()- await protocol.update_task(agent_id, task_id, update)- task = await protocol.get_task(agent_id, task_id)- return {"status": "updated", "updates_count": len(task.updates)}---async def finalise_task(task_id: str, outcome: str, ctx: Context) -> dict[str, Any]:- """Complete a task with final outcome. Requires can_accept capability.-- Args:- task_id: The id of an ongoing task you have accepted.- outcome: One-string final result — describe success or failure and- any output/links the requester needs. After this call the task- moves to `finalised` and cannot be updated further.-- Returns:- {"status": "finalised", "finalised_at": "<iso timestamp>"}.- """- agent_id = _get_agent_id()- await _require_connected_room(ctx)-- protocol = _get_protocol()- await protocol.finalise_task(agent_id, task_id, outcome)- task = await protocol.get_task(agent_id, task_id)- finalised_at = None- if task.finalised_at:- finalised_at = (- task.finalised_at.isoformat()- if hasattr(task.finalised_at, "isoformat")- else str(task.finalised_at)- )- return {- "status": task.status,- "finalised_at": finalised_at,- }---async def list_tasks(- role: str | None = None, status: str | None = None, ctx: Any = None-) -> list[dict[str, Any]]:- """List tasks for the connected agent in the connected room.-- Args:- role: Perspective filter.- - "delegated": tasks this agent created as requester- - "assigned": tasks assigned to this agent as performer- - None: both- status: Lifecycle filter. One of "pending", "ongoing", "finalised",- "cancelled", or None for all.-- Returns:- List of task dicts {id, summary, description, status,- requester_agent_id, performer_agent_id, updates, outcome,- created_at, accepted_at, finalised_at}. Timestamps are ISO-8601- strings or null.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx) # type: ignore[arg-type]-- protocol = _get_protocol()- tasks = await protocol.list_tasks(- agent_id, room_id=room_id, role=role, status=status- )-- result = []- for t in tasks:- created_at = None- if t.created_at:- created_at = (- t.created_at.isoformat()- if hasattr(t.created_at, "isoformat")- else str(t.created_at)- )- accepted_at = None- if t.accepted_at:- accepted_at = (- t.accepted_at.isoformat()- if hasattr(t.accepted_at, "isoformat")- else str(t.accepted_at)- )- finalised_at = None- if t.finalised_at:- finalised_at = (- t.finalised_at.isoformat()- if hasattr(t.finalised_at, "isoformat")- else str(t.finalised_at)- )- result.append(- {- "id": t.id,- "summary": t.summary,- "description": t.description,- "status": t.status,- "requester_agent_id": t.requester_agent_id,- "performer_agent_id": t.performer_agent_id,- "updates": t.updates,- "outcome": t.outcome,- "created_at": created_at,- "accepted_at": accepted_at,- "finalised_at": finalised_at,- }- )- return result-+ try:+ return await call_next(context)+ finally:+ reset_call_context(token)-# ── Moderation ───────────────────────────────────────────────────────────────+mcp = FastMCP("Switch")+mcp.add_middleware(CallContextMiddleware())-async def create_room(- name: str,- description: str,- agent_names: list[str],- user_names: list[str] | None = None,- channel_type: str | None = None,- bridge_id: str | None = None,- internal_only: bool = False,- admin_mode: bool = False,- security_config: dict[str, Any] | None = None,- instructions: str | None = None,- reference_ids: list[str] | None = None,- package_ids: list[str] | None = None,- linked_rooms: list[dict[str, str]] | None = None,- read_visibility: str = "public",- write_visibility: str = "public",- group_name: str | None = None,- roles: list[dict[str, Any]] | None = None,- include_subagents_for: list[str] | None = None,- join_event_listeners: list[str] | None = None,- aliases: dict[str, str] | None = None,-) -> dict[str, Any]:- """Create a new Switch room.-- Rooms are bridged by default: omitting `bridge_id` uses the instance's- default bridge (on a standalone deployment, the bundled Mattermost), so the- room is readable by humans without the caller knowing the deployment's- topology. Pass `bridge_id` to choose a specific bridge — call- `list_bridges` to discover ids and present the choice to the user. Pass- `internal_only=True` for an agent-only room with no external channel.-- If the instance has no default bridge configured and you omit `bridge_id`,- the room is created internal-only.-- Args:- name: Display name for the room.- description: Free-text description shown to participants.- agent_names: Names of agents to add to the room at creation. The- calling agent is not added automatically — include its name here- if it should join. Names must already exist in the registry.- user_names: Optional list of human user names to add. Only meaningful- for bridged rooms.- channel_type: One of "channel_public", "channel_private", or "direct".- Required when `bridge_id` is set; ignored for internal-only rooms.- Use "direct" to open a 1:1 DM room — exactly one entry in- `agent_names` and one in `user_names`. On Slack this is provisioned- as a private channel with that user invited; the user must already- be known to Switch on the bridge (creation fails otherwise).- bridge_id: Optional id of the collaboration bridge backing this room.- Omit to use the instance's default bridge.- internal_only: Create a room with no external channel, opting out of- the default bridge. Ignored when `bridge_id` is set.- admin_mode: When true, the room is created in administrative mode.- security_config: Optional dict overriding default protection checks.- instructions: Room-specific system prompt / guidance shown to agents- when they connect.- reference_ids: References to attach at creation. Authorization is- checked against the calling agent's owner; you can only attach- references your owning user has access to.- package_ids: Packages to attach at creation. Same authorization as- references.- linked_rooms: Directed links from this room to existing rooms. Each- entry is `{"target_room_id": "...", "label": "..."}`.- read_visibility: "public" (anyone may read) or "private" (owner/admin- only). Defaults to "public".- write_visibility: "public" (anyone may modify — invite, attach, edit)- or "private" (owner/admin only). Defaults to "public". Must not be- "public" while read_visibility is "private".- group_name: Optional name of an existing room group to file this room- under (a navigation/visualization layer surfaced in the room list- and graph). Must match an existing group exactly; errors if unknown- or ambiguous. Omit to leave the room standalone.- roles: Optional room-roles to define at creation. Each entry is- `{"name": "...", "instructions": "...", "exclusive": bool}`.- Roles are assumable instruction bundles agents pick up with- `assume_role`; exclusive roles allow at most one live holder.- include_subagents_for: Per-agent opt-in. A subset of `agent_names`- whose subagents (child agents — e.g. a Claude Code agent's- registered `.claude/agents` subagents) should also be added to the- room. Only the named parents are expanded, not every agent.- join_event_listeners: Per-agent opt-in. A subset of `agent_names` that- should receive `room_join` events in this room (fired when someone- joins). Agents not listed do not receive them. Use for a welcome /- onboarding agent that should greet new arrivals.- aliases: Optional per-room agent aliases, keyed by agent name → alias.- `@<alias>` then addresses that agent in the room exactly like its- real name. Each agent must be in `agent_names`; an alias may- contain only letters, digits, '.', '-', '_' and must not clash- with an agent's real name, a room role, or another alias.-- Returns:- `{"id", "name", "matrix_room_id", "failed_attachments": [...]}`.- `failed_attachments` is empty on full success; otherwise it lists- `{kind, id, error}` for each attachment that could not be applied- after the room was created (race-time failures only; predictable- errors like missing ids abort creation upfront).- """- agent_id = _get_agent_id()- protocol = _get_protocol()- result = await protocol.create_moderation_room(- agent_id=agent_id,- name=name,- description=description,- agent_names=agent_names,- include_subagents_for=include_subagents_for,- join_event_listeners=join_event_listeners,- user_names=user_names,- channel_type=channel_type,- bridge_id=bridge_id,- internal_only=internal_only,- admin_mode=admin_mode,- security_config=security_config,- instructions=instructions,- reference_ids=reference_ids,- package_ids=package_ids,- linked_rooms=linked_rooms,- read_visibility=read_visibility,- write_visibility=write_visibility,- group_name=group_name,- roles=roles,- aliases=aliases,- )- return {- "id": result.room.id,- "name": result.room.name,- "matrix_room_id": result.room.matrix_room_id,- "failed_attachments": result.failed_attachments,- }---async def list_roles(ctx: Context) -> list[dict[str, Any]]:- """List the roles defined in the connected room.-- Roles are room-scoped, assumable instruction bundles. Each entry carries- `name`,- `exclusive`, an `instructions_preview`, `assumable_by_me` (whether you could- `assume_role` it right now), and `held_by` — the live holders (empty if- free, possibly several for a shared role). Each holder is an object- `{"name", "present_here", "session_room"}`: `present_here` is True when that- holder's assuming session is connected to THIS room right now; otherwise- `session_room` names the room its session is currently attending (a lease- survives room hops, so a holder can be live but looking elsewhere), or is- null if no bound session can be located.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- return await _get_protocol().list_room_roles(agent_id, room_id)---async def get_role_detail(room_id: str, role_name: str) -> dict[str, Any]:- """Get one room role's FULL untruncated instructions.-- `list_roles` and `get_room_detail` only expose a 200-char- `instructions_preview`; use this when you need a role's complete- instructions — e.g. before assuming it. You must be a member of the room- (it does not have to be the room your session is currently connected to).-- Args:- room_id: The Switch room id (UUID string).- role_name: The exact role name (as shown by `list_roles`).-- Returns:- {name, exclusive, instructions (the FULL untruncated bundle),- held_by (live holder objects {name, present_here, session_room}), and- assumable_by_me}. The `held_by` and `assumable_by_me` fields carry the- same semantics as `list_roles`. Raises if no such role exists in the- room, or if you are not a member.- """- agent_id = _get_agent_id()- return await _get_protocol().get_room_role(agent_id, room_id, role_name)---async def define_role(- ctx: Context, name: str, instructions: str, exclusive: bool = False-) -> dict[str, Any]:- """Define a new role in the connected room. Requires write access to the room.-- Args:- name: Role name, unique within the room (e.g. "manager", "worker").- instructions: The instruction bundle delivered when an agent assumes- this role.- exclusive: When true, at most one live agent may hold the role at a- time (a lease with auto-release). When false, unrestricted.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- await _get_protocol().define_room_role(- agent_id, room_id, name, instructions, exclusive- )- return {"status": "defined", "name": name}---async def edit_role(- ctx: Context,- name: str,- instructions: str | None = None,- exclusive: bool | None = None,-) -> dict[str, Any]:- """Edit a role's instructions and/or exclusivity. Requires write access.-- Edits take effect on the next `assume_role`; any current holder keeps the- instructions it already received.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- await _get_protocol().edit_room_role(- agent_id, room_id, name, instructions, exclusive- )- return {"status": "edited", "name": name}---async def delete_role(ctx: Context, name: str) -> dict[str, Any]:- """Delete a role from the connected room (and any lease on it).-- Requires write access to the room.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- await _get_protocol().delete_room_role(agent_id, room_id, name)- return {"status": "deleted", "name": name}---async def assume_role(ctx: Context, role: str) -> dict[str, Any]:- """Assume a role in the connected room and receive its instructions.-- Returns `{"role", "instructions"}` — the role's instruction delta to layer- on top of the room context you already have. Any room member may assume a- role. Fails if you already hold a role (release it first), or if the role- is exclusive and currently held by another live agent.-- For exclusive roles, this acquires a lease with a fast heartbeat: while- your session stays alive the seat is yours, and it auto-releases shortly- after you disconnect so another agent can take over.- """- agent_id = _get_agent_id()- room_id = await _require_connected_room(ctx)- return await _get_protocol().assume_room_role(- agent_id, room_id, role, ctx.session_id- )---async def release_role(ctx: Context) -> dict[str, Any]:- """Release the role you currently hold, freeing it for others. Idempotent."""- agent_id = _get_agent_id()- await _require_connected_room(ctx)- await _get_protocol().release_room_role(agent_id)- return {"status": "released"}---async def list_reference_types() -> list[dict[str, Any]]:- """List the Reference sub-types this Switch instance supports.-- Call this before `create_reference` to discover which `type` values- are valid and what shape the `value` payload must have.-- Returns:- List of `{type, display_name, instructions, value_schema}`.- `value_schema` is the JSON Schema for the per-type value- payload — use it to build the `value` dict for `create_reference`.- """- protocol = _get_protocol()- return protocol.list_reference_types()---async def create_reference(- type: str,- name: str,- description: str,- instructions: str,- value: dict[str, Any],- read_visibility: str = "private",- write_visibility: str = "private",-) -> dict[str, Any]:- """Create a new Reference owned by your user.-- A Reference is a pointer to external content (e.g. Google Drive- documents, Confluence pages, GitHub repositories, Jira issues) that can- be attached to rooms so other agents and humans in the room can discover- and access it.-- Args:- type: Reference type. Supported values: "google_drive",- "confluence", "github", "jira". Each type expects a specific- `value` shape. Call `list_reference_types` for the authoritative- list and each type's `value_schema`.- name: Short display name.- description: One-or-two sentence summary of what this reference- points at, shown in listings.- instructions: Free-text guidance for agents on how to USE this- reference — what's in it, when to consult it, any caveats.- This is the field agents read when the reference shows up in- their room context.- value: Type-specific payload. For every built-in type today the- shape is `{"urls": ["https://...", ...]}` — `min_length=1`. For- "jira" the URLs point at projects, issues, or boards (e.g.- `https://your-org.atlassian.net/browse/PROJ-123`).- read_visibility: "private" (default — only you can read/attach it) or- "public" (anyone can read/attach).- write_visibility: "private" (default — only you can edit it) or- "public" (anyone can edit). Must not be "public" while- read_visibility is "private".-- Returns:- `{"id", "type", "name", "read_visibility", "write_visibility"}` of the- created reference.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- ref = await protocol.create_reference(- agent_id=agent_id,- type=type,- name=name,- description=description,- instructions=instructions,- value=value,- read_visibility=read_visibility,- write_visibility=write_visibility,- )- return {- "id": ref.id,- "type": ref.type,- "name": ref.name,- "read_visibility": ref.read_visibility,- "write_visibility": ref.write_visibility,- }---async def attach_reference_to_room(room_id: str, reference_id: str) -> dict[str, bool]:- """Attach an existing Reference to an existing room.-- Authorization: your agent's owner must be able to access the- reference (public, owned by them, or they are an admin). Use- `create_reference` first if you need to create one.-- Args:- room_id: Switch room id to attach to.- reference_id: Id of the reference to attach.-- Returns:- `{"ok": true}` on success.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- await protocol.attach_reference_to_room_as_agent(agent_id, room_id, reference_id)- return {"ok": True}---async def link_rooms(- source_room_id: str, target_room_id: str, label: str-) -> dict[str, Any]:- """Create a directed link from one room to another.-- Links are advertised to agents connected to `source_room_id` via- the `linked_rooms` array, with the `label` you supply as the- relationship hint (e.g. "support", "parent project", "depends on").- Links are one-way; create the reverse link separately if you want- both directions.-- Args:- source_room_id: The room the link is attached to (where the- pointer will appear).- target_room_id: The room the link points at.- label: Free-text relationship hint, shown to agents and humans.- Must not be empty.-- Returns:- `{"target_room_id", "target_room_name", "target_room_description",- "label"}` for the freshly-created link.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- return await protocol.link_rooms(agent_id, source_room_id, target_room_id, label)---async def unlink_rooms(source_room_id: str, target_room_id: str) -> dict[str, bool]:- """Remove a directed link from one room to another.-- The inverse of `link_rooms`: detaches the existing pointer from- `source_room_id` to `target_room_id` so it no longer appears in the- source room's `linked_rooms` array. Links are one-way, so this only- removes the `source_room_id → target_room_id` direction; remove the- reverse link separately if one exists.-- Args:- source_room_id: The room the link is attached to (where the- pointer currently appears).- target_room_id: The room the link points at.-- Returns:- `{"ok": true}` on success. Raises an error if no such link- exists.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- await protocol.unlink_rooms(agent_id, source_room_id, target_room_id)- return {"ok": True}---async def list_bridges() -> list[dict[str, Any]]:- """List collaboration bridges available on this Switch instance.-- Use this when creating a room and you need to pick a bridge — present- the list to the user and let them choose, rather than guessing.-- Returns:- List of `{id, type, display_name, status, is_default}` dicts. Only- `status` == "active" bridges are usable for new rooms; others are- shown for context. `is_default` marks the bridge that `create_room`- uses when no `bridge_id` is given (at most one).- """- protocol = _get_protocol()- return await protocol.list_bridges()---async def invite_agent_to_room(- room_id: str, agent_name: str, include_subagents: bool = False-) -> dict[str, bool]:- """Invite an agent into an existing room by name.-- Args:- room_id: The Switch room id (UUID string).- agent_name: Registry name of the agent to add.- include_subagents: When true, also add the invited agent's subagents- (child agents — e.g. a Claude Code agent's registered- `.claude/agents` subagents).-- Returns:- {"ok": true} on success.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- await protocol.invite_agent_to_room(- agent_id, room_id, agent_name, include_subagents=include_subagents- )- return {"ok": True}---async def add_users_to_room(room_id: str, user_names: list[str]) -> dict[str, Any]:- """Add one or more human users to an existing bridged room by name.-- Unlike `invite_agent_to_room` (which adds agents), this adds humans. The- room must already be bridged: each user is added to the room's external- channel (Slack/Mattermost) and joined to the Switch room. Each name must- be a user already known to that bridge — e.g. someone who has signed into- the workspace — otherwise the bridge cannot resolve them. Use this after a- bridge change to re-invite the humans who were dropped, since their- identities are bridge-specific and are not carried across.-- Args:- room_id: The Switch room id (UUID string).- user_names: Registry names of the users to add.-- Returns:- `{"ok": bool, "added": [...], "unresolved": [...]}`. `unresolved`- lists names the bridge had no external user for — they were skipped,- not added (likely they have not signed into the workspace yet). `ok`- is true only when every requested name was added.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- unresolved = await protocol.add_users_to_room(agent_id, room_id, user_names)- added = [name for name in user_names if name not in unresolved]- return {"ok": not unresolved, "added": added, "unresolved": unresolved}---async def list_all_rooms(include_archived: bool = False) -> list[dict[str, Any]]:- """List every room on this Switch instance (not just rooms this agent- is a member of). Use `list_rooms` instead to see only the rooms this- agent is assigned to.-- Args:- include_archived: When false (default), archived rooms are omitted.- Set true to also include archived rooms (each carries- `archived: true`).-- Returns:- List of {room_id, name, description, archived} dicts.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- rooms = await protocol.list_all_rooms(agent_id, include_archived=include_archived)- return [- {- "room_id": r.id,- "name": r.name,- "description": r.description,- "archived": r.archived_at is not None,- }- for r in rooms- ]---async def list_room_groups() -> list[dict[str, Any]]:- """List the room groups on this Switch instance.-- Room groups are a navigation/organization layer: a room can belong to a- group (or be standalone), and groups can nest under a parent group. Use- this to discover the group names you can pass as `group_name` to- `create_room`, or to understand how rooms are organized.-- Returns:- List of {id, name, description, parent_group_id, room_count, path}- dicts, where `path` is the group's root-first ancestry (e.g.- "Parent / Child") and `room_count` is the number of rooms directly in- the group. Sorted by path.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- return await protocol.list_room_groups(agent_id)---async def create_room_group(- name: str,- description: str | None = None,- color: str | None = None,- parent_group_name: str | None = None,-) -> dict[str, Any]:- """Create a new room group (a navigation/organization layer for rooms).-- A room group is a named bucket that rooms can be filed under (via- `create_room`'s `group_name`), and groups can nest under a parent group to- form a tree. Creating a group does not move any rooms into it.-- Args:- name: The group's display name.- description: Optional free-text description.- color: Optional UI colour hint (e.g. a hex string).- parent_group_name: Optional name of an existing group to nest this one- under. Must match an existing group exactly; errors if unknown or- ambiguous. Omit to create a top-level group.-- Returns:- {id, name, description, color, parent_group_id, room_count, path,- member_rooms, child_groups} for the new group (room_count 0, empty- member_rooms/child_groups). `path` is the root-first ancestry.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- return await protocol.create_room_group(- agent_id, name, description, color, parent_group_name- )---async def get_room_group_detail(group_id: str) -> dict[str, Any]:- """Get full detail for a room group, including its members and children.-- Args:- group_id: The room group's id (from `list_room_groups`).-- Returns:- {id, name, description, color, parent_group_id, room_count, path,- member_rooms, child_groups}, where `path` is the group's root-first- ancestry (e.g. "Parent / Child"), `member_rooms` is the rooms directly- in this group as {id, name}, and `child_groups` is the immediate- subgroups as {id, name}.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- return await protocol.get_room_group_detail(agent_id, group_id)---async def list_agents(- name_contains: str | None = None,- owner_name: str | None = None,- known_agent_type: str | None = None,-) -> list[dict[str, Any]]:- """List the agents registered on this Switch instance.-- Unlike `list_participants` (which is scoped to the connected room), this- lists every agent on the instance. Use the optional filters to narrow the- result; they are ANDed together, and omitting one ignores it.-- Args:- name_contains: Case-insensitive substring to match against agent names.- owner_name: Return only agents owned by the user with this exact name.- known_agent_type: Return only agents of this known-agent type (e.g.- "claude-code").-- Returns:- A list of agent summaries (sorted by name), each- {id, name, description, connector_type, connection_model,- tool_count, model_count, owner_id, owner_name, oauth_client_id,- created_at, parent_agent_id, known_agent_type, known_agent_options}.- Use `get_agent_detail` for the full detail of one agent.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- return await protocol.list_agents(- agent_id, name_contains, owner_name, known_agent_type- )---async def get_agent_detail(agent_id: str) -> dict[str, Any]:- """Get full detail for an agent on this Switch instance.-- Readable for any agent (not just your own). Use it to inspect another- agent's configuration, capabilities, room memberships, and live sessions.-- Args:- agent_id: The target agent's id (from `list_participants` or- `list_all_rooms`/`get_room_detail`).-- Returns:- {id, name, description, connector_type, connection_model,- tool_count, model_count, owner_id, owner_name, oauth_client_id,- created_at, parent_agent_id, known_agent_type, known_agent_options,- agent_type, integration_profile, tools, models, rooms, sessions,- children}.- """- caller_id = _get_agent_id()- protocol = _get_protocol()- detail = await protocol.get_agent_detail(caller_id, agent_id)- return detail.model_dump()---async def update_agent_detail(- agent_id: str,- options: dict[str, Any] | None = None,- parent_agent_id: str | None = None,- clear_parent: bool = False,-) -> dict[str, Any]:- """Update an agent's editable settings and return its fresh detail.-- Owner-only: you may only update an agent whose owner is the same as your- own owner (the call fails with a permission error otherwise). Only agents- registered with a known-agent type (e.g. "claude-code") have editable- options.-- Editable fields:- - `options`: a PARTIAL map of the agent's known-agent options to- change — only the keys you pass are updated; the rest are left as-is.- For a claude-code agent the options are `repo_dir` (the working- directory), `channels_enabled`, `notify_user`, and `subagent_name`.- The merged options are validated against the agent type's schema and- its integration profile is rebuilt to match.- - `parent_agent_id`: set the agent's parent (e.g. to make it a subagent- of another agent). Validated against self-parenting and cycles.- - `clear_parent`: pass True to detach the agent from its parent (make it- top-level). Mutually exclusive with `parent_agent_id`.-- Omit a field to leave it unchanged. Returns the same shape as- `get_agent_detail`.- """- caller_id = _get_agent_id()- protocol = _get_protocol()- detail = await protocol.update_agent_detail(- caller_id, agent_id, options, parent_agent_id, clear_parent- )- return detail.model_dump()---async def get_room_detail(room_id: str) -> dict[str, Any]:- """Get full detail for a room you are a member of.-- You must be a member of the room (assigned to it); this does not have to- be the room your session is currently connected to. Fails with a- permission error if you are not a member.-- Args:- room_id: The Switch room id (UUID string).-- Returns:- {id, name, description, channel_type, admin_mode, instructions,- matrix_room_id, created_at, bridge_id, bridge_display_name,- external_channel_id, group_id, group_name, group_path (the group's- root-first ancestry, e.g. "Parent / Child"; null when standalone),- agent_names, agent_statuses (keyed by agent name), connected_user_names,- aliases (per-room agent aliases, keyed by agent name → alias),- roles (the room's assumable roles, mirroring list_roles: each entry has- name, exclusive, instructions_preview, held_by (holder objects with- presence), and assumable_by_me)}.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- detail = await protocol.get_room_detail(agent_id, room_id)- return detail.model_dump()---async def update_room(- room_id: str,- name: str | None = None,- description: str | None = None,- instructions: str | None = None,- admin_mode: bool | None = None,- join_event_listeners: dict[str, bool] | None = None,- bridge_id: str | None = None,- channel_type: str | None = None,- external_channel_id: str | None = None,- aliases: dict[str, str] | None = None,-) -> dict[str, Any]:- """Update attributes of a room you are a member of.-- You must be a member of the room (assigned to it); fails with a- permission error otherwise. Only the fields you pass are changed —- omit (leave as None) any attribute you want to keep unchanged.-- Args:- room_id: The Switch room id (UUID string).- name: New room name, or None to leave unchanged.- description: New room description, or None to leave unchanged.- instructions: New room-specific instructions, or None to leave- unchanged.- admin_mode: New admin-mode flag, or None to leave unchanged.- join_event_listeners: Partial map of agent name → whether that agent- should receive `room_join` events in this room. Only the named- agents change; omit to leave all memberships unchanged. Each named- agent must already be a member of the room.- bridge_id: Move the room onto this collaboration bridge. A fresh- external channel is provisioned on the target bridge and the- room's current agents are re-added, then the old bridge is detached- (the old external channel is left in place on its platform but is- no longer synced). Human users are NOT carried over — their- identities are bridge-specific — so re-invite them to the new- channel manually. Call `list_bridges` for valid ids. Omit to leave- the room's bridge unchanged. This sets or moves a bridge only — it- cannot remove one.- channel_type: Visibility for the newly provisioned channel when- `bridge_id` is set — "channel_public" or "channel_private". Omit- to keep the room's current privacy. Ignored unless `bridge_id` is- given.- external_channel_id: Bind to this EXISTING channel on the target- bridge instead of provisioning a new one — e.g. to move a room- back onto a channel it previously used (channels are left in place- on a bridge change, so the old one still exists). The id must be a- real channel on the target bridge whose bridge bot is a member.- Ignored unless `bridge_id` is given.- aliases: Per-room agent aliases to set, keyed by agent name → alias.- `@<alias>` then addresses that agent in the room like its real- name. Pass an empty string ("") as the value to clear an agent's- alias. Only the agents you name are touched; others keep their- current alias. An alias may contain only letters, digits, '.',- '-', '_' and must not clash with an agent's real name, a room- role, or another alias. Omit to leave aliases unchanged.-- Returns:- The full, updated room detail (same shape as get_room_detail),- including the room's current `aliases` map.- """- agent_id = _get_agent_id()- protocol = _get_protocol()- detail = await protocol.update_room(- agent_id,- room_id,- name=name,- description=description,- instructions=instructions,- admin_mode=admin_mode,- join_event_listeners=join_event_listeners,- bridge_id=bridge_id,- channel_type=channel_type,- external_channel_id=external_channel_id,- aliases=aliases,- )- return detail.model_dump()---async def archive_room(room_id: str) -> dict[str, Any]:- """Archive a room you are a member of, hiding it from the default active- room lists once its work is complete.-- Archiving is metadata-only and fully reversible: the Matrix room, its- members, and any bridge channel are left intact, and the room can still- be connected to and read. It simply stops appearing in `list_rooms` /- `list_all_rooms` (and the management UI) unless archived rooms are- explicitly requested. Use this for ephemeral rooms (e.g. a finished- feature-implementation or bug-fix room) to keep the active list tidy.- Reverse it with `unarchive_room`.-- You must be a member of the room and have write access to it; fails with- a permission error otherwise.-- Args:- room_id: The Switch room id (UUID string).-- Returns:- The full, updated room detail (same shape as get_room_detail).- """- agent_id = _get_agent_id()- protocol = _get_protocol()- detail = await protocol.set_room_archived(agent_id, room_id, True)- return detail.model_dump()---async def unarchive_room(room_id: str) -> dict[str, Any]:- """Unarchive a room you are a member of, restoring it to the default- active room lists.-- The inverse of `archive_room`. You must be a member of the room and have- write access to it; fails with a permission error otherwise.-- Args:- room_id: The Switch room id (UUID string).+# Every operation, registered as a tool. This loop is the only thing that makes+# an operation an MCP tool, so the two surfaces cannot diverge.+for _op in all_operations().values():+ mcp.tool(_op.fn)- Returns:- The full, updated room detail (same shape as get_room_detail).- """- agent_id = _get_agent_id()- protocol = _get_protocol()- detail = await protocol.set_room_archived(agent_id, room_id, False)- return detail.model_dump()+logger.debug("Registered %d operations as MCP tools", len(all_operations()))def create_mcp_app(diff --git a/core/switch_core/bridges/agent/operations/__init__.py b/core/switch_core/bridges/agent/operations/__init__.pynew file mode 100644index 000000000..070d1ad56--- /dev/null+++ b/core/switch_core/bridges/agent/operations/__init__.py@@ -0,0 +1,16 @@+"""Agent operations: defined once, served through every front door."""++# Importing the definitions module is what populates the registry. Both front+# doors read the registry, so this import is the single point at which the+# operation set comes into existence.+from switch_core.bridges.agent.operations import (+ definitions as _definitions, # noqa: E402,F401+)+from switch_core.bridges.agent.operations.registry import (+ Operation,+ all_operations,+ get_operation,+ operation,+)++__all__ = ["Operation", "all_operations", "get_operation", "operation"]diff --git a/core/switch_core/bridges/agent/operations/callctx.py b/core/switch_core/bridges/agent/operations/callctx.pynew file mode 100644index 000000000..302c54b94--- /dev/null+++ b/core/switch_core/bridges/agent/operations/callctx.py@@ -0,0 +1,41 @@+"""The call context shared by both agent-facing front doors (CHOO-1857/490).++An operation needs two things about its caller: which agent is making it, and+which session or connection it belongs to. Over MCP both come from the FastMCP+transport; over HTTP they come from the bearer token and the `connection_id` on+the request. Everything above this indirection is written once and served by+both doors, which is what keeps them from drifting apart.++`session_key` is deliberately vague about what it identifies: an MCP transport+session today, a connection id over HTTP. Both are "the thing that owns the+room binding", and operations only ever compare them for equality.+"""++from __future__ import annotations++from contextvars import ContextVar+from dataclasses import dataclass+++@dataclass(frozen=True)+class CallContext:+ agent_id: str+ session_key: str | None+++_current: ContextVar[CallContext | None] = ContextVar(+ "switch_call_context", default=None+)+++def set_call_context(context: CallContext):+ """Bind the caller for the duration of one operation. Returns a reset token."""+ return _current.set(context)+++def reset_call_context(token) -> None: # type: ignore[no-untyped-def]+ _current.reset(token)+++def current_call_context() -> CallContext | None:+ return _current.get()diff --git a/core/switch_core/bridges/agent/operations/context.py b/core/switch_core/bridges/agent/operations/context.pynew file mode 100644index 000000000..c0fded0f0--- /dev/null+++ b/core/switch_core/bridges/agent/operations/context.py@@ -0,0 +1,88 @@+"""Who is calling an operation, and what they are bound to.++Operations take their arguments and nothing else. Everything about the caller —+which agent, which connection or session, and therefore which room — is+resolved here, so an operation's signature carries no transport types and the+same function serves both front doors.+"""++from __future__ import annotations++import logging+from typing import TYPE_CHECKING++from switch_core.bridges.agent.operations.callctx import current_call_context++if TYPE_CHECKING:+ from switch_core.bridges.agent.protocol.service import ProtocolService++logger = logging.getLogger(__name__)++_protocol: ProtocolService | None = None+++def init_operations_protocol(protocol: ProtocolService) -> None:+ global _protocol+ _protocol = protocol+++def get_protocol() -> ProtocolService:+ assert _protocol is not None, "operations protocol not initialized"+ return _protocol+++def get_agent_id() -> str:+ """The agent this call is being made on behalf of.++ Every front door binds a call context before dispatching, so operations+ never reach into a transport to find out who is calling.+ """+ bound = current_call_context()+ if bound is None:+ raise ValueError(+ "No call context bound — the front door must establish the caller "+ "before dispatching an operation"+ )+ return bound.agent_id+++def session_key() -> str | None:+ """The thing that owns this caller's room binding.++ A connection id, or an MCP transport session — operations only ever compare+ it for equality, so which one it is does not matter above this line. None+ when the caller is bound to nothing, which the operations that need a room+ report as "not connected".+ """+ bound = current_call_context()+ return bound.session_key if bound is not None else None+++async def require_connected_room() -> str:+ """The room this caller is bound to, or a clear error saying it is not.++ The live connection is asked first: a connection that has claimed a room is+ in it, whether or not anything was ever written to a table. The table is+ consulted only for callers that predate connections (an MCP transport+ session), and goes away with them.+ """+ key = session_key()+ if not key:+ raise ValueError("Not connected to a room. Call connect_to_room first.")++ protocol = get_protocol()+ connection = protocol.connections.get(key)+ if connection is not None and connection.rooms:+ if len(connection.rooms) > 1:+ raise ValueError(+ "This connection covers several rooms; the operation needs one "+ "— pass the room explicitly or use a single-room connection."+ )+ return next(iter(connection.rooms))++ async with protocol.session_factory() as db:+ result = await protocol.agent_session_store.get_connected_room(db, key)+ if result is None:+ raise ValueError("Not connected to a room. Call connect_to_room first.")+ _, room_id = result+ return room_iddiff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pynew file mode 100644index 000000000..124432870--- /dev/null+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -0,0 +1,1657 @@+"""Agent operations — what an agent can do, defined once (CHOO-1857 / CHOO-490).++These functions are the operations themselves. The MCP server registers them as+tools and the HTTP endpoint dispatches into them; neither owns them. Adding one+here makes it available through both doors at once, which is what keeps the two+from drifting apart.++Each takes its arguments and nothing else — the caller's identity, connection+and room come from `operations.context`.+"""++from __future__ import annotations++import logging+from typing import Any++from switch_core.bridges.agent.api.handlers import parse_timestamp_ms+from switch_core.bridges.agent.operations.context import (+ get_agent_id,+ get_protocol,+ require_connected_room,+ session_key,+)+from switch_core.bridges.agent.operations.registry import operation+from switch_core.bridges.agent.protocol.connections import ConnectionError_+from switch_core.bridges.agent.protocol.instructions import build_room_instructions+from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.types import IntegrationProfile+from switch_core.db.models import CollaborationBridge++logger = logging.getLogger(__name__)+++def claim_room_on_caller_connection(+ protocol: ProtocolService, agent_id: str, connection_id: str, room_id: str+) -> None:+ """Bind the room to the connection that asked to connect.++ Connecting IS claiming the room slot. The caller identified itself with a+ connection, so the room is bound to it here rather than left to a follow-up+ subscribe the client has to remember — two steps that can disagree, where+ forgetting the second means silently receiving nothing.++ It also carries the fact to whoever holds that connection's stream. When a+ supervisor spawned this session and handed it the connection id, the claim+ surfaces there as ``subscription_changed``, so the supervisor learns the+ room *from Switch* rather than by reading the agent's tool result and+ hoping its shape never changes.++ **Without takeover.** A dead connection is not a claimant at all —+ ``claimant_of`` filters on liveness — so the only thing takeover could ever+ win against is a connection that is genuinely alive and covering the room.+ Usually that is a supervisor delivering for this very session, and taking+ the slot from it stops delivery: the tool call succeeds, the agent believes+ it is in the room, and nothing reaches it again.++ That is not hypothetical. A session started before its supervisor learned to+ share connections holds its own; when it reconnects, taking over would+ silence the supervisor that is actually feeding it.++ Never fatal. The room binding is written before this runs, so a failure here+ costs delivery routing, not membership, and says so.+ """+ connection = protocol.connections.get(connection_id)+ if connection is None or connection.agent_id != agent_id:+ # No connection behind this caller: an MCP transport session, or a+ # runtime borrowing an id whose connection has since expired. The+ # binding row still stands and room-scoped calls resolve through it.+ return+ try:+ protocol.connections.claim_room(connection, room_id)+ except ConnectionError_ as exc:+ logger.warning(+ "[CONNECT] agent=%s connection=%s could not claim room %s: %s",+ agent_id,+ connection_id,+ room_id,+ exc,+ )+++@operation+async def list_rooms(include_archived: bool = False) -> list[dict[str, Any]]:+ """List rooms this agent is assigned to.++ Args:+ include_archived: When false (default), archived rooms are omitted so+ the active list stays uncluttered. Set true to also include+ archived rooms (each carries `archived: true`).++ Returns:+ List of {room_id, name, description, connected, archived} dicts.+ `connected` is true for the room this session is currently connected+ to (if any); `archived` is true for archived rooms.+ """+ agent_id = get_agent_id()++ protocol = get_protocol()+ connected_room_id: str | None = None+ key = session_key()+ if key:+ async with protocol.session_factory() as db:+ row = await protocol.agent_session_store.get_connected_room(db, key)+ if row is not None:+ _, connected_room_id = row+ rooms = await protocol.list_rooms(agent_id, include_archived=include_archived)++ return [+ {+ "room_id": r.id,+ "name": r.name,+ "description": r.description,+ "connected": r.id == connected_room_id,+ "archived": r.archived,+ }+ for r in rooms+ ]+++@operation+async def connect_to_room(+ room_id: str,+ include_general_instructions: bool = True,+) -> dict[str, Any]:+ """Connect this session to a room. The agent must be assigned to the room.++ Args:+ room_id: The Switch room id (UUID string) to connect to. Get valid+ ids from list_rooms. This is the Switch room id, not the Matrix+ room id. Calling again switches the active room for this session.+ include_general_instructions: When true (default) the `instructions`+ field carries the full room-onboarding text (interaction modes,+ task protocol, agent statuses, room setup) followed by any+ room-specific instructions. Set false if your host already+ injects the general Switch usage instructions out-of-band (e.g.+ via a Claude Code skill); the general sections are then omitted+ but room-specific instructions configured at room creation are+ still returned.++ Returns:+ {agent_id, room_id, name, description, participants, instructions,+ reference_types, references, documents, packages, linked_rooms,+ roles}.+ Each reference, document, and package carries its own `instructions`+ field — agent-facing guidance for that resource — alongside a short+ `description`. `roles` lists the room's assumable roles, each+ `{name, exclusive, instructions_preview, held_by, assumable_by_me}` —+ `held_by` is the list of agent names currently holding it (live lease;+ empty if free, and a shared role may list several), so you can see+ which roles are taken and by whom before calling+ `assume_role`. `linked_rooms` lists directed pointers from this room+ to other Switch rooms: each entry has `target_room_id`,+ `target_room_name`, `target_room_description`, `label` (free-text+ relationship hint set by the operator) and `access` —+ either ``"member"`` (you can `connect_to_room(target_room_id)`) or+ ``"not_member"`` (you have NOT been assigned to that room; the+ connect call WILL fail — ask the operator to add you first).+ """+ agent_id = get_agent_id()+ protocol = get_protocol()++ try:+ room = await protocol.require_room_member(agent_id, room_id)+ except ValueError as e:+ raise ValueError(str(e)) from e+ except PermissionError as e:+ raise ValueError(str(e)) from e++ participants = await protocol.list_participants(room_id)++ async with protocol.session_factory() as session:+ agent = await protocol.agent_store.get(session, agent_id)+ room_model = await protocol.room_store.get(session, room.id)+ if agent is None or room_model is None:+ raise ValueError("Agent or room not found")+ bridge: CollaborationBridge | None = None+ if room_model.bridge_id:+ bridge = await session.get(CollaborationBridge, room_model.bridge_id)++ profile = IntegrationProfile(**agent.integration_profile)+ instructions = build_room_instructions(+ agent,+ room_model,+ profile,+ participants,+ bridge,+ include_general=include_general_instructions,+ )+ resources = await protocol.list_room_resources(room.id)+ linked_rooms = await _decorate_linked_rooms(+ protocol, agent_id, resources["linked_rooms"]+ )+ roles = await protocol.list_room_roles(agent_id, room.id)++ key = session_key()+ if not key:+ raise ValueError("MCP session has no session id; cannot connect to room")+ # session_passive agents have no poll loop, so the row exists only to+ # bind the MCP transport to a room — lifecycle="explicit". always_on and+ # session_addressable agents also receive heartbeat upserts; we mark the+ # row "heartbeat" so the poll path's on-conflict update doesn't need to+ # special-case it.+ lifecycle = (+ "explicit" if profile.connection_model == "session_passive" else "heartbeat"+ )+ async with protocol.session_factory() as db:+ await protocol.agent_session_store.set_connected_room(+ db,+ agent_id=agent_id,+ room_id=room.id,+ transport_session_id=key,+ lifecycle=lifecycle,+ )+ await db.commit()++ claim_room_on_caller_connection(protocol, agent_id, key, room.id)++ return {+ "agent_id": agent_id,+ "room_id": room.id,+ "name": room.name,+ "description": room.description,+ "participants": [+ {+ "id": p.id,+ "name": p.name,+ "type": p.type,+ "agent_type": p.agent_type,+ "can_delegate": p.can_delegate,+ "can_accept": p.can_accept,+ "status": p.status.value if p.status is not None else None,+ "room_role": p.room_role,+ "alias": p.alias,+ }+ for p in participants+ ],+ "instructions": instructions,+ "reference_types": resources["reference_types"],+ "references": resources["references"],+ "documents": resources["documents"],+ "packages": resources["packages"],+ "linked_rooms": linked_rooms,+ "roles": roles,+ }+++async def _decorate_linked_rooms(+ protocol: ProtocolService,+ agent_id: str,+ linked_rooms: list[dict[str, Any]],+) -> list[dict[str, Any]]:+ """Annotate each linked-room entry with an explicit ``access`` field —+ ``"member"`` if the calling agent is assigned to the target room,+ ``"not_member"`` otherwise. For ``not_member`` rows, also include a+ human-readable ``access_note`` warning that ``connect_to_room`` will+ fail until the agent is added by an operator."""+ if not linked_rooms:+ return []+ async with protocol.session_factory() as session:+ agent_rooms = await protocol.room_store.get_rooms_for_agent(session, agent_id)+ member_ids = {r.id for r in agent_rooms}+ out: list[dict[str, Any]] = []+ for entry in linked_rooms:+ is_member = entry["target_room_id"] in member_ids+ decorated = {+ **entry,+ "access": "member" if is_member else "not_member",+ }+ if not is_member:+ decorated["access_note"] = (+ "You are NOT assigned to this room. connect_to_room will fail; "+ "ask the room operator to add you before trying."+ )+ out.append(decorated)+ return out+++@operation+async def list_references() -> dict[str, Any]:+ """List references, documents, and packages attached to this session's+ connected room.++ Returns:+ {reference_types, references, documents, packages} — same shape as+ the equivalent fields in `connect_to_room`. Use this to refresh+ after attachments change mid-session.++ External references carry their `value` inline (URLs / IDs); fetch the+ underlying content using your own tools as described in+ `reference_types[<type>].instructions`.++ Internal documents are advertised by id + description + instructions+ only; call `load_internal_documents` to fetch their content.++ Packages bundle other refs and documents and have their own+ `instructions`; their `references` and `documents` arrays mirror the+ same shape as the top-level fields.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()+ protocol = get_protocol()+ await protocol.require_room_member(agent_id, room_id)+ return await protocol.list_room_resources(room_id)+++@operation+async def list_linked_rooms() -> list[dict[str, Any]]:+ """List the rooms linked from this session's connected room.++ Returns the directed outbound links from the current room — each link+ points at another Switch room and carries a free-text ``label`` set by+ the room's operator (e.g. "support", "parent project", "related+ workstream"). Pointers grant NO implicit access: the ``access`` field+ tells you whether you (the calling agent) can act on the target —+ ``"member"`` means ``connect_to_room(target_room_id)`` will work,+ ``"not_member"`` means you are not assigned to that room and the call+ WILL fail until an operator adds you. ``not_member`` entries also+ carry an ``access_note`` spelling that out.++ Returns:+ List of {target_room_id, target_room_name, target_room_description,+ label, access, access_note?} dicts.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()+ protocol = get_protocol()+ await protocol.require_room_member(agent_id, room_id)+ resources = await protocol.list_room_resources(room_id)+ return await _decorate_linked_rooms(protocol, agent_id, resources["linked_rooms"])+++@operation+async def load_internal_documents(ids: list[str]) -> list[dict[str, Any]]:+ """Load the content of internal documents attached to the connected room.++ Args:+ ids: List of document ids to load (from `documents[*].id` in the+ connect payload or `list_references`).++ Returns:+ List of {id, description, content} entries in the same order as+ the requested ids. Raises an error if any id is not attached to the+ current room.++ The load goes through the Switch resource manager as a Matrix event+ round-trip, mirroring how tool and LLM mediation works.+ """+ import uuid++ agent_id = get_agent_id()+ room_id = await require_connected_room()+ protocol = get_protocol()+ await protocol.require_room_member(agent_id, room_id)+ request_id = str(uuid.uuid4())+ return await protocol.request_document_load(+ agent_id=agent_id,+ room_id=room_id,+ document_ids=ids,+ request_id=request_id,+ timeout=30.0,+ )+++_ROOM_DOCUMENT_MAX_CONTENT_BYTES = 1_048_576+++@operation+async def create_room_document(+ name: str,+ description: str,+ instructions: str,+ content: str,+) -> dict[str, str]:+ """Create a new internal document scoped to the connected room.++ The document lives only in this room, is visible to all participants,+ and never appears in the global resources library. Only you (the creating+ agent) can later update or delete it via `update_room_document` /+ `delete_room_document`. Other room members can read it via+ `load_internal_documents`, and human users can delete it from the room UI.++ Args:+ name: Short identifier for the document. Must be unique within this room.+ description: One-line summary (shown in pickers and listings).+ instructions: Agent-facing notes on when/how to use this document.+ content: Full text content (max 1 MiB).++ Returns:+ ``{"document_id": "..."}`` once the resource manager confirms creation.+ """+ import uuid++ if len(content.encode("utf-8")) > _ROOM_DOCUMENT_MAX_CONTENT_BYTES:+ raise ValueError(f"content exceeds {_ROOM_DOCUMENT_MAX_CONTENT_BYTES} bytes")+ agent_id = get_agent_id()+ room_id = await require_connected_room()+ protocol = get_protocol()+ await protocol.require_room_member(agent_id, room_id)+ request_id = str(uuid.uuid4())+ document_id = await protocol.request_room_document_create(+ agent_id=agent_id,+ room_id=room_id,+ name=name,+ description=description,+ instructions=instructions,+ content=content,+ request_id=request_id,+ timeout=30.0,+ )+ return {"document_id": document_id}+++@operation+async def update_room_document(+ document_id: str,+ name: str | None = None,+ description: str | None = None,+ instructions: str | None = None,+ content: str | None = None,+) -> dict[str, str]:+ """Update a room-scoped document you created in the connected room.++ Only the agent that created the document can update it. Pass only the+ fields you want to change; omit (or set to None) the others.+ """+ import uuid++ if (+ content is not None+ and len(content.encode("utf-8")) > _ROOM_DOCUMENT_MAX_CONTENT_BYTES+ ):+ raise ValueError(f"content exceeds {_ROOM_DOCUMENT_MAX_CONTENT_BYTES} bytes")+ agent_id = get_agent_id()+ room_id = await require_connected_room()+ protocol = get_protocol()+ await protocol.require_room_member(agent_id, room_id)+ request_id = str(uuid.uuid4())+ await protocol.request_room_document_update(+ agent_id=agent_id,+ room_id=room_id,+ document_id=document_id,+ name=name,+ description=description,+ instructions=instructions,+ content=content,+ request_id=request_id,+ timeout=30.0,+ )+ return {"document_id": document_id, "status": "ok"}+++@operation+async def delete_room_document(document_id: str) -> dict[str, str]:+ """Delete a room-scoped document you created in the connected room.++ Only the agent that created the document can delete it via MCP. Users+ can also delete from the room UI as an admin escape hatch.+ """+ import uuid++ agent_id = get_agent_id()+ room_id = await require_connected_room()+ protocol = get_protocol()+ await protocol.require_room_member(agent_id, room_id)+ request_id = str(uuid.uuid4())+ await protocol.request_room_document_delete(+ agent_id=agent_id,+ room_id=room_id,+ document_id=document_id,+ request_id=request_id,+ timeout=30.0,+ )+ return {"document_id": document_id, "status": "ok"}+++@operation+async def read_context(+ limit: int = 50,+ since: str | None = None,+ before: str | None = None,+) -> list[dict[str, Any]]:+ """Get the conversation timeline for the connected room, grouped into threads.++ Returns a list of thread groups ordered by latest activity (most-recently+ active LAST, so the tail is the freshest), each shaped as::++ {"root": <message>, "replies": [<message>, ...]}++ where <message> is {"id", "sender", "sender_name", "body", "timestamp",+ "attachments"}. Top-level messages are roots with an empty `replies` list;+ replies are oldest-first within a thread. Use a root's (or any message's)+ `id` as the `thread_id` argument to post_message / send_targeted_message to+ reply into that thread.++ `attachments` is a (usually empty) list of files on the message, each+ {"filename", "mimetype", "size", "mxc", "msgtype"}. Any file type can+ appear, and a message may carry several. To actually view one, pass its+ `mxc` to the channel's `download_attachment` tool, which fetches it to a+ local file you can read.++ Args:+ limit: Maximum number of messages to scan (default 50), grouped into+ threads before returning.+ since: ISO-8601 timestamp string (e.g. "2026-05-20T20:55:00Z"). Only+ messages at or after this time are returned. Use this when an event+ arrives to fetch just the recent context — pass a timestamp a few+ minutes before the event ts. None = no lower bound.+ before: ISO-8601 timestamp string. Only messages strictly before this+ time are returned. Combine with `since` to page through history.+ None = no upper bound.++ The room is implicit (the session's currently connected room). Reads+ fail if you have not called connect_to_room first.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()++ protocol = get_protocol()+ since_ms = parse_timestamp_ms(since) if since else None+ before_ms = parse_timestamp_ms(before) if before else None++ return await protocol.read_context(+ agent_id, room_id, limit=limit, since_ms=since_ms, before_ms=before_ms+ )+++@operation+async def list_participants() -> list[dict[str, Any]]:+ """List agents and users in the connected room.++ Args:+ (none) — operates on the session's currently connected room. Call+ connect_to_room first.++ Returns:+ List of {id, name, type} dicts for each participant.+ """+ get_agent_id()+ room_id = await require_connected_room()++ protocol = get_protocol()+ participants = await protocol.list_participants(room_id)++ return [+ {+ "id": p.id,+ "name": p.name,+ "type": p.type,+ "status": p.status.value if p.status is not None else None,+ "alias": p.alias,+ }+ for p in participants+ ]+++@operation+async def post_message(body: str, thread_id: str | None = None) -> dict[str, str]:+ """Send a message to the connected room (broadcast, no specific recipient).++ Args:+ body: The message text to send. Plain string — do not wrap in JSON or+ prefix with `@name` (use send_targeted_message for addressed+ messages). The room is implicit: messages go to the room this+ session is currently connected to via connect_to_room, so there+ is no `room_id` parameter.+ thread_id: Optional. The `id` of a message to reply into, making this a+ threaded reply. Pass any message id from the thread (a root or a+ reply) — it is normalised to the thread root. Omit for a top-level+ message. Get ids from read_context or from a notification's+ thread_id.++ Returns:+ {"event_id": "<matrix event id>"} for the posted message.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()++ protocol = get_protocol()+ event_id = await protocol.send_message(agent_id, room_id, body, thread_id=thread_id)+ return {"event_id": event_id}+++@operation+async def send_targeted_message(+ body: str,+ target_names: list[str] | None = None,+ target_roles: list[str] | None = None,+ thread_id: str | None = None,+) -> dict[str, Any]:+ """Send a message addressed to specific agents/users and/or roles.++ Prepends `@name` for each name target and `@role` for each role target so+ they receive it as an addressed event. Other participants still see the+ message as room context. Use when you need specific participants to act,+ but the work is informal (a question, nudge, or handoff that doesn't need+ task tracking).++ Args:+ body: The message text. Plain string — do not pre-add `@` prefixes;+ this tool adds them for each target.+ target_names: Agent or user names (the `name` field from+ list_participants, not ids) to address. Prepended as `@name`.+ target_roles: Role names (from list_roles) to address. Each is+ prepended as `@role` and fans out to every live holder of that+ role — the single holder for an exclusive role, all current+ holders for a shared one. Use this to reach "whoever holds the+ manager role" without naming the agent.+ thread_id: Optional. The `id` of a message to reply into, making this a+ threaded reply. Pass any message id from the thread — it is+ normalised to the thread root. Omit for a top-level message.++ At least one of target_names / target_roles is required.++ Returns:+ {"event_id": "<matrix event id>", "target_statuses": {name: status}}.+ `target_statuses` reports each addressed *agent*'s reachability at send+ time — for a role target, that is each of its live holders: `live`+ (will receive immediately), `awaiting_manual_poll` (must read context+ to see it), `no_session`/`disconnected` (not reachable; may not see the+ message until they reconnect). User targets are omitted — their+ reachability is the collaboration bridge's concern. A role with no live+ holder contributes no entries.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()++ protocol = get_protocol()+ result = await protocol.send_targeted_message(+ agent_id,+ room_id,+ target_names or [],+ body,+ thread_id=thread_id,+ target_roles=target_roles or [],+ )+ return {+ "event_id": result.event_id,+ "target_statuses": {n: s.value for n, s in result.target_statuses.items()},+ }+++# ── Task Protocol ───────────────────────────────────────────────────────────+++@operation+async def delegate_task(+ performer_agent_id: str, summary: str, description: str+) -> dict[str, str]:+ """Delegate a task to a performer agent. Requires can_delegate capability.++ Args:+ performer_agent_id: The id of the agent to assign the task to. Must+ be a participant in the connected room. Use list_participants to+ find ids (the `id` field, not `name`).+ summary: Short one-line title for the task (shown in lists/headers).+ description: Full instructions: what to do, inputs, expected output,+ constraints. The performer reads this when accepting.++ Returns:+ {"task_id": "<id>", "status": "pending", "target_status": "<status>"}.+ `target_status` reports the performer's reachability at delegation+ time; for `no_session`/`disconnected` the performer won't see the+ task until they reconnect.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()++ protocol = get_protocol()+ result = await protocol.delegate_task(+ agent_id, room_id, performer_agent_id, summary, description+ )+ return {+ "task_id": result.task_id,+ "status": "pending",+ "target_status": result.target_status.value,+ }+++@operation+async def accept_task(task_id: str) -> dict[str, Any]:+ """Accept a delegated task. Requires can_accept capability.++ Args:+ task_id: The id of the task to accept (from the task_delegate event+ or list_tasks). Caller must be the assigned performer.++ Returns:+ {"status": "ongoing", "accepted_at": "<iso timestamp>"}.+ """+ agent_id = get_agent_id()+ await require_connected_room()++ protocol = get_protocol()+ await protocol.accept_task(agent_id, task_id)+ task = await protocol.get_task(agent_id, task_id)+ accepted_at = None+ if task.accepted_at:+ accepted_at = (+ task.accepted_at.isoformat()+ if hasattr(task.accepted_at, "isoformat")+ else str(task.accepted_at)+ )+ return {+ "status": task.status,+ "accepted_at": accepted_at,+ }+++@operation+async def update_task(task_id: str, update: str) -> dict[str, Any]:+ """Post a progress update on an assigned task. Requires can_accept capability.++ Args:+ task_id: The id of an ongoing task you have accepted.+ update: One-string progress note (what you've done, what's next, any+ blockers). Appended to the task's update log; does not finalise.++ Returns:+ {"status": "updated", "updates_count": <int>} with the new total.+ """+ agent_id = get_agent_id()+ await require_connected_room()++ protocol = get_protocol()+ await protocol.update_task(agent_id, task_id, update)+ task = await protocol.get_task(agent_id, task_id)+ return {"status": "updated", "updates_count": len(task.updates)}+++@operation+async def finalise_task(task_id: str, outcome: str) -> dict[str, Any]:+ """Complete a task with final outcome. Requires can_accept capability.++ Args:+ task_id: The id of an ongoing task you have accepted.+ outcome: One-string final result — describe success or failure and+ any output/links the requester needs. After this call the task+ moves to `finalised` and cannot be updated further.++ Returns:+ {"status": "finalised", "finalised_at": "<iso timestamp>"}.+ """+ agent_id = get_agent_id()+ await require_connected_room()++ protocol = get_protocol()+ await protocol.finalise_task(agent_id, task_id, outcome)+ task = await protocol.get_task(agent_id, task_id)+ finalised_at = None+ if task.finalised_at:+ finalised_at = (+ task.finalised_at.isoformat()+ if hasattr(task.finalised_at, "isoformat")+ else str(task.finalised_at)+ )+ return {+ "status": task.status,+ "finalised_at": finalised_at,+ }+++@operation+async def list_tasks(+ role: str | None = None, status: str | None = None+) -> list[dict[str, Any]]:+ """List tasks for the connected agent in the connected room.++ Args:+ role: Perspective filter.+ - "delegated": tasks this agent created as requester+ - "assigned": tasks assigned to this agent as performer+ - None: both+ status: Lifecycle filter. One of "pending", "ongoing", "finalised",+ "cancelled", or None for all.++ Returns:+ List of task dicts {id, summary, description, status,+ requester_agent_id, performer_agent_id, updates, outcome,+ created_at, accepted_at, finalised_at}. Timestamps are ISO-8601+ strings or null.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room() # type: ignore[arg-type]++ protocol = get_protocol()+ tasks = await protocol.list_tasks(+ agent_id, room_id=room_id, role=role, status=status+ )++ result = []+ for t in tasks:+ created_at = None+ if t.created_at:+ created_at = (+ t.created_at.isoformat()+ if hasattr(t.created_at, "isoformat")+ else str(t.created_at)+ )+ accepted_at = None+ if t.accepted_at:+ accepted_at = (+ t.accepted_at.isoformat()+ if hasattr(t.accepted_at, "isoformat")+ else str(t.accepted_at)+ )+ finalised_at = None+ if t.finalised_at:+ finalised_at = (+ t.finalised_at.isoformat()+ if hasattr(t.finalised_at, "isoformat")+ else str(t.finalised_at)+ )+ result.append(+ {+ "id": t.id,+ "summary": t.summary,+ "description": t.description,+ "status": t.status,+ "requester_agent_id": t.requester_agent_id,+ "performer_agent_id": t.performer_agent_id,+ "updates": t.updates,+ "outcome": t.outcome,+ "created_at": created_at,+ "accepted_at": accepted_at,+ "finalised_at": finalised_at,+ }+ )+ return result+++# ── Moderation ───────────────────────────────────────────────────────────────+++@operation+async def create_room(+ name: str,+ description: str,+ agent_names: list[str],+ user_names: list[str] | None = None,+ channel_type: str | None = None,+ bridge_id: str | None = None,+ internal_only: bool = False,+ admin_mode: bool = False,+ security_config: dict[str, Any] | None = None,+ instructions: str | None = None,+ reference_ids: list[str] | None = None,+ package_ids: list[str] | None = None,+ linked_rooms: list[dict[str, str]] | None = None,+ read_visibility: str = "public",+ write_visibility: str = "public",+ group_name: str | None = None,+ roles: list[dict[str, Any]] | None = None,+ include_subagents_for: list[str] | None = None,+ join_event_listeners: list[str] | None = None,+ aliases: dict[str, str] | None = None,+) -> dict[str, Any]:+ """Create a new Switch room.++ Rooms are bridged by default: omitting `bridge_id` uses the instance's+ default bridge (on a standalone deployment, the bundled Mattermost), so the+ room is readable by humans without the caller knowing the deployment's+ topology. Pass `bridge_id` to choose a specific bridge — call+ `list_bridges` to discover ids and present the choice to the user. Pass+ `internal_only=True` for an agent-only room with no external channel.++ If the instance has no default bridge configured and you omit `bridge_id`,+ the room is created internal-only.++ Args:+ name: Display name for the room.+ description: Free-text description shown to participants.+ agent_names: Names of agents to add to the room at creation. The+ calling agent is not added automatically — include its name here+ if it should join. Names must already exist in the registry.+ user_names: Optional list of human user names to add. Only meaningful+ for bridged rooms.+ channel_type: One of "channel_public", "channel_private", or "direct".+ Required when `bridge_id` is set; ignored for internal-only rooms.+ Use "direct" to open a 1:1 DM room — exactly one entry in+ `agent_names` and one in `user_names`. On Slack this is provisioned+ as a private channel with that user invited; the user must already+ be known to Switch on the bridge (creation fails otherwise).+ bridge_id: Optional id of the collaboration bridge backing this room.+ Omit to use the instance's default bridge.+ internal_only: Create a room with no external channel, opting out of+ the default bridge. Ignored when `bridge_id` is set.+ admin_mode: When true, the room is created in administrative mode.+ security_config: Optional dict overriding default protection checks.+ instructions: Room-specific system prompt / guidance shown to agents+ when they connect.+ reference_ids: References to attach at creation. Authorization is+ checked against the calling agent's owner; you can only attach+ references your owning user has access to.+ package_ids: Packages to attach at creation. Same authorization as+ references.+ linked_rooms: Directed links from this room to existing rooms. Each+ entry is `{"target_room_id": "...", "label": "..."}`.+ read_visibility: "public" (anyone may read) or "private" (owner/admin+ only). Defaults to "public".+ write_visibility: "public" (anyone may modify — invite, attach, edit)+ or "private" (owner/admin only). Defaults to "public". Must not be+ "public" while read_visibility is "private".+ group_name: Optional name of an existing room group to file this room+ under (a navigation/visualization layer surfaced in the room list+ and graph). Must match an existing group exactly; errors if unknown+ or ambiguous. Omit to leave the room standalone.+ roles: Optional room-roles to define at creation. Each entry is+ `{"name": "...", "instructions": "...", "exclusive": bool}`.+ Roles are assumable instruction bundles agents pick up with+ `assume_role`; exclusive roles allow at most one live holder.+ include_subagents_for: Per-agent opt-in. A subset of `agent_names`+ whose subagents (child agents — e.g. a Claude Code agent's+ registered `.claude/agents` subagents) should also be added to the+ room. Only the named parents are expanded, not every agent.+ join_event_listeners: Per-agent opt-in. A subset of `agent_names` that+ should receive `room_join` events in this room (fired when someone+ joins). Agents not listed do not receive them. Use for a welcome /+ onboarding agent that should greet new arrivals.+ aliases: Optional per-room agent aliases, keyed by agent name → alias.+ `@<alias>` then addresses that agent in the room exactly like its+ real name. Each agent must be in `agent_names`; an alias may+ contain only letters, digits, '.', '-', '_' and must not clash+ with an agent's real name, a room role, or another alias.++ Returns:+ `{"id", "name", "matrix_room_id", "failed_attachments": [...]}`.+ `failed_attachments` is empty on full success; otherwise it lists+ `{kind, id, error}` for each attachment that could not be applied+ after the room was created (race-time failures only; predictable+ errors like missing ids abort creation upfront).+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ result = await protocol.create_moderation_room(+ agent_id=agent_id,+ name=name,+ description=description,+ agent_names=agent_names,+ include_subagents_for=include_subagents_for,+ join_event_listeners=join_event_listeners,+ user_names=user_names,+ channel_type=channel_type,+ bridge_id=bridge_id,+ internal_only=internal_only,+ admin_mode=admin_mode,+ security_config=security_config,+ instructions=instructions,+ reference_ids=reference_ids,+ package_ids=package_ids,+ linked_rooms=linked_rooms,+ read_visibility=read_visibility,+ write_visibility=write_visibility,+ group_name=group_name,+ roles=roles,+ aliases=aliases,+ )+ return {+ "id": result.room.id,+ "name": result.room.name,+ "matrix_room_id": result.room.matrix_room_id,+ "failed_attachments": result.failed_attachments,+ }+++@operation+async def list_roles() -> list[dict[str, Any]]:+ """List the roles defined in the connected room.++ Roles are room-scoped, assumable instruction bundles. Each entry carries+ `name`,+ `exclusive`, an `instructions_preview`, `assumable_by_me` (whether you could+ `assume_role` it right now), and `held_by` — the live holders (empty if+ free, possibly several for a shared role). Each holder is an object+ `{"name", "present_here", "session_room"}`: `present_here` is True when that+ holder's assuming session is connected to THIS room right now; otherwise+ `session_room` names the room its session is currently attending (a lease+ survives room hops, so a holder can be live but looking elsewhere), or is+ null if no bound session can be located.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()+ return await get_protocol().list_room_roles(agent_id, room_id)+++@operation+async def get_role_detail(room_id: str, role_name: str) -> dict[str, Any]:+ """Get one room role's FULL untruncated instructions.++ `list_roles` and `get_room_detail` only expose a 200-char+ `instructions_preview`; use this when you need a role's complete+ instructions — e.g. before assuming it. You must be a member of the room+ (it does not have to be the room your session is currently connected to).++ Args:+ room_id: The Switch room id (UUID string).+ role_name: The exact role name (as shown by `list_roles`).++ Returns:+ {name, exclusive, instructions (the FULL untruncated bundle),+ held_by (live holder objects {name, present_here, session_room}), and+ assumable_by_me}. The `held_by` and `assumable_by_me` fields carry the+ same semantics as `list_roles`. Raises if no such role exists in the+ room, or if you are not a member.+ """+ agent_id = get_agent_id()+ return await get_protocol().get_room_role(agent_id, room_id, role_name)+++@operation+async def define_role(+ name: str, instructions: str, exclusive: bool = False+) -> dict[str, Any]:+ """Define a new role in the connected room. Requires write access to the room.++ Args:+ name: Role name, unique within the room (e.g. "manager", "worker").+ instructions: The instruction bundle delivered when an agent assumes+ this role.+ exclusive: When true, at most one live agent may hold the role at a+ time (a lease with auto-release). When false, unrestricted.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()+ await get_protocol().define_room_role(+ agent_id, room_id, name, instructions, exclusive+ )+ return {"status": "defined", "name": name}+++@operation+async def edit_role(+ name: str,+ instructions: str | None = None,+ exclusive: bool | None = None,+) -> dict[str, Any]:+ """Edit a role's instructions and/or exclusivity. Requires write access.++ Edits take effect on the next `assume_role`; any current holder keeps the+ instructions it already received.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()+ await get_protocol().edit_room_role(+ agent_id, room_id, name, instructions, exclusive+ )+ return {"status": "edited", "name": name}+++@operation+async def delete_role(name: str) -> dict[str, Any]:+ """Delete a role from the connected room (and any lease on it).++ Requires write access to the room.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()+ await get_protocol().delete_room_role(agent_id, room_id, name)+ return {"status": "deleted", "name": name}+++@operation+async def assume_role(role: str) -> dict[str, Any]:+ """Assume a role in the connected room and receive its instructions.++ Returns `{"role", "instructions"}` — the role's instruction delta to layer+ on top of the room context you already have. Any room member may assume a+ role. Fails if you already hold a role (release it first), or if the role+ is exclusive and currently held by another live agent.++ For exclusive roles, this acquires a lease with a fast heartbeat: while+ your session stays alive the seat is yours, and it auto-releases shortly+ after you disconnect so another agent can take over.+ """+ agent_id = get_agent_id()+ room_id = await require_connected_room()+ return await get_protocol().assume_room_role(agent_id, room_id, role, session_key())+++@operation+async def release_role() -> dict[str, Any]:+ """Release the role you currently hold, freeing it for others. Idempotent."""+ agent_id = get_agent_id()+ await require_connected_room()+ await get_protocol().release_room_role(agent_id)+ return {"status": "released"}+++@operation+async def list_reference_types() -> list[dict[str, Any]]:+ """List the Reference sub-types this Switch instance supports.++ Call this before `create_reference` to discover which `type` values+ are valid and what shape the `value` payload must have.++ Returns:+ List of `{type, display_name, instructions, value_schema}`.+ `value_schema` is the JSON Schema for the per-type value+ payload — use it to build the `value` dict for `create_reference`.+ """+ protocol = get_protocol()+ return protocol.list_reference_types()+++@operation+async def create_reference(+ type: str,+ name: str,+ description: str,+ instructions: str,+ value: dict[str, Any],+ read_visibility: str = "private",+ write_visibility: str = "private",+) -> dict[str, Any]:+ """Create a new Reference owned by your user.++ A Reference is a pointer to external content (e.g. Google Drive+ documents, Confluence pages, GitHub repositories, Jira issues) that can+ be attached to rooms so other agents and humans in the room can discover+ and access it.++ Args:+ type: Reference type. Supported values: "google_drive",+ "confluence", "github", "jira". Each type expects a specific+ `value` shape. Call `list_reference_types` for the authoritative+ list and each type's `value_schema`.+ name: Short display name.+ description: One-or-two sentence summary of what this reference+ points at, shown in listings.+ instructions: Free-text guidance for agents on how to USE this+ reference — what's in it, when to consult it, any caveats.+ This is the field agents read when the reference shows up in+ their room context.+ value: Type-specific payload. For every built-in type today the+ shape is `{"urls": ["https://...", ...]}` — `min_length=1`. For+ "jira" the URLs point at projects, issues, or boards (e.g.+ `https://your-org.atlassian.net/browse/PROJ-123`).+ read_visibility: "private" (default — only you can read/attach it) or+ "public" (anyone can read/attach).+ write_visibility: "private" (default — only you can edit it) or+ "public" (anyone can edit). Must not be "public" while+ read_visibility is "private".++ Returns:+ `{"id", "type", "name", "read_visibility", "write_visibility"}` of the+ created reference.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ ref = await protocol.create_reference(+ agent_id=agent_id,+ type=type,+ name=name,+ description=description,+ instructions=instructions,+ value=value,+ read_visibility=read_visibility,+ write_visibility=write_visibility,+ )+ return {+ "id": ref.id,+ "type": ref.type,+ "name": ref.name,+ "read_visibility": ref.read_visibility,+ "write_visibility": ref.write_visibility,+ }+++@operation+async def attach_reference_to_room(room_id: str, reference_id: str) -> dict[str, bool]:+ """Attach an existing Reference to an existing room.++ Authorization: your agent's owner must be able to access the+ reference (public, owned by them, or they are an admin). Use+ `create_reference` first if you need to create one.++ Args:+ room_id: Switch room id to attach to.+ reference_id: Id of the reference to attach.++ Returns:+ `{"ok": true}` on success.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ await protocol.attach_reference_to_room_as_agent(agent_id, room_id, reference_id)+ return {"ok": True}+++@operation+async def link_rooms(+ source_room_id: str, target_room_id: str, label: str+) -> dict[str, Any]:+ """Create a directed link from one room to another.++ Links are advertised to agents connected to `source_room_id` via+ the `linked_rooms` array, with the `label` you supply as the+ relationship hint (e.g. "support", "parent project", "depends on").+ Links are one-way; create the reverse link separately if you want+ both directions.++ Args:+ source_room_id: The room the link is attached to (where the+ pointer will appear).+ target_room_id: The room the link points at.+ label: Free-text relationship hint, shown to agents and humans.+ Must not be empty.++ Returns:+ `{"target_room_id", "target_room_name", "target_room_description",+ "label"}` for the freshly-created link.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ return await protocol.link_rooms(agent_id, source_room_id, target_room_id, label)+++@operation+async def unlink_rooms(source_room_id: str, target_room_id: str) -> dict[str, bool]:+ """Remove a directed link from one room to another.++ The inverse of `link_rooms`: detaches the existing pointer from+ `source_room_id` to `target_room_id` so it no longer appears in the+ source room's `linked_rooms` array. Links are one-way, so this only+ removes the `source_room_id → target_room_id` direction; remove the+ reverse link separately if one exists.++ Args:+ source_room_id: The room the link is attached to (where the+ pointer currently appears).+ target_room_id: The room the link points at.++ Returns:+ `{"ok": true}` on success. Raises an error if no such link+ exists.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ await protocol.unlink_rooms(agent_id, source_room_id, target_room_id)+ return {"ok": True}+++@operation+async def list_bridges() -> list[dict[str, Any]]:+ """List collaboration bridges available on this Switch instance.++ Use this when creating a room and you need to pick a bridge — present+ the list to the user and let them choose, rather than guessing.++ Returns:+ List of `{id, type, display_name, status, is_default}` dicts. Only+ `status` == "active" bridges are usable for new rooms; others are+ shown for context. `is_default` marks the bridge that `create_room`+ uses when no `bridge_id` is given (at most one).+ """+ protocol = get_protocol()+ return await protocol.list_bridges()+++@operation+async def invite_agent_to_room(+ room_id: str, agent_name: str, include_subagents: bool = False+) -> dict[str, bool]:+ """Invite an agent into an existing room by name.++ Args:+ room_id: The Switch room id (UUID string).+ agent_name: Registry name of the agent to add.+ include_subagents: When true, also add the invited agent's subagents+ (child agents — e.g. a Claude Code agent's registered+ `.claude/agents` subagents).++ Returns:+ {"ok": true} on success.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ await protocol.invite_agent_to_room(+ agent_id, room_id, agent_name, include_subagents=include_subagents+ )+ return {"ok": True}+++@operation+async def add_users_to_room(room_id: str, user_names: list[str]) -> dict[str, Any]:+ """Add one or more human users to an existing bridged room by name.++ Unlike `invite_agent_to_room` (which adds agents), this adds humans. The+ room must already be bridged: each user is added to the room's external+ channel (Slack/Mattermost) and joined to the Switch room. Each name must+ be a user already known to that bridge — e.g. someone who has signed into+ the workspace — otherwise the bridge cannot resolve them. Use this after a+ bridge change to re-invite the humans who were dropped, since their+ identities are bridge-specific and are not carried across.++ Args:+ room_id: The Switch room id (UUID string).+ user_names: Registry names of the users to add.++ Returns:+ `{"ok": bool, "added": [...], "unresolved": [...]}`. `unresolved`+ lists names the bridge had no external user for — they were skipped,+ not added (likely they have not signed into the workspace yet). `ok`+ is true only when every requested name was added.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ unresolved = await protocol.add_users_to_room(agent_id, room_id, user_names)+ added = [name for name in user_names if name not in unresolved]+ return {"ok": not unresolved, "added": added, "unresolved": unresolved}+++@operation+async def list_all_rooms(include_archived: bool = False) -> list[dict[str, Any]]:+ """List every room on this Switch instance (not just rooms this agent+ is a member of). Use `list_rooms` instead to see only the rooms this+ agent is assigned to.++ Args:+ include_archived: When false (default), archived rooms are omitted.+ Set true to also include archived rooms (each carries+ `archived: true`).++ Returns:+ List of {room_id, name, description, archived} dicts.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ rooms = await protocol.list_all_rooms(agent_id, include_archived=include_archived)+ return [+ {+ "room_id": r.id,+ "name": r.name,+ "description": r.description,+ "archived": r.archived_at is not None,+ }+ for r in rooms+ ]+++@operation+async def list_room_groups() -> list[dict[str, Any]]:+ """List the room groups on this Switch instance.++ Room groups are a navigation/organization layer: a room can belong to a+ group (or be standalone), and groups can nest under a parent group. Use+ this to discover the group names you can pass as `group_name` to+ `create_room`, or to understand how rooms are organized.++ Returns:+ List of {id, name, description, parent_group_id, room_count, path}+ dicts, where `path` is the group's root-first ancestry (e.g.+ "Parent / Child") and `room_count` is the number of rooms directly in+ the group. Sorted by path.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ return await protocol.list_room_groups(agent_id)+++@operation+async def create_room_group(+ name: str,+ description: str | None = None,+ color: str | None = None,+ parent_group_name: str | None = None,+) -> dict[str, Any]:+ """Create a new room group (a navigation/organization layer for rooms).++ A room group is a named bucket that rooms can be filed under (via+ `create_room`'s `group_name`), and groups can nest under a parent group to+ form a tree. Creating a group does not move any rooms into it.++ Args:+ name: The group's display name.+ description: Optional free-text description.+ color: Optional UI colour hint (e.g. a hex string).+ parent_group_name: Optional name of an existing group to nest this one+ under. Must match an existing group exactly; errors if unknown or+ ambiguous. Omit to create a top-level group.++ Returns:+ {id, name, description, color, parent_group_id, room_count, path,+ member_rooms, child_groups} for the new group (room_count 0, empty+ member_rooms/child_groups). `path` is the root-first ancestry.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ return await protocol.create_room_group(+ agent_id, name, description, color, parent_group_name+ )+++@operation+async def get_room_group_detail(group_id: str) -> dict[str, Any]:+ """Get full detail for a room group, including its members and children.++ Args:+ group_id: The room group's id (from `list_room_groups`).++ Returns:+ {id, name, description, color, parent_group_id, room_count, path,+ member_rooms, child_groups}, where `path` is the group's root-first+ ancestry (e.g. "Parent / Child"), `member_rooms` is the rooms directly+ in this group as {id, name}, and `child_groups` is the immediate+ subgroups as {id, name}.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ return await protocol.get_room_group_detail(agent_id, group_id)+++@operation+async def list_agents(+ name_contains: str | None = None,+ owner_name: str | None = None,+ known_agent_type: str | None = None,+) -> list[dict[str, Any]]:+ """List the agents registered on this Switch instance.++ Unlike `list_participants` (which is scoped to the connected room), this+ lists every agent on the instance. Use the optional filters to narrow the+ result; they are ANDed together, and omitting one ignores it.++ Args:+ name_contains: Case-insensitive substring to match against agent names.+ owner_name: Return only agents owned by the user with this exact name.+ known_agent_type: Return only agents of this known-agent type (e.g.+ "claude-code").++ Returns:+ A list of agent summaries (sorted by name), each+ {id, name, description, connector_type, connection_model,+ tool_count, model_count, owner_id, owner_name, oauth_client_id,+ created_at, parent_agent_id, known_agent_type, known_agent_options}.+ Use `get_agent_detail` for the full detail of one agent.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ return await protocol.list_agents(+ agent_id, name_contains, owner_name, known_agent_type+ )+++@operation+async def get_agent_detail(agent_id: str) -> dict[str, Any]:+ """Get full detail for an agent on this Switch instance.++ Readable for any agent (not just your own). Use it to inspect another+ agent's configuration, capabilities, room memberships, and live sessions.++ Args:+ agent_id: The target agent's id (from `list_participants` or+ `list_all_rooms`/`get_room_detail`).++ Returns:+ {id, name, description, connector_type, connection_model,+ tool_count, model_count, owner_id, owner_name, oauth_client_id,+ created_at, parent_agent_id, known_agent_type, known_agent_options,+ agent_type, integration_profile, tools, models, rooms, sessions,+ children}.+ """+ caller_id = get_agent_id()+ protocol = get_protocol()+ detail = await protocol.get_agent_detail(caller_id, agent_id)+ return detail.model_dump()+++@operation+async def update_agent_detail(+ agent_id: str,+ options: dict[str, Any] | None = None,+ parent_agent_id: str | None = None,+ clear_parent: bool = False,+) -> dict[str, Any]:+ """Update an agent's editable settings and return its fresh detail.++ Owner-only: you may only update an agent whose owner is the same as your+ own owner (the call fails with a permission error otherwise). Only agents+ registered with a known-agent type (e.g. "claude-code") have editable+ options.++ Editable fields:+ - `options`: a PARTIAL map of the agent's known-agent options to+ change — only the keys you pass are updated; the rest are left as-is.+ For a claude-code agent the options are `repo_dir` (the working+ directory), `channels_enabled`, `notify_user`, and `subagent_name`.+ The merged options are validated against the agent type's schema and+ its integration profile is rebuilt to match.+ - `parent_agent_id`: set the agent's parent (e.g. to make it a subagent+ of another agent). Validated against self-parenting and cycles.+ - `clear_parent`: pass True to detach the agent from its parent (make it+ top-level). Mutually exclusive with `parent_agent_id`.++ Omit a field to leave it unchanged. Returns the same shape as+ `get_agent_detail`.+ """+ caller_id = get_agent_id()+ protocol = get_protocol()+ detail = await protocol.update_agent_detail(+ caller_id, agent_id, options, parent_agent_id, clear_parent+ )+ return detail.model_dump()+++@operation+async def get_room_detail(room_id: str) -> dict[str, Any]:+ """Get full detail for a room you are a member of.++ You must be a member of the room (assigned to it); this does not have to+ be the room your session is currently connected to. Fails with a+ permission error if you are not a member.++ Args:+ room_id: The Switch room id (UUID string).++ Returns:+ {id, name, description, channel_type, admin_mode, instructions,+ matrix_room_id, created_at, bridge_id, bridge_display_name,+ external_channel_id, group_id, group_name, group_path (the group's+ root-first ancestry, e.g. "Parent / Child"; null when standalone),+ agent_names, agent_statuses (keyed by agent name), connected_user_names,+ aliases (per-room agent aliases, keyed by agent name → alias),+ roles (the room's assumable roles, mirroring list_roles: each entry has+ name, exclusive, instructions_preview, held_by (holder objects with+ presence), and assumable_by_me)}.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ detail = await protocol.get_room_detail(agent_id, room_id)+ return detail.model_dump()+++@operation+async def update_room(+ room_id: str,+ name: str | None = None,+ description: str | None = None,+ instructions: str | None = None,+ admin_mode: bool | None = None,+ join_event_listeners: dict[str, bool] | None = None,+ bridge_id: str | None = None,+ channel_type: str | None = None,+ external_channel_id: str | None = None,+ aliases: dict[str, str] | None = None,+) -> dict[str, Any]:+ """Update attributes of a room you are a member of.++ You must be a member of the room (assigned to it); fails with a+ permission error otherwise. Only the fields you pass are changed —+ omit (leave as None) any attribute you want to keep unchanged.++ Args:+ room_id: The Switch room id (UUID string).+ name: New room name, or None to leave unchanged.+ description: New room description, or None to leave unchanged.+ instructions: New room-specific instructions, or None to leave+ unchanged.+ admin_mode: New admin-mode flag, or None to leave unchanged.+ join_event_listeners: Partial map of agent name → whether that agent+ should receive `room_join` events in this room. Only the named+ agents change; omit to leave all memberships unchanged. Each named+ agent must already be a member of the room.+ bridge_id: Move the room onto this collaboration bridge. A fresh+ external channel is provisioned on the target bridge and the+ room's current agents are re-added, then the old bridge is detached+ (the old external channel is left in place on its platform but is+ no longer synced). Human users are NOT carried over — their+ identities are bridge-specific — so re-invite them to the new+ channel manually. Call `list_bridges` for valid ids. Omit to leave+ the room's bridge unchanged. This sets or moves a bridge only — it+ cannot remove one.+ channel_type: Visibility for the newly provisioned channel when+ `bridge_id` is set — "channel_public" or "channel_private". Omit+ to keep the room's current privacy. Ignored unless `bridge_id` is+ given.+ external_channel_id: Bind to this EXISTING channel on the target+ bridge instead of provisioning a new one — e.g. to move a room+ back onto a channel it previously used (channels are left in place+ on a bridge change, so the old one still exists). The id must be a+ real channel on the target bridge whose bridge bot is a member.+ Ignored unless `bridge_id` is given.+ aliases: Per-room agent aliases to set, keyed by agent name → alias.+ `@<alias>` then addresses that agent in the room like its real+ name. Pass an empty string ("") as the value to clear an agent's+ alias. Only the agents you name are touched; others keep their+ current alias. An alias may contain only letters, digits, '.',+ '-', '_' and must not clash with an agent's real name, a room+ role, or another alias. Omit to leave aliases unchanged.++ Returns:+ The full, updated room detail (same shape as get_room_detail),+ including the room's current `aliases` map.+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ detail = await protocol.update_room(+ agent_id,+ room_id,+ name=name,+ description=description,+ instructions=instructions,+ admin_mode=admin_mode,+ join_event_listeners=join_event_listeners,+ bridge_id=bridge_id,+ channel_type=channel_type,+ external_channel_id=external_channel_id,+ aliases=aliases,+ )+ return detail.model_dump()+++@operation+async def archive_room(room_id: str) -> dict[str, Any]:+ """Archive a room you are a member of, hiding it from the default active+ room lists once its work is complete.++ Archiving is metadata-only and fully reversible: the Matrix room, its+ members, and any bridge channel are left intact, and the room can still+ be connected to and read. It simply stops appearing in `list_rooms` /+ `list_all_rooms` (and the management UI) unless archived rooms are+ explicitly requested. Use this for ephemeral rooms (e.g. a finished+ feature-implementation or bug-fix room) to keep the active list tidy.+ Reverse it with `unarchive_room`.++ You must be a member of the room and have write access to it; fails with+ a permission error otherwise.++ Args:+ room_id: The Switch room id (UUID string).++ Returns:+ The full, updated room detail (same shape as get_room_detail).+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ detail = await protocol.set_room_archived(agent_id, room_id, True)+ return detail.model_dump()+++@operation+async def unarchive_room(room_id: str) -> dict[str, Any]:+ """Unarchive a room you are a member of, restoring it to the default+ active room lists.++ The inverse of `archive_room`. You must be a member of the room and have+ write access to it; fails with a permission error otherwise.++ Args:+ room_id: The Switch room id (UUID string).++ Returns:+ The full, updated room detail (same shape as get_room_detail).+ """+ agent_id = get_agent_id()+ protocol = get_protocol()+ detail = await protocol.set_room_archived(agent_id, room_id, False)+ return detail.model_dump()diff --git a/core/switch_core/bridges/agent/operations/registry.py b/core/switch_core/bridges/agent/operations/registry.pynew file mode 100644index 000000000..c05254b6d--- /dev/null+++ b/core/switch_core/bridges/agent/operations/registry.py@@ -0,0 +1,84 @@+"""The agent operation registry — the single definition of what an agent can do.++Both agent-facing front doors are built from this: the HTTP operations endpoint+dispatches into it, and the MCP server registers its tools from it. Neither+owns the operations, so neither can drift from the other, and removing a door+is removing a door rather than a refactor of everything underneath.++An operation is a plain async function. It takes its arguments and nothing+else — who is calling and which connection they belong to come from the call+context, so operations carry no transport types in their signatures.+"""++from __future__ import annotations++import inspect+from collections.abc import Awaitable, Callable+from dataclasses import dataclass+from typing import Any++from pydantic import create_model++OperationFn = Callable[..., Awaitable[Any]]+++@dataclass(frozen=True)+class Operation:+ name: str+ fn: OperationFn+ description: str+ input_schema: dict[str, Any]+++def _input_schema(fn: OperationFn) -> dict[str, Any]:+ """JSON Schema for an operation's arguments, derived from its signature.++ Built here rather than taken from a transport library, so the schema a+ client sees is the same whichever door it came through — and so the+ operations layer stays free of transport dependencies.+ """+ fields: dict[str, Any] = {}+ for name, param in inspect.signature(fn).parameters.items():+ annotation = (+ param.annotation if param.annotation is not inspect.Parameter.empty else Any+ )+ default = ... if param.default is inspect.Parameter.empty else param.default+ fields[name] = (annotation, default)++ if not fields:+ return {"type": "object", "properties": {}}++ model = create_model(f"{fn.__name__}_arguments", **fields) # type: ignore[call-overload]+ schema = model.model_json_schema()+ schema.pop("title", None)+ return schema+++_REGISTRY: dict[str, Operation] = {}+++def operation(fn: OperationFn) -> OperationFn:+ """Register an agent operation under its own function name.++ The name is the function name verbatim — it is what an agent calls over+ MCP and what appears in `POST /ops/{operation}`. One vocabulary, so a+ translating runtime needs no mapping table.+ """+ name = fn.__name__+ if name in _REGISTRY:+ raise RuntimeError(f"operation {name!r} is already registered")+ _REGISTRY[name] = Operation(+ name=name,+ fn=fn,+ description=(fn.__doc__ or "").strip(),+ input_schema=_input_schema(fn),+ )+ return fn+++def all_operations() -> dict[str, Operation]:+ return dict(_REGISTRY)+++def get_operation(name: str) -> Operation | None:+ return _REGISTRY.get(name)diff --git a/core/switch_core/bridges/agent/protocol/agent_detail.py b/core/switch_core/bridges/agent/protocol/agent_detail.pyindex 80acfe48c..0d3c5e28b 100644--- a/core/switch_core/bridges/agent/protocol/agent_detail.py+++ b/core/switch_core/bridges/agent/protocol/agent_detail.py@@ -16,6 +16,7 @@ from typing import Any, castfrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.addressing import AddressingPolicy+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.statuses import compute_agent_statusesfrom switch_core.db.models import Agent, AgentSessionfrom switch_core.db.stores.agent_session_store import AgentSessionStore@@ -147,7 +148,11 @@ async def assemble_agent_detail(user_store: UserStore,agent_session_store: AgentSessionStore,room_role_store: RoomRoleStore,+ connections: ConnectionRegistry,) -> AgentDetail:+ # Presence is the union of the heartbeat rows and the live connections+ # (CHOO-1857 stage B); an empty set means "rows only".+ alive_agent_ids = connections.live_agent_ids()owner_names: dict[str, str] = {}async def owner_name(owner_id: str | None) -> str | None:@@ -173,9 +178,11 @@ async def assemble_agent_detail(memberships: list[AgentRoomMembership] = []for room in rooms:statuses = await compute_agent_statuses(- session, [agent], room.id, agent_session_store+ session, [agent], room.id, agent_session_store, connections+ )+ room_role = await room_role_store.agent_room_role(+ session, room.id, agent.id, alive_agent_ids)- room_role = await room_role_store.agent_room_role(session, room.id, agent.id)memberships.append(AgentRoomMembership(room_id=room.id,@@ -188,7 +195,8 @@ async def assemble_agent_detail(now = datetime.now(UTC)sessions: list[AgentSessionDetail] = []- for row in await agent_session_store.get_sessions_for_agent(session, agent.id):+ session_rows = await agent_session_store.get_sessions_for_agent(session, agent.id)+ for row in session_rows:room_name: str | None = Noneif row.room_id is not None:room_name = room_name_by_id.get(row.room_id)@@ -205,6 +213,36 @@ async def assemble_agent_detail())+ # Connections are sessions too. A client on the push transport writes no+ # agent_sessions row, so listing only the rows would show a live agent with+ # no sessions at all — presence and the session list disagreeing is worse+ # than either being wrong alone. Rooms already covered by a row are skipped+ # so a client running both (a migration in progress) is not listed twice.+ listed_rooms = {row.room_id for row in session_rows}+ for conn in connections.for_agent(agent.id):+ # An `all`-scope connection claiming nothing is one room-agnostic+ # session, not none.+ conn_rooms: list[str | None] = list(sorted(conn.rooms)) or [None]+ for conn_room in conn_rooms:+ if conn_room in listed_rooms:+ continue+ listed_rooms.add(conn_room)+ room_name = None+ if conn_room is not None:+ room_name = room_name_by_id.get(conn_room)+ if room_name is None:+ linked_room = await room_store.get(session, conn_room)+ room_name = linked_room.name if linked_room else None+ sessions.append(+ AgentSessionDetail(+ room_id=conn_room,+ room_name=room_name,+ lifecycle="connection",+ state="live",+ last_seen_at=str(now),+ )+ )+child_agents = await agent_store.get_children(session, [agent.id])children = [await build_agent_summary(diff --git a/core/switch_core/bridges/agent/protocol/connections.py b/core/switch_core/bridges/agent/protocol/connections.pynew file mode 100644index 000000000..bad4eca79--- /dev/null+++ b/core/switch_core/bridges/agent/protocol/connections.py@@ -0,0 +1,475 @@+"""Agent connections: the unit of reachability (CHOO-1857).++A connection is created by opening the event stream and owns everything that+used to be spread across a table, three heartbeat endpoints and four agent+profiles: which rooms it covers, which events it wants, how far it has+consumed, whether it is alive, and which rooms it is entitled to act in.++Two properties matter most:++* **The connection outlives its socket.** Losing the stream stops delivery; it+ does not end the connection. A client that reattaches within the heartbeat+ TTL keeps its room slot and its role lease, so a brief network drop costs a+ gap in delivery rather than the agent's place in a room.+* **The heartbeat is the authority.** An open socket proves nothing — a+ sleeping laptop leaves one behind for minutes. A connection is alive while+ its client keeps ticking, and dead when it stops, whatever the socket says.++Connections live in memory only. They cannot outlive the process (their+sockets and buffers cannot), so persisting them would recreate the stale-state+bug this design removes.+"""++from __future__ import annotations++import asyncio+import logging+import time+from collections.abc import Iterable+from dataclasses import dataclass, field+from typing import Literal++logger = logging.getLogger(__name__)++Scope = Literal["single", "all"]+DeliveryFilter = Literal["all", "addressed"]++# Clients tick every HEARTBEAT_INTERVAL_SECONDS; a connection is declared dead+# once nothing has arrived for HEARTBEAT_TTL_SECONDS. One mechanism replaces+# /connection/renew, /watch/heartbeat and /leases/renew.+HEARTBEAT_INTERVAL_SECONDS = 2.0+HEARTBEAT_TTL_SECONDS = 6.0++# Refuse a client that speaks a different protocol rather than degrading in+# ways neither side can see. The runtime lives on the user's machine and Switch+# moves independently.+PROTOCOL_VERSION = 1++# Upper bound on simultaneous connections per agent. Runaway growth becomes a+# visible error instead of quiet resource creep.+MAX_CONNECTIONS_PER_AGENT = 32+++class ConnectionError_(Exception):+ """Base for connection faults that a client must be told about."""+++class UnknownConnectionError(ConnectionError_):+ def __init__(self, connection_id: str) -> None:+ super().__init__(+ f"connection {connection_id} is not open; reconnect and resume from "+ "your cursor"+ )+ self.connection_id = connection_id+++class NoStreamAttachedError(ConnectionError_):+ def __init__(self, connection_id: str) -> None:+ super().__init__(+ f"connection {connection_id} has no stream attached; reopen the "+ "event stream"+ )+ self.connection_id = connection_id+++class RoomOccupiedError(ConnectionError_):+ def __init__(self, room_id: str, holder_id: str) -> None:+ super().__init__(+ f"room {room_id} is already held by connection {holder_id} for this "+ "agent; close it or pass takeover"+ )+ self.room_id = room_id+ self.holder_id = holder_id+++class ProtocolVersionError(ConnectionError_):+ def __init__(self, requested: int) -> None:+ super().__init__(+ f"protocol version {requested} is not supported (server speaks "+ f"{PROTOCOL_VERSION}); update the Switch agent runtime"+ )+ self.requested = requested+++class TooManyConnectionsError(ConnectionError_):+ def __init__(self, agent_id: str, limit: int) -> None:+ super().__init__(+ f"agent {agent_id} already has {limit} open connections; close one "+ "before opening another"+ )+ self.agent_id = agent_id+++@dataclass+class Connection:+ id: str+ agent_id: str+ scope: Scope+ delivery_filter: DeliveryFilter+ spawn_capable: bool+ cursor: int+ last_beat: float+ opened_at: float+ # Rooms this connection has subscribed to. A `single` connection holds at+ # most one; an `all` connection leaves this empty and covers every room the+ # agent belongs to that no sibling has claimed.+ rooms: set[str] = field(default_factory=set)+ stream_attached: bool = False+ # How many heartbeats this connection has received. Diagnostic: it is the+ # difference between a client that never started beating and one that beat+ # and then stopped, which the timestamp alone cannot tell you.+ beats: int = 0+ # Bumped when a new stream attaches, so a superseded stream can notice it+ # has been replaced and stop writing.+ stream_generation: int = 0+ closed_reason: str | None = None+ wake: asyncio.Event = field(default_factory=asyncio.Event)++ def is_alive(self, now: float) -> bool:+ return (+ self.closed_reason is None+ and (now - self.last_beat) < HEARTBEAT_TTL_SECONDS+ )+++class ConnectionRegistry:+ """The live set of agent connections. Authoritative, in memory."""++ def __init__(self) -> None:+ self._by_id: dict[str, Connection] = {}+ self._by_agent: dict[str, set[str]] = {}++ # ------------------------------------------------------------------+ # Opening and closing+ # ------------------------------------------------------------------++ def open(+ self,+ *,+ agent_id: str,+ connection_id: str,+ scope: Scope,+ delivery_filter: DeliveryFilter,+ spawn_capable: bool,+ cursor: int,+ protocol_version: int,+ ) -> Connection:+ """Open a connection, or reattach to one the client already owns.++ The client chooses the id, which makes opening idempotent: a timed-out+ request can be retried without leaving an orphan behind. Reopening a+ live id takes it over — "the same client returning" and "the same+ client duplicated" are indistinguishable, and takeover is right for+ both.+ """+ if protocol_version != PROTOCOL_VERSION:+ raise ProtocolVersionError(protocol_version)++ existing = self._by_id.get(connection_id)+ if existing is not None:+ if existing.agent_id != agent_id:+ # Never let one agent attach to another's connection.+ raise UnknownConnectionError(connection_id)+ existing.scope = scope+ existing.delivery_filter = delivery_filter+ existing.spawn_capable = spawn_capable+ existing.cursor = cursor+ existing.last_beat = time.monotonic()+ existing.closed_reason = None+ existing.stream_attached = True+ existing.stream_generation += 1+ logger.info(+ "[CONN] reattached agent=%s connection=%s scope=%s generation=%s",+ agent_id,+ connection_id,+ scope,+ existing.stream_generation,+ )+ return existing++ owned = self._by_agent.setdefault(agent_id, set())+ if len(owned) >= MAX_CONNECTIONS_PER_AGENT:+ raise TooManyConnectionsError(agent_id, MAX_CONNECTIONS_PER_AGENT)++ now = time.monotonic()+ conn = Connection(+ id=connection_id,+ agent_id=agent_id,+ scope=scope,+ delivery_filter=delivery_filter,+ spawn_capable=spawn_capable,+ cursor=cursor,+ last_beat=now,+ opened_at=now,+ stream_attached=True,+ )+ self._by_id[connection_id] = conn+ owned.add(connection_id)+ logger.info(+ "[CONN] opened agent=%s connection=%s scope=%s filter=%s spawn=%s",+ agent_id,+ connection_id,+ scope,+ delivery_filter,+ spawn_capable,+ )+ return conn++ def detach_stream(self, connection_id: str, generation: int) -> None:+ """Mark the stream gone while leaving the connection alive.++ Only the generation that is currently attached may detach: a superseded+ stream unwinding must not clear the flag its replacement just set.+ """+ conn = self._by_id.get(connection_id)+ if conn is not None and conn.stream_generation == generation:+ conn.stream_attached = False+ logger.info(+ "[CONN] stream detached agent=%s connection=%s (connection still "+ "alive until heartbeat lapses)",+ conn.agent_id,+ connection_id,+ )++ def close(self, connection_id: str, reason: str) -> Connection | None:+ conn = self._by_id.pop(connection_id, None)+ if conn is None:+ return None+ owned = self._by_agent.get(conn.agent_id)+ if owned:+ owned.discard(connection_id)+ if not owned:+ self._by_agent.pop(conn.agent_id, None)+ conn.closed_reason = reason+ conn.stream_attached = False+ conn.wake.set()+ # `beats` and the age separate the two ways a connection dies, which+ # otherwise look identical in the log: a client that never beat at all+ # (beats=0 — it is not running the heartbeat, or cannot reach us) versus+ # one that beat and then stopped (beats>0 — it went away, or the server+ # was too busy to process ticks).+ logger.info(+ "[CONN] closed agent=%s connection=%s reason=%s beats=%d last_beat_age=%.1fs",+ conn.agent_id,+ connection_id,+ reason,+ conn.beats,+ time.monotonic() - conn.last_beat,+ )+ return conn++ def sweep(self) -> list[Connection]:+ """Close connections whose heartbeat has lapsed. Returns those closed."""+ now = time.monotonic()+ stale = [+ conn+ for conn in self._by_id.values()+ if (now - conn.last_beat) >= HEARTBEAT_TTL_SECONDS+ ]+ closed = []+ for conn in stale:+ gone = self.close(conn.id, "heartbeat lapsed")+ if gone is not None:+ closed.append(gone)+ return closed++ # ------------------------------------------------------------------+ # Liveness+ # ------------------------------------------------------------------++ def beat(self, agent_id: str, connection_id: str, cursor: int) -> Connection:+ """Record a client tick and its cursor.++ Rejects a tick for a connection with no stream: the client is alive but+ receiving nothing, and must be told to reopen rather than left believing+ it is connected.+ """+ conn = self.require(agent_id, connection_id)+ if not conn.stream_attached:+ raise NoStreamAttachedError(connection_id)+ conn.last_beat = time.monotonic()+ conn.beats += 1+ if cursor > conn.cursor:+ conn.cursor = cursor+ return conn++ def require(self, agent_id: str, connection_id: str) -> Connection:+ conn = self._by_id.get(connection_id)+ if conn is None or conn.agent_id != agent_id:+ raise UnknownConnectionError(connection_id)+ if not conn.is_alive(time.monotonic()):+ self.close(connection_id, "heartbeat lapsed")+ raise UnknownConnectionError(connection_id)+ return conn++ def get(self, connection_id: str) -> Connection | None:+ return self._by_id.get(connection_id)++ def for_agent(self, agent_id: str) -> list[Connection]:+ now = time.monotonic()+ return [+ conn+ for cid in self._by_agent.get(agent_id, set())+ if (conn := self._by_id.get(cid)) is not None and conn.is_alive(now)+ ]++ # ------------------------------------------------------------------+ # Room slots+ # ------------------------------------------------------------------++ def claim_room(+ self, conn: Connection, room_id: str, *, takeover: bool = False+ ) -> Connection | None:+ """Subscribe a connection to a room, claiming its slot.++ At most one connection per agent may act in a room. A `single`+ connection subscribing to a new room drops the previous one, so "one+ room at a time" is enforced here rather than left to the client.++ Returns the connection that was evicted, if any.+ """+ claimant = self.claimant_of(conn.agent_id, room_id)+ evicted: Connection | None = None+ if claimant is not None and claimant.id != conn.id:+ if not takeover:+ raise RoomOccupiedError(room_id, claimant.id)+ claimant.rooms.discard(room_id)+ claimant.wake.set()+ evicted = claimant++ if conn.scope == "single":+ conn.rooms.clear()+ conn.rooms.add(room_id)+ conn.wake.set()+ return evicted++ def release_room(self, conn: Connection, room_id: str) -> None:+ conn.rooms.discard(room_id)+ conn.wake.set()++ def claimant_of(self, agent_id: str, room_id: str) -> Connection | None:+ """The connection that has explicitly claimed this room, if any.++ Only an explicit claim conflicts. An `all`-scope connection covering a+ room has not claimed it — it yields to a session that wants it, which+ is the whole point of the fallback.+ """+ for conn in self.for_agent(agent_id):+ if room_id in conn.rooms:+ return conn+ return None++ def holder_of(self, agent_id: str, room_id: str) -> Connection | None:+ """The connection entitled to act as this agent in this room, if any.++ The claimant if there is one, otherwise an `all`-scope connection —+ that is what makes a supervising daemon go dark on rooms a session has+ taken, and pick them up again when the session ends.+ """+ claimant = self.claimant_of(agent_id, room_id)+ if claimant is not None:+ return claimant+ for conn in self.for_agent(agent_id):+ if conn.scope == "all":+ return conn+ return None++ def covers(self, conn: Connection, room_id: str) -> bool:+ if conn.scope == "single":+ return room_id in conn.rooms+ # An `all` connection covers everything no sibling has claimed.+ if room_id in conn.rooms:+ return True+ for sibling in self.for_agent(conn.agent_id):+ if sibling.id != conn.id and room_id in sibling.rooms:+ return False+ return True++ # ------------------------------------------------------------------+ # Presence+ # ------------------------------------------------------------------+ #+ # Presence readers union these with the `agent_sessions` rows the+ # pre-connection clients maintain (CHOO-1857 stage B). A client on the new+ # transport sends none of the old renews, so without the connection arm it+ # would read as DISCONNECTED while alive on the stream; a client still+ # polling keeps its DB arm. When the old clients are gone, the DB arm goes+ # with them and these remain.++ def is_live(self, agent_id: str) -> bool:+ """Whether the agent has any live connection at all.++ The connection equivalent of the room-agnostic heartbeat slot: what+ `always_on` liveness and the `auto_session` DORMANT state ask for.+ """+ return bool(self.for_agent(agent_id))++ def live_in_room(self, agent_id: str, room_id: str) -> bool:+ """Whether some live connection of this agent covers this room.++ Covers, not claims: an `all`-scope daemon is genuinely reachable in the+ rooms it has not yielded to a session. This is the *delivery* question.+ For "is a session attending this room", use `has_session_in`.+ """+ return any(self.covers(conn, room_id) for conn in self.for_agent(agent_id))++ def has_session_in(self, agent_id: str, room_id: str) -> bool:+ """Whether a connection has **claimed** this room — i.e. a session is in it.++ Distinct from `live_in_room`, and the distinction matters. An+ `all`-scope watcher covers every room no session has taken, so `covers`+ answers "would this connection receive the room's events" — true for a+ daemon that is merely watching. Presence for a session-shaped agent asks+ something narrower: is a session actually attending? Only an explicit+ claim answers that.++ Conflating the two reports an agent LIVE in a room where nothing is+ listening but a watcher, which suppresses both the "no session" reply+ and the `auto_session` promise to start one.+ """+ return self.claimant_of(agent_id, room_id) is not None++ def can_spawn_for(self, agent_id: str, room_id: str) -> bool:+ """Whether something live will start a session for this room on demand.++ Declared by the client when it opens the stream (`spawn_capable`), so+ this is an *observed* capability rather than a property inferred from+ the agent's `connection_model`. That matters: the enum says what an+ agent was configured as, this says what is actually connected and+ willing right now. Promising "Starting a session…" on the strength of+ the enum alone is how a room gets told a session is coming when nothing+ is listening.+ """+ return any(+ conn.spawn_capable and self.covers(conn, room_id)+ for conn in self.for_agent(agent_id)+ )++ def live_agent_ids(self) -> set[str]:+ """Every agent with at least one live connection.++ Passed to the role-lease predicates: a connection keeps a role held,+ so a client that has stopped sending `/leases/renew` because it moved+ to the single heartbeat does not silently lose its seat.+ """+ now = time.monotonic()+ return {conn.agent_id for conn in self._by_id.values() if conn.is_alive(now)}++ def live_agents_in_room(self, agent_ids: Iterable[str], room_id: str) -> set[str]:+ return {aid for aid in agent_ids if self.live_in_room(aid, room_id)}++ def agents_with_session_in(+ self, agent_ids: Iterable[str], room_id: str+ ) -> set[str]:+ return {aid for aid in agent_ids if self.has_session_in(aid, room_id)}++ def live_agents(self, agent_ids: Iterable[str]) -> set[str]:+ return {aid for aid in agent_ids if self.is_live(aid)}++ def rooms_covered(self, agent_id: str, candidate_rooms: Iterable[str]) -> set[str]:+ """Which of `candidate_rooms` this agent is reachable in right now."""+ return {room for room in candidate_rooms if self.live_in_room(agent_id, room)}++ def wake_agent(self, agent_id: str) -> None:+ for conn in self.for_agent(agent_id):+ conn.wake.set()diff --git a/core/switch_core/bridges/agent/protocol/event_buffer.py b/core/switch_core/bridges/agent/protocol/event_buffer.pynew file mode 100644index 000000000..d3256896c--- /dev/null+++ b/core/switch_core/bridges/agent/protocol/event_buffer.py@@ -0,0 +1,393 @@+"""Per-agent sequenced event buffer (CHOO-1857).++Replaces the destructive per-room `asyncio.Queue` fan-out. Events are appended+with a monotonically increasing sequence number and stay readable until they+age out of the retention window or the per-agent cap forces them out. Reading+never removes, so several readers can consume the same events independently and+a reader that drops off can resume from its cursor.++Retention is deliberately independent of what readers have confirmed: an event+remains readable for its window whether or not somebody has already consumed+it. Cursors record progress; they do not decide what is kept.++The buffer lives in memory: it cannot outlive the process, and persisting it+would recreate the stale-state bug this design removes. `switch-core` is+single-process by construction, so an in-process structure is authoritative.+It sits behind a narrow surface (`enqueue`, `read_from`, `wait`, `confirm`)+so it can be moved to Postgres later without touching its callers.++Overflow is never silent: when the cap forces events out, the agent is flagged+as having a gap and the next reader to ask is told it missed events.+"""++from __future__ import annotations++import asyncio+import logging+import time+from collections import deque+from dataclasses import dataclass++from switch_core.bridges.agent.protocol.types import AgentEvent++logger = logging.getLogger(__name__)++# Maximum events retained per agent. Beyond this the oldest are dropped and the+# agent is flagged with a gap. Sized for chat-rate traffic: an agent would have+# to accumulate this many unread events before any reader catches up.+DEFAULT_MAX_EVENTS_PER_AGENT = 2000++# How long an event stays readable. This is the resume window: a client that+# reconnects within it recovers every event it missed, and one that reconnects+# later is told it has a gap rather than handed a partial stream.+DEFAULT_RETENTION_SECONDS = 15 * 60+++class CursorExpiredError(Exception):+ """A reader asked to resume from a point the buffer no longer retains.++ Raised rather than fast-forwarding to head: a client that has missed events+ must be told, never handed a stream that looks complete.+ """++ def __init__(self, agent_id: str, requested: int, oldest: int) -> None:+ super().__init__(+ f"cursor {requested} for agent {agent_id} is older than the retained "+ f"buffer (oldest retained: {oldest}); missed events, re-read context"+ )+ self.agent_id = agent_id+ self.requested = requested+ self.oldest = oldest+++def is_notifiable(event: AgentEvent) -> bool:+ """Whether an event is addressed at the agent rather than ambient context.++ Addressed messages, task events, and room_join events the agent is+ configured to listen for. Excludes unaddressed chatter and admin command+ events. This is the `addressed` delivery filter: a supervising connection+ watching every room wants only these, while a session in a single room+ wants everything.+ """+ if event.type == "message":+ return getattr(event.payload, "addressed", False)+ if event.type == "room_join":+ return getattr(event.payload, "listening", False)+ if event.type == "command":+ return False+ # All task_* events are enqueued only for the directly-involved agent.+ return event.type.startswith("task_")+++@dataclass(frozen=True)+class BufferedEvent:+ """An event with its position in the agent's stream."""++ seq: int+ room_id: str+ event: AgentEvent+ notifiable: bool+ appended_at: float+++class EventBuffer:+ def __init__(+ self,+ max_events_per_agent: int = DEFAULT_MAX_EVENTS_PER_AGENT,+ retention_seconds: float = DEFAULT_RETENTION_SECONDS,+ ) -> None:+ self._max_events = max_events_per_agent+ self._retention_seconds = retention_seconds+ self._events: dict[str, deque[BufferedEvent]] = {}+ self._next_seq: dict[str, int] = {}+ self._notify: dict[str, asyncio.Event] = {}+ # reader id -> last sequence number that reader has confirmed. Used to+ # resume a reader and to report progress; deliberately NOT used to+ # decide what to drop. Retention is by age and cap alone, so a reader+ # that connects after an event was already consumed by someone else+ # still sees it.+ self._cursors: dict[str, dict[str, int]] = {}+ # Highest sequence number dropped by overflow, per agent. Any reader+ # resuming from at or below this has missed events.+ self._dropped_through: dict[str, int] = {}++ # ------------------------------------------------------------------+ # Producing+ # ------------------------------------------------------------------++ def enqueue(self, agent_id: str, room_id: str, event: AgentEvent) -> int:+ """Append an event for an agent and return its sequence number."""+ seq = self._next_seq.get(agent_id, 1)+ self._next_seq[agent_id] = seq + 1++ events = self._events.setdefault(agent_id, deque())+ events.append(+ BufferedEvent(+ seq=seq,+ room_id=room_id,+ event=event,+ notifiable=is_notifiable(event),+ appended_at=time.monotonic(),+ )+ )+ logger.debug(+ "[EVENT-BUF] append agent=%s room=%s type=%s seq=%s",+ agent_id,+ room_id,+ event.type,+ seq,+ )+ self._trim(agent_id)+ self._wake(agent_id)+ return seq++ # ------------------------------------------------------------------+ # Consuming+ # ------------------------------------------------------------------++ def read_from(+ self,+ agent_id: str,+ after_seq: int,+ *,+ rooms: set[str] | None = None,+ notifiable_only: bool = False,+ limit: int | None = None,+ ) -> list[BufferedEvent]:+ """Return retained events after `after_seq`, oldest first.++ `rooms=None` means every room the agent has events for; otherwise only+ the given rooms. Raises `CursorExpiredError` if `after_seq` predates+ what the buffer still holds.+ """+ self._check_cursor(agent_id, after_seq)++ out: list[BufferedEvent] = []+ for item in self._events.get(agent_id, ()):+ if item.seq <= after_seq:+ continue+ if rooms is not None and item.room_id not in rooms:+ continue+ if notifiable_only and not item.notifiable:+ continue+ out.append(item)+ if limit is not None and len(out) >= limit:+ break+ return out++ async def wait(self, agent_id: str, timeout: float) -> None:+ """Block until an event is appended for the agent, or the timeout passes.++ A wake-up is advisory: callers re-read from their cursor rather than+ trusting this to deliver anything. The buffer is the record; this is+ only the doorbell.+ """+ notify = self._notify.setdefault(agent_id, asyncio.Event())+ notify.clear()+ try:+ await asyncio.wait_for(notify.wait(), timeout=timeout)+ except TimeoutError:+ return++ def doorbell(self, agent_id: str) -> asyncio.Event:+ """The wake-up signal for an agent, shared by every reader.++ Set whenever an event is appended. Readers re-read from their own+ cursor when woken; the signal carries no payload, so a spurious or+ missed wake costs latency, never correctness.+ """+ return self._notify.setdefault(agent_id, asyncio.Event())++ def head(self, agent_id: str) -> int:+ """The sequence number of the most recent event (0 if none)."""+ return self._next_seq.get(agent_id, 1) - 1++ def oldest_retained(self, agent_id: str) -> int:+ """Sequence number of the oldest retained event (0 if the buffer is empty)."""+ events = self._events.get(agent_id)+ return events[0].seq if events else 0++ def has_gap_before(self, agent_id: str, after_seq: int) -> bool:+ """Whether resuming from `after_seq` would skip dropped events."""+ dropped = self._dropped_through.get(agent_id)+ return dropped is not None and after_seq < dropped++ # ------------------------------------------------------------------+ # Reader bookkeeping+ # ------------------------------------------------------------------++ def register_reader(self, agent_id: str, reader_id: str, cursor: int) -> None:+ self._cursors.setdefault(agent_id, {})[reader_id] = cursor++ def confirm(self, agent_id: str, reader_id: str, cursor: int) -> None:+ """Record how far a reader has consumed, so its events can be trimmed.++ Cursors only move forward. A reader reporting a lower value than it has+ already confirmed is ignored rather than allowed to rewind the buffer.+ """+ readers = self._cursors.setdefault(agent_id, {})+ if cursor > readers.get(reader_id, 0):+ readers[reader_id] = cursor++ def drop_reader(self, agent_id: str, reader_id: str) -> None:+ readers = self._cursors.get(agent_id)+ if readers:+ readers.pop(reader_id, None)++ def remove(self, agent_id: str) -> None:+ self._events.pop(agent_id, None)+ self._next_seq.pop(agent_id, None)+ self._notify.pop(agent_id, None)+ self._cursors.pop(agent_id, None)+ self._dropped_through.pop(agent_id, None)++ # ------------------------------------------------------------------+ # Legacy long-poll compatibility+ #+ # Polling clients send no cursor and have nowhere to keep one, so the+ # server holds it for them: "everything after the last thing I gave you,+ # and record that I gave it". Behaviour is unchanged from their point of+ # view — they never see a duplicate — but reads are no longer destructive,+ # so a streaming reader on the same agent is unaffected.+ #+ # Delivery stays at-most-once for these callers, exactly as before: the+ # cursor advances on send, so a response lost in flight loses its events.+ # Confirming clients get at-least-once instead.+ # ------------------------------------------------------------------++ async def poll(self, agent_id: str, timeout: float = 30) -> list[AgentEvent]:+ return await self._legacy_poll(agent_id, "legacy:all", timeout=timeout)++ async def poll_room(+ self, agent_id: str, room_id: str, timeout: float = 30+ ) -> list[AgentEvent]:+ return await self._legacy_poll(+ agent_id, f"legacy:room:{room_id}", timeout=timeout, rooms={room_id}+ )++ async def poll_notifications(+ self, agent_id: str, timeout: float = 30+ ) -> list[AgentEvent]:+ return await self._legacy_poll(+ agent_id, "legacy:notifications", timeout=timeout, notifiable_only=True+ )++ async def _legacy_poll(+ self,+ agent_id: str,+ reader_id: str,+ *,+ timeout: float,+ rooms: set[str] | None = None,+ notifiable_only: bool = False,+ ) -> list[AgentEvent]:+ cursor = self._legacy_cursor(agent_id, reader_id)++ events = self._legacy_read(agent_id, reader_id, cursor, rooms, notifiable_only)+ if events:+ return self._advance_legacy(agent_id, reader_id, events)++ await self.wait(agent_id, timeout)++ cursor = self._legacy_cursor(agent_id, reader_id)+ events = self._legacy_read(agent_id, reader_id, cursor, rooms, notifiable_only)+ return self._advance_legacy(agent_id, reader_id, events)++ def _legacy_cursor(self, agent_id: str, reader_id: str) -> int:+ readers = self._cursors.setdefault(agent_id, {})+ if reader_id not in readers:+ # A poller seen for the first time starts before the oldest+ # retained event, mirroring the queue it replaces: events+ # accumulated while nobody was polling and the first poll drained+ # them. Starting at head would silently swallow anything that+ # arrived before the client got around to asking.+ readers[reader_id] = max(self.oldest_retained(agent_id) - 1, 0)+ return readers[reader_id]++ def _legacy_read(+ self,+ agent_id: str,+ reader_id: str,+ cursor: int,+ rooms: set[str] | None,+ notifiable_only: bool,+ ) -> list[BufferedEvent]:+ try:+ return self.read_from(+ agent_id, cursor, rooms=rooms, notifiable_only=notifiable_only+ )+ except CursorExpiredError as exc:+ # A polling client cannot be told about a gap — it has no protocol+ # for it. Log loudly and resume from what is retained rather than+ # silently returning nothing. Migrating the client is the real fix.+ logger.error(+ "[EVENT-BUF] legacy poller %s for agent %s missed events "+ "(cursor %s, oldest retained %s); resuming from oldest retained",+ reader_id,+ agent_id,+ exc.requested,+ exc.oldest,+ )+ resumed = max(exc.oldest - 1, 0)+ self._cursors.setdefault(agent_id, {})[reader_id] = resumed+ return self.read_from(+ agent_id, resumed, rooms=rooms, notifiable_only=notifiable_only+ )++ def _advance_legacy(+ self, agent_id: str, reader_id: str, events: list[BufferedEvent]+ ) -> list[AgentEvent]:+ if events:+ self.confirm(agent_id, reader_id, events[-1].seq)+ return [item.event for item in events]++ # ------------------------------------------------------------------+ # Internals+ # ------------------------------------------------------------------++ def _wake(self, agent_id: str) -> None:+ notify = self._notify.get(agent_id)+ if notify is not None:+ notify.set()++ def _check_cursor(self, agent_id: str, after_seq: int) -> None:+ if self.has_gap_before(agent_id, after_seq):+ raise CursorExpiredError(+ agent_id, after_seq, self._dropped_through[agent_id] + 1+ )++ def _trim(self, agent_id: str) -> None:+ """Enforce the retention window and the cap.++ Both are lossy, so both record a gap that the next reader resuming from+ before it will be told about. Retention is deliberately independent of+ what readers have confirmed: an event stays readable for its window+ whether or not somebody has already consumed it, so a reader that+ arrives late still sees recent history.+ """+ events = self._events.get(agent_id)+ if not events:+ return++ dropped_seq = 0+ cutoff = time.monotonic() - self._retention_seconds+ while events and events[0].appended_at < cutoff:+ dropped_seq = events.popleft().seq++ overflow = len(events) - self._max_events+ if overflow > 0:+ for _ in range(overflow):+ dropped_seq = events.popleft().seq+ logger.warning(+ "[EVENT-BUF] agent=%s exceeded %s buffered events; dropped "+ "through seq=%s — readers resuming from before this will be "+ "told they missed events",+ agent_id,+ self._max_events,+ dropped_seq,+ )++ if dropped_seq:+ self._dropped_through[agent_id] = max(+ dropped_seq, self._dropped_through.get(agent_id, 0)+ )diff --git a/core/switch_core/bridges/agent/protocol/event_queue.py b/core/switch_core/bridges/agent/protocol/event_queue.pydeleted file mode 100644index ac7908cdd..000000000--- a/core/switch_core/bridges/agent/protocol/event_queue.py+++ /dev/null@@ -1,140 +0,0 @@-from __future__ import annotations--import asyncio-import logging--from switch_core.bridges.agent.protocol.types import AgentEvent--logger = logging.getLogger(__name__)---def _is_notifiable(event: AgentEvent) -> bool:- """Whether an event should also fan out to the agent's notification stream.-- The notification stream mirrors exactly what a connector treats as a- notification: addressed messages, task events, and room_join events the- agent is configured to listen for. It deliberately excludes unaddressed- chatter and admin command events. The auto_session watcher consumes this- stream to decide when to spin up a session.- """- if event.type == "message":- return getattr(event.payload, "addressed", False)- if event.type == "room_join":- return getattr(event.payload, "listening", False)- if event.type == "command":- return False- # All task_* events are enqueued only for the directly-involved agent.- return event.type.startswith("task_")---class EventQueue:- def __init__(self) -> None:- self._queues: dict[str, dict[str, asyncio.Queue[AgentEvent]]] = {}- self._notify: dict[str, asyncio.Event] = {}- # A separate, agent-scoped notification stream (not keyed by room).- # Notifiable events are fanned out here in addition to the per-room- # queues above, so the auto_session watcher can long-poll it without- # draining the per-room queues that live session pollers consume.- self._notif_queues: dict[str, asyncio.Queue[AgentEvent]] = {}-- def _get_queue(self, agent_id: str, room_id: str) -> asyncio.Queue[AgentEvent]:- agent_queues = self._queues.setdefault(agent_id, {})- if room_id not in agent_queues:- agent_queues[room_id] = asyncio.Queue()- return agent_queues[room_id]-- def _get_notify(self, agent_id: str) -> asyncio.Event:- if agent_id not in self._notify:- self._notify[agent_id] = asyncio.Event()- return self._notify[agent_id]-- def _get_notif_queue(self, agent_id: str) -> asyncio.Queue[AgentEvent]:- if agent_id not in self._notif_queues:- self._notif_queues[agent_id] = asyncio.Queue()- return self._notif_queues[agent_id]-- def enqueue(self, agent_id: str, room_id: str, event: AgentEvent) -> None:- logger.debug(- "[EVENT-Q] enqueue agent=%s room=%s event=%s", agent_id, room_id, event.type- )- self._get_queue(agent_id, room_id).put_nowait(event)- self._get_notify(agent_id).set()- # Fan out to the agent-scoped notification stream. This is a SEPARATE- # queue, so consuming it never removes the event from the per-room- # queue a live session poller reads — no event stealing.- if _is_notifiable(event):- self._get_notif_queue(agent_id).put_nowait(event)-- async def poll(self, agent_id: str, timeout: float = 30) -> list[AgentEvent]:- events = self._drain_all(agent_id)- if events:- return events-- notify = self._get_notify(agent_id)- notify.clear()- try:- await asyncio.wait_for(notify.wait(), timeout=timeout)- except TimeoutError:- return []-- return self._drain_all(agent_id)-- async def poll_room(- self, agent_id: str, room_id: str, timeout: float = 30- ) -> list[AgentEvent]:- queue = self._get_queue(agent_id, room_id)-- events: list[AgentEvent] = []- while not queue.empty():- events.append(queue.get_nowait())-- if events:- return events-- try:- event = await asyncio.wait_for(queue.get(), timeout=timeout)- events.append(event)- except TimeoutError:- pass-- return events-- async def poll_notifications(- self, agent_id: str, timeout: float = 30- ) -> list[AgentEvent]:- """Long-poll the agent's notification stream (across all rooms).-- Mirrors `poll_room` but drains the agent-scoped notification queue.- Returns notifiable events only (see `_is_notifiable`).- """- queue = self._get_notif_queue(agent_id)-- events: list[AgentEvent] = []- while not queue.empty():- events.append(queue.get_nowait())-- if events:- return events-- try:- event = await asyncio.wait_for(queue.get(), timeout=timeout)- events.append(event)- except TimeoutError:- pass-- return events-- def remove(self, agent_id: str) -> None:- self._queues.pop(agent_id, None)- self._notify.pop(agent_id, None)- self._notif_queues.pop(agent_id, None)-- def _drain_all(self, agent_id: str) -> list[AgentEvent]:- agent_queues = self._queues.get(agent_id)- if not agent_queues:- return []- events: list[AgentEvent] = []- for queue in agent_queues.values():- while not queue.empty():- events.append(queue.get_nowait())- return eventsdiff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex e59b08d40..ac5a6c3d5 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -25,7 +25,8 @@ from switch_core.bridges.agent.protocol.agent_detail import (list_agent_summaries,reparent_agent,)-from switch_core.bridges.agent.protocol.event_queue import EventQueue+from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.statuses import compute_agent_statusesfrom switch_core.bridges.agent.protocol.types import (AgentEvent,@@ -117,7 +118,8 @@ class ProtocolService:room_service: RoomService,client_lifecycle: ClientLifecycleService,collab_lifecycle: CollaborationBridgeLifecycleService,- event_queue: EventQueue,+ event_buffer: EventBuffer,+ connections: ConnectionRegistry,task_store: TaskStore,request_tracker: RequestTracker,resource_request_tracker: ResourceRequestTracker,@@ -138,7 +140,12 @@ class ProtocolService:self.room_service = room_serviceself.client_lifecycle = client_lifecycleself.collab_lifecycle = collab_lifecycle- self.event_queue = event_queue+ self.event_buffer = event_buffer+ # Injected, not constructed: more than one ProtocolService exists in a+ # running server, and a connection registered through one must be+ # visible to all of them. Owning a registry here would split the live+ # connection set in two.+ self.connections = connectionsself.task_store = task_storeself.request_tracker = request_trackerself.resource_request_tracker = resource_request_tracker@@ -505,7 +512,7 @@ class ProtocolService:resolved_id = agent.idresolved_name = agent.nameawait self.client_lifecycle.stop(client_id)- self.event_queue.remove(resolved_id)+ self.event_buffer.remove(resolved_id)await self._remove_bridge_identities(resolved_name)@@ -578,7 +585,7 @@ class ProtocolService:# holds at most one role (unique agent_id), so the inverse map is# well-defined even for shared roles with several holders.live_holders = await self.room_role_store.live_holders_for_room(- session, room_id+ session, room_id, self.connections.live_agent_ids())roles = await self.room_role_store.list_roles(session, room_id)role_name_by_id = {r.id: r.name for r in roles}@@ -623,7 +630,7 @@ class ProtocolService:room_id: str,) -> dict[str, AgentStatus]:return await compute_agent_statuses(- session, agents, room_id, self.agent_session_store+ session, agents, room_id, self.agent_session_store, self.connections)async def get_agent_statuses_by_name(@@ -908,7 +915,7 @@ class ProtocolService:)role_by_id = {role.id: role.name for role in defined_roles}holders = await self.room_role_store.live_holders_for_room(- session, room_id+ session, room_id, self.connections.live_agent_ids())for role_id, agent_ids in holders.items():if role_by_id.get(role_id) not in roles:@@ -1092,10 +1099,20 @@ class ProtocolService:stuck on the bridge. Each non-idle row is checked against the sameliveness window `!status` uses; stale ones are collapsed to idle and aclear event is emitted.++ Liveness is the same union every other reader takes (CHOO-1857): the+ heartbeat rows for clients still polling, the live connections for+ clients on the push transport. Checking only the rows made this sweep+ clear the state of a perfectly live session on every pass — and because+ the bridge deletes the "working on it…" message on idle and posts a new+ one on the next update, the visible effect was the status message being+ deleted and recreated on every refresh rather than edited in place."""async with self.session_factory() as session:rows = await self.agent_runtime_state_store.get_active(session)for row in rows:+ if self.connections.has_session_in(row.agent_id, row.room_id):+ continueasync with self.session_factory() as session:live = await self.agent_session_store.get_live_agent_ids(session, [row.agent_id], row.room_id@@ -1317,7 +1334,7 @@ class ProtocolService:async with self.session_factory() as session:await self.agent_session_store.touch_heartbeat(session, agent_id, None)await session.commit()- return await self.event_queue.poll(agent_id, timeout=timeout)+ return await self.event_buffer.poll(agent_id, timeout=timeout)async def poll_notifications(self, agent_id: str, timeout: float = 10@@ -1325,14 +1342,14 @@ class ProtocolService:"""Long-poll the agent's notification stream across all its rooms.Returns only notifiable events (addressed messages, task events, and- room_join events the agent listens for) — see EventQueue. Unlike+ room_join events the agent listens for) — see EventBuffer. Unlike`poll_events`, this does NOT touch any heartbeat: an auto_sessionconnector maintains its "watching" presence via the dedicated`touch_watch_heartbeat` path, decoupled from this long-poll. Consumingthis stream never drains the per-room queues, so live session pollersare unaffected."""- return await self.event_queue.poll_notifications(agent_id, timeout=timeout)+ return await self.event_buffer.poll_notifications(agent_id, timeout=timeout)async def touch_watch_heartbeat(self, agent_id: str) -> None:"""Refresh an auto_session connector's global "watching" heartbeat.@@ -1358,7 +1375,7 @@ class ProtocolService:the long-poll cadence so the TTL can stay short."""await self.require_room_member(agent_id, room_id)- return await self.event_queue.poll_room(agent_id, room_id, timeout=timeout)+ return await self.event_buffer.poll_room(agent_id, room_id, timeout=timeout)async def report_events(self,@@ -1988,8 +2005,13 @@ class ProtocolService:could `assume_role` it right now: the caller holds no other live lease,and the role is either non-exclusive or not live-held by someone else."""- leases = await self.room_role_store.live_leases_for_room(session, room_id)- my_lease = await self.room_role_store.get_agent_live_lease(session, agent_id)+ alive = self.connections.live_agent_ids()+ leases = await self.room_role_store.live_leases_for_room(+ session, room_id, alive+ )+ my_lease = await self.room_role_store.get_agent_live_lease(+ session, agent_id, alive+ )# Resolve holder agent ids → names.holder_names: dict[str, str] = {}for lease_list in leases.values():@@ -2116,10 +2138,13 @@ class ProtocolService:role = await self.room_role_store.get_role(session, room_id, role_name)if role is None:raise ValueError(f"Role '{role_name}' not found in this room")- prior = await self.room_role_store.get_agent_live_lease(session, agent_id)+ alive = self.connections.live_agent_ids()+ prior = await self.room_role_store.get_agent_live_lease(+ session, agent_id, alive+ )already_held = prior is not None and prior.role_id == role.idawait self.room_role_store.acquire_lease(- session, role, agent_id, transport_session_id+ session, role, agent_id, transport_session_id, alive)await session.commit()result = {"role": role.name, "instructions": role.instructions}@@ -2136,12 +2161,14 @@ class ProtocolService:If a live lease is dropped, announce the release in its room."""async with self.session_factory() as session:- live = await self.room_role_store.get_agent_live_lease(session, agent_id)+ live = await self.room_role_store.get_agent_live_lease(+ session, agent_id, self.connections.live_agent_ids()+ )released_role: str | None = Nonematrix_room_id: str | None = Noneif live is not None:released_role = await self.room_role_store.agent_room_role(- session, live.room_id, agent_id+ session, live.room_id, agent_id, self.connections.live_agent_ids())room = await self.room_store.get(session, live.room_id)matrix_room_id = room.matrix_room_id if room is not None else None@@ -2491,6 +2518,7 @@ class ProtocolService:user_store=self.user_store,agent_session_store=self.agent_session_store,room_role_store=self.room_role_store,+ connections=self.connections,)async def update_agent_detail(@@ -2545,6 +2573,7 @@ class ProtocolService:user_store=self.user_store,agent_session_store=self.agent_session_store,room_role_store=self.room_role_store,+ connections=self.connections,)async def get_room_detail(diff --git a/core/switch_core/bridges/agent/protocol/statuses.py b/core/switch_core/bridges/agent/protocol/statuses.pyindex 18b185723..7f5e4b0da 100644--- a/core/switch_core/bridges/agent/protocol/statuses.py+++ b/core/switch_core/bridges/agent/protocol/statuses.py@@ -2,6 +2,7 @@ from __future__ import annotationsfrom sqlalchemy.ext.asyncio import AsyncSession+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.types import AgentStatusfrom switch_core.db.models import Agentfrom switch_core.db.stores.agent_session_store import AgentSessionStore@@ -12,18 +13,34 @@ async def compute_agent_statuses(agents: list[Agent],room_id: str,agent_session_store: AgentSessionStore,+ connections: ConnectionRegistry,) -> dict[str, AgentStatus]:"""Derive each agent's presence status in a room, keyed by agent id.- The status follows the agent's ``connection_model``:+ Presence is the **union of two sources** during the transport migration+ (CHOO-1857):- - ``always_on``: LIVE if it has a live (room-agnostic) session, else- DISCONNECTED.- - ``session_addressable``: LIVE if it has a live session for this room,- else NO_SESSION.- - ``auto_session``: LIVE if it has a live session for this room; else- DORMANT if a connector is actively watching (global "watching"- heartbeat) and will spawn on demand; else DISCONNECTED.+ - the ``agent_sessions`` rows, maintained by clients still polling and+ still sending ``/connection/renew`` and ``/watch/heartbeat``;+ - the live connection registry, which is all a client on the push+ transport maintains — it sends one heartbeat and no renews.++ Neither alone is correct while both kinds of client exist: without the+ connection arm a migrated client reads DISCONNECTED while demonstrably+ alive on its stream, and without the DB arm an un-migrated one does. When+ the old clients are gone the DB arm goes with them, and what remains is the+ connection arm — this is the shape the code keeps, minus one branch.++ ``connections`` is required rather than defaulted: a call site that forgot+ it would report a migrated agent as offline, and that failure is invisible+ at the call site. Pass an empty registry to mean "DB arm only".++ The status then follows the agent's ``connection_model``:++ - ``always_on``: LIVE if reachable at all, else DISCONNECTED.+ - ``session_addressable``: LIVE if reachable in this room, else NO_SESSION.+ - ``auto_session``: LIVE if reachable in this room; else DORMANT if a+ connector is watching and will spawn on demand; else DISCONNECTED.- ``session_passive``: always AWAITING_MANUAL_POLL (no heartbeat).Shared by ProtocolService (room detail / participants) and the in-room@@ -48,8 +65,8 @@ async def compute_agent_statuses(live_always_on = await agent_session_store.get_live_agent_ids(session, always_on_ids, None)- # auto_session agents are LIVE when a session heartbeats for this room,- # and DORMANT when only the global "watching" heartbeat is fresh.+ # auto_session agents are LIVE when something covers this room, and DORMANT+ # when only the room-agnostic "watching" signal is present.live_auto_room = await agent_session_store.get_live_agent_ids(session, auto_session_ids, room_id)@@ -60,6 +77,30 @@ async def compute_agent_statuses(session, addressable_ids, room_id)+ # always_on has no separate notion of a session: any live connection is the+ # agent being up, and its scope is room-agnostic.+ live_always_on |= connections.live_agents(always_on_ids)+ # For the session-shaped models, LIVE means a session is *attending* the+ # room — a claimed room slot. An `all`-scope watcher covers rooms it has+ # not yielded, which is the delivery rule, not presence: treating it as+ # LIVE would report an agent as present in a room where nothing but a+ # watcher is listening, suppressing both the "no session" reply and the+ # auto_session promise to start one.+ live_auto_room |= connections.agents_with_session_in(auto_session_ids, room_id)+ live_addressable |= connections.agents_with_session_in(addressable_ids, room_id)+ # …whereas watching is exactly "has any live connection": that is what the+ # /watch/heartbeat loop used to assert, and what DORMANT means.+ watching_auto |= connections.live_agents(auto_session_ids)+ # A spawn-capable connection covering the room will start a session on+ # demand, whatever the agent was configured as. DORMANT rather than+ # NO_SESSION is the honest report: nothing is attending yet, but something+ # is watching and will be.+ spawn_ready = {+ aid+ for aid in addressable_ids+ if aid not in live_addressable and connections.can_spawn_for(aid, room_id)+ }+statuses: dict[str, AgentStatus] = {}for agent in agents:model = model_by_id[agent.id]@@ -70,11 +111,12 @@ async def compute_agent_statuses(else AgentStatus.DISCONNECTED)elif model == "session_addressable":- statuses[agent.id] = (- AgentStatus.LIVE- if agent.id in live_addressable- else AgentStatus.NO_SESSION- )+ if agent.id in live_addressable:+ statuses[agent.id] = AgentStatus.LIVE+ elif agent.id in spawn_ready:+ statuses[agent.id] = AgentStatus.DORMANT+ else:+ statuses[agent.id] = AgentStatus.NO_SESSIONelif model == "auto_session":if agent.id in live_auto_room:statuses[agent.id] = AgentStatus.LIVEdiff --git a/core/switch_core/bridges/agent/protocol/stream.py b/core/switch_core/bridges/agent/protocol/stream.pynew file mode 100644index 000000000..4cb964b28--- /dev/null+++ b/core/switch_core/bridges/agent/protocol/stream.py@@ -0,0 +1,299 @@+"""Server-sent event stream for agent connections (CHOO-1857).++Turns a connection plus the event buffer into a `text/event-stream`: catch-up+from the client's cursor, then live delivery as events are appended. The client+never asks again — it opens once and reads.++Every event carries its sequence number as the SSE `id`, so a client that+reconnects sends `Last-Event-ID` and resumes exactly where it stopped. Gaps are+reported as their own event rather than skipped: a client that has missed+events must never see a stream that looks complete.+"""++from __future__ import annotations++import asyncio+import json+import logging+import time+from collections.abc import AsyncIterator+from typing import Any++from switch_core.bridges.agent.protocol.connections import (+ PROTOCOL_VERSION,+ Connection,+ ConnectionRegistry,+)+from switch_core.bridges.agent.protocol.event_buffer import (+ CursorExpiredError,+ EventBuffer,+)++logger = logging.getLogger(__name__)++# How long to wait for an event before writing a keepalive comment. This exists+# only to stop proxies dropping an idle connection — liveness comes from the+# client's heartbeat, never from this.+KEEPALIVE_INTERVAL_SECONDS = 15.0++# Cap on how many buffered events are written in one batch, so a large catch-up+# cannot monopolise the loop.+CATCH_UP_BATCH = 200+++def _frame(event: str, data: dict[str, Any], *, seq: int | None = None) -> bytes:+ lines = []+ if seq is not None:+ lines.append(f"id: {seq}")+ lines.append(f"event: {event}")+ lines.append(f"data: {json.dumps(data, separators=(',', ':'))}")+ return ("\n".join(lines) + "\n\n").encode()+++def _connection_state(conn: Connection) -> dict[str, Any]:+ return {+ "connection_id": conn.id,+ "agent_id": conn.agent_id,+ "scope": conn.scope,+ "filter": conn.delivery_filter,+ "spawn_capable": conn.spawn_capable,+ "rooms": sorted(conn.rooms),+ "cursor": conn.cursor,+ "protocol": PROTOCOL_VERSION,+ "heartbeat_interval_seconds": 2.0,+ }+++async def event_stream(+ *,+ conn: Connection,+ registry: ConnectionRegistry,+ buffer: EventBuffer,+) -> AsyncIterator[bytes]:+ """Yield SSE frames for a connection until its stream is superseded or it dies."""+ generation = conn.stream_generation+ agent_id = conn.agent_id+ bell = buffer.doorbell(agent_id)+ # Captured before the first yield: the generator suspends there, and any+ # subscription change that lands while it is suspended must still be+ # reported when it resumes.+ last_rooms = set(conn.rooms)++ try:+ yield _frame("connection_state", _connection_state(conn))++ # A cursor ahead of everything we hold is a cursor from a previous+ # life of this process: the buffer is in memory, so a restart resets+ # the sequence. Say so. Staying quiet would leave the client believing+ # it is caught up when its numbering no longer means anything.+ head = buffer.head(agent_id)+ if conn.cursor > head:+ logger.warning(+ "[STREAM] agent=%s connection=%s resumed from cursor %s but the "+ "buffer only reaches %s — treating as a restart",+ agent_id,+ conn.id,+ conn.cursor,+ head,+ )+ conn.cursor = head+ yield _frame(+ "gap",+ {+ "from_sequence": head,+ "resumed_at": head,+ "reason": "the server restarted since your last connection; "+ "sequence numbers have been reset and events from before "+ "the restart are gone — re-read room context",+ },+ )++ # A cursor the buffer can no longer serve is reported, not silently+ # moved to head. The client re-reads room context to recover.+ if buffer.has_gap_before(agent_id, conn.cursor):+ oldest = buffer.oldest_retained(agent_id)+ logger.warning(+ "[STREAM] agent=%s connection=%s resumed from expired cursor %s "+ "(oldest retained %s)",+ agent_id,+ conn.id,+ conn.cursor,+ oldest,+ )+ resumed_at = max(oldest - 1, 0)+ conn.cursor = resumed_at+ yield _frame(+ "gap",+ {+ "from_sequence": conn.cursor,+ "resumed_at": resumed_at,+ "reason": "events older than the retention window were "+ "dropped; re-read room context",+ },+ )++ while True:+ if conn.stream_generation != generation:+ # Another stream took this connection over.+ yield _frame(+ "evicted",+ {"reason": "another stream attached to this connection"},+ )+ return+ if conn.closed_reason is not None:+ yield _frame("evicted", {"reason": conn.closed_reason})+ return+ if not conn.is_alive(time.monotonic()):+ # Delivering to a connection whose heartbeat has lapsed is the+ # worst of both worlds: every presence reader treats it as dead+ # (they filter on liveness), so the agent is reported offline+ # while its socket keeps handing it events. That combination is+ # invisible from either side — the client sees traffic and+ # believes it is fine, the room is told nobody is home.+ logger.warning(+ "[STREAM] agent=%s connection=%s heartbeat lapsed — closing "+ "the stream rather than delivering to a connection nothing "+ "else considers alive",+ agent_id,+ conn.id,+ )+ registry.close(conn.id, "heartbeat lapsed")+ yield _frame(+ "evicted",+ {+ "reason": "heartbeat lapsed; reopen the stream and resume "+ "from your cursor"+ },+ )+ return++ if conn.rooms != last_rooms:+ last_rooms = set(conn.rooms)+ yield _frame(+ "subscription_changed",+ {"rooms": sorted(last_rooms), "reason": "subscription updated"},+ )++ if conn.scope == "single" and not conn.rooms:+ # A session connection that has not claimed a room yet must not+ # read. It would find every event uncovered — it covers nothing+ # — and the skip path advances the cursor, so it would consume+ # its way to the end of the buffer while waiting for its room.+ #+ # That window is not an edge case: a session spawned to answer a+ # message opens its connection *before* the session boots and+ # calls connect_to_room. Reading during it burns past the very+ # message the session was started for, which then never arrives.+ #+ # Park until a room is claimed. `claim_room` sets `wake`, so the+ # loop resumes the moment there is something to cover, with the+ # cursor still where it started.+ conn.wake.clear()+ if not conn.rooms and not await _wait_for_wake(conn):+ yield b": keepalive\n\n"+ continue++ try:+ pending = buffer.read_from(+ agent_id,+ conn.cursor,+ notifiable_only=conn.delivery_filter == "addressed",+ limit=CATCH_UP_BATCH,+ )+ except CursorExpiredError as exc:+ yield _frame(+ "gap",+ {+ "from_sequence": exc.requested,+ "resumed_at": max(exc.oldest - 1, 0),+ "reason": str(exc),+ },+ )+ conn.cursor = max(exc.oldest - 1, 0)+ continue++ if not pending:+ # Nothing above the cursor is for this connection: the filter+ # excluded all of it. Advance past it anyway.+ #+ # `read_from` does not return filtered-out events, so the cursor+ # cannot advance through them the way it does for events skipped+ # by room coverage below. Leaving it behind them makes the+ # "anything new?" re-check further down permanently true, and+ # this loop spins at full speed instead of waiting — starving the+ # event loop, so no heartbeat is processed, so every connection+ # in the process is declared dead and reconnects, forever.+ #+ # An empty result means the scan reached the end without hitting+ # the batch limit, so head is exactly how far we have looked.+ head = buffer.head(agent_id)+ if head > conn.cursor:+ conn.cursor = head++ delivered = False+ for item in pending:+ # Room coverage is evaluated per event rather than up front: a+ # sibling claiming a room must take effect immediately, without+ # tearing the stream down.+ if not registry.covers(conn, item.room_id):+ conn.cursor = item.seq+ continue+ payload = item.event.model_dump(mode="json")+ payload["sequence"] = item.seq+ # Advance before yielding: the cursor tracks what the server has+ # written out. What the client has actually processed comes back+ # on its heartbeat, which is the value that governs resume.+ conn.cursor = item.seq+ delivered = True+ yield _frame(item.event.type, payload, seq=item.seq)++ if delivered:+ continue++ bell.clear()+ conn.wake.clear()+ # Re-check after clearing: an event appended between the read above+ # and the clear would otherwise wait for the keepalive timeout.+ if buffer.head(agent_id) > conn.cursor or conn.rooms != last_rooms:+ continue++ if not await _wait_for_work(bell, conn):+ yield b": keepalive\n\n"+ finally:+ registry.detach_stream(conn.id, generation)+++async def _wait_for_wake(conn: Connection) -> bool:+ """Wait for the connection itself to change — a room claim, or a close.++ Deliberately not waiting on the event bell: a parked connection covers+ nothing, so new events are not news to it, and waking for each one would+ spin through a busy room for no reason.+ """+ try:+ await asyncio.wait_for(conn.wake.wait(), timeout=KEEPALIVE_INTERVAL_SECONDS)+ return True+ except TimeoutError:+ return False+++async def _wait_for_work(bell: asyncio.Event, conn: Connection) -> bool:+ """Wait for a new event or a change to the connection itself.++ Returns False when neither happened before the keepalive interval, so the+ caller can write a comment and keep the socket warm.+ """+ waiters = [+ asyncio.ensure_future(bell.wait()),+ asyncio.ensure_future(conn.wake.wait()),+ ]+ try:+ done, _ = await asyncio.wait(+ waiters,+ timeout=KEEPALIVE_INTERVAL_SECONDS,+ return_when=asyncio.FIRST_COMPLETED,+ )+ return bool(done)+ finally:+ for waiter in waiters:+ waiter.cancel()diff --git a/core/switch_core/clients/admin_client.py b/core/switch_core/clients/admin_client.pyindex 64d1495b9..41909fd1d 100644--- a/core/switch_core/clients/admin_client.py+++ b/core/switch_core/clients/admin_client.py@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Any, Literalfrom nio import MatrixRoom, RoomMessage, RoomMessageTextfrom switch_core.bridges.agent.commands import dispatch_admin_command+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.clients.admin_messages import (ADMIN_MARKER,AdminMessageType,@@ -53,6 +54,7 @@ class AdminClient(ClientBase[ClientConfig]):agent_store: AgentStore,room_store: RoomStore,room_role_store: RoomRoleStore,+ connections: ConnectionRegistry,document_store: DocumentStore,reference_store: ReferenceStore,agent_session_store: AgentSessionStore,@@ -64,6 +66,7 @@ class AdminClient(ClientBase[ClientConfig]):self._agent_store = agent_storeself._room_store = room_storeself._room_role_store = room_role_store+ self._connections = connectionsself._document_store = document_storeself._reference_store = reference_storeself._agent_session_store = agent_session_store@@ -145,7 +148,9 @@ class AdminClient(ClientBase[ClientConfig]):for role in roles:if mention_regex(role.name).search(strip_emphasis(body)) is None:continue- if not await self._room_role_store.has_live_holder(session, role.id):+ if not await self._room_role_store.has_live_holder(+ session, role.id, self._connections.live_agent_ids()+ ):unreachable.append(role.name)handle = self._sender_handle(event)for name in unreachable:diff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.pyindex 72c48151a..e8215d78d 100644--- a/core/switch_core/clients/agent_client.py+++ b/core/switch_core/clients/agent_client.py@@ -24,7 +24,8 @@ from switch_core.bridges.agent.commands import (_addressed_by_name_or_role,dispatch_command,)-from switch_core.bridges.agent.protocol.event_queue import EventQueue+from switch_core.bridges.agent.protocol.connections import ConnectionRegistry+from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.types import (AgentEvent,AttachmentRef,@@ -178,7 +179,7 @@ class AgentClient(ClientBase[ClientConfig]):def __init__(self,*,- event_queue: EventQueue,+ event_buffer: EventBuffer,agent_store: AgentStore,room_store: RoomStore,bridge_store: CollaborationBridgeStore,@@ -189,11 +190,12 @@ class AgentClient(ClientBase[ClientConfig]):external_user_store: ExternalUserStore,request_tracker: RequestTracker,resource_request_tracker: ResourceRequestTracker,+ connections: ConnectionRegistry,frontend_base_url: str | None,**kwargs: object,) -> None:super().__init__(**kwargs) # type: ignore[arg-type]- self._event_queue = event_queue+ self._event_buffer = event_bufferself._agent_store = agent_storeself._room_store = room_storeself._bridge_store = bridge_store@@ -204,6 +206,7 @@ class AgentClient(ClientBase[ClientConfig]):self._external_user_store = external_user_storeself._request_tracker = request_trackerself._resource_request_tracker = resource_request_tracker+ self._connections = connectionsself._frontend_base_url = (frontend_base_url.rstrip("/") if frontend_base_url else None)@@ -289,7 +292,7 @@ class AgentClient(ClientBase[ClientConfig]):listening = await self._room_store.get_receives_join_events(session, meta.room_id, self.agent.id)- self._event_queue.enqueue(+ self._event_buffer.enqueue(self.agent.id,meta.room_id,AgentEvent(@@ -370,7 +373,7 @@ class AgentClient(ClientBase[ClientConfig]):)logger.debug("Enqueuing event %s", agent_event.model_dump_json(indent=2))- self._event_queue.enqueue(+ self._event_buffer.enqueue(self.agent.id,meta.room_id,agent_event,@@ -569,7 +572,7 @@ class AgentClient(ClientBase[ClientConfig]):)logger.debug("Enqueuing media event %s", agent_event.model_dump_json(indent=2))- self._event_queue.enqueue(+ self._event_buffer.enqueue(self.agent.id,meta.room_id,agent_event,@@ -597,7 +600,7 @@ class AgentClient(ClientBase[ClientConfig]):if handled:return- self._event_queue.enqueue(+ self._event_buffer.enqueue(self.agent.id,meta.room_id,AgentEvent(@@ -690,21 +693,40 @@ class AgentClient(ClientBase[ClientConfig]):# it will spin a session up to handle this — promise that rather than# the "elsewhere"/offline wording. With no watcher, fall through to the# generic offline reply below.+ # A live connection that declared itself spawn-capable and covers this+ # room WILL start a session, whatever the agent's configured model says.+ # Keying the promise off the observed capability rather than the enum+ # means a mis-set (or merely stale) connection_model can no longer+ # produce "my connector isn't reporting in" while a watcher is sitting+ # right there, connected, about to spawn.+ if self._connections.can_spawn_for(self.agent.id, meta.room_id):+ return _STARTING_SESSION_MESSAGE+if connection_model == "auto_session":async with self.session_factory() as session:watching = await self._agent_session_store.get_live_agent_ids(session, [self.agent.id], None)- if self.agent.id in watching:+ if self.agent.id in watching or self._connections.is_live(self.agent.id):return _STARTING_SESSION_MESSAGEasync with self.session_factory() as session:room_ids = await self._agent_session_store.live_connected_rooms(session, self.agent.id)+ # A connection covering a room is a session in it, whether or not+ # anything wrote an agent_sessions row for it.+ room_ids = sorted(+ set(room_ids)+ | {+ room+ for conn in self._connections.for_agent(self.agent.id)+ for room in conn.rooms+ }+ )bound_here = await self._agent_session_store.has_room_binding(session, self.agent.id, meta.room_id- )+ ) or self._connections.has_session_in(self.agent.id, meta.room_id)names: list[str] = []holds_role_here = Falseother_room_ids = [rid for rid in room_ids if rid != meta.room_id]@@ -716,7 +738,10 @@ class AgentClient(ClientBase[ClientConfig]):names.append(name)holds_role_here = (await self._room_role_store.agent_room_role(- session, meta.room_id, self.agent.id+ session,+ meta.room_id,+ self.agent.id,+ self._connections.live_agent_ids(),)is not None)@@ -795,6 +820,17 @@ class AgentClient(ClientBase[ClientConfig]):)if connection_model == "session_passive":return False+ # Union of the two presence sources while both kinds of client exist+ # (CHOO-1857 stage B): a client on the push transport keeps only a+ # connection, one still polling keeps only the heartbeat row.+ if connection_model == "always_on":+ if self._connections.is_live(self.agent.id):+ return True+ elif self._connections.has_session_in(self.agent.id, room_id):+ # A claimed room slot, not mere coverage: an `all`-scope watcher+ # covering this room is not a session that can answer.+ return True+heartbeat_room = None if connection_model == "always_on" else room_idasync with self.session_factory() as session:live = await self._agent_session_store.get_live_agent_ids(@@ -815,7 +851,7 @@ class AgentClient(ClientBase[ClientConfig]):meta = await self._resolve_room_meta(room.room_id)if meta is None:return- self._event_queue.enqueue(+ self._event_buffer.enqueue(self.agent.id,meta.room_id,AgentEvent(@@ -839,7 +875,7 @@ class AgentClient(ClientBase[ClientConfig]):meta = await self._resolve_room_meta(room.room_id)if meta is None:return- self._event_queue.enqueue(+ self._event_buffer.enqueue(self.agent.id,meta.room_id,AgentEvent(@@ -861,7 +897,7 @@ class AgentClient(ClientBase[ClientConfig]):meta = await self._resolve_room_meta(room.room_id)if meta is None:return- self._event_queue.enqueue(+ self._event_buffer.enqueue(self.agent.id,meta.room_id,AgentEvent(@@ -884,7 +920,7 @@ class AgentClient(ClientBase[ClientConfig]):meta = await self._resolve_room_meta(room.room_id)if meta is None:return- self._event_queue.enqueue(+ self._event_buffer.enqueue(self.agent.id,meta.room_id,AgentEvent(@@ -907,7 +943,7 @@ class AgentClient(ClientBase[ClientConfig]):meta = await self._resolve_room_meta(room.room_id)if meta is None:return- self._event_queue.enqueue(+ self._event_buffer.enqueue(self.agent.id,meta.room_id,AgentEvent(@@ -1132,7 +1168,7 @@ class AgentClient(ClientBase[ClientConfig]):return Falseasync with self.session_factory() as session:role_name = await self._room_role_store.agent_room_role(- session, room_id, self.agent.id+ session, room_id, self.agent.id, self._connections.live_agent_ids())if not role_name:return Falsediff --git a/core/switch_core/db/stores/room_role_store.py b/core/switch_core/db/stores/room_role_store.pyindex 5f221501c..8ac8ad90c 100644--- a/core/switch_core/db/stores/room_role_store.py+++ b/core/switch_core/db/stores/room_role_store.py@@ -10,10 +10,12 @@ argument and never commits (the caller owns the transaction), mirroring`AgentSessionStore`."""+from collections.abc import Collectionfrom datetime import UTC, datetime, timedelta-from sqlalchemy import delete, select, update+from sqlalchemy import delete, or_, select, updatefrom sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.sql.elements import ColumnElementfrom switch_core.db.models import RoleLease, RoomRole@@ -112,8 +114,29 @@ class RoomRoleStore:def _cutoff(self) -> datetime:return datetime.now(UTC) - self.LEASE_TTL+ def _live(self, alive_agent_ids: Collection[str]) -> ColumnElement[bool]:+ """SQL predicate for "this lease is still held".++ A lease is live if its heartbeat is fresh **or** its agent has a live+ connection (CHOO-1857 stage B). Both arms are needed while both kinds+ of client exist: a client on the push transport sends one connection+ heartbeat and no `/leases/renew`, so the freshness arm alone would drop+ its role within the TTL; a client still polling has only that arm.++ `alive_agent_ids` comes from the connection registry and defaults to+ empty, which means "freshness only" — today's behaviour for any caller+ that has no registry to hand.+ """+ fresh = RoleLease.last_seen_at > self._cutoff()+ if not alive_agent_ids:+ return fresh+ return or_(fresh, RoleLease.agent_id.in_(list(alive_agent_ids)))+async def get_live_lease(- self, session: AsyncSession, role_id: str+ self,+ session: AsyncSession,+ role_id: str,+ alive_agent_ids: Collection[str] = (),) -> RoleLease | None:"""Return the live lease on an *exclusive* `role_id`, or None if free.@@ -125,28 +148,36 @@ class RoomRoleStore:result = await session.execute(select(RoleLease).where(RoleLease.role_id == role_id)- .where(RoleLease.last_seen_at > self._cutoff())+ .where(self._live(alive_agent_ids)))return result.scalar_one_or_none()- async def has_live_holder(self, session: AsyncSession, role_id: str) -> bool:+ async def has_live_holder(+ self,+ session: AsyncSession,+ role_id: str,+ alive_agent_ids: Collection[str] = (),+ ) -> bool:"""True if at least one live lease holds `role_id` (any exclusivity)."""result = await session.execute(select(RoleLease.id).where(RoleLease.role_id == role_id)- .where(RoleLease.last_seen_at > self._cutoff())+ .where(self._live(alive_agent_ids)).limit(1))return result.first() is not Noneasync def get_agent_live_lease(- self, session: AsyncSession, agent_id: str+ self,+ session: AsyncSession,+ agent_id: str,+ alive_agent_ids: Collection[str] = (),) -> RoleLease | None:"""Return the agent's live lease (across any room), or None."""result = await session.execute(select(RoleLease).where(RoleLease.agent_id == agent_id)- .where(RoleLease.last_seen_at > self._cutoff())+ .where(self._live(alive_agent_ids)))return result.scalar_one_or_none()@@ -164,7 +195,10 @@ class RoomRoleStore:return result.scalar_one_or_none()async def live_holders_for_room(- self, session: AsyncSession, room_id: str+ self,+ session: AsyncSession,+ room_id: str,+ alive_agent_ids: Collection[str] = (),) -> dict[str, list[str]]:"""Map role_id → live holder agent_ids for the room.@@ -174,7 +208,7 @@ class RoomRoleStore:result = await session.execute(select(RoleLease.role_id, RoleLease.agent_id).where(RoleLease.room_id == room_id)- .where(RoleLease.last_seen_at > self._cutoff())+ .where(self._live(alive_agent_ids)))holders: dict[str, list[str]] = {}for role_id, agent_id in result.all():@@ -182,7 +216,10 @@ class RoomRoleStore:return holdersasync def live_leases_for_room(- self, session: AsyncSession, room_id: str+ self,+ session: AsyncSession,+ room_id: str,+ alive_agent_ids: Collection[str] = (),) -> dict[str, list[RoleLease]]:"""Map role_id → live lease rows for the room.@@ -193,7 +230,7 @@ class RoomRoleStore:result = await session.execute(select(RoleLease).where(RoleLease.room_id == room_id)- .where(RoleLease.last_seen_at > self._cutoff())+ .where(self._live(alive_agent_ids)))leases: dict[str, list[RoleLease]] = {}for lease in result.scalars().all():@@ -201,7 +238,11 @@ class RoomRoleStore:return leasesasync def agent_room_role(- self, session: AsyncSession, room_id: str, agent_id: str+ self,+ session: AsyncSession,+ room_id: str,+ agent_id: str,+ alive_agent_ids: Collection[str] = (),) -> str | None:"""Return the role NAME the agent currently (live) holds in the room."""result = await session.execute(@@ -209,7 +250,7 @@ class RoomRoleStore:.join(RoleLease, RoleLease.role_id == RoomRole.id).where(RoleLease.room_id == room_id).where(RoleLease.agent_id == agent_id)- .where(RoleLease.last_seen_at > self._cutoff())+ .where(self._live(alive_agent_ids)))return result.scalar_one_or_none()@@ -219,6 +260,7 @@ class RoomRoleStore:role: RoomRole,agent_id: str,transport_session_id: str | None,+ alive_agent_ids: Collection[str] = (),) -> RoleLease:"""Acquire the lease on `role` for `agent_id`.@@ -230,7 +272,7 @@ class RoomRoleStore:now = datetime.now(UTC)# Reject if the agent already holds a *live* lease (one lease per session).- existing = await self.get_agent_live_lease(session, agent_id)+ existing = await self.get_agent_live_lease(session, agent_id, alive_agent_ids)if existing is not None:if existing.role_id == role.id:# Idempotent re-assume of the same role: just refresh.@@ -249,7 +291,7 @@ class RoomRoleStore:)if role.exclusive:- holder = await self.get_live_lease(session, role.id)+ holder = await self.get_live_lease(session, role.id, alive_agent_ids)if holder is not None and holder.agent_id != agent_id:raise ValueError(f"Role '{role.name}' is exclusive and currently held by another agent"diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.pyindex e3d53b797..5f0749c6c 100644--- a/core/switch_core/gateway/agents.py+++ b/core/switch_core/gateway/agents.py@@ -422,6 +422,7 @@ async def update_addressing_policy(user_store=user_store,agent_session_store=protocol.agent_session_store,room_role_store=protocol.room_role_store,+ connections=protocol.connections,)@@ -449,4 +450,5 @@ async def get_agent_detail(user_store=user_store,agent_session_store=protocol.agent_session_store,room_role_store=protocol.room_role_store,+ connections=protocol.connections,)diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex ade20bf79..ab24b4e3c 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom fastapi import FastAPIfrom starlette.middleware.sessions import SessionMiddleware-from switch_core.bridges.agent.protocol.event_queue import EventQueue+from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.server_connectors.lifecycle import (ServerSideConnectorLifecycleService,@@ -51,7 +51,7 @@ def create_gateway_app(collab_lifecycle: CollaborationBridgeLifecycleService,connector_lifecycle: ServerSideConnectorLifecycleService,connector_store: ServerConnectorStore,- event_queue: EventQueue,+ event_buffer: EventBuffer,session_factory: object,user_store: UserStore,external_user_store: ExternalUserStore,@@ -70,7 +70,7 @@ def create_gateway_app(collab_lifecycle=collab_lifecycle,connector_lifecycle=connector_lifecycle,connector_store=connector_store,- event_queue=event_queue,+ event_buffer=event_buffer,session_factory=session_factory,user_store=user_store,external_user_store=external_user_store,diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.pyindex a87f140df..5858cdab3 100644--- a/core/switch_core/gateway/dependencies.py+++ b/core/switch_core/gateway/dependencies.py@@ -5,7 +5,7 @@ from typing import Anyfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.bridges.agent.protocol.event_queue import EventQueue+from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.server_connectors.lifecycle import (ServerSideConnectorLifecycleService,@@ -41,7 +41,7 @@ def init_dependencies(collab_lifecycle: CollaborationBridgeLifecycleService,connector_lifecycle: ServerSideConnectorLifecycleService,connector_store: ServerConnectorStore,- event_queue: EventQueue,+ event_buffer: EventBuffer,session_factory: Any,user_store: UserStore,external_user_store: ExternalUserStore,@@ -59,7 +59,7 @@ def init_dependencies(_state["collab_lifecycle"] = collab_lifecycle_state["connector_lifecycle"] = connector_lifecycle_state["connector_store"] = connector_store- _state["event_queue"] = event_queue+ _state["event_buffer"] = event_buffer_state["session_factory"] = session_factory_state["user_store"] = user_store_state["external_user_store"] = external_user_store@@ -120,8 +120,8 @@ def get_collab_lifecycle() -> CollaborationBridgeLifecycleService:return _state["collab_lifecycle"] # type: ignore[no-any-return]-def get_event_queue() -> EventQueue:- return _state["event_queue"] # type: ignore[no-any-return]+def get_event_buffer() -> EventBuffer:+ return _state["event_buffer"] # type: ignore[no-any-return]def get_user_store() -> UserStore:diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.pyindex fb392f954..094d711cf 100644--- a/core/switch_core/gateway/rooms.py+++ b/core/switch_core/gateway/rooms.py@@ -174,7 +174,9 @@ async def _list_room_role_details("""store = protocol.room_role_storeroles = await store.list_roles(session, room_id)- holders = await store.live_holders_for_room(session, room_id)+ holders = await store.live_holders_for_room(+ session, room_id, protocol.connections.live_agent_ids()+ )holder_names: dict[str, str] = {}for holder_id in {h for ids in holders.values() for h in ids}:holder = await protocol.agent_store.get(session, holder_id)diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 7bf123919..94cc26f5c 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -5,6 +5,7 @@ import hashlibimport loggingimport osimport signal+import timefrom collections.abc import AsyncIteratorfrom contextlib import asynccontextmanagerfrom pathlib import Path@@ -15,7 +16,11 @@ from alembic.config import Config as AlembicConfigfrom fastapi.responses import JSONResponsefrom switch_core.bridges.agent.app import create_agent_bridge_app-from switch_core.bridges.agent.protocol.event_queue import EventQueue+from switch_core.bridges.agent.protocol.connections import (+ HEARTBEAT_TTL_SECONDS,+ ConnectionRegistry,+)+from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.request_tracker import RequestTrackerfrom switch_core.bridges.agent.server_connectors.lifecycle import (@@ -90,6 +95,11 @@ logger = logging.getLogger(__name__)# after a session crashes, while staying well above the per-pass DB cost._RUNTIME_STATE_SWEEP_INTERVAL = 5.0+# How often to close connections whose heartbeat has lapsed. Kept well under+# the heartbeat TTL so a dead connection's room slot and role lease are freed+# promptly rather than at the next unrelated request.+_CONNECTION_SWEEP_INTERVAL = 2.0+async def _runtime_state_sweep_loop(protocol: ProtocolService) -> None:while True:@@ -100,6 +110,42 @@ async def _runtime_state_sweep_loop(protocol: ProtocolService) -> None:logger.exception("Runtime-state sweep failed")+async def _connection_sweep_loop(protocol: ProtocolService) -> None:+ """Expire connections whose client has stopped beating.++ Skips a round after the event loop has been blocked. A stall stops us+ *processing* heartbeats, so every connection looks lapsed at once through no+ fault of its client — and expiring them all drops their room slots and role+ leases, then every client reconnects together, which is a worse stall. The+ clients were never given the chance to beat, so the honest reading is "we+ were not listening", not "they went away".+ """+ while True:+ started = time.monotonic()+ await asyncio.sleep(_CONNECTION_SWEEP_INTERVAL)+ overslept = (time.monotonic() - started) - _CONNECTION_SWEEP_INTERVAL+ if overslept > HEARTBEAT_TTL_SECONDS / 2:+ logger.warning(+ "Connection sweep skipped: the event loop was blocked for %.1fs, "+ "so heartbeats could not be processed and every connection would "+ "look lapsed. Something is blocking the loop — that is the bug, "+ "not the connections.",+ overslept,+ )+ continue+ try:+ for conn in protocol.connections.sweep():+ logger.info(+ "Connection %s for agent %s expired (heartbeat lapsed, "+ "%d beats received)",+ conn.id,+ conn.agent_id,+ conn.beats,+ )+ except Exception:+ logger.exception("Connection sweep failed")++logging.getLogger("httpx").setLevel(logging.WARNING)logging.getLogger("nio.rooms").setLevel(logging.ERROR)logging.getLogger("nio.client.base_client").setLevel(logging.WARNING)@@ -166,7 +212,7 @@ async def run() -> None:)# ── Event queue + request trackers ───────────────────────────────────────- event_queue = EventQueue()+ event_buffer = EventBuffer()request_tracker = RequestTracker()resource_request_tracker = ResourceRequestTracker()connector_store = ServerConnectorStore()@@ -180,6 +226,12 @@ async def run() -> None:session_factory=session_factory,)+ # One connection registry for the process. Created here rather than inside+ # the agent bridge because the Matrix agent clients are wired first and read+ # presence from it — an agent is reachable if it has a live connection OR a+ # fresh heartbeat row (CHOO-1857 stage B).+ connections = ConnectionRegistry()+# ── Client factory ───────────────────────────────────────────────────────client_factory = ClientFactory(client_store=client_store,@@ -189,7 +241,7 @@ async def run() -> None:client_factory.register("agent",AgentClient,- event_queue=event_queue,+ event_buffer=event_buffer,agent_store=agent_store,room_store=room_store,bridge_store=bridge_store,@@ -200,6 +252,7 @@ async def run() -> None:external_user_store=external_user_store,request_tracker=request_tracker,resource_request_tracker=resource_request_tracker,+ connections=connections,frontend_base_url=config.frontend_base_url,)client_factory.register(@@ -263,6 +316,7 @@ async def run() -> None:reference_store=reference_store,agent_session_store=agent_session_store,room_service=room_service,+ connections=connections,frontend_base_url=config.frontend_base_url,)@@ -274,7 +328,7 @@ async def run() -> None:room_service=room_service,client_lifecycle=client_lifecycle,collab_lifecycle=collab_lifecycle,- event_queue=event_queue,+ event_buffer=event_buffer,task_store=task_store,request_tracker=request_tracker,resource_request_tracker=resource_request_tracker,@@ -284,6 +338,7 @@ async def run() -> None:bridge_store=bridge_store,session_factory=session_factory,config=config,+ connections=connections,)collab_bridge_app = create_collaboration_bridge_app(bridge_store=bridge_store,@@ -314,7 +369,7 @@ async def run() -> None:collab_lifecycle=collab_lifecycle,connector_lifecycle=connector_lifecycle,connector_store=connector_store,- event_queue=event_queue,+ event_buffer=event_buffer,session_factory=session_factory,user_store=user_store,external_user_store=external_user_store,@@ -354,10 +409,14 @@ async def run() -> None:async with original_lifespan(app): # type: ignore[arg-type]asyncio.create_task(connector_lifecycle.start_all())sweep_task = asyncio.create_task(_runtime_state_sweep_loop(protocol))+ connection_sweep_task = asyncio.create_task(+ _connection_sweep_loop(protocol)+ )try:yieldfinally:sweep_task.cancel()+ connection_sweep_task.cancel()agent_bridge_app.router.lifespan_context = lifespan # type: ignore[assignment]diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex 6d35a64da..9eaff31df 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -3,7 +3,7 @@Unlike the unit suite (which fakes the nio client), these fixtures boot a realMatrix homeserver and wire up the subset of `switch_core.main:run()` the featureunder test needs, in-process. This lets a test drive the genuine path-RoomService → Matrix invite/join → AgentClient sync loop → EventQueue.+RoomService → Matrix invite/join → AgentClient sync loop → EventBuffer.The two containers mirror the `postgres` / `tuwunel` services in`deploy/local/docker-compose.yml` (see constants below — keep in sync). They get@@ -40,7 +40,7 @@ from testcontainers.postgres import PostgresContainer# Importing models registers every table on Base.metadata for create_all.import switch_core.db.models # noqa: F401-from switch_core.bridges.agent.protocol.event_queue import EventQueue+from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import (IntegrationProfile,@@ -247,7 +247,7 @@ class Harness:Holds the real services and exposes the few operations a test needs:register agents, start their Matrix sync clients, and reach the RoomService- / EventQueue.+ / EventBuffer."""def __init__(@@ -257,7 +257,7 @@ class Harness:room_service: RoomService,client_lifecycle: ClientLifecycleService,room_store: RoomStore,- event_queue: EventQueue,+ event_buffer: EventBuffer,owner_id: str,session_factory: object,) -> None:@@ -265,7 +265,7 @@ class Harness:self.room_service = room_serviceself.client_lifecycle = client_lifecycleself.room_store = room_store- self.event_queue = event_queue+ self.event_buffer = event_bufferself.owner_id = owner_idself.session_factory = session_factoryself._registered: list[str] = []@@ -424,9 +424,9 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:await session.commit()owner_id = owner.id- # Per-test in-memory wiring: a fresh EventQueue / client registry so queued+ # Per-test in-memory wiring: a fresh EventBuffer / client registry so queued# events and client registrations never leak across tests.- event_queue = EventQueue()+ event_buffer = EventBuffer()request_tracker = RequestTracker()resource_request_tracker = ResourceRequestTracker()collab_lifecycle = _NoBridges()@@ -447,7 +447,7 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:client_factory.register("agent",AgentClient,- event_queue=event_queue,+ event_buffer=event_buffer,agent_store=session_env.agent_store,room_store=session_env.room_store,bridge_store=session_env.bridge_store,@@ -487,7 +487,7 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:room_service=room_service,client_lifecycle=client_lifecycle,collab_lifecycle=collab_lifecycle, # type: ignore[arg-type]- event_queue=event_queue,+ event_buffer=event_buffer,task_store=session_env.task_store,request_tracker=request_tracker,resource_request_tracker=resource_request_tracker,@@ -504,7 +504,7 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:room_service=room_service,client_lifecycle=client_lifecycle,room_store=session_env.room_store,- event_queue=event_queue,+ event_buffer=event_buffer,owner_id=owner_id,session_factory=session_factory,)diff --git a/core/tests/integration/test_room_join_e2e.py b/core/tests/integration/test_room_join_e2e.pyindex c30606865..6958e6d9f 100644--- a/core/tests/integration/test_room_join_e2e.py+++ b/core/tests/integration/test_room_join_e2e.py@@ -2,7 +2,7 @@Drives the genuine path: RoomService adds an agent to a room → Matrix invite →the watcher's AgentClient sync loop receives the join → on_member_event enqueues-a `room_join` AgentEvent → it is read off the EventQueue. No mocks, no HTTP layer.+a `room_join` AgentEvent → it is read off the event buffer. No mocks, no HTTP layer."""from __future__ import annotations@@ -39,7 +39,7 @@ async def _drain_room_join(deadline = asyncio.get_event_loop().time() + timeoutwhile asyncio.get_event_loop().time() < deadline:remaining = deadline - asyncio.get_event_loop().time()- events = await harness.event_queue.poll_room(+ events = await harness.event_buffer.poll_room(agent_id, room_id, timeout=min(5, max(0.1, remaining)))for ev in events:diff --git a/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py b/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.pynew file mode 100644index 000000000..7cedef2c0--- /dev/null+++ b/core/tests/switch_core/bridges/agent/api/test_events_endpoint_dispatch.py@@ -0,0 +1,206 @@+"""The /events endpoint serves both transports off one path (CHOO-1857).++`Accept: text/event-stream` opens a connection and streams; anything else gets+the long poll. Both read the same buffer, so the two cannot diverge while they+coexist — but the dispatch itself is easy to break silently, hence these.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest+from fastapi import HTTPException+from starlette.responses import StreamingResponse++from switch_core.bridges.agent.api.handlers import _resolve_start_cursor, poll_events+from switch_core.bridges.agent.protocol.connections import (+ PROTOCOL_VERSION,+ ConnectionRegistry,+)+from switch_core.bridges.agent.protocol.event_buffer import EventBuffer++AGENT_ID = "agent-1"+++class _Protocol:+ def __init__(self) -> None:+ self.event_buffer = EventBuffer()+ self.connections = ConnectionRegistry()+ self.polled = False++ async def poll_events(self, agent_id: str, timeout: float) -> list[Any]:+ self.polled = True+ return []++ async def require_room_member(self, agent_id: str, room_id: str) -> None:+ return None+++def _agent() -> Any:+ return SimpleNamespace(id=AGENT_ID)+++async def _call(protocol: _Protocol, **kw: Any) -> Any:+ params: dict[str, Any] = {+ "agent_id": AGENT_ID,+ "agent": _agent(),+ "protocol": protocol,+ "timeout": 0,+ "accept": None,+ "connection_id": None,+ "scope": "single",+ "event_filter": "all",+ "start_from": "head",+ "spawn_capable": False,+ "protocol_version": PROTOCOL_VERSION,+ "rooms": None,+ "last_event_id": None,+ }+ params.update(kw)+ return await poll_events(**params)+++async def test_without_the_sse_accept_header_it_long_polls() -> None:+ protocol = _Protocol()+ resp = await _call(protocol, accept="application/json")++ assert protocol.polled+ assert resp.status_code == 204+++async def test_with_the_sse_accept_header_it_opens_a_connection() -> None:+ protocol = _Protocol()+ resp = await _call(+ protocol, accept="text/event-stream", connection_id="c1", scope="all"+ )++ assert isinstance(resp, StreamingResponse)+ assert resp.media_type == "text/event-stream"+ # Buffering proxies would defeat the point of a push channel.+ assert resp.headers["x-accel-buffering"] == "no"+ assert not protocol.polled++ conn = protocol.connections.get("c1")+ assert conn is not None+ assert conn.scope == "all"+++async def test_streaming_without_a_connection_id_is_refused() -> None:+ protocol = _Protocol()+ with pytest.raises(HTTPException) as excinfo:+ await _call(protocol, accept="text/event-stream")++ assert excinfo.value.status_code == 400+ assert "connection_id is required" in excinfo.value.detail+++ ("field", "value"),+ [("scope", "everything"), ("event_filter", "some")],+)+async def test_bad_scope_or_filter_is_refused(field: str, value: str) -> None:+ protocol = _Protocol()+ with pytest.raises(HTTPException) as excinfo:+ await _call(+ protocol, accept="text/event-stream", connection_id="c1", **{field: value}+ )++ assert excinfo.value.status_code == 400+++async def test_an_incompatible_protocol_version_is_refused() -> None:+ protocol = _Protocol()+ with pytest.raises(HTTPException) as excinfo:+ await _call(+ protocol,+ accept="text/event-stream",+ connection_id="c1",+ protocol_version=PROTOCOL_VERSION + 1,+ )++ assert excinfo.value.status_code == 409+ assert "update the Switch agent runtime" in excinfo.value.detail+++# ── Start cursor ────────────────────────────────────────────────────────────+++def test_head_means_only_what_happens_next() -> None:+ protocol = _Protocol()+ protocol.event_buffer.enqueue(AGENT_ID, "room", _event())+ assert _resolve_start_cursor(protocol, AGENT_ID, "head", None) == 1+++def test_last_event_id_wins_over_start_from() -> None:+ protocol = _Protocol()+ assert _resolve_start_cursor(protocol, AGENT_ID, "head", "42") == 42+++def test_explicit_start_from_is_honoured() -> None:+ protocol = _Protocol()+ assert _resolve_start_cursor(protocol, AGENT_ID, "17", None) == 17+++def test_a_nonsense_cursor_is_refused_rather_than_guessed() -> None:+ protocol = _Protocol()+ with pytest.raises(HTTPException) as excinfo:+ _resolve_start_cursor(protocol, AGENT_ID, "banana", None)+ assert excinfo.value.status_code == 400+++def _event() -> Any:+ from switch_core.bridges.agent.protocol.types import AgentEvent, MessagePayload++ return AgentEvent(+ type="message",+ room_id="room",+ payload=MessagePayload(+ addressed=True,+ sender="@u:s",+ sender_name="u",+ message_id="$e",+ body="hi",+ timestamp=0,+ ),+ )+++class TestDeclaringARoomAtOpenTakesOver:+ """A supervisor opening a stream for a room it manages must win the slot.++ The rule: the client doing the delivering owns the room. Naming a room on+ the URL is a supervisor asserting ownership of a session it is about to+ feed; a `connect_to_room` claim is cooperative and yields.++ Without the takeover, a session started before its supervisor learned to+ share connections keeps the slot, and the supervisor's restored stream 409s+ and retries forever while the session sits silent.+ """++ async def test_an_incumbent_is_evicted_from_the_room(self) -> None:+ protocol = _Protocol()+ incumbent = protocol.connections.open(+ agent_id=AGENT_ID,+ connection_id="in-session-runtime",+ scope="single",+ delivery_filter="all",+ spawn_capable=False,+ cursor=0,+ protocol_version=PROTOCOL_VERSION,+ )+ protocol.connections.claim_room(incumbent, "room-1")++ resp = await _call(+ protocol,+ accept="text/event-stream",+ connection_id="supervisor",+ rooms="room-1",+ )++ assert isinstance(resp, StreamingResponse)+ claimant = protocol.connections.claimant_of(AGENT_ID, "room-1")+ assert claimant is not None+ assert claimant.id == "supervisor"+ assert "room-1" not in incumbent.roomsdiff --git a/core/tests/switch_core/bridges/agent/api/test_operations.py b/core/tests/switch_core/bridges/agent/api/test_operations.pynew file mode 100644index 000000000..289c3df5d--- /dev/null+++ b/core/tests/switch_core/bridges/agent/api/test_operations.py@@ -0,0 +1,172 @@+"""HTTP operations front door (CHOO-1857 / CHOO-490).++The property under test is parity: every operation is reachable through both+doors under the same name, because both are built from one registry. If someone+adds an operation and these fail, that is the point.+"""++from __future__ import annotations++import pytest++from switch_core.bridges.agent.api.operations import (+ BadArgumentsError,+ UnknownOperationError,+ call_operation,+ list_operations,+)+from switch_core.bridges.agent.mcp import server as mcp_server+from switch_core.bridges.agent.operations import context as op_context+from switch_core.bridges.agent.operations import get_operation+from switch_core.bridges.agent.operations.callctx import (+ CallContext,+ current_call_context,+ reset_call_context,+ set_call_context,+)++AGENT = "agent-1"+++async def _tool_names() -> set[str]:+ return {tool.name for tool in await mcp_server.mcp._list_tools()}+++async def test_every_operation_is_registered_as_an_mcp_tool() -> None:+ # The MCP door registers whatever the registry holds, so this is the+ # parity guarantee: neither door can be missing an operation the other has.+ assert set(list_operations()) == await _tool_names()+++async def test_operation_names_are_the_tool_names_verbatim() -> None:+ # One vocabulary: a translating runtime is POST /ops/${toolName}, nothing+ # more. Renaming or namespacing here would reintroduce a mapping table.+ ops = list_operations()+ for expected in ("connect_to_room", "post_message", "assume_role", "list_tasks"):+ assert expected in ops+++def test_operations_advertise_a_json_schema_for_their_arguments() -> None:+ """Clients build their tool surface from this, so it must be real schema."""+ op = list_operations()["connect_to_room"]+ schema = op["input_schema"]++ assert schema["type"] == "object"+ assert schema["properties"]["room_id"]["type"] == "string"+ assert schema["required"] == ["room_id"]+ assert schema["properties"]["include_general_instructions"]["default"] is True+ # Transport details are not arguments an agent supplies.+ assert "ctx" not in schema["properties"]+ # The full docstring is the tool description an agent reads.+ assert "Connect this session to a room" in op["description"]+++async def test_unknown_operation_names_what_is_available() -> None:+ with pytest.raises(UnknownOperationError) as excinfo:+ await call_operation(+ operation="teleport",+ arguments={},+ agent_id=AGENT,+ connection_id=None,+ )+ assert "connect_to_room" in str(excinfo.value)+++async def test_unexpected_arguments_are_refused() -> None:+ with pytest.raises(BadArgumentsError) as excinfo:+ await call_operation(+ operation="connect_to_room",+ arguments={"room_id": "r", "colour": "blue"},+ agent_id=AGENT,+ connection_id=None,+ )+ assert "colour" in str(excinfo.value)+++async def test_missing_required_arguments_are_refused() -> None:+ with pytest.raises(BadArgumentsError) as excinfo:+ await call_operation(+ operation="connect_to_room",+ arguments={},+ agent_id=AGENT,+ connection_id=None,+ )+ assert "room_id" in str(excinfo.value)+++# ── Call context ────────────────────────────────────────────────────────────+++async def test_the_call_context_carries_agent_and_connection() -> None:+ """The operation sees who called and which connection it belongs to."""+ seen: dict[str, object] = {}++ async def fake_op(room_id: str) -> str:+ seen["agent_id"] = op_context.get_agent_id()+ seen["session_key"] = op_context.session_key()+ return "ok"++ from switch_core.bridges.agent.operations import registry++ registry._REGISTRY["fake_op"] = registry.Operation(+ name="fake_op",+ fn=fake_op,+ description="fake",+ input_schema=registry._input_schema(fake_op),+ )+ try:+ result = await call_operation(+ operation="fake_op",+ arguments={"room_id": "room-1"},+ agent_id=AGENT,+ connection_id="conn-9",+ )+ finally:+ registry._REGISTRY.pop("fake_op", None)++ assert result == "ok"+ assert seen["agent_id"] == AGENT+ # The connection is the caller's session key: this is what lets an+ # operation resolve the room binding without an MCP transport session.+ assert seen["session_key"] == "conn-9"+++def test_the_call_context_is_cleared_after_the_call() -> None:+ assert current_call_context() is None+ token = set_call_context(CallContext(agent_id=AGENT, session_key="c1"))+ assert current_call_context() is not None+ reset_call_context(token)+ assert current_call_context() is None+++def test_agent_id_prefers_the_bound_context_over_the_request_scope() -> None:+ token = set_call_context(CallContext(agent_id="bound-agent", session_key=None))+ try:+ # No HTTP request in scope at all: resolving would fail if the bound+ # context were not consulted first.+ assert op_context.get_agent_id() == "bound-agent"+ finally:+ reset_call_context(token)+++def test_session_key_prefers_the_bound_context() -> None:+ token = set_call_context(CallContext(agent_id=AGENT, session_key="conn-7"))+ try:+ assert op_context.session_key() == "conn-7"+ finally:+ reset_call_context(token)+++def test_session_key_is_none_when_bound_to_nothing() -> None:+ # Neither an HTTP call context nor an MCP session: operations that need a+ # room report "not connected" rather than guessing one.+ assert op_context.session_key() is None+++def test_the_registry_refuses_duplicate_operation_names() -> None:+ from switch_core.bridges.agent.operations import registry++ existing = get_operation("post_message")+ assert existing is not None+ with pytest.raises(RuntimeError):+ registry.operation(existing.fn)diff --git a/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py b/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.pynew file mode 100644index 000000000..d1e10071f--- /dev/null+++ b/core/tests/switch_core/bridges/agent/operations/test_connect_claims_room.py@@ -0,0 +1,163 @@+"""Connecting to a room claims the caller's room slot (CHOO-1857).++`connect_to_room` arrives tagged with a connection id, so the room is bound to+that connection rather than left to a follow-up subscribe the client has to+remember. Two consequences, and the second is the point:++- one step instead of two, so there is no window in which the agent is "in" a+ room its own connection does not cover;+- the claim lands on that connection's stream as `subscription_changed`, so a+ supervisor holding the connection learns the room **from Switch** instead of+ reading the agent's tool result. Reading the tool result is what switchdash+ did, and it broke silently the moment the result's shape changed.+"""++from __future__ import annotations++import logging+from types import SimpleNamespace+from typing import Any++from switch_core.bridges.agent.operations.definitions import (+ claim_room_on_caller_connection,+)+from switch_core.bridges.agent.protocol.connections import (+ PROTOCOL_VERSION,+ ConnectionRegistry,+)++AGENT = "agent-1"+ROOM = "room-1"+CONN = "conn-1"+++def _protocol(registry: ConnectionRegistry) -> Any:+ return SimpleNamespace(connections=registry)+++def _open(registry: ConnectionRegistry, connection_id: str, agent_id: str = AGENT):+ return registry.open(+ agent_id=agent_id,+ connection_id=connection_id,+ scope="single",+ delivery_filter="all",+ spawn_capable=False,+ cursor=0,+ protocol_version=PROTOCOL_VERSION,+ )+++def test_the_calling_connection_ends_up_holding_the_room() -> None:+ registry = ConnectionRegistry()+ _open(registry, CONN)++ claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)++ claimant = registry.claimant_of(AGENT, ROOM)+ assert claimant is not None+ assert claimant.id == CONN+++def test_the_claim_wakes_the_stream_so_its_holder_is_told() -> None:+ """The wake is what carries the room to whoever holds the stream.++ Without it the supervisor stays blocked on its read and learns nothing+ until the next event happens along.+ """+ registry = ConnectionRegistry()+ conn = _open(registry, CONN)+ conn.wake.clear()++ claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)++ assert conn.wake.is_set()+++def test_a_dead_sibling_does_not_lock_the_agent_out() -> None:+ """The same agent returning after a restart must be able to re-enter.++ Its previous connection is usually still registered but no longer beating.+ That is not a claimant — `claimant_of` filters on liveness — so there is+ nothing to take over and the claim simply succeeds.+ """+ import time as _time++ registry = ConnectionRegistry()+ dead = _open(registry, "previous-life")+ registry.claim_room(dead, ROOM)+ dead.last_beat = _time.monotonic() - 3600+ _open(registry, CONN)++ claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)++ claimant = registry.claimant_of(AGENT, ROOM)+ assert claimant is not None+ assert claimant.id == CONN+++def test_a_live_sibling_keeps_the_room() -> None:+ """A tool call does not take a room off a connection that is delivering.++ The only thing a takeover here could ever win against is a live connection+ covering the room — typically a supervisor feeding this very session. Taking+ the slot from it stops delivery *silently*: the call succeeds, the agent+ believes it is in the room, and nothing reaches it again.++ Ownership goes the other way: a supervisor declaring a room when it opens+ its stream takes over; a `connect_to_room` yields.+ """+ registry = ConnectionRegistry()+ supervisor = _open(registry, "supervisor")+ registry.claim_room(supervisor, ROOM)+ _open(registry, CONN)++ claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)++ claimant = registry.claimant_of(AGENT, ROOM)+ assert claimant is not None+ assert claimant.id == "supervisor"+ assert ROOM in supervisor.rooms+++def test_an_unknown_connection_is_not_an_error() -> None:+ """An MCP transport session has no connection; the binding row covers it."""+ registry = ConnectionRegistry()++ claim_room_on_caller_connection(_protocol(registry), AGENT, "no-such", ROOM)++ assert registry.claimant_of(AGENT, ROOM) is None+++def test_another_agents_connection_is_never_claimed_on() -> None:+ """The key comes off the caller's own header, but never trust it blindly."""+ registry = ConnectionRegistry()+ _open(registry, CONN, agent_id="someone-else")++ claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)++ assert registry.claimant_of("someone-else", ROOM) is None+ assert registry.claimant_of(AGENT, ROOM) is None+++def test_a_failure_to_claim_is_logged_and_not_raised(+ caplog: Any,+) -> None:+ """Membership is already written; only routing is affected.++ Raising here would fail a `connect_to_room` that genuinely succeeded.+ """+ registry = ConnectionRegistry()+ conn = _open(registry, CONN)++ def _explode(*_a: Any, **_kw: Any) -> None:+ from switch_core.bridges.agent.protocol.connections import RoomOccupiedError++ raise RoomOccupiedError(ROOM, "other")++ registry.claim_room = _explode # type: ignore[method-assign]++ with caplog.at_level(logging.WARNING):+ claim_room_on_caller_connection(_protocol(registry), AGENT, CONN, ROOM)++ assert any("could not claim room" in r.getMessage() for r in caplog.records)+ assert conn.closed_reason is Nonediff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.pyindex 3f3581fff..5b6350ee1 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_detail_mcp_tools.py@@ -4,6 +4,7 @@ import pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.protocol.agent_detail import AgentOptionsNotEditable+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.db.models import Agent, ApiKey, Client, Userfrom switch_core.db.stores.agent_session_store import AgentSessionStore@@ -16,6 +17,9 @@ from switch_core.gateway.known_agents import KNOWN_AGENTSdef _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.room_store = RoomStore() # type: ignore[attr-defined]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_connections.py b/core/tests/switch_core/bridges/agent/protocol/test_connections.pynew file mode 100644index 000000000..699b66669--- /dev/null+++ b/core/tests/switch_core/bridges/agent/protocol/test_connections.py@@ -0,0 +1,232 @@+"""Connection lifecycle, room slots and liveness (CHOO-1857)."""++from __future__ import annotations++import time++import pytest++from switch_core.bridges.agent.protocol.connections import (+ HEARTBEAT_TTL_SECONDS,+ MAX_CONNECTIONS_PER_AGENT,+ PROTOCOL_VERSION,+ ConnectionRegistry,+ NoStreamAttachedError,+ ProtocolVersionError,+ RoomOccupiedError,+ TooManyConnectionsError,+ UnknownConnectionError,+)++AGENT = "agent-1"+OTHER_AGENT = "agent-2"+ROOM_A = "room-a"+ROOM_B = "room-b"+++def _open(+ registry: ConnectionRegistry,+ connection_id: str,+ *,+ agent_id: str = AGENT,+ scope: str = "single",+ delivery_filter: str = "all",+ spawn_capable: bool = False,+ cursor: int = 0,+):+ return registry.open(+ agent_id=agent_id,+ connection_id=connection_id,+ scope=scope, # type: ignore[arg-type]+ delivery_filter=delivery_filter, # type: ignore[arg-type]+ spawn_capable=spawn_capable,+ cursor=cursor,+ protocol_version=PROTOCOL_VERSION,+ )+++def test_open_is_idempotent_for_the_same_id() -> None:+ registry = ConnectionRegistry()+ first = _open(registry, "c1")+ second = _open(registry, "c1")++ assert first is second+ assert len(registry.for_agent(AGENT)) == 1+++def test_reopening_bumps_the_generation_so_the_old_stream_can_stand_down() -> None:+ registry = ConnectionRegistry()+ conn = _open(registry, "c1")+ generation = conn.stream_generation++ _open(registry, "c1")+ assert conn.stream_generation == generation + 1+++def test_another_agent_cannot_attach_to_a_connection_id() -> None:+ registry = ConnectionRegistry()+ _open(registry, "c1")++ with pytest.raises(UnknownConnectionError):+ _open(registry, "c1", agent_id=OTHER_AGENT)+++def test_incompatible_protocol_is_refused() -> None:+ registry = ConnectionRegistry()+ with pytest.raises(ProtocolVersionError):+ registry.open(+ agent_id=AGENT,+ connection_id="c1",+ scope="single",+ delivery_filter="all",+ spawn_capable=False,+ cursor=0,+ protocol_version=PROTOCOL_VERSION + 1,+ )+++def test_connection_cap_is_enforced_loudly() -> None:+ registry = ConnectionRegistry()+ for i in range(MAX_CONNECTIONS_PER_AGENT):+ _open(registry, f"c{i}")++ with pytest.raises(TooManyConnectionsError):+ _open(registry, "one-too-many")+++# ── Liveness ────────────────────────────────────────────────────────────────+++def test_losing_the_stream_does_not_kill_the_connection() -> None:+ registry = ConnectionRegistry()+ conn = _open(registry, "c1")+ registry.claim_room(conn, ROOM_A)++ registry.detach_stream(conn.id, conn.stream_generation)++ # Still alive, still holding its room: a brief drop must not cost the slot.+ assert registry.require(AGENT, "c1") is conn+ assert registry.holder_of(AGENT, ROOM_A) is conn+++def test_a_beat_without_a_stream_is_rejected() -> None:+ registry = ConnectionRegistry()+ conn = _open(registry, "c1")+ registry.detach_stream(conn.id, conn.stream_generation)++ # The client is alive but receiving nothing. It must be told, not left+ # believing it is connected.+ with pytest.raises(NoStreamAttachedError):+ registry.beat(AGENT, "c1", 5)+++def test_a_stale_heartbeat_kills_the_connection_even_with_a_stream() -> None:+ registry = ConnectionRegistry()+ conn = _open(registry, "c1")+ assert conn.stream_attached++ conn.last_beat = time.monotonic() - HEARTBEAT_TTL_SECONDS - 1++ assert registry.sweep() == [conn]+ with pytest.raises(UnknownConnectionError):+ registry.require(AGENT, "c1")+++def test_a_superseded_stream_cannot_clear_the_flag_of_its_replacement() -> None:+ registry = ConnectionRegistry()+ conn = _open(registry, "c1")+ stale_generation = conn.stream_generation++ _open(registry, "c1") # reattach; generation bumps+ registry.detach_stream(conn.id, stale_generation)++ assert conn.stream_attached+++def test_beat_advances_the_cursor_but_never_rewinds_it() -> None:+ registry = ConnectionRegistry()+ _open(registry, "c1")++ assert registry.beat(AGENT, "c1", 7).cursor == 7+ assert registry.beat(AGENT, "c1", 3).cursor == 7+++# ── Room slots ──────────────────────────────────────────────────────────────+++def test_single_scope_holds_one_room_at_a_time() -> None:+ registry = ConnectionRegistry()+ conn = _open(registry, "c1", scope="single")++ registry.claim_room(conn, ROOM_A)+ registry.claim_room(conn, ROOM_B)++ assert conn.rooms == {ROOM_B}+++def test_a_second_connection_cannot_take_a_claimed_room() -> None:+ registry = ConnectionRegistry()+ first = _open(registry, "c1")+ registry.claim_room(first, ROOM_A)++ second = _open(registry, "c2")+ with pytest.raises(RoomOccupiedError):+ registry.claim_room(second, ROOM_A)+++def test_takeover_evicts_the_incumbent() -> None:+ registry = ConnectionRegistry()+ first = _open(registry, "c1")+ registry.claim_room(first, ROOM_A)+ second = _open(registry, "c2")++ evicted = registry.claim_room(second, ROOM_A, takeover=True)++ assert evicted is first+ assert first.rooms == set()+ assert registry.holder_of(AGENT, ROOM_A) is second+++def test_all_scope_covers_rooms_no_session_has_claimed() -> None:+ registry = ConnectionRegistry()+ daemon = _open(registry, "daemon", scope="all", delivery_filter="addressed")++ assert registry.covers(daemon, ROOM_A)+ assert registry.covers(daemon, ROOM_B)+++def test_all_scope_goes_fully_dark_on_a_claimed_room() -> None:+ registry = ConnectionRegistry()+ daemon = _open(registry, "daemon", scope="all", delivery_filter="addressed")+ session = _open(registry, "session", scope="single")+ registry.claim_room(session, ROOM_A)++ assert not registry.covers(daemon, ROOM_A)+ assert registry.covers(daemon, ROOM_B)+ assert registry.covers(session, ROOM_A)+ assert not registry.covers(session, ROOM_B)+++def test_coverage_returns_to_the_daemon_when_the_session_goes() -> None:+ registry = ConnectionRegistry()+ daemon = _open(registry, "daemon", scope="all")+ session = _open(registry, "session", scope="single")+ registry.claim_room(session, ROOM_A)+ assert not registry.covers(daemon, ROOM_A)++ registry.close("session", "session ended")++ assert registry.covers(daemon, ROOM_A)+ assert registry.holder_of(AGENT, ROOM_A) is daemon+++def test_rooms_of_one_agent_do_not_block_another() -> None:+ registry = ConnectionRegistry()+ mine = _open(registry, "c1")+ registry.claim_room(mine, ROOM_A)++ theirs = _open(registry, "c2", agent_id=OTHER_AGENT)+ registry.claim_room(theirs, ROOM_A)++ assert registry.holder_of(AGENT, ROOM_A) is mine+ assert registry.holder_of(OTHER_AGENT, ROOM_A) is theirsdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.pyindex 2f7c4bdfb..dbdda7c20 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import AgentStatusfrom switch_core.db.models import Agent, ApiKey, Client, Room, User@@ -13,6 +14,9 @@ from switch_core.db.stores.task_store import TaskStoredef _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.room_store = RoomStore() # type: ignore[attr-defined]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_event_queue.py b/core/tests/switch_core/bridges/agent/protocol/test_event_buffer.pysimilarity index 92%rename from core/tests/switch_core/bridges/agent/protocol/test_event_queue.pyrename to core/tests/switch_core/bridges/agent/protocol/test_event_buffer.pyindex 3f7524665..c68fd10ea 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_event_queue.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_event_buffer.py@@ -1,4 +1,4 @@-"""Unit tests for the EventQueue notification fan-out (CHOO-889).+"""Unit tests for the EventBuffer notification fan-out (CHOO-889).The auto_session watcher consumes a separate, agent-scoped notification stream.The critical invariant: fanning an event out to that stream must NOT remove it@@ -8,7 +8,7 @@ would steal events from connected rooms.from __future__ import annotations-from switch_core.bridges.agent.protocol.event_queue import EventQueue+from switch_core.bridges.agent.protocol.event_buffer import EventBufferfrom switch_core.bridges.agent.protocol.types import (AgentEvent,MessagePayload,@@ -60,7 +60,7 @@ def _task_delegate() -> AgentEvent:async def test_addressed_message_fans_out_without_draining_room_queue() -> None:- q = EventQueue()+ q = EventBuffer()q.enqueue(AGENT, ROOM, _message(addressed=True))# The notification stream sees it...@@ -74,7 +74,7 @@ async def test_addressed_message_fans_out_without_draining_room_queue() -> None:async def test_unaddressed_message_does_not_fan_out() -> None:- q = EventQueue()+ q = EventBuffer()q.enqueue(AGENT, ROOM, _message(addressed=False))assert await q.poll_notifications(AGENT, timeout=0) == []@@ -84,7 +84,7 @@ async def test_unaddressed_message_does_not_fan_out() -> None:async def test_task_event_fans_out() -> None:- q = EventQueue()+ q = EventBuffer()q.enqueue(AGENT, ROOM, _task_delegate())notifs = await q.poll_notifications(AGENT, timeout=0)assert len(notifs) == 1@@ -92,7 +92,7 @@ async def test_task_event_fans_out() -> None:async def test_room_join_fans_out_only_when_listening() -> None:- q = EventQueue()+ q = EventBuffer()q.enqueue(AGENT, ROOM, _room_join(listening=False))assert await q.poll_notifications(AGENT, timeout=0) == []@@ -103,7 +103,7 @@ async def test_room_join_fans_out_only_when_listening() -> None:async def test_remove_clears_notification_queue() -> None:- q = EventQueue()+ q = EventBuffer()q.enqueue(AGENT, ROOM, _message(addressed=True))q.remove(AGENT)assert await q.poll_notifications(AGENT, timeout=0) == []diff --git a/core/tests/switch_core/bridges/agent/protocol/test_event_buffer_resume.py b/core/tests/switch_core/bridges/agent/protocol/test_event_buffer_resume.pynew file mode 100644index 000000000..d68328e63--- /dev/null+++ b/core/tests/switch_core/bridges/agent/protocol/test_event_buffer_resume.py@@ -0,0 +1,195 @@+"""Sequencing, resume and gap behaviour of the event buffer (CHOO-1857).++These cover the properties the push transport depends on: reads do not consume,+a reader can resume from a cursor across a disconnect, and a reader that has+fallen off the end of the buffer is told rather than quietly fast-forwarded.+"""++from __future__ import annotations++import pytest++from switch_core.bridges.agent.protocol.event_buffer import (+ CursorExpiredError,+ EventBuffer,+)+from switch_core.bridges.agent.protocol.types import AgentEvent, MessagePayload++AGENT = "agent-1"+ROOM_A = "room-a"+ROOM_B = "room-b"+++def _message(body: str, *, addressed: bool = False, room: str = ROOM_A) -> AgentEvent:+ return AgentEvent(+ type="message",+ room_id=room,+ payload=MessagePayload(+ addressed=addressed,+ sender="@u:s",+ sender_name="u",+ message_id=f"$evt-{body}",+ body=body,+ timestamp=0,+ ),+ )+++def _bodies(items: list) -> list[str]:+ return [item.event.payload.body for item in items]+++def test_sequence_numbers_are_monotonic_per_agent() -> None:+ buf = EventBuffer()+ assert buf.enqueue(AGENT, ROOM_A, _message("one")) == 1+ assert buf.enqueue(AGENT, ROOM_B, _message("two", room=ROOM_B)) == 2+ assert buf.enqueue(AGENT, ROOM_A, _message("three")) == 3+ assert buf.head(AGENT) == 3+++def test_reading_does_not_consume() -> None:+ buf = EventBuffer()+ buf.enqueue(AGENT, ROOM_A, _message("one"))++ assert _bodies(buf.read_from(AGENT, 0)) == ["one"]+ # The same event is still there for a second, independent reader — this is+ # what removes the need for DISABLE_POLL.+ assert _bodies(buf.read_from(AGENT, 0)) == ["one"]+++def test_resume_returns_only_events_after_the_cursor() -> None:+ buf = EventBuffer()+ for body in ("one", "two", "three"):+ buf.enqueue(AGENT, ROOM_A, _message(body))++ assert _bodies(buf.read_from(AGENT, 1)) == ["two", "three"]+ assert _bodies(buf.read_from(AGENT, 3)) == []+++def test_events_missed_while_disconnected_are_replayed_on_resume() -> None:+ buf = EventBuffer()+ buf.enqueue(AGENT, ROOM_A, _message("before"))+ seen = buf.read_from(AGENT, 0)+ cursor = seen[-1].seq++ # Client is gone; events keep arriving.+ buf.enqueue(AGENT, ROOM_A, _message("during-1"))+ buf.enqueue(AGENT, ROOM_A, _message("during-2"))++ assert _bodies(buf.read_from(AGENT, cursor)) == ["during-1", "during-2"]+++def test_room_and_notifiable_filters_are_independent() -> None:+ buf = EventBuffer()+ buf.enqueue(AGENT, ROOM_A, _message("a-chatter"))+ buf.enqueue(AGENT, ROOM_A, _message("a-addressed", addressed=True))+ buf.enqueue(AGENT, ROOM_B, _message("b-addressed", addressed=True, room=ROOM_B))++ # A session: one room, everything in it.+ assert _bodies(buf.read_from(AGENT, 0, rooms={ROOM_A})) == [+ "a-chatter",+ "a-addressed",+ ]+ # A supervising connection: every room, addressed only.+ assert _bodies(buf.read_from(AGENT, 0, notifiable_only=True)) == [+ "a-addressed",+ "b-addressed",+ ]+ # Both dials at once.+ assert _bodies(buf.read_from(AGENT, 0, rooms={ROOM_B}, notifiable_only=True)) == [+ "b-addressed"+ ]+++def test_overflow_drops_oldest_and_flags_a_gap() -> None:+ buf = EventBuffer(max_events_per_agent=3)+ for body in ("one", "two", "three", "four"):+ buf.enqueue(AGENT, ROOM_A, _message(body))++ assert _bodies(buf.read_from(AGENT, 1)) == ["two", "three", "four"]+ assert buf.has_gap_before(AGENT, 0)+ assert not buf.has_gap_before(AGENT, 1)+++def test_resuming_from_an_expired_cursor_raises_rather_than_skipping() -> None:+ buf = EventBuffer(max_events_per_agent=2)+ for body in ("one", "two", "three"):+ buf.enqueue(AGENT, ROOM_A, _message(body))++ with pytest.raises(CursorExpiredError) as excinfo:+ buf.read_from(AGENT, 0)++ assert excinfo.value.requested == 0+ assert excinfo.value.oldest == 2+++def test_retention_window_expires_events_and_flags_a_gap(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ clock = {"now": 1000.0}+ monkeypatch.setattr(+ "switch_core.bridges.agent.protocol.event_buffer.time.monotonic",+ lambda: clock["now"],+ )++ buf = EventBuffer(retention_seconds=60)+ buf.enqueue(AGENT, ROOM_A, _message("old"))++ clock["now"] += 61+ buf.enqueue(AGENT, ROOM_A, _message("new"))++ assert _bodies(buf.read_from(AGENT, 1)) == ["new"]+ with pytest.raises(CursorExpiredError):+ buf.read_from(AGENT, 0)+++def test_confirming_does_not_discard_events_for_other_readers() -> None:+ buf = EventBuffer()+ buf.enqueue(AGENT, ROOM_A, _message("one"))++ buf.confirm(AGENT, "reader-a", 1)++ # A reader that arrives afterwards still sees it: retention is by age and+ # cap, not by what someone else has consumed.+ assert _bodies(buf.read_from(AGENT, 0)) == ["one"]+++def test_confirm_never_rewinds() -> None:+ buf = EventBuffer()+ buf.register_reader(AGENT, "reader-a", 0)+ buf.confirm(AGENT, "reader-a", 5)+ buf.confirm(AGENT, "reader-a", 2)+ assert buf._cursors[AGENT]["reader-a"] == 5+++async def test_legacy_pollers_no_longer_steal_from_each_other() -> None:+ buf = EventBuffer()+ buf.enqueue(AGENT, ROOM_A, _message("hello", addressed=True))++ room = await buf.poll_room(AGENT, ROOM_A, timeout=0)+ notif = await buf.poll_notifications(AGENT, timeout=0)+ every = await buf.poll(AGENT, timeout=0)++ assert [e.payload.body for e in room] == ["hello"]+ assert [e.payload.body for e in notif] == ["hello"]+ assert [e.payload.body for e in every] == ["hello"]+++async def test_legacy_poller_does_not_see_the_same_event_twice() -> None:+ buf = EventBuffer()+ buf.enqueue(AGENT, ROOM_A, _message("one"))++ assert len(await buf.poll_room(AGENT, ROOM_A, timeout=0)) == 1+ assert await buf.poll_room(AGENT, ROOM_A, timeout=0) == []++ buf.enqueue(AGENT, ROOM_A, _message("two"))+ second = await buf.poll_room(AGENT, ROOM_A, timeout=0)+ assert [e.payload.body for e in second] == ["two"]+++async def test_legacy_poller_receives_events_queued_before_it_polled() -> None:+ buf = EventBuffer()+ buf.enqueue(AGENT, ROOM_A, _message("queued-while-away"))++ events = await buf.poll_room(AGENT, ROOM_A, timeout=0)+ assert [e.payload.body for e in events] == ["queued-while-away"]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_read_context_attachments.py b/core/tests/switch_core/bridges/agent/protocol/test_read_context_attachments.pyindex da043a60c..d868b5f33 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_read_context_attachments.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_read_context_attachments.py@@ -4,6 +4,7 @@ from types import SimpleNamespaceimport nio+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolService@@ -50,6 +51,9 @@ def _build_service(chunk: list[object]) -> ProtocolService:return SimpleNamespace(matrix_room_id="!room")svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.require_room_member = _require # type: ignore[assignment]svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]get_by_agent_id=lambda agent_id: fake_clientdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.py b/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.pyindex a1879d0a6..a8a4a4660 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolService@@ -67,17 +68,19 @@ class _FakeRoomRoleStore:async def get_role(self, _session: Any, _room_id: str, _name: str) -> Any:return self._role- async def get_agent_live_lease(self, _session: Any, _agent_id: str) -> Any | None:+ async def get_agent_live_lease(+ self, _session: Any, _agent_id: str, _alive: Any = ()+ ) -> Any | None:return self._agent_leaseasync def acquire_lease(- self, _session: Any, role: Any, agent_id: str, _tx: str | None+ self, _session: Any, role: Any, agent_id: str, _tx: str | None, _alive: Any = ()) -> Any:self.acquired = Truereturn SimpleNamespace(role_id=role.id, agent_id=agent_id)async def agent_room_role(- self, _session: Any, _room_id: str, _agent_id: str+ self, _session: Any, _room_id: str, _agent_id: str, _alive: Any = ()) -> str | None:return self._lease_role_name@@ -98,6 +101,9 @@ def _build_service(*, role_store: _FakeRoomRoleStore, client: Any, members: list[str]) -> ProtocolService:svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_role_store = role_store # type: ignore[assignment]svc.room_store = _FakeRoomStore(_ROOM, members) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_role_detail.py b/core/tests/switch_core/bridges/agent/protocol/test_role_detail.pyindex 26b83888b..277570532 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_role_detail.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_role_detail.py@@ -5,6 +5,7 @@ from typing import Anyimport pytest+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolService@@ -41,11 +42,13 @@ class _FakeRoomRoleStore:return Noneasync def live_leases_for_room(- self, _session: Any, _room_id: str+ self, _session: Any, _room_id: str, _alive: Any = ()) -> dict[str, list[Any]]:return {k: list(v) for k, v in self._leases.items()}- async def get_agent_live_lease(self, _session: Any, _agent_id: str) -> Any | None:+ async def get_agent_live_lease(+ self, _session: Any, _agent_id: str, _alive: Any = ()+ ) -> Any | None:return self._my_lease@@ -112,6 +115,9 @@ def _build_service(my_lease: Any | None = None,) -> ProtocolService:svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_role_store = _FakeRoomRoleStore(roles, leases, my_lease) # type: ignore[assignment]svc.agent_store = _FakeAgentStore(agents) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_role_listing.py b/core/tests/switch_core/bridges/agent/protocol/test_role_listing.pyindex 7cf19ece0..0bdff0e85 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_role_listing.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_role_listing.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolService@@ -36,11 +37,13 @@ class _FakeRoomRoleStore:return list(self._roles)async def live_leases_for_room(- self, _session: Any, _room_id: str+ self, _session: Any, _room_id: str, _alive: Any = ()) -> dict[str, list[Any]]:return {k: list(v) for k, v in self._leases.items()}- async def get_agent_live_lease(self, _session: Any, _agent_id: str) -> Any | None:+ async def get_agent_live_lease(+ self, _session: Any, _agent_id: str, _alive: Any = ()+ ) -> Any | None:return self._my_lease@@ -98,6 +101,9 @@ def _build_service(my_lease: Any | None = None,) -> ProtocolService:svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_role_store = _FakeRoomRoleStore(roles, leases, my_lease) # type: ignore[assignment]svc.agent_store = _FakeAgentStore(agents) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.py b/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.pyindex b723ef530..e3ca85efe 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.py@@ -6,6 +6,7 @@ from typing import Anyimport pytestfrom switch_core.aliases import AliasError+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import AgentStatus@@ -118,6 +119,9 @@ def _build_service() -> ProtocolService:room = _room()svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_store = _FakeRoomStore({room.id: room}, agent_ids, aliases or {}) # type: ignore[assignment]svc.agent_store = _FakeAgentStore(agents) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_detail.py b/core/tests/switch_core/bridges/agent/protocol/test_room_detail.pyindex efde63b4c..e12a086a4 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_detail.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_detail.py@@ -5,6 +5,7 @@ from typing import Anyimport pytest+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import AgentStatus@@ -143,6 +144,9 @@ def _build_service(roles: list[dict[str, Any]] | None = None,) -> ProtocolService:svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_store = _FakeRoomStore({room.id: room}, agent_ids, client_ids or []) # type: ignore[assignment]svc.agent_store = _FakeAgentStore(agents or {}) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py b/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.pyindex 7adb8e12e..c3c43f267 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_group_mcp_tools.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.db.models import Roomfrom switch_core.db.stores.room_group_store import RoomGroupStore@@ -14,6 +15,9 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolServi# exercise them on an un-__init__'d instance (matching the other protocol# tests) with just those attributes set.svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = session_factory # type: ignore[attr-defined]svc.room_group_store = RoomGroupStore() # type: ignore[attr-defined]return svcdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_links.py b/core/tests/switch_core/bridges/agent/protocol/test_room_links.pyindex 82964143e..0b33add74 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_links.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_links.py@@ -5,6 +5,7 @@ from typing import Anyimport pytest+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolService@@ -69,6 +70,9 @@ def _build_service(resource_service = _FakeResourceService(exists=exists)svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = lambda: session # type: ignore[assignment]svc.resource_service = resource_service # type: ignore[assignment]svc.agent_store = _FakeAgentStore() # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py b/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.pynew file mode 100644index 000000000..2f972e8a7--- /dev/null+++ b/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py@@ -0,0 +1,139 @@+"""The runtime-state sweep must not clear a live session (CHOO-1857).++The sweep exists because there is no session-close signal: a session that+crashes while `working` would leave "working on it…" stuck on the bridge+forever. So it collapses to idle any non-idle row whose session looks dead.++"Looks dead" has to be the same union every other reader takes. It was not —+it checked only the `agent_sessions` heartbeat rows, which a client on the push+transport no longer writes. So the sweep cleared the state of a perfectly live+session on every pass, and because the bridge deletes the working message on+idle and posts a fresh one on the next update, the status message was deleted+and recreated on every refresh instead of being edited in place.++That is the bug these tests hold shut. It is worth noting it was invisible from+the server's side: nothing errored, the state was simply reset by something+that believed it was tidying up.+"""++from __future__ import annotations++from types import SimpleNamespace+from typing import Any++from switch_core.bridges.agent.protocol.connections import (+ PROTOCOL_VERSION,+ ConnectionRegistry,+)+from switch_core.bridges.agent.protocol.service import ProtocolService++AGENT = "agent-1"+ROOM = "room-1"+++class _RuntimeStateStore:+ def __init__(self, rows: list[Any]) -> None:+ self.rows = rows+ self.cleared: list[tuple[str, str]] = []++ async def get_active(self, _session: Any) -> list[Any]:+ return self.rows++ async def upsert(+ self, _session: Any, agent_id: str, room_id: str, _state: str+ ) -> None:+ self.cleared.append((agent_id, room_id))+++class _SessionStore:+ """No heartbeat rows at all — the situation for a migrated client."""++ async def get_live_agent_ids(+ self, _session: Any, _agent_ids: list[str], _room_id: str | None+ ) -> set[str]:+ return set()+++def _service(+ registry: ConnectionRegistry, store: _RuntimeStateStore+) -> ProtocolService:+ svc = object.__new__(ProtocolService)+ svc.connections = registry+ svc.agent_runtime_state_store = store # type: ignore[assignment]+ svc.agent_session_store = _SessionStore() # type: ignore[assignment]+ svc.agent_store = SimpleNamespace(get=_an_agent) # type: ignore[assignment]+ svc.room_store = SimpleNamespace(get=_a_room) # type: ignore[assignment]+ svc.session_factory = _session_factory # type: ignore[assignment]+ # The emit reaches Matrix and the bridge; the decision to clear is what is+ # under test, and `cleared` records it.+ svc._emit_runtime_state = _noop # type: ignore[assignment]+ return svc+++async def _an_agent(*_a: Any, **_kw: Any) -> Any:+ return SimpleNamespace(id=AGENT, name="agent", integration_profile={}, metadata_={})+++async def _a_room(*_a: Any, **_kw: Any) -> Any:+ return SimpleNamespace(id=ROOM, matrix_room_id="!m:server")+++def _session_factory() -> Any:+ class _Session:+ async def __aenter__(self) -> Any:+ return SimpleNamespace(commit=_noop)++ async def __aexit__(self, *_a: Any) -> None:+ return None++ return _Session()+++async def _noop(*_a: Any, **_kw: Any) -> None:+ return None+++def _connected(room: str | None) -> ConnectionRegistry:+ registry = ConnectionRegistry()+ conn = registry.open(+ agent_id=AGENT,+ connection_id="c1",+ scope="single",+ delivery_filter="all",+ spawn_capable=False,+ cursor=0,+ protocol_version=PROTOCOL_VERSION,+ )+ if room:+ registry.claim_room(conn, room)+ return registry+++def _row() -> Any:+ return SimpleNamespace(agent_id=AGENT, room_id=ROOM, state="working")+++async def test_a_live_connection_in_the_room_is_left_alone() -> None:+ store = _RuntimeStateStore([_row()])++ await _service(_connected(ROOM), store).sweep_runtime_states()++ assert store.cleared == []+++async def test_a_connection_in_another_room_does_not_protect_this_one() -> None:+ # Otherwise any live session would freeze every room's status message.+ store = _RuntimeStateStore([_row()])++ await _service(_connected("other-room"), store).sweep_runtime_states()++ assert store.cleared == [(AGENT, ROOM)]+++async def test_with_nothing_live_the_sweep_still_clears() -> None:+ """The sweep's whole purpose: a crashed session must not stay 'working'."""+ store = _RuntimeStateStore([_row()])++ await _service(ConnectionRegistry(), store).sweep_runtime_states()++ assert store.cleared == [(AGENT, ROOM)]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py b/core/tests/switch_core/bridges/agent/protocol/test_send_media.pyindex 3ac1d42de..bc4ee49f4 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_media.py@@ -5,6 +5,7 @@ from typing import Anyimport pytest+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolService@@ -57,6 +58,9 @@ def _build_service(client: _FakeClient, *, max_bytes: int = 100) -> ProtocolServreturn f"root-of-{thread_id}"svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.require_room_member = _require # type: ignore[assignment]svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]get_by_agent_id=lambda agent_id: clientdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py b/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.pyindex cd73ebd42..7d4660a7e 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_targeted_roles.py@@ -5,6 +5,7 @@ from typing import Anyimport pytest+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import AgentStatus@@ -30,7 +31,7 @@ class _FakeRoomRoleStore:return list(self._roles)async def live_holders_for_room(- self, _session: Any, _room_id: str+ self, _session: Any, _room_id: str, _alive: Any = ()) -> dict[str, list[str]]:return {k: list(v) for k, v in self._holders.items()}@@ -57,6 +58,9 @@ def _build_service(sent_bodies: list[str] = []svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = _session_factory # type: ignore[assignment]svc.room_role_store = _FakeRoomRoleStore(roles, holders) # type: ignore[assignment]svc.agent_store = _FakeAgentStore(agents) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/protocol/test_statuses.py b/core/tests/switch_core/bridges/agent/protocol/test_statuses.pyindex de1369028..278f5ba95 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_statuses.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_statuses.py@@ -3,6 +3,10 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom typing import Any+from switch_core.bridges.agent.protocol.connections import (+ PROTOCOL_VERSION,+ ConnectionRegistry,+)from switch_core.bridges.agent.protocol.statuses import compute_agent_statusesfrom switch_core.bridges.agent.protocol.types import AgentStatus@@ -21,6 +25,30 @@ class _FakeSessionStore:return {aid for aid in agent_ids if aid in self._live}+def _registry(+ *,+ agent_id: str | None = None,+ scope: str = "single",+ room: str | None = None,+ spawn_capable: bool = False,+) -> ConnectionRegistry:+ """A registry holding at most one live connection."""+ registry = ConnectionRegistry()+ if agent_id is not None:+ conn = registry.open(+ agent_id=agent_id,+ connection_id=f"c-{agent_id}",+ scope=scope, # type: ignore[arg-type]+ delivery_filter="all",+ spawn_capable=spawn_capable,+ cursor=0,+ protocol_version=PROTOCOL_VERSION,+ )+ if room is not None:+ registry.claim_room(conn, room)+ return registry++def _agent(agent_id: str, connection_model: str) -> SimpleNamespace:return SimpleNamespace(id=agent_id,@@ -39,7 +67,9 @@ class TestComputeAgentStatuses:]store = _FakeSessionStore(live_ids={"on-live", "addr-live"})- statuses = await compute_agent_statuses(None, agents, "room-1", store)+ statuses = await compute_agent_statuses(+ None, agents, "room-1", store, _registry()+ )assert statuses == {"on-live": AgentStatus.LIVE,@@ -58,7 +88,7 @@ class TestComputeAgentStatuses:]store = _FakeSessionStore(live_ids=set())- await compute_agent_statuses(None, agents, "room-9", store)+ await compute_agent_statuses(None, agents, "room-9", store, _registry())assert (["on"], None) in store.callsassert (["addr"], "room-9") in store.calls@@ -67,6 +97,187 @@ class TestComputeAgentStatuses:agent = SimpleNamespace(id="x", integration_profile={})store = _FakeSessionStore(live_ids=set())- statuses = await compute_agent_statuses(None, [agent], "room-1", store)+ statuses = await compute_agent_statuses(+ None, [agent], "room-1", store, _registry()+ )assert statuses == {"x": AgentStatus.AWAITING_MANUAL_POLL}+++class TestPresenceIsAUnion:+ """A live connection counts as presence, and so does a heartbeat row.++ Both arms are needed while both kinds of client exist (CHOO-1857 stage B):+ a client on the push transport keeps only a connection, one still polling+ keeps only the row. When the polling clients are gone the DB arm goes with+ them — these tests then describe what is left.+ """++ async def test_a_connection_makes_an_addressable_agent_live(self) -> None:+ # Nothing in the DB: this is a migrated client, which sends no+ # /connection/renew at all.+ agents = [_agent("addr", "session_addressable")]+ store = _FakeSessionStore(live_ids=set())+ registry = _registry(agent_id="addr", room="room-1")++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"addr": AgentStatus.LIVE}++ async def test_a_connection_elsewhere_does_not_make_it_live_here(self) -> None:+ agents = [_agent("addr", "session_addressable")]+ store = _FakeSessionStore(live_ids=set())+ registry = _registry(agent_id="addr", room="other-room")++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"addr": AgentStatus.NO_SESSION}++ async def test_the_db_arm_still_stands_on_its_own(self) -> None:+ """An un-migrated client keeps working with no connection at all."""+ agents = [_agent("addr", "session_addressable")]+ store = _FakeSessionStore(live_ids={"addr"})++ statuses = await compute_agent_statuses(+ None, agents, "room-1", store, _registry()+ )++ assert statuses == {"addr": AgentStatus.LIVE}++ async def test_an_all_scope_connection_makes_an_always_on_agent_live(self) -> None:+ # always_on has no separate session: the connection IS the agent being+ # up, and its liveness is room-agnostic.+ agents = [_agent("daemon", "always_on")]+ store = _FakeSessionStore(live_ids=set())+ registry = _registry(agent_id="daemon", scope="all")++ statuses = await compute_agent_statuses(+ None, agents, "any-room", store, registry+ )++ assert statuses == {"daemon": AgentStatus.LIVE}++ async def test_a_watcher_is_not_a_session(self) -> None:+ """An `all`-scope watcher covering a room is not a session in it.++ `covers()` is the delivery rule and deliberately includes the+ all-scope fallback. Presence for a session-shaped agent asks something+ narrower — is a session attending? — and only a claimed room slot+ answers that. Reading coverage as presence reports the agent LIVE in a+ room where nothing but a watcher is listening, which suppresses the+ "no session" reply.+ """+ agents = [_agent("addr", "session_addressable")]+ store = _FakeSessionStore(live_ids=set())+ registry = _registry(agent_id="addr", scope="all")++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"addr": AgentStatus.NO_SESSION}++ async def test_a_watcher_leaves_auto_session_dormant_not_live(self) -> None:+ """The same distinction, where it matters most.++ DORMANT is what licenses "Starting a session…". Reporting LIVE instead+ means the room looks attended, the promise is never made, and the+ message waits with nothing to answer it.+ """+ agents = [_agent("auto", "auto_session")]+ store = _FakeSessionStore(live_ids=set())+ registry = _registry(agent_id="auto", scope="all")++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"auto": AgentStatus.DORMANT}++ async def test_a_watching_connection_makes_auto_session_dormant_not_down(+ self,+ ) -> None:+ """The connection replaces /watch/heartbeat.++ DORMANT is what licenses the "Starting a session…" reply, so losing it+ would silently turn a spawnable agent into an unreachable one.+ """+ agents = [_agent("auto", "auto_session")]+ store = _FakeSessionStore(live_ids=set())+ # `single` scope, no room claimed: watching, covering nothing.+ registry = _registry(agent_id="auto")++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"auto": AgentStatus.DORMANT}++ async def test_a_connection_in_the_room_makes_auto_session_live(self) -> None:+ agents = [_agent("auto", "auto_session")]+ store = _FakeSessionStore(live_ids=set())+ registry = _registry(agent_id="auto", room="room-1")++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"auto": AgentStatus.LIVE}++ async def test_a_connection_never_rescues_a_passive_agent(self) -> None:+ """session_passive has no heartbeat by definition — including this one."""+ agents = [_agent("passive", "session_passive")]+ store = _FakeSessionStore(live_ids={"passive"})+ registry = _registry(agent_id="passive", room="room-1")++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"passive": AgentStatus.AWAITING_MANUAL_POLL}++ async def test_a_dead_connection_is_not_presence(self) -> None:+ """Liveness is the heartbeat, not the socket."""+ import time as _time++ agents = [_agent("addr", "session_addressable")]+ store = _FakeSessionStore(live_ids=set())+ registry = _registry(agent_id="addr", room="room-1")+ conn = registry.get("c-addr")+ assert conn is not None+ # Stop beating: past the TTL the connection stops counting.+ conn.last_beat = _time.monotonic() - 3600++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"addr": AgentStatus.NO_SESSION}+++class TestSpawnCapableConnections:+ """A connection that will start a session is reported DORMANT, not absent.++ The promise is keyed off what the client *declared* when it connected, not+ off the agent's configured `connection_model`. A stale or mis-set enum+ otherwise produces "my connector isn't reporting in" while a watcher sits+ connected and about to spawn — which is exactly what it looked like in+ production.+ """++ async def test_a_spawn_capable_watcher_makes_an_addressable_agent_dormant(+ self,+ ) -> None:+ agents = [_agent("addr", "session_addressable")]+ store = _FakeSessionStore(live_ids=set())+ registry = _registry(agent_id="addr", scope="all", spawn_capable=True)++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"addr": AgentStatus.DORMANT}++ async def test_a_watcher_that_cannot_spawn_leaves_it_absent(self) -> None:+ agents = [_agent("addr", "session_addressable")]+ store = _FakeSessionStore(live_ids=set())+ registry = _registry(agent_id="addr", scope="all", spawn_capable=False)++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"addr": AgentStatus.NO_SESSION}++ async def test_a_live_session_still_wins_over_dormant(self) -> None:+ agents = [_agent("addr", "session_addressable")]+ store = _FakeSessionStore(live_ids=set())+ registry = _registry(agent_id="addr", room="room-1", spawn_capable=True)++ statuses = await compute_agent_statuses(None, agents, "room-1", store, registry)++ assert statuses == {"addr": AgentStatus.LIVE}diff --git a/core/tests/switch_core/bridges/agent/protocol/test_stream.py b/core/tests/switch_core/bridges/agent/protocol/test_stream.pynew file mode 100644index 000000000..0dff4793f--- /dev/null+++ b/core/tests/switch_core/bridges/agent/protocol/test_stream.py@@ -0,0 +1,538 @@+"""SSE delivery: catch-up, live push, resume and the control events (CHOO-1857)."""++from __future__ import annotations++import asyncio+import json+from typing import Any++import pytest++from switch_core.bridges.agent.protocol import stream as stream_module+from switch_core.bridges.agent.protocol.connections import (+ HEARTBEAT_TTL_SECONDS,+ PROTOCOL_VERSION,+ ConnectionRegistry,+)+from switch_core.bridges.agent.protocol.event_buffer import EventBuffer+from switch_core.bridges.agent.protocol.stream import event_stream+from switch_core.bridges.agent.protocol.types import AgentEvent, MessagePayload++AGENT = "agent-1"+ROOM_A = "room-a"+ROOM_B = "room-b"+++def _message(body: str, *, addressed: bool = False, room: str = ROOM_A) -> AgentEvent:+ return AgentEvent(+ type="message",+ room_id=room,+ payload=MessagePayload(+ addressed=addressed,+ sender="@u:s",+ sender_name="u",+ message_id=f"$evt-{body}",+ body=body,+ timestamp=0,+ ),+ )+++def _parse(frame: bytes) -> tuple[str, dict[str, Any]]:+ """Split one SSE frame into (event name, data)."""+ text = frame.decode()+ name = ""+ data = "{}"+ for line in text.strip().splitlines():+ if line.startswith("event: "):+ name = line[len("event: ") :]+ elif line.startswith("data: "):+ data = line[len("data: ") :]+ return name, json.loads(data)+++async def _take(stream, count: int, timeout: float = 2.0) -> list[tuple[str, dict]]:+ """Pull `count` non-keepalive frames off the stream."""+ out: list[tuple[str, dict]] = []++ async def pump() -> None:+ async for frame in stream:+ if frame.startswith(b":"):+ continue+ out.append(_parse(frame))+ if len(out) >= count:+ return++ await asyncio.wait_for(pump(), timeout=timeout)+ return out+++def _open(registry: ConnectionRegistry, **kw: Any):+ params: dict[str, Any] = {+ "agent_id": AGENT,+ "connection_id": kw.pop("connection_id", "c1"),+ "scope": "single",+ "delivery_filter": "all",+ "spawn_capable": False,+ "cursor": 0,+ "protocol_version": PROTOCOL_VERSION,+ }+ params.update(kw)+ return registry.open(**params)+++async def test_first_frame_is_the_connection_state() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ ((name, data),) = await _take(stream, 1)++ assert name == "connection_state"+ assert data["connection_id"] == "c1"+ assert data["scope"] == "single"+ assert data["rooms"] == [ROOM_A]+ assert data["protocol"] == PROTOCOL_VERSION+++async def test_catch_up_then_live_delivery() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)++ # Queued before the stream opened: must be caught up, not skipped.+ buffer.enqueue(AGENT, ROOM_A, _message("before"))++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)+ assert frames[1][0] == "message"+ assert frames[1][1]["payload"]["body"] == "before"++ # Appended while the stream is open: pushed without being asked for.+ async def append_soon() -> None:+ await asyncio.sleep(0.01)+ buffer.enqueue(AGENT, ROOM_A, _message("after"))++ task = asyncio.create_task(append_soon())+ live = await _take(stream, 1)+ await task++ assert live[0][1]["payload"]["body"] == "after"+++async def test_sequence_number_is_carried_for_resume() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)+ seq = buffer.enqueue(AGENT, ROOM_A, _message("one"))++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)++ assert frames[1][1]["sequence"] == seq+ assert conn.cursor == seq+++async def test_resuming_from_a_cursor_skips_what_was_already_seen() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ first = buffer.enqueue(AGENT, ROOM_A, _message("seen"))+ buffer.enqueue(AGENT, ROOM_A, _message("missed"))++ conn = _open(registry, cursor=first)+ registry.claim_room(conn, ROOM_A)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)++ assert frames[1][1]["payload"]["body"] == "missed"+++async def test_expired_cursor_produces_a_gap_event_rather_than_silence() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer(max_events_per_agent=1)+ buffer.enqueue(AGENT, ROOM_A, _message("dropped"))+ buffer.enqueue(AGENT, ROOM_A, _message("kept"))++ conn = _open(registry, cursor=0)+ registry.claim_room(conn, ROOM_A)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)++ assert frames[1][0] == "gap"+ assert "re-read" in frames[1][1]["reason"]+++async def test_events_for_rooms_the_connection_does_not_cover_are_skipped() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)++ buffer.enqueue(AGENT, ROOM_B, _message("elsewhere", room=ROOM_B))+ buffer.enqueue(AGENT, ROOM_A, _message("mine"))++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)++ assert frames[1][1]["payload"]["body"] == "mine"+++async def test_addressed_filter_drops_ambient_chatter() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry, scope="all", delivery_filter="addressed")++ buffer.enqueue(AGENT, ROOM_A, _message("chatter"))+ buffer.enqueue(AGENT, ROOM_B, _message("wanted", addressed=True, room=ROOM_B))++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)++ assert frames[1][1]["payload"]["body"] == "wanted"+++async def test_a_superseded_stream_is_told_it_was_evicted() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ await _take(stream, 1)++ # A second stream attaches to the same connection id.+ _open(registry)+ buffer.enqueue(AGENT, ROOM_A, _message("wake up"))++ frames = await _take(stream, 1)+ assert frames[0][0] == "evicted"+++async def test_closing_the_connection_ends_the_stream_with_a_reason() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ await _take(stream, 1)++ registry.close(conn.id, "heartbeat lapsed")++ frames = await _take(stream, 1)+ assert frames[0][0] == "evicted"+ assert frames[0][1]["reason"] == "heartbeat lapsed"+++async def test_subscription_change_is_announced() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ await _take(stream, 1)++ registry.claim_room(conn, ROOM_B)++ frames = await _take(stream, 1)+ assert frames[0][0] == "subscription_changed"+ assert frames[0][1]["rooms"] == [ROOM_B]+++async def test_stream_detaches_on_exit_without_killing_the_connection() -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ await _take(stream, 1)+ await stream.aclose()++ assert not conn.stream_attached+ assert registry.get(conn.id) is conn++[email protected]("scope", ["single", "all"])+async def test_two_connections_receive_the_same_event(scope: str) -> None:+ """Non-destructive reads: one reader must not steal from another."""+ registry = ConnectionRegistry()+ buffer = EventBuffer()++ session = registry.open(+ agent_id=AGENT,+ connection_id="session",+ scope="single",+ delivery_filter="all",+ spawn_capable=False,+ cursor=0,+ protocol_version=PROTOCOL_VERSION,+ )+ registry.claim_room(session, ROOM_A)++ other_agent = registry.open(+ agent_id="agent-2",+ connection_id="other",+ scope=scope, # type: ignore[arg-type]+ delivery_filter="all",+ spawn_capable=False,+ cursor=0,+ protocol_version=PROTOCOL_VERSION,+ )+ registry.claim_room(other_agent, ROOM_A)++ buffer.enqueue(AGENT, ROOM_A, _message("shared"))+ buffer.enqueue("agent-2", ROOM_A, _message("shared"))++ a = event_stream(conn=session, registry=registry, buffer=buffer)+ b = event_stream(conn=other_agent, registry=registry, buffer=buffer)++ assert (await _take(a, 2))[1][1]["payload"]["body"] == "shared"+ assert (await _take(b, 2))[1][1]["payload"]["body"] == "shared"+++async def test_resume_replays_buffered_events_for_a_room_claimed_at_open() -> None:+ """The reconnect case the whole design exists for.++ A client that drops and comes back declares its room when it reopens. If+ the room were only claimed after the stream started, catch-up would run+ first, skip those events as "not covered", and advance the cursor past+ them — losing exactly what resume is meant to recover.+ """+ registry = ConnectionRegistry()+ buffer = EventBuffer()++ seen = buffer.enqueue(AGENT, ROOM_A, _message("before the drop"))+ buffer.enqueue(AGENT, ROOM_A, _message("while disconnected"))++ conn = _open(registry, connection_id="c-resumed", cursor=seen)+ # Claimed before the stream is created, as the endpoint does.+ registry.claim_room(conn, ROOM_A)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)++ assert frames[1][0] == "message"+ assert frames[1][1]["payload"]["body"] == "while disconnected"+++async def test_events_for_uncovered_rooms_do_not_block_the_cursor() -> None:+ """Skipping is deliberate for rooms this connection does not cover."""+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)++ buffer.enqueue(AGENT, ROOM_B, _message("someone else's room", room=ROOM_B))+ last = buffer.enqueue(AGENT, ROOM_A, _message("mine"))++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)++ assert frames[1][1]["payload"]["body"] == "mine"+ assert conn.cursor == last+++async def test_a_cursor_from_before_a_restart_is_reported_not_ignored() -> None:+ """The buffer is in memory, so a restart resets the numbering.++ A client that comes back with a cursor from the previous process would+ otherwise sit quietly at a position that no longer means anything, looking+ caught up while its history has a hole in it.+ """+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ buffer.enqueue(AGENT, ROOM_A, _message("after the restart"))++ conn = _open(registry, cursor=4812) # from a previous life+ registry.claim_room(conn, ROOM_A)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)++ assert frames[1][0] == "gap"+ assert "restarted" in frames[1][1]["reason"]+++class TestALapsedHeartbeatStopsDelivery:+ """A connection nothing considers alive must not keep receiving.++ Every presence reader filters on liveness, so a connection whose heartbeat+ has lapsed is invisible to all of them — while its socket happily keeps+ handing over events. That pairing is undetectable from either side: the+ client sees traffic and assumes it is healthy, the room is told the agent is+ offline. It is what produced "my connector isn't reporting in" while+ switchdash was demonstrably receiving the same message and spawning a+ session from it.+ """++ async def test_the_stream_evicts_when_the_heartbeat_lapses(self) -> None:+ import time as _time++ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ # Consume the opening frame while still healthy.+ await _take(stream, 1)++ conn.last_beat = _time.monotonic() - (HEARTBEAT_TTL_SECONDS + 1)+ buffer.enqueue(AGENT, ROOM_A, _message("should not arrive"))++ ((name, data),) = await _take(stream, 1)++ assert name == "evicted"+ assert "heartbeat" in data["reason"]++ async def test_the_connection_is_closed_not_merely_ignored(self) -> None:+ """Otherwise the room slot stays claimed by a connection that is gone."""+ import time as _time++ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry)+ registry.claim_room(conn, ROOM_A)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ await _take(stream, 1)+ conn.last_beat = _time.monotonic() - (HEARTBEAT_TTL_SECONDS + 1)+ await _take(stream, 1)++ assert registry.claimant_of(AGENT, ROOM_A) is None+ assert conn.closed_reason is not None+++class TestFilteredEventsDoNotSpinTheLoop:+ """A connection must not busy-loop over events its filter excludes.++ `read_from` does not return filtered-out events, so unlike events skipped+ for room coverage they cannot advance the cursor on their way past. Left+ behind them, the stream's "anything new?" check is permanently true and the+ generator spins at full speed instead of awaiting.++ That is not a slow stream, it is a stopped server: one spinning generator+ starves the event loop, so no heartbeat is processed, so every connection in+ the process is declared dead and reconnects — which is exactly what was+ observed, with `beats=0` on connections that had only just opened.+ """++ async def test_the_cursor_advances_past_events_the_filter_excludes(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry, delivery_filter="addressed")+ registry.claim_room(conn, ROOM_A)++ # Unaddressed chatter: real events, none of them notifiable.+ for i in range(3):+ buffer.enqueue(AGENT, ROOM_A, _message(f"chatter-{i}", addressed=False))++ # Shorten the keepalive so "did it reach its wait?" is answered in+ # milliseconds. A spinning generator never yields one at any interval.+ monkeypatch.setattr(stream_module, "KEEPALIVE_INTERVAL_SECONDS", 0.05)++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ await _take(stream, 1) # connection_state+ await asyncio.wait_for(anext(stream), timeout=2.0)++ assert conn.cursor == buffer.head(AGENT)+ await stream.aclose()++ async def test_an_addressed_event_after_the_excluded_ones_still_arrives(+ self,+ ) -> None:+ """Advancing past the excluded events must not skip what follows."""+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry, delivery_filter="addressed")+ registry.claim_room(conn, ROOM_A)++ buffer.enqueue(AGENT, ROOM_A, _message("chatter", addressed=False))+ buffer.enqueue(AGENT, ROOM_A, _message("for-you", addressed=True))++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)++ assert frames[1][0] == "message"+ assert frames[1][1]["payload"]["body"] == "for-you"+ await stream.aclose()+++class TestAConnectionWithNoRoomDoesNotConsume:+ """A session connection must not burn through the buffer before it has a room.++ A session spawned to answer a message opens its connection *before* the+ session boots and calls connect_to_room. During that window it covers no+ room, so every event looks uncovered — and the skip path advances the+ cursor. Left to read, it consumes its way to the end of the buffer and the+ message it was started for is behind it by the time its room arrives.++ This is the last link in that chain: the spawn hand-off can pass the right+ cursor, the client can open at the right place, and the message is still+ lost here.+ """++ async def test_the_cursor_survives_the_wait_for_a_room(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(stream_module, "KEEPALIVE_INTERVAL_SECONDS", 0.05)+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ # Opened at 0, like a session handed its trigger's position.+ conn = _open(registry, cursor=0)++ buffer.enqueue(AGENT, ROOM_A, _message("the trigger", addressed=True))++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ await _take(stream, 1) # connection_state+ # Parked: a keepalive rather than the event, and no cursor movement.+ await asyncio.wait_for(anext(stream), timeout=2.0)++ assert conn.cursor == 0+ await stream.aclose()++ async def test_the_trigger_arrives_once_the_room_is_claimed(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(stream_module, "KEEPALIVE_INTERVAL_SECONDS", 0.05)+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry, cursor=0)++ buffer.enqueue(AGENT, ROOM_A, _message("the trigger", addressed=True))++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ await _take(stream, 1)+ await asyncio.wait_for(anext(stream), timeout=2.0) # parked++ # connect_to_room, arriving late as it does in practice.+ registry.claim_room(conn, ROOM_A)++ frames = await _take(stream, 2)+ assert frames[0][0] == "subscription_changed"+ assert frames[1][0] == "message"+ assert frames[1][1]["payload"]["body"] == "the trigger"+ await stream.aclose()++ async def test_an_all_scope_connection_is_not_parked(self) -> None:+ """A watcher holds no room by design and must keep receiving."""+ registry = ConnectionRegistry()+ buffer = EventBuffer()+ conn = _open(registry, scope="all", connection_id="watcher")++ buffer.enqueue(AGENT, ROOM_A, _message("hello", addressed=True))++ stream = event_stream(conn=conn, registry=registry, buffer=buffer)+ frames = await _take(stream, 2)++ assert frames[1][0] == "message"+ await stream.aclose()diff --git a/core/tests/switch_core/bridges/agent/protocol/test_threads.py b/core/tests/switch_core/bridges/agent/protocol/test_threads.pyindex 7859c9179..048cd92f8 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_threads.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_threads.py@@ -6,6 +6,7 @@ from typing import Anyimport pytestfrom nio import RoomGetEventError+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolService@@ -55,6 +56,9 @@ class _FakeNio:def _service_with_client(nio: _FakeNio) -> ProtocolService:client = SimpleNamespace(nio_client=nio)svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()async def _require_room_member(agent_id: str, room_id: str) -> SimpleNamespace:return SimpleNamespace(matrix_room_id="!matrix:server")diff --git a/core/tests/switch_core/bridges/agent/protocol/test_update_room_bridge.py b/core/tests/switch_core/bridges/agent/protocol/test_update_room_bridge.pyindex 64f39a502..af0a4115a 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_update_room_bridge.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_update_room_bridge.py@@ -5,6 +5,7 @@ from typing import Anyimport pytest+from switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolService@@ -59,6 +60,9 @@ def _build_service() -> tuple[ProtocolService, _FakeRoomService]:room_service = _FakeRoomService()svc = object.__new__(ProtocolService)+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); an empty registry means "rows only".+ svc.connections = ConnectionRegistry()svc.session_factory = lambda: _FakeSession() # type: ignore[assignment]svc.room_store = _FakeRoomStore() # type: ignore[assignment]svc.bridge_store = _FakeBridgeStore(bridge_found) # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/agent/test_control_commands.py b/core/tests/switch_core/bridges/agent/test_control_commands.pyindex 81827ff6e..1d83aecb9 100644--- a/core/tests/switch_core/bridges/agent/test_control_commands.py+++ b/core/tests/switch_core/bridges/agent/test_control_commands.py@@ -61,7 +61,7 @@ def _client(async def _session_factory() -> Any:yield SimpleNamespace()- async def _agent_room_role(_s: Any, _r: str, _a: str) -> None:+ async def _agent_room_role(_s: Any, _r: str, _a: str, _alive: Any = ()) -> None:return Nonereturn SimpleNamespace(@@ -71,7 +71,10 @@ def _client(session_factory=_session_factory,_agent_session_store=SimpleNamespace(),_room_role_store=SimpleNamespace(agent_room_role=_agent_room_role),- _event_queue=SimpleNamespace(enqueue=lambda *a, **k: enqueue.append((a, k))),+ # Presence unions the heartbeat rows with the live connections+ # (CHOO-1857); nothing is connected in these tests.+ _connections=SimpleNamespace(live_agent_ids=lambda: set()),+ _event_buffer=SimpleNamespace(enqueue=lambda *a, **k: enqueue.append((a, k))),)diff --git a/core/tests/switch_core/clients/test_admin_client.py b/core/tests/switch_core/clients/test_admin_client.pyindex 6424a2299..1129456e2 100644--- a/core/tests/switch_core/clients/test_admin_client.py+++ b/core/tests/switch_core/clients/test_admin_client.py@@ -9,6 +9,23 @@ from switch_core.clients.admin_messages import ADMIN_MARKER, AdminMessageTypefrom switch_core.events import CommandEvent+def _no_connections() -> SimpleNamespace:+ """A connection registry with nothing live.++ Presence is the union of the heartbeat rows and the live connections+ (CHOO-1857); these tests drive the DB arm, so the connection arm must+ contribute nothing.+ """+ return SimpleNamespace(+ live_agent_ids=lambda: set(),+ is_live=lambda _agent_id: False,+ live_in_room=lambda _agent_id, _room_id: False,+ has_session_in=lambda _agent_id, _room_id: False,+ can_spawn_for=lambda _agent_id, _room_id: False,+ for_agent=lambda _agent_id: [],+ )++def _event(body: str, sender_name: str = "alice") -> SimpleNamespace:"""A room message as the admin client sees it: body + sender + thebridge-provided sender_name in content (used to tag the asker)."""@@ -53,7 +70,7 @@ def _admin_client(async def _list_roles(_session, _room_id): # type: ignore[no-untyped-def]return roles- async def _has_live_holder(_session, role_id): # type: ignore[no-untyped-def]+ async def _has_live_holder(_session, role_id, _alive=()): # type: ignore[no-untyped-def]return role_id in live_role_idsasync def _get_by_name_insensitive(_session, name): # type: ignore[no-untyped-def]@@ -79,6 +96,7 @@ def _admin_client(client = SimpleNamespace(session_factory=_session_factory,+ _connections=_no_connections(),send_message=_send_message,_room_store=SimpleNamespace(get_agent_ids=_get_agent_ids),_room_role_store=SimpleNamespace(diff --git a/core/tests/switch_core/clients/test_agent_client_attachment_groups.py b/core/tests/switch_core/clients/test_agent_client_attachment_groups.pyindex 3432c3d3f..85c4010ae 100644--- a/core/tests/switch_core/clients/test_agent_client_attachment_groups.py+++ b/core/tests/switch_core/clients/test_agent_client_attachment_groups.py@@ -68,7 +68,7 @@ def _fake_client() -> SimpleNamespace:ns = SimpleNamespace(agent=SimpleNamespace(id="agent-1", name="agent-a"),- _event_queue=queue,+ _event_buffer=queue,_attachment_groups={},_attachment_group_timers={},_resolve_room_meta=_resolve_room_meta,diff --git a/core/tests/switch_core/clients/test_mention_routing.py b/core/tests/switch_core/clients/test_mention_routing.pyindex 09aef6cfb..091d9de02 100644--- a/core/tests/switch_core/clients/test_mention_routing.py+++ b/core/tests/switch_core/clients/test_mention_routing.py@@ -10,6 +10,23 @@ from switch_core.clients.agent_client import ()+def _no_connections() -> SimpleNamespace:+ """A connection registry with nothing live.++ Presence is the union of the heartbeat rows and the live connections+ (CHOO-1857); these tests drive the DB arm, so the connection arm must+ contribute nothing.+ """+ return SimpleNamespace(+ live_agent_ids=lambda: set(),+ is_live=lambda _agent_id: False,+ live_in_room=lambda _agent_id, _room_id: False,+ has_session_in=lambda _agent_id, _room_id: False,+ can_spawn_for=lambda _agent_id, _room_id: False,+ for_agent=lambda _agent_id: [],+ )++def _event(body: str, formatted_body: str | None = None) -> SimpleNamespace:return SimpleNamespace(body=body, formatted_body=formatted_body)@@ -137,12 +154,13 @@ def _role_client(agent_name: str, held_role: str | None) -> SimpleNamespace:async def _session_factory(): # type: ignore[no-untyped-def]yield object()- async def _agent_room_role(_session, _room_id, _agent_id): # type: ignore[no-untyped-def]+ async def _agent_room_role(_session, _room_id, _agent_id, _alive=()): # type: ignore[no-untyped-def]return held_rolereturn SimpleNamespace(agent=SimpleNamespace(id="agent-1", name=agent_name),session_factory=_session_factory,+ _connections=_no_connections(),_room_role_store=SimpleNamespace(agent_room_role=_agent_room_role),)@@ -207,6 +225,7 @@ def _alias_client(agent_name: str, alias_by_room: dict[str, str]) -> SimpleNamesreturn SimpleNamespace(agent=SimpleNamespace(id="agent-1", name=agent_name),session_factory=_session_factory,+ _connections=_no_connections(),_room_store=SimpleNamespace(get_alias=_get_alias),)@@ -311,7 +330,7 @@ def _unavailable_client(async def _live_connected_rooms(_session, _agent_id): # type: ignore[no-untyped-def]return list(live_rooms)- async def _agent_room_role(_session, _room_id, _agent_id): # type: ignore[no-untyped-def]+ async def _agent_room_role(_session, _room_id, _agent_id, _alive=()): # type: ignore[no-untyped-def]return "worker" if role_here else Noneasync def _has_room_binding(_session, _agent_id, _room_id): # type: ignore[no-untyped-def]@@ -341,6 +360,7 @@ def _unavailable_client(agent=agent,_fresh_agent=_fresh_agent,session_factory=_session_factory,+ _connections=_no_connections(),_room_role_store=SimpleNamespace(agent_room_role=_agent_room_role),_agent_session_store=SimpleNamespace(live_connected_rooms=_live_connected_rooms,diff --git a/core/tests/switch_core/clients/test_no_session_reply_threading.py b/core/tests/switch_core/clients/test_no_session_reply_threading.pyindex 2db474b38..b694ffa91 100644--- a/core/tests/switch_core/clients/test_no_session_reply_threading.py+++ b/core/tests/switch_core/clients/test_no_session_reply_threading.py@@ -63,7 +63,7 @@ def _fake_self(_is_available=_is_available,_reply_when_unavailable_here=_reply_when_unavailable_here,send_message=send_message,- _event_queue=SimpleNamespace(enqueue=lambda *a, **k: None),+ _event_buffer=SimpleNamespace(enqueue=lambda *a, **k: None),)# Exercise the real sender-tagging helper.ns._sender_handle = AgentClient._sender_handle.__get__(ns)diff --git a/core/tests/switch_core/clients/test_room_join_events.py b/core/tests/switch_core/clients/test_room_join_events.pyindex f64ea6bb6..7585c8f73 100644--- a/core/tests/switch_core/clients/test_room_join_events.py+++ b/core/tests/switch_core/clients/test_room_join_events.py@@ -48,7 +48,7 @@ def _client(meta: RoomMeta | None = None, *, receives: bool = True) -> SimpleNamyield SimpleNamespace()return SimpleNamespace(- _event_queue=_FakeQueue(),+ _event_buffer=_FakeQueue(),agent=SimpleNamespace(id="agent-1"),_resolve_room_meta=_resolve_room_meta,_room_store=_FakeRoomStore(receives),@@ -86,8 +86,8 @@ class TestRoomJoinEnqueue:client = _client()await _run(client, _member_event())- assert len(client._event_queue.enqueued) == 1- agent_id, room_id, event = client._event_queue.enqueued[0]+ assert len(client._event_buffer.enqueued) == 1+ agent_id, room_id, event = client._event_buffer.enqueued[0]assert agent_id == "agent-1"assert room_id == "room-1"assert event.type == "room_join"@@ -106,8 +106,8 @@ class TestRoomJoinEnqueue:client = _client(receives=False)await _run(client, _member_event())- assert len(client._event_queue.enqueued) == 1- _, _, event = client._event_queue.enqueued[0]+ assert len(client._event_buffer.enqueued) == 1+ _, _, event = client._event_buffer.enqueued[0]assert event.payload.listening is Falseasync def test_missing_displayname_falls_back_to_localpart(self) -> None:@@ -117,20 +117,20 @@ class TestRoomJoinEnqueue:_member_event(displayname=None, state_key="@bob:switch.local"),)- assert len(client._event_queue.enqueued) == 1- _, _, event = client._event_queue.enqueued[0]+ assert len(client._event_buffer.enqueued) == 1+ _, _, event = client._event_buffer.enqueued[0]assert event.payload.member_name == "bob"async def test_leave_does_not_enqueue(self) -> None:client = _client()await _run(client, _member_event(membership="leave", prev_membership="join"))- assert client._event_queue.enqueued == []+ assert client._event_buffer.enqueued == []async def test_profile_update_does_not_enqueue(self) -> None:# membership-preserving update (e.g. display-name change): join -> join.client = _client()await _run(client, _member_event(membership="join", prev_membership="join"))- assert client._event_queue.enqueued == []+ assert client._event_buffer.enqueued == []async def test_no_room_meta_does_not_enqueue(self) -> None:async def _none(_matrix_room_id: str) -> RoomMeta | None:@@ -139,7 +139,7 @@ class TestRoomJoinEnqueue:client = _client()client._resolve_room_meta = _noneawait _run(client, _member_event())- assert client._event_queue.enqueued == []+ assert client._event_buffer.enqueued == []class TestRoomJoinPayloadRegistry:diff --git a/core/tests/switch_core/db/stores/test_room_role_store.py b/core/tests/switch_core/db/stores/test_room_role_store.pyindex 0edb656c6..01fd00d61 100644--- a/core/tests/switch_core/db/stores/test_room_role_store.py+++ b/core/tests/switch_core/db/stores/test_room_role_store.py@@ -362,3 +362,109 @@ class TestSharedRoles:await session.commit()leases = await store.live_leases_for_room(session, room.id)assert [lease.agent_id for lease in leases[role.id]] == [a2.id]+++class TestLeaseLivenessIsAUnion:+ """A lease survives on a fresh heartbeat OR a live connection (CHOO-1857).++ A client on the push transport sends one connection heartbeat and no+ `/leases/renew`, so freshness alone would drop its role within the TTL —+ silently, and within six seconds of it migrating. `alive_agent_ids` is the+ connection arm; an empty set means "freshness only", which is exactly what+ an un-migrated client still relies on.+ """++ async def test_a_stale_lease_survives_while_its_agent_is_connected(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = RoomRoleStore()+ async with session_factory() as session:+ room = await _make_room(session, "r1")+ agent = await _make_agent(session, "a1")+ role = await store.define_role(session, room.id, "manager", "lead", True)+ await session.commit()++ await store.acquire_lease(session, role, agent.id, "tx1")+ await session.commit()+ await _age_lease(+ session, agent.id, RoomRoleStore.LEASE_TTL + timedelta(seconds=5)+ )+ await session.commit()++ # Freshness alone: gone.+ assert await store.live_holders_for_room(session, room.id) == {}+ # With the connection arm: still held.+ assert await store.live_holders_for_room(session, room.id, {agent.id}) == {+ role.id: [agent.id]+ }++ async def test_a_connected_holder_still_blocks_an_exclusive_role(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The seat is not free just because the old heartbeat stopped.++ Without this, a second session could take a role its holder still has —+ the exact double-holder the exclusivity rule exists to prevent.+ """+ store = RoomRoleStore()+ async with session_factory() as session:+ room = await _make_room(session, "r1")+ a1 = await _make_agent(session, "a1")+ a2 = await _make_agent(session, "a2")+ role = await store.define_role(session, room.id, "manager", "lead", True)+ await session.commit()++ await store.acquire_lease(session, role, a1.id, "tx1")+ await session.commit()+ await _age_lease(+ session, a1.id, RoomRoleStore.LEASE_TTL + timedelta(seconds=5)+ )+ await session.commit()++ with pytest.raises(ValueError, match="exclusive"):+ await store.acquire_lease(session, role, a2.id, "tx2", {a1.id})++ async def test_an_unconnected_agent_does_not_keep_a_stale_lease(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The connection arm names specific agents; it is not a blanket amnesty."""+ store = RoomRoleStore()+ async with session_factory() as session:+ room = await _make_room(session, "r1")+ a1 = await _make_agent(session, "a1")+ a2 = await _make_agent(session, "a2")+ role = await store.define_role(session, room.id, "manager", "lead", True)+ await session.commit()++ await store.acquire_lease(session, role, a1.id, "tx1")+ await session.commit()+ await _age_lease(+ session, a1.id, RoomRoleStore.LEASE_TTL + timedelta(seconds=5)+ )+ await session.commit()++ # Some *other* agent is connected: a1's lease is still stale.+ assert await store.live_holders_for_room(session, room.id, {a2.id}) == {}++ async def test_agent_room_role_reads_through_the_connection_arm(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = RoomRoleStore()+ async with session_factory() as session:+ room = await _make_room(session, "r1")+ agent = await _make_agent(session, "a1")+ role = await store.define_role(session, room.id, "manager", "lead", True)+ await session.commit()++ await store.acquire_lease(session, role, agent.id, "tx1")+ await session.commit()+ await _age_lease(+ session, agent.id, RoomRoleStore.LEASE_TTL + timedelta(seconds=5)+ )+ await session.commit()++ assert await store.agent_room_role(session, room.id, agent.id) is None+ assert (+ await store.agent_room_role(session, room.id, agent.id, {agent.id})+ == role.name+ )diff --git a/core/uv.lock b/core/uv.lockindex 44a6dddc6..862b7f2f5 100644--- a/core/uv.lock+++ b/core/uv.lock@@ -2433,7 +2433,7 @@ wheels = [[[package]]name = "switch-core"-version = "0.9.0"+version = "0.10.0"source = { editable = "." }dependencies = [{ name = "aiohttp" },diff --git a/dash/AGENTS.md b/dash/AGENTS.mdindex 234c08bb6..25748cc85 100644--- a/dash/AGENTS.md+++ b/dash/AGENTS.md@@ -328,6 +328,63 @@ pnpm run lint- Do not bypass path-safety, shell escaping, or validation helpers.- Use `pnpm-lock.yaml` for dependency integrity and review dependency changes.+## The Sidecar Mirrors switchdash — Check Both++`src/sidecar/` is a second, headless implementation of what the desktop app does+for a session: it starts sessions, keeps them connected to their room, and+injects messages into their pane. It runs on the agent's VM with no Electron, no+database and no renderer.++**So whenever you add or change logic in the desktop app, ask whether the sidecar+needs the same thing — and answer it in the same change.** Not "later": the+sidecar has no UI, so when it lacks something the symptom is a remote session+that quietly does less than a local one, and nobody notices until someone is+debugging a VM.++The pairs that must stay in step:++| Desktop | Sidecar | Shared by |+|---|---|---|+| `agent-runtime/impl/local-agent-runtime.ts` (spawn env) | `sidecar/session-spawner.ts` + `sidecar/index.ts` | nothing — **the usual place to forget** |+| `switch-rooms/auto-session-watcher.ts` | `sidecar/notification-watcher.ts` | nothing — two implementations of one watcher |+| `switch-rooms/room-connection.ts` | — | shared: the sidecar constructs the same class |+| protocol client (stream, heartbeat, cursor) | — | shared: `@sandbox-quantum/switch-agent-runtime` |++Where a row says *shared*, a change lands in both for free — prefer putting+logic there. Where it says *nothing*, you are editing one of two copies and the+other will not follow you.++Things that reach a session through its **environment** are the sharpest edge,+because both sides build that separately. If you add a variable in+`local-agent-runtime`, it almost certainly belongs in the sidecar's `switchEnv`+too.++## Versioned Artifacts — Bump Them++Three things here ship independently of the app and carry their own version.+**If you make a non-trivial change to one, bump its version in the same commit.**+Not at release time, not "later" — in the commit that changes it, or it will be+forgotten and someone will debug a build they think is newer than it is.++| Artifact | Version lives in | Bump when |+|---|---|---|+| Remote sidecar | `src/sidecar/sidecar-version.ts` | any behaviour change; **major only** on a client↔sidecar wire break (ready line, endpoint shapes, shared on-disk layout) |+| Claude Code plugin | `connectors/claude-code-plugin/.claude-plugin/plugin.json` | any change to the plugin — installs will not pick it up otherwise |+| Agent runtime package | `packages/switch-agent-runtime/package.json` | any change; it is published, and `.mcp.json` pins an exact version that must move with it |++"Non-trivial" means anything a user could observe: behaviour, protocol, wiring,+dependencies. A comment or a rename that changes nothing does not need one.++Two traps worth knowing rather than rediscovering:++- **A sidecar major replaces every sidecar on sight, live sessions included.**+ It is judged on the contract *switchdash* speaks to, not on how much changed+ inside. Changing how the sidecar talks to Switch is not a major.+- **Redeploy is decided by the bundle's content hash, not by the version.** So a+ forgotten bump does not strand a VM on old code — but it does make the version+ a lie, which is worse in its own way, because it is the number people reason+ from when something misbehaves.+## Agent Guardrails- Load only the relevant `agents/` docs for the area being changed.diff --git a/dash/apps/switchdash-desktop/package.json b/dash/apps/switchdash-desktop/package.jsonindex 607347ac6..c5bdeefdf 100644--- a/dash/apps/switchdash-desktop/package.json+++ b/dash/apps/switchdash-desktop/package.json@@ -51,6 +51,7 @@},"dependencies": {"@parcel/watcher": "^2.5.6",+ "@sandbox-quantum/switch-agent-runtime": "workspace:*","@switchdash/core": "workspace:*","@switchdash/plugins": "workspace:*","@switchdash/shared": "workspace:*",diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.tsindex 6e9c7a27a..922dc4139 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts@@ -40,6 +40,77 @@ describe('parseHookEvent', () => {expect(parsed).toEqual({ kind: 'ignore' });});+ /**+ * A local MCP runtime that returns only text content — no structuredContent —+ * surfaces the tool result as an envelope, with the fields one level down.+ * Reading only the top level meant the hook was silently ignored: the session+ * was never bound to its room, so the sidebar showed no room AND the room+ * poller was never started, which looked like "messages stopped arriving".+ */+ describe('tool responses that arrive as an MCP content envelope', () => {+ const payload = { room_id: 'room-1', agent_id: 'agent-1', name: 'Room One' };+ const expected = {+ kind: 'switch-room',+ ctx,+ roomId: 'room-1',+ agentId: 'agent-1',+ roomName: 'Room One',+ };++ it('reads structuredContent when the server provides it', async () => {+ const parsed = await parseHookEvent(+ raw('switch_room_connect', {+ tool_response: {+ content: [{ type: 'text', text: JSON.stringify(payload) }],+ structuredContent: payload,+ },+ }),+ fixedResolver+ );+ expect(parsed).toEqual(expected);+ });++ it('falls back to parsing the text block when it does not', async () => {+ const parsed = await parseHookEvent(+ raw('switch_room_connect', {+ tool_response: { content: [{ type: 'text', text: JSON.stringify(payload) }] },+ }),+ fixedResolver+ );+ expect(parsed).toEqual(expected);+ });++ it('handles a bare content array', async () => {+ const parsed = await parseHookEvent(+ raw('switch_room_connect', {+ tool_response: [{ type: 'text', text: JSON.stringify(payload) }],+ }),+ fixedResolver+ );+ expect(parsed).toEqual(expected);+ });++ it('still ignores an envelope carrying no room', async () => {+ const parsed = await parseHookEvent(+ raw('switch_room_connect', {+ tool_response: { content: [{ type: 'text', text: '{"ok":true}' }] },+ }),+ fixedResolver+ );+ expect(parsed).toEqual({ kind: 'ignore' });+ });++ it('prefers a direct top-level result over the envelope', async () => {+ const parsed = await parseHookEvent(+ raw('switch_room_connect', {+ ...{ tool_response: { ...payload, content: [{ type: 'text', text: '{}' }] } },+ }),+ fixedResolver+ );+ expect(parsed).toEqual(expected);+ });+ });+it('throws when the context resolver cannot resolve the ptyId', async () => {const nullResolver: ContextResolver = async () => null;await expect(parseHookEvent(raw('Stop', {}), nullResolver)).rejects.toThrow(diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.tsindex 20df99d5b..70d10e73f 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts@@ -39,11 +39,22 @@ const SWITCH_ROOM_CONNECT_EVENT = 'switch_room_connect';/*** Claude reports the tool result under `tool_response`, which may arrive as an- * already-parsed object or a JSON string. The Switch `connect_to_room` result- * carries `room_id` and `agent_id`.+ * already-parsed object, a JSON string, or an MCP content envelope. The Switch+ * `connect_to_room` result carries `room_id` and `agent_id`.+ *+ * The envelope case matters: a server that returns only text content — no+ * `structuredContent` — surfaces as `{content: [{type: 'text', text: '<json>'}]}`+ * or as the bare content array. The fields are in there, one level down. Failing+ * to look meant the hook was silently ignored and the session was never bound to+ * its room: no room in the sidebar, and no room poller started either.*/function parseToolResponse(body: Record<string, unknown>): Record<string, unknown> | null {- const raw = body.tool_response;+ const direct = coerceObject(body.tool_response);+ if (direct && ('room_id' in direct || 'agent_id' in direct)) return direct;+ return unwrapContentEnvelope(body.tool_response) ?? direct;+}++function coerceObject(raw: unknown): Record<string, unknown> | null {if (raw && typeof raw === 'object') return raw as Record<string, unknown>;if (typeof raw === 'string') {try {@@ -54,6 +65,22 @@ function parseToolResponse(body: Record<string, unknown>): Record<string, unknowreturn null;}+/** Pull the first JSON object out of an MCP text-content envelope. */+function unwrapContentEnvelope(raw: unknown): Record<string, unknown> | null {+ const container = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : null;+ const structured = coerceObject(container?.structuredContent);+ if (structured) return structured;++ const blocks = Array.isArray(raw) ? raw : container?.content;+ if (!Array.isArray(blocks)) return null;+ for (const block of blocks) {+ const text = (block as Record<string, unknown> | null)?.text;+ const parsed = typeof text === 'string' ? coerceObject(text) : null;+ if (parsed) return parsed;+ }+ return null;+}+function parseBody(raw: RawHookRequest): Record<string, unknown> {if (!raw.body) return {};try {diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.tsindex 793f80a05..d14be4844 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts@@ -44,7 +44,7 @@ vi.mock('@main/core/agent-hooks/dir-trust-service', () => ({// electron-compiled.vi.mock('@main/core/switch-rooms/switch-room-service', () => ({switchRoomService: {- restorePoller: vi.fn(() => Promise.resolve()),+ restoreConnection: vi.fn(() => Promise.resolve()),clearSession: vi.fn(),},}));@@ -52,6 +52,9 @@ vi.mock('@main/core/switch-rooms/switch-room-service', () => ({vi.mock('@main/core/switch-rooms/switch-notification-poller', () => ({switchNotificationPoller: {disconnect: vi.fn(),+ // Sessions in these tests are not Switch agents, so no connection is+ // opened and no SWITCH_CONNECTION_ID reaches the spawn.+ ensureForSession: vi.fn(async () => null),},}));@@ -59,6 +62,12 @@ vi.mock('@main/core/switch-rooms/switch-credentials', () => ({readAgentSwitchEnv: vi.fn(async () => ({})),}));+// Reads the app's userData path and shells out to `gh`; neither exists here,+// and these tests are about the spawn, not the registry.+vi.mock('@main/core/switch-rooms/npm-registry-auth', () => ({+ npmRegistryAuthEnv: vi.fn(async () => ({})),+}));+vi.mock('@main/core/providers/plugin-registry', () => ({getPlugin: vi.fn((id: string) => ({metadata: { id },diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.tsindex 9220a5ff3..aed5be977 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts@@ -20,6 +20,7 @@ import { getTerminalColorEnv } from '@main/core/pty/terminal-color-scheme';import { killTmuxSession, makeAgentTmuxSessionName } from '@main/core/pty/tmux-session-name';import { sessionHooks } from '@main/core/sessions/session-hooks';import { providerOverrideSettings } from '@main/core/settings/provider-settings-service';+import { npmRegistryAuthEnv } from '@main/core/switch-rooms/npm-registry-auth';import { readAgentSwitchEnv } from '@main/core/switch-rooms/switch-credentials';import { switchNotificationPoller } from '@main/core/switch-rooms/switch-notification-poller';import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';@@ -176,6 +177,60 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {const tmuxSessionName = this.tmux ? makeAgentTmuxSessionName(this.sessionId) : undefined;+ const ptyId = makePtyId(session.providerId, this.sessionId);+ const port = agentHookService.getPort();+ const token = agentHookService.getToken();+ const colorEnv = await getTerminalColorEnv();+ // A session talks to Switch as its own agent, not whatever identity happens+ // to sit in `.claude/settings.local.json`. Real env vars outrank every+ // settings file and reach the spawned MCP server, so inject the agent's+ // identity last (highest precedence): a subagent from its definition creds,+ // and a plain agent from its provider-neutral `.switch/agents/<id>.json`+ // (empty when absent — the session then falls back to settings.local.json,+ // which Claude reads natively). Lets agents sharing a location keep distinct+ // identities (CHOO-1440).+ const subagentVars =+ session.agentName && repoAgents+ ? await repoAgents.readLaunchEnv(createPluginFs(this.sessionPath), session.agentName)+ : await readAgentSwitchEnv(agentSettingsPath(this.sessionPath, session.agentId), log);++ // Open this session's Switch connection before the session exists, and+ // hand it the id. Its tool calls then arrive on the connection switchdash+ // is reading, so `connect_to_room` claims the room *there* and the server+ // tells us which room the session is in. Before this, the two held+ // separate connections and switchdash had to infer the room by scraping+ // the agent's tool response through a hook.+ //+ // Order matters: the server refuses a call naming a connection that is+ // not open, and the session may call connect_to_room immediately.+ // Null when the session has no Switch credentials — most sessions —+ // in which case nothing here applies and the var is simply absent.+ const switchConnectionId = await switchNotificationPoller.ensureForSession({+ sessionId: this.sessionId,+ providerId: session.providerId,+ ptyId,+ });++ // The Claude Code plugin resolves its MCP server with `npx` from a+ // private registry, so the session needs to know where that registry is+ // and how to authenticate. Empty when `gh` has no token, which lets the+ // session start regardless — a session with no MCP server beats no+ // session, and the missing login is reported at host setup.+ const npmAuthEnv = await npmRegistryAuthEnv();++ const sessionEnv = {+ ...buildAgentEnv({+ hook: port > 0 ? { port, ptyId, token } : undefined,+ providerVars,+ shellProfile: this.shellProfile,+ }),+ ...colorEnv,+ ...this.sessionEnvVars,+ ...subagentVars,+ ...npmAuthEnv,+ ...(switchConnectionId ? { SWITCH_CONNECTION_ID: switchConnectionId } : {}),+ };+const resolved = resolveLocalPtySpawn({platform: process.platform,env: process.env,@@ -186,6 +241,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {shellProfile: this.shellProfile,shellSetup: this.shellSetup,tmuxSessionName,+ paneEnv: tmuxSessionName ? sessionEnv : undefined,},});@@ -193,37 +249,12 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {sessionId: ptySessionId,});- const ptyId = makePtyId(session.providerId, this.sessionId);- const port = agentHookService.getPort();- const token = agentHookService.getToken();- const colorEnv = await getTerminalColorEnv();- // A session talks to Switch as its own agent, not whatever identity happens- // to sit in `.claude/settings.local.json`. Real env vars outrank every- // settings file and reach the spawned MCP server, so inject the agent's- // identity last (highest precedence): a subagent from its definition creds,- // and a plain agent from its provider-neutral `.switch/agents/<id>.json`- // (empty when absent — the session then falls back to settings.local.json,- // which Claude reads natively). Lets agents sharing a location keep distinct- // identities (CHOO-1440).- const subagentVars =- session.agentName && repoAgents- ? await repoAgents.readLaunchEnv(createPluginFs(this.sessionPath), session.agentName)- : await readAgentSwitchEnv(agentSettingsPath(this.sessionPath, session.agentId), log);const pty = spawnLocalPty({id: ptySessionId,command: resolved.command,args: resolved.args,cwd: resolved.cwd,- env: {- ...buildAgentEnv({- hook: port > 0 ? { port, ptyId, token } : undefined,- providerVars,- shellProfile: this.shellProfile,- }),- ...colorEnv,- ...this.sessionEnvVars,- ...subagentVars,- },+ env: sessionEnv,cols: spawnSize.cols,rows: spawnSize.rows,});@@ -282,7 +313,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {// resume polling that room — the connect_to_room hook only fires on a// live tool call, so a resumed session would otherwise go silent.void switchRoomService- .restorePoller({+ .restoreConnection({sessionId: this.sessionId,providerId: session.providerId,ptyId,diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.tsindex 33bbb67d9..8b37279f7 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts@@ -48,6 +48,15 @@ vi.mock('@main/core/pty/ssh2-pty', () => ({ openSsh2Pty }));vi.mock('@main/core/pty/spawn-utils', () => ({ resolveSshCommand }));+const remoteNpmRegistryAuthEnv = vi.hoisted(() =>+ vi.fn(async () => ({+ npm_config_userconfig: '/repo/.switchdash/npmrc',+ SWITCHDASH_GITHUB_TOKEN: 'remote-tok',+ }))+);++vi.mock('@main/core/switch-rooms/npm-registry-auth', () => ({ remoteNpmRegistryAuthEnv }));+vi.mock('@main/core/pty/terminal-color-scheme', () => ({getTerminalColorEnv: vi.fn(async () => ({})),}));@@ -205,6 +214,7 @@ describe('SshAgentRuntime', () => {buildCommandMock.mockReturnValue({ command: 'agent', args: [], env: {} });resolveSshCommand.mockClear();deployAndLaunch.mockClear();+ remoteNpmRegistryAuthEnv.mockClear();sidecarStop.mockClear();httpPostJsonOverChannel.mockClear();vi.mocked(events.emit).mockClear();@@ -324,6 +334,40 @@ describe('SshAgentRuntime', () => {expect(env.SWITCH_CHANNEL_DISABLE_POLL).toBe('1');});+ // The runtime is fetched with `npx` from a private registry, so without this+ // the remote session comes up with no MCP server and npm reports a 404 that+ // names neither the registry nor the missing credential.+ it('gives a freshly launched remote session its registry access', async () => {+ const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];+ mockSpawn(exitHandlers);++ await sshProvider({ tmux: true }).start(session());++ expect(remoteNpmRegistryAuthEnv).toHaveBeenCalledTimes(1);+ const env = (resolveSshCommand.mock.calls[0] as unknown[])[2] as Record<string, string>;+ expect(env.npm_config_userconfig).toBe('/repo/.switchdash/npmrc');+ expect(env.SWITCHDASH_GITHUB_TOKEN).toBe('remote-tok');+ });++ // Re-attach must be decided before the launch branch runs, because+ // `launchSidecar()` assigns `this.relay`. Read afterwards, every fresh launch+ // looks like a re-attach and silently loses its registry config.+ it('does not recompute registry access when re-attaching', async () => {+ const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];+ mockSpawn(exitHandlers);++ await sshProvider({ tmux: true }).start(session());+ expect(remoteNpmRegistryAuthEnv).toHaveBeenCalledTimes(1);++ for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 1 });+ emitReconnected('ssh-1');+ await vi.waitFor(() => expect(openSsh2Pty).toHaveBeenCalledTimes(2));++ // The pane still has the environment it was created with; tmux applies+ // `-e` only at creation, so recomputing would cost round trips for nothing.+ expect(remoteNpmRegistryAuthEnv).toHaveBeenCalledTimes(1);+ });+it('starts the hook-event relay against the sidecar endpoint when tmux is on', async () => {const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];mockSpawn(exitHandlers);diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.tsindex 3eddc80f4..bc81bf7a3 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts@@ -20,6 +20,7 @@ import { providerOverrideSettings } from '@main/core/settings/provider-settings-import { sshConnectionManager } from '@main/core/ssh/lifecycle/production-ssh-connection-manager';import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';import type { SshConnectionManagerEvent } from '@main/core/ssh/lifecycle/ssh-connection-manager';+import { remoteNpmRegistryAuthEnv } from '@main/core/switch-rooms/npm-registry-auth';import { events } from '@main/lib/events';import { runWithLogContext } from '@main/lib/log-context';import { log } from '@main/lib/logger';@@ -477,8 +478,13 @@ export class SshAgentRuntime implements AgentRuntimeProvider {// switchdash is closed; it injects room messages into the agent's tmux pane.// It therefore requires tmux, must be up before the agent so the agent's// hook env can point at it, and shares the tmux session as its inject target.+ // Decided before the branch below, not inside it: `launchSidecar()`+ // assigns `this.relay`, so once it has run a fresh launch is+ // indistinguishable from a re-attach.+ const reattaching = Boolean(tmuxSessionName && this.relay);+let hookEnv: Record<string, string> = {};- if (tmuxSessionName && this.relay) {+ if (reattaching) {// Re-attach path (e.g. after an SSH reconnect): the agent is still// running in its tmux pane and the sidecar + its self-healing relay are// already live, so re-open the PTY onto the existing pane and skip the@@ -508,6 +514,13 @@ export class SshAgentRuntime implements AgentRuntimeProvider {);}+ // Skipped on the re-attach path above: the pane already has its+ // environment and tmux applies `-e` only when it creates a session, so+ // recomputing this would cost two round trips and change nothing.+ const npmAuthEnv = reattaching+ ? {}+ : await remoteNpmRegistryAuthEnv(this.ctx, this.sessionPath);+const [profile, colorEnv] = await Promise.all([this.proxy.getRemoteShellProfile(),getTerminalColorEnv(),@@ -515,7 +528,14 @@ export class SshAgentRuntime implements AgentRuntimeProvider {const sshCommand = resolveSshCommand('agent',cfg,- { ...providerEnv, ...colorEnv, ...this.sessionEnvVars, ...hookEnv, ...identityVars },+ {+ ...providerEnv,+ ...colorEnv,+ ...this.sessionEnvVars,+ ...hookEnv,+ ...npmAuthEnv,+ ...identityVars,+ },profile);diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/pty-spawn-platform.test.ts b/dash/apps/switchdash-desktop/src/main/core/pty/pty-spawn-platform.test.tsindex b67b10090..9723750f5 100644--- a/dash/apps/switchdash-desktop/src/main/core/pty/pty-spawn-platform.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/pty/pty-spawn-platform.test.ts@@ -638,4 +638,64 @@ describe('resolveLocalPtySpawn - POSIX', () => {warnings: [],});});++ // A tmux pane inherits the tmux SERVER's environment, not that of the shell+ // running `new-session`, so env handed to the pty stops at that boundary+ // unless `new-session -e` repeats it. Local sessions used to omit it while+ // remote ones passed it, which left tmux-enabled local sessions without the+ // registry config and hook credentials their non-tmux equivalents had.+ describe('tmux pane environment', () => {+ const paneEnv = {+ npm_config_userconfig: '/home/me/.config/switchdash/npm/npmrc',+ SWITCH_CONNECTION_ID: 'conn-1',+ };++ it('passes paneEnv to new-session for run-command', () => {+ const result = resolveLocalPtySpawn({+ platform: 'linux',+ env: posixEnv,+ intent: {+ kind: 'run-command',+ cwd: '/repo',+ command: { kind: 'argv', command: 'claude', args: [] },+ tmuxSessionName: 'session-1',+ paneEnv,+ },+ });++ const line = result.args.at(-1) ?? '';+ expect(line).toContain("-e 'npm_config_userconfig=/home/me/.config/switchdash/npm/npmrc'");+ expect(line).toContain("-e 'SWITCH_CONNECTION_ID=conn-1'");+ });++ it('passes paneEnv to new-session for interactive-shell', () => {+ const result = resolveLocalPtySpawn({+ platform: 'linux',+ env: posixEnv,+ intent: {+ kind: 'interactive-shell',+ cwd: '/repo',+ tmuxSessionName: 'session-1',+ paneEnv,+ },+ });++ expect(result.args.at(-1) ?? '').toContain("-e 'SWITCH_CONNECTION_ID=conn-1'");+ });++ it('omits -e entirely when there is no paneEnv', () => {+ const result = resolveLocalPtySpawn({+ platform: 'linux',+ env: posixEnv,+ intent: {+ kind: 'run-command',+ cwd: '/repo',+ command: { kind: 'argv', command: 'claude', args: [] },+ tmuxSessionName: 'session-1',+ },+ });++ expect(result.args.at(-1) ?? '').not.toContain('-e ');+ });+ });});diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/pty-spawn-platform.ts b/dash/apps/switchdash-desktop/src/main/core/pty/pty-spawn-platform.tsindex a0cd8d10d..803a08011 100644--- a/dash/apps/switchdash-desktop/src/main/core/pty/pty-spawn-platform.ts+++ b/dash/apps/switchdash-desktop/src/main/core/pty/pty-spawn-platform.ts@@ -10,22 +10,34 @@ export type PtyCommandSpec =| { kind: 'argv'; command: string; args: string[] }| { kind: 'shell-line'; commandLine: string };+/**+ * Environment for the tmux pane, set with `new-session -e`.+ *+ * Only meaningful alongside `tmuxSessionName`. A pane inherits the tmux+ * SERVER's environment rather than that of the shell running `new-session`,+ * so anything handed to the pty — hook credentials, registry config, the+ * Switch connection id — stops at that boundary unless it is repeated here.+ * Without it a tmux session sees a materially different environment from an+ * otherwise identical non-tmux one.+ */+type PaneEnv = { paneEnv?: Record<string, string> };+export type PtySpawnIntent =- | {+ | ({kind: 'interactive-shell';cwd: string;shellProfile?: ResolvedShellProfile;shellSetup?: string;tmuxSessionName?: string;- }- | {+ } & PaneEnv)+ | ({kind: 'run-command';cwd: string;command: PtyCommandSpec;shellProfile?: ResolvedShellProfile;shellSetup?: string;tmuxSessionName?: string;- };+ } & PaneEnv);export type LocalPtySpawnWarning = 'shell_setup_ignored_on_windows' | 'tmux_unsupported_on_windows';@@ -358,7 +370,7 @@ function resolvePosixSpawn(intent: PtySpawnIntent, env: NodeJS.ProcessEnv): Resocommand: shell,args: [...(intent.shellSetup ? setupWrapperArgs : commandArgs),- buildTmuxShellLine(intent.tmuxSessionName, commandLine),+ buildTmuxShellLine(intent.tmuxSessionName, commandLine, intent.paneEnv),],cwd: intent.cwd,warnings: [],@@ -401,7 +413,10 @@ function resolvePosixSpawn(intent: PtySpawnIntent, env: NodeJS.ProcessEnv): Resoif (intent.tmuxSessionName) {return {command: shell,- args: [...commandArgs, buildTmuxShellLine(intent.tmuxSessionName, fullCommandLine)],+ args: [+ ...commandArgs,+ buildTmuxShellLine(intent.tmuxSessionName, fullCommandLine, intent.paneEnv),+ ],cwd: intent.cwd,warnings: [],};diff --git a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.tsindex 85e4f16c5..ab693706d 100644--- a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts@@ -51,7 +51,23 @@ export type RemoteDependencyView = {ghAuth?: GhAuthStatus;};-export type GhAuthStatus = { authenticated: boolean; account: string | null };+export type GhAuthStatus = {+ authenticated: boolean;+ account: string | null;+ /**+ * Whether the token can read GitHub Packages.+ *+ * Authenticated is not sufficient: `gh auth login` requests `gist`,+ * `read:org`, `repo` and `workflow`, and not `read:packages`. Sessions on+ * this host fetch their MCP runtime from GitHub Packages, so without it they+ * start with no tools and the registry's `403 … does not match expected+ * scopes` is the only clue — reported nowhere near the host that caused it.+ *+ * A host set up before this was requested will be authenticated with this+ * false; `gh auth refresh -h github.com -s read:packages` fixes it.+ */+ canReadPackages: boolean;+};export type TestConnectionResult = { ok: true } | { ok: false; message: string };@@ -83,11 +99,16 @@ async function probeGhAuth(sshHost: string): Promise<GhAuthStatus> {const ctx = new SshExecutionContext(proxy);try {const { stdout, stderr } = await ctx.exec('gh', ['auth', 'status']);- const account = GH_AUTH_ACCOUNT_RE.exec(`${stdout}\n${stderr}`)?.[1] ?? null;- return { authenticated: true, account };+ const output = `${stdout}\n${stderr}`;+ const account = GH_AUTH_ACCOUNT_RE.exec(output)?.[1] ?? null;+ // gh prints "Token scopes: 'gist', 'read:org', …". Absent on very old+ // versions, in which case assume the scope is there rather than nagging+ // about something we cannot see.+ const canReadPackages = !output.includes('Token scopes:') || output.includes('read:packages');+ return { authenticated: true, account, canReadPackages };} catch (error) {if (isTransportFailure(error)) throw error;- return { authenticated: false, account: null };+ return { authenticated: false, account: null, canReadPackages: false };}}@@ -205,13 +226,31 @@ async function getHostSetup(sshHost: string): Promise<HostSetupStatus> {* can attach a live terminal (subscribe to output, send keystrokes) via the pty* RPC/events. gh prints a one-time code and a verification URL; the user opens the* URL in their own browser and enters the code. Returns the PTY session id.+ *+ * `read:packages` is requested explicitly because `gh auth login` does not ask+ * for it — its defaults are `gist`, `read:org`, `repo` and `workflow`. Sessions+ * on this host fetch their MCP runtime from GitHub Packages, and without that+ * scope the registry refuses with+ * `403 … token provided does not match expected scopes`, several layers below+ * anything that mentions `gh`. Asking for it during the one interactive login+ * the user already performs is the only point where it costs nothing; every+ * other route ends in `gh auth refresh` on a box they thought was set up.*/async function startGhAuth(sshHost: string): Promise<{ sessionId: string }> {const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);const profile = await proxy.getRemoteShellProfile();+ // Login when logged out, refresh when already logged in. `gh auth login` on+ // an authenticated host stops to ask whether you meant to re-authenticate,+ // which is a confusing thing to meet when all you needed was a scope; `gh+ // auth refresh` adds it without disturbing the existing login. Both are the+ // same device-code flow in this PTY, so the user sees no difference.const remoteCommand = buildRemoteShellCommand(profile,- 'gh auth login --hostname github.com --git-protocol https --web'+ 'if gh auth status >/dev/null 2>&1; then ' ++ 'gh auth refresh --hostname github.com --scopes read:packages; ' ++ 'else ' ++ 'gh auth login --hostname github.com --git-protocol https --web --scopes read:packages; ' ++ 'fi');const sessionId = `gh-auth:${crypto.randomUUID()}`;diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.tsindex 263d32152..7329af652 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts@@ -1,7 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';const createSession = vi.fn();-const getConnections = vi.fn();const getAgentById = vi.fn();vi.mock('@main/lib/logger', () => ({@@ -12,13 +11,20 @@ vi.mock('@main/core/sessions/session-service', () => ({sessionService: { createSession: (...args: unknown[]) => createSession(...args) },}));-vi.mock('./switch-room-service', () => ({- switchRoomService: { getConnections: () => getConnections() },-}));-// spawnForRoom reads the agent to decide autoApprove; startForAgent / the loops// also touch this. Route it through a controllable mock so tests can set the// per-agent flag.+const getConnections = vi.fn(() => [] as Array<{ roomId: string; agentId: string | null }>);+vi.mock('./switch-room-service', () => ({+ switchRoomService: {+ getConnections: () => getConnections(),+ onSessionRoomChanged: () => () => {},+ },+}));+vi.mock('./switch-notification-poller', () => ({+ switchNotificationPoller: { noteSpawnTrigger: vi.fn() },+}));+vi.mock('@main/core/agents/getAgentById', () => ({getAgentById: (...args: unknown[]) => getAgentById(...args),}));@@ -39,6 +45,7 @@ function fakeWatcher() {localAgentId: 'local-1',creds: CREDS,inFlight: new Map<string, ReturnType<typeof setTimeout>>(),+ connectionId: 'watch-conn-1',};}@@ -54,13 +61,13 @@ describe('AutoSessionWatcher.handleNotification', () => {beforeEach(() => {createSession.mockReset();getConnections.mockReset();+ getConnections.mockReturnValue([]);getAgentById.mockReset();getAgentById.mockResolvedValue({ id: 'local-1', autoApprove: false });createSession.mockResolvedValue({ success: true, data: { session: { id: 'new' } } });});it('spawns a session when no live session is attending the room', async () => {- getConnections.mockReturnValue([]);const watcher = fakeWatcher();handle(watcher, 'room-x');@@ -72,7 +79,6 @@ describe('AutoSessionWatcher.handleNotification', () => {});it('spawns with permissions enforced when the agent has autoApprove off', async () => {- getConnections.mockReturnValue([]);getAgentById.mockResolvedValue({ id: 'local-1', autoApprove: false });const watcher = fakeWatcher();@@ -84,7 +90,6 @@ describe('AutoSessionWatcher.handleNotification', () => {});it('spawns with permissions bypassed when the agent has autoApprove on', async () => {- getConnections.mockReturnValue([]);getAgentById.mockResolvedValue({ id: 'local-1', autoApprove: true });const watcher = fakeWatcher();@@ -95,19 +100,7 @@ describe('AutoSessionWatcher.handleNotification', () => {expect(params.autoApprove).toBe(true);});- it('does not spawn when a live session already attends the room', async () => {- getConnections.mockReturnValue([- { sessionId: 'c1', roomId: 'room-x', agentId: 'switch-agent-1' },- ]);- const watcher = fakeWatcher();-- handle(watcher, 'room-x');- await new Promise((r) => setTimeout(r, 10));- expect(createSession).not.toHaveBeenCalled();- });-it('in-flight guard prevents a second spawn for the same room', async () => {- getConnections.mockReturnValue([]);const watcher = fakeWatcher();handle(watcher, 'room-x');@@ -116,13 +109,99 @@ describe('AutoSessionWatcher.handleNotification', () => {expect(createSession).toHaveBeenCalledTimes(1);});- it('treats a live session in a different room as not attending', async () => {- getConnections.mockReturnValue([- { sessionId: 'c1', roomId: 'other-room', agentId: 'switch-agent-1' },- ]);- const watcher = fakeWatcher();+ /**+ * "A session already attends this room" is no longer checked here — the+ * server never delivers the event, because the session's connection claims+ * the room and this watcher's `all`-scope connection goes dark on it. The+ * guarantee moved rather than disappeared, and it is covered on the server+ * side (room slots) and by the stream tests.+ *+ * What stays here is the boot window, which no server can close.+ */+ describe('the boot window', () => {+ it('spawns exactly one session when messages arrive during boot', async () => {+ // The spawned session takes tens of seconds to start and claim the room.+ // Until it does, the server still sees the room as unattended and keeps+ // delivering — so every message in that window would spawn again.+ const watcher = fakeWatcher();++ handle(watcher, 'room-x');+ handle(watcher, 'room-x');+ handle(watcher, 'room-x');+ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));+ await new Promise((r) => setTimeout(r, 20));++ expect(createSession).toHaveBeenCalledTimes(1);+ });++ it("does not let one room's boot block another room", async () => {+ const watcher = fakeWatcher();++ handle(watcher, 'room-x');+ handle(watcher, 'room-y');+ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(2));++ const rooms = createSession.mock.calls.map(+ (c) => (c[0] as { initialPrompt: string }).initialPrompt+ );+ expect(rooms.some((p) => p.includes('room-x'))).toBe(true);+ expect(rooms.some((p) => p.includes('room-y'))).toBe(true);+ });++ it('spawns again for a room whose guard has been cleared', async () => {+ // Cleared when the session connects (or on the TTL backstop). A session+ // that dies must be replaceable — a guard that never cleared would leave+ // the room permanently unattended.+ const watcher = fakeWatcher();++ handle(watcher, 'room-x');+ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));++ const timer = watcher.inFlight.get('room-x');+ if (timer) clearTimeout(timer);+ watcher.inFlight.delete('room-x');++ handle(watcher, 'room-x');+ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(2));+ });+ });- handle(watcher, 'room-x');- await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));+ /**+ * The restore window: switchdash has a session for this room, but its+ * connection has not claimed the room yet — so the server still reports the+ * room as unattended and delivers the event here.+ *+ * The server owns "who is in this room" once it has been told. Before that+ * there are windows only switchdash can see: a session booting, and one being+ * restored after a restart. Spawning in either gives the user a second+ * session beside a working one.+ */+ describe('a session we already have', () => {+ it('does not spawn when one of our sessions attends the room', async () => {+ getConnections.mockReturnValue([{ roomId: 'room-x', agentId: CREDS.agentId }]);+ const watcher = fakeWatcher();++ handle(watcher, 'room-x');+ await new Promise((r) => setTimeout(r, 20));++ expect(createSession).not.toHaveBeenCalled();+ });++ it('still spawns when our session is in a different room', async () => {+ getConnections.mockReturnValue([{ roomId: 'other-room', agentId: CREDS.agentId }]);+ const watcher = fakeWatcher();++ handle(watcher, 'room-x');+ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));+ });++ it('still spawns when the room is attended by a different agent', async () => {+ // Two agents can share a room; another agent's session is not ours.+ getConnections.mockReturnValue([{ roomId: 'room-x', agentId: 'someone-else' }]);+ const watcher = fakeWatcher();++ handle(watcher, 'room-x');+ await vi.waitFor(() => expect(createSession).toHaveBeenCalledTimes(1));+ });});});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.tsindex f1830fcea..abbbe10ef 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts@@ -1,5 +1,6 @@import { randomUUID } from 'node:crypto';import path from 'node:path';+import { SwitchEventStream } from '@sandbox-quantum/switch-agent-runtime';import { getRemoteAgentLocation } from '@main/core/agents/agent-location';import { getAgentById } from '@main/core/agents/getAgentById';import {@@ -8,9 +9,7 @@ import {} from '@main/core/agents/switch-settings-paths';import { getLocationById } from '@main/core/locations/store';import { sessionService } from '@main/core/sessions/session-service';-import { events } from '@main/lib/events';import { log } from '@main/lib/logger';-import { sessionRoomChangedChannel } from '@shared/core/switch-rooms/switchRoomEvents';import {listAutoSessionAgentIds,listAutoSessionSubagents,@@ -22,22 +21,18 @@ import {readSwitchAgentCredentialsFromSettings,type SwitchAgentCredentials,} from './switch-credentials';-import type { AgentBridgeEventResponse } from './switch-event-format';+import { switchNotificationPoller } from './switch-notification-poller';import { switchRoomService } from './switch-room-service';-const NOTIF_POLL_TIMEOUT_S = 10;-const INITIAL_BACKOFF_MS = 1000;-const MAX_BACKOFF_MS = 30_000;-// Refresh the global "watching" heartbeat well under the server's ALWAYS_ON_TTL-// (90s) so a dormant agent reports DORMANT (and replies "Starting a session…")-// while switchdash is up.-const WATCH_HEARTBEAT_INTERVAL_MS = 30_000;const SPAWN_MAX_ATTEMPTS = 3;const SPAWN_RETRY_DELAY_MS = 2000;-// How long a room stays "spawn in flight" before the guard is cleared. Covers-// the boot+connect window; once the session connects, the live-session check-// no-ops further notifications anyway. If the spawn failed, clearing lets the-// next notification retry.+// How long a room stays "spawn in flight" before the guard is cleared.+//+// This covers the window the server cannot: it learns a session exists only+// when that session's connection claims the room, tens of seconds after the+// process starts. Until then the room looks unattended and every further+// addressed message would spawn again. Cleared early once the session+// connects; this TTL is the backstop for a spawn that failed.const INFLIGHT_TTL_MS = 120_000;interface AgentWatcher {@@ -49,9 +44,21 @@ interface AgentWatcher {/** When set, spawn sessions as this Claude Code subagent of `localAgentId`. */agentName?: string;creds: SwitchAgentCredentials;- /** Room ids with a spawn in flight (booting / connecting) → guards against- * duplicate spawns while a notification storm lands during the boot window. */+ /**+ * Room ids with a spawn in flight (booting / connecting) → guards against+ * duplicate spawns while a notification storm lands during the boot window.+ *+ * This is NOT made redundant by the server's room slots. The server goes dark+ * on a room only once the spawned session's connection claims it, which is+ * tens of seconds after we start the process — until then the room genuinely+ * has nobody in it as far as the server can tell, and every further message+ * would spawn another session. No protocol rule can close that window,+ * because the fact "a process is booting here" exists only on this machine.+ */inFlight: Map<string, ReturnType<typeof setTimeout>>;+ /** Chosen once per watcher so the connection survives a dropped socket. */+ connectionId: string;+ stream?: SwitchEventStream;}/** Watcher map key for a subagent (distinct from its parent's plain id). */@@ -68,19 +75,6 @@ async function getAgentLocalDir(localAgentId: string): Promise<string | null> {return location.dir;}-/** Refresh the agent's global "watching" heartbeat. Throws on non-OK. */-async function postWatchHeartbeat(- creds: SwitchAgentCredentials,- signal: AbortSignal-): Promise<void> {- const resp = await fetch(`${creds.apiEndpoint}/agents/${creds.agentId}/watch/heartbeat`, {- method: 'POST',- headers: { Authorization: `Bearer ${creds.token}`, 'Content-Type': 'application/json' },- signal,- });- if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);-}-/** Post a message to a room on the agent's behalf (used for the spawn-failure* notice). Best-effort; throws on non-OK so the caller can log. */async function postRoomMessage(@@ -165,7 +159,13 @@ class AutoSessionWatcher {*/private subscribeToRoomConnections(): void {if (this.roomChangeUnsub) return;- this.roomChangeUnsub = events.on(sessionRoomChangedChannel, ({ roomId, agentId }) => {+ // An in-process subscription, NOT the `events` bus. In main, `events.emit`+ // is webContents.send and `events.on` is ipcMain.on — opposite directions+ // of the renderer bridge — so this listener never fired for a room+ // connected in main. The guard was therefore only ever cleared by its 120s+ // TTL, which is why a room whose session had already arrived kept+ // reporting "a spawn is already in flight".+ this.roomChangeUnsub = switchRoomService.onSessionRoomChanged(({ roomId, agentId }) => {if (!roomId || !agentId) return;for (const watcher of this.watchers.values()) {if (watcher.creds.agentId === agentId) this.clearInFlight(watcher, roomId);@@ -260,7 +260,12 @@ class AutoSessionWatcher {creds: SwitchAgentCredentials;}): void {const abort = new AbortController();- const watcher: AgentWatcher = { ...init, abort, inFlight: new Map() };+ const watcher: AgentWatcher = {+ ...init,+ abort,+ inFlight: new Map(),+ connectionId: randomUUID(),+ };this.watchers.set(init.key, watcher);log.info('AutoSessionWatcher: watching agent', {key: init.key,@@ -269,8 +274,7 @@ class AutoSessionWatcher {agentId: init.creds.agentId,});- void this.notificationLoop(watcher);- void this.watchHeartbeatLoop(watcher);+ void this.startStream(watcher);}/** Stop watching one local agent (toggle off / shutdown). */@@ -311,74 +315,81 @@ class AutoSessionWatcher {for (const id of [...this.watchers.keys()]) this.stopForAgent(id);}- private async watchHeartbeatLoop(watcher: AgentWatcher): Promise<void> {- const { abort, creds } = watcher;- log.debug('AutoSessionWatcher: watch-heartbeat loop started', {- localAgentId: watcher.localAgentId,- agentId: creds.agentId,- intervalMs: WATCH_HEARTBEAT_INTERVAL_MS,- });- while (!abort.signal.aborted) {- try {- await postWatchHeartbeat(creds, abort.signal);- } catch (error) {- if (abort.signal.aborted) return;- log.warn('AutoSessionWatcher: watch heartbeat error', {- agentId: creds.agentId,- error: String(error),- });- }- await new Promise((r) => setTimeout(r, WATCH_HEARTBEAT_INTERVAL_MS));- }- }-- private async notificationLoop(watcher: AgentWatcher): Promise<void> {+ /**+ * Open the watcher's connection: `all` scope, `addressed` filter.+ *+ * One connection replaces the `/notifications` poll AND the+ * `/watch/heartbeat` loop — its heartbeat is what makes the agent report+ * DORMANT (and answer "Starting a session…") rather than DISCONNECTED.+ *+ * `all` scope means the server delivers every room the agent belongs to+ * *except* those a session's connection has claimed. That is the split-brain+ * fix: "a session is already attending this room" stops being a fact+ * switchdash keeps its own copy of and starts being one the server enforces —+ * we simply never hear about a covered room.+ */+ private startStream(watcher: AgentWatcher): void {const { abort, creds } = watcher;- const url = `${creds.apiEndpoint}/agents/${creds.agentId}/notifications?timeout=${NOTIF_POLL_TIMEOUT_S}`;- let backoff = INITIAL_BACKOFF_MS;- log.debug('AutoSessionWatcher: notification loop started', {+ log.debug('AutoSessionWatcher: opening watch connection', {localAgentId: watcher.localAgentId,agentId: creds.agentId,- url,+ connectionId: watcher.connectionId,});- while (!abort.signal.aborted) {- try {- const resp = await fetch(url, {- headers: { Authorization: `Bearer ${creds.token}` },- signal: abort.signal,+ const stream = new SwitchEventStream({+ creds: { agentId: creds.agentId, apiEndpoint: creds.apiEndpoint, token: creds.token },+ connectionId: watcher.connectionId,+ scope: 'all',+ // Only reasons to start a session: addressed messages, task events, and+ // opted-in joins. Room chatter is not one.+ filter: 'addressed',+ rooms: [],+ // This watcher exists to spawn sessions; saying so is what licenses the+ // server's "Starting a session…" reply instead of reporting the agent+ // offline.+ spawnCapable: true,+ onEvent: (event) => {+ if (event.room_id) this.handleNotification(watcher, event.room_id, event.sequence);+ },+ onGap: (info) => {+ // A gap here means we may have missed a request to start a session.+ // There is nothing to replay it from, so say so loudly rather than let+ // an unanswered mention look like an idle agent.+ log.warn('AutoSessionWatcher: gap — may have missed a spawn trigger', {+ localAgentId: watcher.localAgentId,+ agentId: creds.agentId,+ fromSequence: info.fromSequence,+ reason: info.reason,});- if (resp.status === 204) {- backoff = INITIAL_BACKOFF_MS;- continue;- }- if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);-- backoff = INITIAL_BACKOFF_MS;- const data = (await resp.json()) as AgentBridgeEventResponse;- for (const event of data.events) {- this.handleNotification(watcher, event.room_id);- }- } catch (error) {- if (abort.signal.aborted) return;- log.warn('AutoSessionWatcher: notification poll error', {+ },+ onEvicted: (reason) => {+ log.warn('AutoSessionWatcher: watch connection evicted', {+ localAgentId: watcher.localAgentId,agentId: creds.agentId,- error: String(error),+ reason,});- await new Promise((r) => setTimeout(r, backoff));- backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);- }- }+ },+ log,+ signal: abort.signal,+ });+ watcher.stream = stream;+ stream.start();}- /** Decide whether to spawn for a notified room, with a per-room in-flight guard. */- private handleNotification(watcher: AgentWatcher, roomId: string): void {- // A live session is already attending this room — the existing per-room- // poller delivers the message; nothing to do.- const hasLiveSession = switchRoomService- .getConnections()- .some((c) => c.roomId === roomId && c.agentId === watcher.creds.agentId);- if (hasLiveSession) return;+ /**+ * Decide whether to spawn for a notified room, with a per-room in-flight guard.+ *+ * There is no longer a "does a session already cover this room?" check here.+ * The server answers that by never delivering the event: a session's+ * connection claims the room and this `all`-scope connection goes dark on it.+ * Keeping a local copy of that fact is what let switchdash and Switch+ * disagree — a stale map meaning either a duplicate session or none at all.+ *+ * The in-flight guard is a different thing and stays: it covers the window+ * between deciding to spawn and the spawned session claiming the room, which+ * the server cannot know about.+ */+ private handleNotification(watcher: AgentWatcher, roomId: string, sequence?: number): void {if (watcher.inFlight.has(roomId)) {log.info('AutoSessionWatcher: notification for room with a spawn already in flight — skipping duplicate spawn',@@ -387,6 +398,54 @@ class AutoSessionWatcher {return;}+ // A session of ours is already attending this room, even though the server+ // has not been told yet.+ //+ // In steady state the server answers this for us — it goes dark on a room a+ // session's connection has claimed, so we never hear about it. That leaves+ // two windows where only we can know: a session booting (the guard above),+ // and one being restored after a restart, whose connection is open but has+ // not yet claimed its room. Receiving an event for a room we are already+ // covering means we are in one of those windows, not that the room is+ // free — and spawning would give the user a second session beside a+ // perfectly good one.+ //+ // Read from the live connection map rather than the persisted one: a stale+ // row would block spawning forever, turning a duplicate session into an+ // unreachable agent, which is both worse and far harder to notice.+ const attending = switchRoomService+ .getConnections()+ .some((c) => c.roomId === roomId && c.agentId === watcher.creds.agentId);+ if (attending) {+ log.info('AutoSessionWatcher: a session of ours already attends this room', {+ event: 'auto_session_spawn_skipped_session_present',+ localAgentId: watcher.localAgentId,+ roomId,+ });+ return;+ }++ // Tell the poller where the session it is about to open should start+ // reading. We have already consumed this event — that is how we know to+ // spawn — so a session starting at head would come up having missed the+ // very message it exists to answer.+ if (sequence !== undefined) {+ switchNotificationPoller.noteSpawnTrigger(watcher.creds.agentId, sequence);+ }+ // The two halves of the hand-off are logged at both ends, so a session that+ // comes up without its triggering message can be diagnosed from the log+ // alone: this line says which event the spawn is for and where the session+ // should therefore start reading, and the poller's counterpart says where+ // it actually started.+ log.info('AutoSessionWatcher: spawning for event', {+ event: 'auto_session_spawn_trigger',+ localAgentId: watcher.localAgentId,+ agentId: watcher.creds.agentId,+ roomId,+ triggerSequence: sequence ?? null,+ sessionWillStartFrom: sequence === undefined ? 'head' : Math.max(sequence - 1, 0),+ });+const timer = setTimeout(() => watcher.inFlight.delete(roomId), INFLIGHT_TTL_MS);watcher.inFlight.set(roomId, timer);diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.test.tsnew file mode 100644index 000000000..4aa78067e--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it, vi } from 'vitest';+import type { IExecutionContext } from '@main/core/execution-context/types';+import { lacksReadPackages, NPMRC_CONTENTS } from '@shared/core/npm-registry';+import { remoteNpmRegistryAuthEnv } from './npm-registry-auth';++vi.mock('electron', () => ({ app: { getPath: () => '/userData' } }));+vi.mock('@main/lib/logger', () => ({+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+}));+vi.mock('@main/core/updates/github-token', () => ({+ GH_EXECUTABLE: 'gh',+ getGithubTokenFromGhCli: vi.fn(),+}));++type Call = { command: string; args: string[] };++function fakeCtx(handlers: {+ token?: () => Promise<{ stdout: string; stderr: string }>;+ status?: () => Promise<{ stdout: string; stderr: string }>;+ write?: () => Promise<{ stdout: string; stderr: string }>;+}): { ctx: IExecutionContext; calls: Call[] } {+ const calls: Call[] = [];+ const ok = async () => ({ stdout: '', stderr: '' });+ const ctx = {+ supportsLocalSpawn: false,+ exec: async (command: string, args: string[] = []) => {+ calls.push({ command, args });+ if (command === 'gh' && args[1] === 'token') return (handlers.token ?? ok)();+ if (command === 'gh' && args[1] === 'status') return (handlers.status ?? ok)();+ return (handlers.write ?? ok)();+ },+ execStreaming: async () => {},+ dispose: () => {},+ } as unknown as IExecutionContext;+ return { ctx, calls };+}++describe('lacksReadPackages', () => {+ it('flags a token missing the scope', () => {+ expect(lacksReadPackages("Token scopes: 'gist', 'read:org', 'repo'")).toBe(true);+ });++ it('accepts a token carrying it', () => {+ expect(lacksReadPackages("Token scopes: 'read:packages', 'repo'")).toBe(false);+ });++ // The output is human-readable and may change. Guessing wrong must not+ // produce a warning that sends someone chasing a scope they already have.+ it('says nothing when there is no scope line', () => {+ expect(lacksReadPackages('not logged in')).toBe(false);+ });+});++describe('remoteNpmRegistryAuthEnv', () => {+ it('writes the npmrc on the remote host and returns the env pointing at it', async () => {+ const { ctx, calls } = fakeCtx({+ token: async () => ({ stdout: 'ghp_remote\n', stderr: '' }),+ status: async () => ({ stdout: "Token scopes: 'read:packages'", stderr: '' }),+ });++ const env = await remoteNpmRegistryAuthEnv(ctx, '/home/ubuntu/repo');++ expect(env).toEqual({+ npm_config_userconfig: '/home/ubuntu/repo/.switchdash/npmrc',+ SWITCHDASH_GITHUB_TOKEN: 'ghp_remote',+ });++ // The file must be written on the remote host — the desktop's own npmrc+ // path does not exist there, which is the whole reason this exists.+ const write = calls.find((c) => c.command === 'sh');+ expect(write?.args[1]).toContain('/home/ubuntu/repo/.switchdash/npmrc');+ expect(write?.args[1]).toContain(NPMRC_CONTENTS.split('\n')[0]);+ });++ it('returns nothing when the remote host has no gh token', async () => {+ const { ctx } = fakeCtx({ token: async () => ({ stdout: ' \n', stderr: '' }) });+ expect(await remoteNpmRegistryAuthEnv(ctx, '/repo')).toEqual({});+ });++ // A session with no MCP server beats no session at all.+ it('returns nothing rather than throwing when gh is absent', async () => {+ const { ctx } = fakeCtx({+ token: async () => {+ throw new Error('command not found: gh');+ },+ });+ expect(await remoteNpmRegistryAuthEnv(ctx, '/repo')).toEqual({});+ });++ it('still returns the env when the scope probe fails', async () => {+ const { ctx } = fakeCtx({+ token: async () => ({ stdout: 'ghp_remote', stderr: '' }),+ status: async () => {+ throw new Error('gh auth status exploded');+ },+ });+ const env = await remoteNpmRegistryAuthEnv(ctx, '/repo');+ expect(env.SWITCHDASH_GITHUB_TOKEN).toBe('ghp_remote');+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.tsnew file mode 100644index 000000000..c10228111--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/npm-registry-auth.ts@@ -0,0 +1,161 @@+import { execFile } from 'node:child_process';+import { mkdir, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { promisify } from 'node:util';+import { app } from 'electron';+import type { IExecutionContext } from '@main/core/execution-context/types';+import { GH_EXECUTABLE, getGithubTokenFromGhCli } from '@main/core/updates/github-token';+import { log } from '@main/lib/logger';+import { quoteShellArg } from '@main/utils/shellEscape';+import {+ lacksReadPackages,+ NPMRC_CONTENTS,+ npmRegistryEnv,+ READ_PACKAGES_FIX,+} from '@shared/core/npm-registry';++const execFileAsync = promisify(execFile);++/**+ * Registry access for sessions switchdash starts, local and remote.+ *+ * Both functions here return an empty environment when `gh` has no usable+ * token. The caller should start the session anyway: one with no MCP server is+ * worse than one whose agent cannot reach Switch, and the warnings below name+ * the cause, which a bare npm 404 would not.+ *+ * See `@shared/core/npm-registry` for what the two settings are and why.+ */++const MISSING_SCOPE_DETAIL =+ 'gh auth login does not request read:packages, so the registry will refuse ' ++ 'with 403 and the session will start without its MCP tools';++function localNpmrcPath(): string {+ return join(app.getPath('userData'), 'npm', 'npmrc');+}++/**+ * Registry access for a session on this machine.+ *+ * The npmrc is ours, not the user's: `~/.npmrc` is their configuration and+ * editing it to make our plugin work is a reach, while a file in their project+ * shows up in git status. `npm_config_userconfig` makes npm read ours instead,+ * confining the footprint to switchdash's own directory.+ */+export async function npmRegistryAuthEnv(): Promise<Record<string, string>> {+ const token = await getGithubTokenFromGhCli();+ if (!token) {+ log.warn('npmRegistryAuth: no GitHub token from `gh` — the agent runtime will not resolve', {+ event: 'npm_registry_auth_missing_token',+ hint: 'run `gh auth login`; a private package reads as 404 without it',+ });+ return {};+ }++ try {+ const { stdout, stderr } = await execFileAsync(GH_EXECUTABLE, ['auth', 'status'], {+ timeout: 10_000,+ });+ if (lacksReadPackages(`${stdout}${stderr}`)) {+ log.warn('npmRegistryAuth: the GitHub token cannot read packages', {+ event: 'npm_registry_auth_missing_scope',+ fix: READ_PACKAGES_FIX,+ detail: MISSING_SCOPE_DETAIL,+ });+ }+ } catch {+ // Never fatal — a diagnostic, not a gate.+ }++ const path = localNpmrcPath();+ try {+ await mkdir(join(app.getPath('userData'), 'npm'), { recursive: true });+ // 0600: it carries no secret today, but it is npm auth configuration and+ // should not be world-readable if that ever changes.+ await writeFile(path, NPMRC_CONTENTS, { mode: 0o600 });+ } catch (error) {+ log.warn('npmRegistryAuth: could not write npmrc', {+ event: 'npm_registry_auth_write_failed',+ path,+ error: String(error),+ });+ return {};+ }++ log.info('npmRegistryAuth: registry access configured for spawned sessions', {+ event: 'npm_registry_auth_ready',+ npmrc: path,+ });+ return npmRegistryEnv(path, token);+}++/**+ * Registry access for a session on a remote host, over that host's execution+ * context.+ *+ * The desktop's own configuration is useless here: its npmrc path does not+ * exist on the VM and its token is the wrong machine's. Both have to be+ * produced there, which is why this exists rather than reusing the above.+ *+ * Writes to the same `<repoDir>/.switchdash/npmrc` the sidecar uses, so a host+ * ends up with one file however its sessions were started.+ */+export async function remoteNpmRegistryAuthEnv(+ ctx: IExecutionContext,+ repoDir: string+): Promise<Record<string, string>> {+ let token = '';+ try {+ const { stdout } = await ctx.exec('gh', ['auth', 'token'], { timeout: 15_000 });+ token = stdout.trim();+ } catch (error) {+ log.warn('npmRegistryAuth: `gh auth token` failed on the remote host', {+ event: 'npm_registry_auth_no_gh',+ error: String(error),+ });+ return {};+ }+ if (!token) {+ log.warn('npmRegistryAuth: no GitHub token on the remote host', {+ event: 'npm_registry_auth_missing_token',+ hint: 'run `gh auth login` there; the package is private and reads as 404 without it',+ });+ return {};+ }++ try {+ const { stdout, stderr } = await ctx.exec('gh', ['auth', 'status'], { timeout: 15_000 });+ if (lacksReadPackages(`${stdout}${stderr}`)) {+ log.warn('npmRegistryAuth: the remote GitHub token cannot read packages', {+ event: 'npm_registry_auth_missing_scope',+ fix: READ_PACKAGES_FIX,+ detail: MISSING_SCOPE_DETAIL,+ });+ }+ } catch {+ // Never fatal — a diagnostic, not a gate.+ }++ const dir = `${repoDir}/.switchdash`;+ const npmrc = `${dir}/npmrc`;+ try {+ await ctx.exec('sh', [+ '-c',+ `mkdir -p ${quoteShellArg(dir)} && printf %s ${quoteShellArg(NPMRC_CONTENTS)} > ${quoteShellArg(npmrc)} && chmod 600 ${quoteShellArg(npmrc)}`,+ ]);+ } catch (error) {+ log.warn('npmRegistryAuth: could not write npmrc on the remote host', {+ event: 'npm_registry_auth_write_failed',+ path: npmrc,+ error: String(error),+ });+ return {};+ }++ log.info('npmRegistryAuth: registry access configured for the remote session', {+ event: 'npm_registry_auth_ready',+ npmrc,+ });+ return npmRegistryEnv(npmrc, token);+}diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.tsindex e5fbe8a7b..b41178303 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts@@ -54,11 +54,38 @@ function messageEvent(}/**- * Serves one batch of events on the first `/events` poll, then parks the loop- * (a never-resolving promise) so the test controls exactly one poll cycle.- * runtime-state + connection/renew always succeed; their request bodies are- * captured on the returned mock for assertions.+ * Serves one batch of events on the `/events` SSE stream, then holds the stream+ * open (never closing it) so the connection neither reconnects nor spins.+ *+ * The stream is the transport under test, so this speaks real SSE framing —+ * `event:`/`id:`/`data:` — rather than handing the client pre-parsed objects.+ * `connection/beat` and `runtime-state` always succeed; their request bodies+ * are captured on the returned mock for assertions.*/+function sseBody(events: AgentBridgeEvent[]): ReadableStream<Uint8Array> {+ const encoder = new TextEncoder();+ return new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(+ encoder.encode(+ 'event: connection_state\n' ++ `data: ${JSON.stringify({ connection_id: 'c1', rooms: ['room-1'], cursor: 0 })}\n\n`+ )+ );+ events.forEach((event, i) => {+ controller.enqueue(+ encoder.encode(+ `id: ${i + 1}\nevent: ${event.type}\n` ++ `data: ${JSON.stringify({ ...event, sequence: i + 1 })}\n\n`+ )+ );+ });+ // Deliberately left open: closing would look like a dropped stream and+ // trigger a reconnect mid-assertion.+ },+ });+}+function makeFetch(events: AgentBridgeEvent[]) {let served = false;return vi.fn(async (url: string, _opts?: RequestInit) => {@@ -74,7 +101,7 @@ function makeFetch(events: AgentBridgeEvent[]) {if (u.includes('/events')) {if (!served) {served = true;- return { ok: true, status: 200, json: async () => ({ events }), text: async () => '' };+ return { ok: true, status: 200, body: sseBody(events), text: async () => '' };}return new Promise(() => {});}@@ -120,6 +147,7 @@ describe('RoomConnection', () => {creds,roomId: 'room-1',roomName: 'Room One',+ connectionId: 'conn-1',sessionId: 'session-1',sink,injector,@@ -493,15 +521,16 @@ describe('RoomConnection', () => {conn.stop();});- it('recovers the renew loop when a renew request hangs (aborts and retries)', async () => {- // First renew hangs until its signal aborts; later renews succeed. A wedge- // would mean only the one hung call is ever seen.- let renewCount = 0;+ it('recovers the heartbeat when a beat request hangs (aborts and retries)', async () => {+ // First beat hangs until its signal aborts; later beats succeed. A wedge+ // would mean only the one hung call is ever seen — and a heartbeat that has+ // stopped is a connection the server declares dead within its 6s TTL.+ let beats = 0;const fetchMock = vi.fn((url: string, opts?: RequestInit) => {const u = String(url);- if (u.includes('/connection/renew')) {- renewCount += 1;- if (renewCount === 1) {+ if (u.includes('/connection/beat')) {+ beats += 1;+ if (beats === 1) {return new Promise((_resolve, reject) => {opts?.signal?.addEventListener('abort', () =>reject(new DOMException('aborted', 'AbortError'))@@ -528,6 +557,7 @@ describe('RoomConnection', () => {creds,roomId: 'room-1',roomName: 'Room One',+ connectionId: 'conn-1',sessionId: 'session-1',sink: { acquire: () => ({ write: vi.fn() }) },injector,@@ -539,14 +569,13 @@ describe('RoomConnection', () => {});conn.start();- // The hung renew aborts on its own request timeout (RENEW_REQUEST_TIMEOUT_MS),- // then the loop backs off CONNECTION_RENEW_INTERVAL_MS and tries again. Wait- // past the timeout + interval and confirm a second renew was attempted.- await new Promise((r) => setTimeout(r, 4_000 + 2_000 + 500));- expect(renewCount).toBeGreaterThanOrEqual(2);+ // The hung beat aborts on its own request timeout (4s), which counts as a+ // failure, so the loop waits out one backoff (4s) before trying again.+ await new Promise((r) => setTimeout(r, 4_000 + 4_000 + 1_000));+ expect(beats).toBeGreaterThanOrEqual(2);conn.stop();- }, 15_000);+ }, 20_000);it('reset without a prior role reconnects without an assume-role clause', async () => {const target: InjectionTarget = { write: vi.fn() };@@ -560,17 +589,120 @@ describe('RoomConnection', () => {conn.stop();});- it('renews the role lease so an assumed role does not auto-release', async () => {- // Without a /leases/renew heartbeat the server drops the seat within- // LEASE_TTL (~6s), so any role assumed from a switchdash session releases- // "instantly". Confirm the loop posts to /leases/renew.+ it('sends one heartbeat and none of the three renews it replaced', async () => {+ // /connection/renew, /leases/renew and /watch/heartbeat collapse into+ // /connection/beat. The server unions connection liveness into presence and+ // role-lease liveness, so the seat and the session survive on this alone —+ // still posting the old renews would be duplicate work against endpoints+ // this client no longer depends on.const target: InjectionTarget = { write: vi.fn() };const { conn, fetchMock } = connect({ acquire: () => target }, []);await flush();- const leaseCalls = fetchMock.mock.calls.filter((c) => String(c[0]).includes('/leases/renew'));- expect(leaseCalls.length).toBeGreaterThanOrEqual(1);- expect((leaseCalls[0][1] as RequestInit).method).toBe('POST');+ const urls = fetchMock.mock.calls.map((c) => String(c[0]));+ const beats = urls.filter((u) => u.includes('/connection/beat'));+ expect(beats.length).toBeGreaterThanOrEqual(1);+ expect(urls.some((u) => u.includes('/connection/renew'))).toBe(false);+ expect(urls.some((u) => u.includes('/leases/renew'))).toBe(false);+ expect(urls.some((u) => u.includes('/watch/heartbeat'))).toBe(false);+ conn.stop();+ });++ it('reports its cursor on every beat so a reconnect can resume', async () => {+ // The cursor is what the whole transport turns on: without it the server+ // cannot know what this client has consumed, and resume degrades to the+ // poll's "whatever is in the queue now".+ const target: InjectionTarget = { write: vi.fn() };+ const { conn, fetchMock } = connect({ acquire: () => target }, [messageEvent(true)]);+ // Past one beat interval: the first beat fires before the stream has+ // delivered anything, so a second is needed to observe the cursor move.+ await new Promise((r) => setTimeout(r, 2_500));++ const beats = fetchMock.mock.calls.filter((c) => String(c[0]).includes('/connection/beat'));+ expect(beats.length).toBeGreaterThanOrEqual(1);+ const bodies = beats.map((c) => JSON.parse((c[1] as RequestInit).body as string));+ expect(bodies[0].connection_id).toEqual(expect.any(String));+ // The first beat fires before anything has been read, so it legitimately+ // reports 0; what matters is that the cursor is reported and advances once+ // an event has been delivered.+ expect(bodies[bodies.length - 1].cursor).toBeGreaterThanOrEqual(1);+ conn.stop();+ }, 10_000);++ it('declares its room when opening the stream, not after', async () => {+ // A room subscribed after the stream opens arrives too late for catch-up:+ // buffered events for it are skipped as "not covered" AND the cursor is+ // advanced past them, losing exactly what resume exists to recover.+ const target: InjectionTarget = { write: vi.fn() };+ const { conn, fetchMock } = connect({ acquire: () => target }, []);+ await flush();++ const open = fetchMock.mock.calls.find((c) => String(c[0]).includes('/events'));+ expect(open).toBeDefined();+ expect(String(open![0])).toContain('rooms=room-1');+ expect((open![1] as RequestInit).headers).toMatchObject({+ Accept: 'text/event-stream',+ });+ conn.stop();+ });++ it('tells the agent to re-read context when the server reports a gap', async () => {+ // A gap must never be silent: the session would otherwise carry on+ // believing its history is complete.+ const encoder = new TextEncoder();+ const fetchMock = vi.fn(async (url: string) => {+ const u = String(url);+ if (u.includes('/events')) {+ return {+ ok: true,+ status: 200,+ text: async (): Promise<string> => '',+ body: new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(+ encoder.encode(+ 'event: gap\n' ++ `data: ${JSON.stringify({+ from_sequence: 7,+ resumed_at: 7,+ reason: 'the server restarted since your last connection',+ })}\n\n`+ )+ );+ },+ }),+ };+ }+ return {+ ok: true,+ status: 200,+ json: async () => ({}),+ text: async (): Promise<string> => '',+ };+ });+ vi.stubGlobal('fetch', fetchMock);+ const target: InjectionTarget = { write: vi.fn() };+ const conn = new RoomConnection({+ creds,+ roomId: 'room-1',+ roomName: 'Room One',+ connectionId: 'conn-1',+ sessionId: 'session-1',+ sink: { acquire: () => target },+ injector,+ control,+ deeplinkScheme: 'switchdash',+ isHumanTyping: () => false,+ mediaDir,+ log: silentLog,+ });+ conn.start();+ await flush(8);++ const written = (target.write as ReturnType<typeof vi.fn>).mock.calls.map((c) => String(c[0]));+ const notice = written.find((w) => w.includes('read_context'));+ expect(notice).toBeDefined();+ expect(notice).toContain('missed');conn.stop();});@@ -578,14 +710,15 @@ describe('RoomConnection', () => {* An endpoint that is simply gone — a managed server's port after the stack* was destroyed — used to produce an unbounded stream of warnings: two renew* loops retrying every 2s with no backoff, plus a watchdog announcing the- * staleness they were already reporting.+ * staleness they were already reporting. One heartbeat replaced all three;+ * these keep the lesson attached to it.*/- describe('renew against a dead endpoint', () => {- /** Fails every renew; parks the poll loop so only renews are under test. */+ describe('heartbeat against a dead endpoint', () => {+ /** Fails every beat; parks the stream so only the heartbeat is under test. */function makeFailingFetch(shouldFail: () => boolean) {return vi.fn(async (url: string) => {const u = String(url);- if (u.includes('/renew')) {+ if (u.includes('/connection/beat')) {if (shouldFail()) throw new TypeError('fetch failed');return { ok: true, status: 200, json: async () => ({}), text: async () => '' };}@@ -600,6 +733,7 @@ describe('RoomConnection', () => {creds,roomId: 'room-1',roomName: 'Room One',+ connectionId: 'conn-1',sessionId: 'session-1',sink: { acquire: () => ({ write: vi.fn() }) },injector,@@ -621,18 +755,20 @@ describe('RoomConnection', () => {vi.useRealTimers();});- it('backs off instead of retrying every two seconds forever', async () => {+ it('backs off instead of beating every two seconds forever', async () => {vi.useFakeTimers();const fetchMock = makeFailingFetch(() => true);const conn = connectWith(fetchMock);await vi.advanceTimersByTimeAsync(120_000);const attempts = fetchMock.mock.calls.filter((c) =>- String(c[0]).includes('/connection/renew')+ String(c[0]).includes('/connection/beat')).length;- // Unbounded retries at the 2s heartbeat would be ~60 in two minutes; with- // the backoff capped at 30s it settles near a tenth of that.+ // A beat that has already missed the server's 6s TTL cannot save the+ // connection — reopening the stream is what does that — so hammering at+ // the healthy cadence buys nothing. Unbounded retries would be ~60 in two+ // minutes; capped at 30s it settles near a tenth of that.expect(attempts).toBeLessThan(15);conn.stop();});@@ -643,7 +779,7 @@ describe('RoomConnection', () => {await vi.advanceTimersByTimeAsync(120_000);- const reported = warnings('connection renew error');+ const reported = warnings('heartbeat failed');expect(reported.length).toBeGreaterThan(0);expect(reported.length).toBeLessThan(8);// The first failure is always reported, with the endpoint that failed.@@ -654,29 +790,353 @@ describe('RoomConnection', () => {conn.stop();});- it('stays quiet about staleness while the loop is failing loudly', async () => {- vi.useFakeTimers();- const conn = connectWith(makeFailingFetch(() => true));-- await vi.advanceTimersByTimeAsync(120_000);-- expect(warnings('renew stale')).toHaveLength(0);- conn.stop();- });-it('says so when the endpoint comes back', async () => {vi.useFakeTimers();let failing = true;const conn = connectWith(makeFailingFetch(() => failing));- await vi.advanceTimersByTimeAsync(30_000);+ await vi.advanceTimersByTimeAsync(60_000);failing = false;await vi.advanceTimersByTimeAsync(60_000);- const recovered = warnings('connection renew recovered');+ const recovered = warnings('heartbeat recovered');expect(recovered).toHaveLength(1);- expect(recovered[0][1]).toMatchObject({ event: 'room_renew_recovered' });+ expect(recovered[0][1]).toMatchObject({ event: 'switch_beat_recovered' });conn.stop();});});});++/**+ * The room comes from the server, on this connection's own stream.+ *+ * switchdash used to learn it by reading the agent's `connect_to_room` tool+ * response through a hook — inference about another process, from a payload+ * shape nobody had agreed to keep stable. It broke the moment that shape+ * changed, and the failure was silent: no room in the sidebar, and no+ * connection started either, because both hang off the same dispatch.+ *+ * Now the session's tool call lands on this connection, the server claims the+ * room on it, and says so.+ */+describe('the room is set by the server', () => {+ function sseWithFrames(frames: string[]): ReadableStream<Uint8Array> {+ const encoder = new TextEncoder();+ return new ReadableStream<Uint8Array>({+ start(controller) {+ for (const frame of frames) controller.enqueue(encoder.encode(frame));+ },+ });+ }++ function connectWithFrames(frames: string[], roomId: string | null = null) {+ const fetchMock = vi.fn(async (url: string) => {+ if (String(url).includes('/events')) {+ return {+ ok: true,+ status: 200,+ body: sseWithFrames(frames),+ text: async (): Promise<string> => '',+ };+ }+ return {+ ok: true,+ status: 200,+ json: async () => ({}),+ text: async (): Promise<string> => '',+ };+ });+ vi.stubGlobal('fetch', fetchMock);+ const rooms: (string | null)[] = [];+ const conn = new RoomConnection({+ creds,+ roomId,+ roomName: null,+ connectionId: 'conn-1',+ sessionId: 'session-1',+ sink: { acquire: () => ({ write: vi.fn() }) },+ injector,+ control,+ deeplinkScheme: 'switchdash',+ isHumanTyping: () => false,+ mediaDir,+ onRoomChanged: (room) => rooms.push(room),+ log: silentLog,+ });+ conn.start();+ return { conn, rooms, fetchMock };+ }++ it('opens with no room when the session has not connected to one yet', async () => {+ const { conn, fetchMock } = connectWithFrames([]);+ await flush();++ const open = fetchMock.mock.calls.find((c) => String(c[0]).includes('/events'));+ expect(String(open?.[0])).not.toContain('rooms=');+ expect(conn.room).toBeNull();+ conn.stop();+ });++ it('takes the room from connection_state', async () => {+ const { conn, rooms } = connectWithFrames([+ `event: connection_state\ndata: ${JSON.stringify({ rooms: ['room-9'] })}\n\n`,+ ]);+ await flush(8);++ expect(conn.room).toBe('room-9');+ expect(rooms).toEqual(['room-9']);+ conn.stop();+ });++ it('follows a subscription_changed when the session moves room', async () => {+ const { conn, rooms } = connectWithFrames([+ `event: connection_state\ndata: ${JSON.stringify({ rooms: ['room-9'] })}\n\n`,+ `event: subscription_changed\ndata: ${JSON.stringify({ rooms: ['room-10'] })}\n\n`,+ ]);+ await flush(8);++ expect(conn.room).toBe('room-10');+ expect(rooms).toEqual(['room-9', 'room-10']);+ conn.stop();+ });++ it('does not re-announce a room that has not changed', async () => {+ // The server repeats the room on every reconnect; treating each as a change+ // would rewrite the session→room mapping and re-emit to the renderer for+ // nothing.+ const { conn, rooms } = connectWithFrames([+ `event: connection_state\ndata: ${JSON.stringify({ rooms: ['room-9'] })}\n\n`,+ `event: subscription_changed\ndata: ${JSON.stringify({ rooms: ['room-9'] })}\n\n`,+ ]);+ await flush(8);++ expect(rooms).toEqual(['room-9']);+ conn.stop();+ });++ it('reports the room going away', async () => {+ const { conn, rooms } = connectWithFrames([+ `event: connection_state\ndata: ${JSON.stringify({ rooms: ['room-9'] })}\n\n`,+ `event: subscription_changed\ndata: ${JSON.stringify({ rooms: [] })}\n\n`,+ ]);+ await flush(8);++ expect(conn.room).toBeNull();+ expect(rooms).toEqual(['room-9', null]);+ conn.stop();+ });++ it('declares a room it already knows, so catch-up covers it', async () => {+ // A restored or adopted session: we know the room before the stream opens,+ // and buffered events for it must be part of the first read.+ const { conn, fetchMock } = connectWithFrames([], 'room-known');+ await flush();++ const open = fetchMock.mock.calls.find((c) => String(c[0]).includes('/events'));+ expect(String(open?.[0])).toContain('rooms=room-known');+ conn.stop();+ });++ it('ignores a control command that arrives before the room is known', async () => {+ // `reset` re-types a prompt naming the room; naming the wrong one would+ // move the session. Refusing beats guessing.+ const { conn } = connectWithFrames([+ `id: 1\nevent: command\ndata: ${JSON.stringify({+ type: 'command',+ room_id: 'room-9',+ payload: { command: 'reset', args: '', user_id: '@u', user_name: 'u', thread_id: null },+ })}\n\n`,+ ]);+ await flush(8);++ expect(+ silentLog.warn.mock.calls.some((c) => String(c[0]).includes('control command before'))+ ).toBe(true);+ conn.stop();+ });+});++/**+ * A session spawned to answer a message must start from before that message.+ *+ * The watcher consumed the triggering event — that is how it knew to spawn — so+ * by the time the session's connection opens, the message is already behind+ * head. Opening at head starts the session *after* the one thing it exists to+ * handle, and it comes up to silence.+ *+ * This worked before the push transport by accident: the notification queue and+ * the per-room queue were separate, so consuming one left the other intact.+ * With a single buffer and per-connection cursors, the start position has to be+ * passed explicitly.+ */+describe('a spawned session starts from its trigger', () => {+ function openWith(startCursor: number | undefined) {+ const fetchMock = vi.fn(async (url: string, _init?: RequestInit) => {+ if (String(url).includes('/events')) {+ return {+ ok: true,+ status: 200,+ body: new ReadableStream<Uint8Array>({ start() {} }),+ text: async (): Promise<string> => '',+ };+ }+ return {+ ok: true,+ status: 200,+ json: async () => ({}),+ text: async (): Promise<string> => '',+ };+ });+ vi.stubGlobal('fetch', fetchMock);+ const conn = new RoomConnection({+ creds,+ roomId: null,+ roomName: null,+ connectionId: 'conn-1',+ startCursor,+ sessionId: 'session-1',+ sink: { acquire: () => ({ write: vi.fn() }) },+ injector,+ control,+ deeplinkScheme: 'switchdash',+ isHumanTyping: () => false,+ mediaDir,+ log: silentLog,+ });+ conn.start();+ return { conn, fetchMock };+ }++ function openUrl(fetchMock: ReturnType<typeof vi.fn>): string {+ const call = fetchMock.mock.calls.find((c) => String(c[0]).includes('/events'));+ return String(call?.[0]);+ }++ it('opens at the given cursor rather than at head', async () => {+ const { conn, fetchMock } = openWith(41);+ await flush();++ expect(openUrl(fetchMock)).toContain('start_from=41');+ expect(openUrl(fetchMock)).not.toContain('start_from=head');+ conn.stop();+ });++ it('sends Last-Event-ID so the server resumes from there', async () => {+ const { conn, fetchMock } = openWith(41);+ await flush();++ const call = fetchMock.mock.calls.find((c) => String(c[0]).includes('/events'));+ expect(call).toBeDefined();+ expect((call![1] as RequestInit).headers).toMatchObject({ 'Last-Event-ID': '41' });+ conn.stop();+ });++ it('still opens at head when nothing triggered the session', async () => {+ // A session the operator started themselves has no message waiting for it;+ // replaying history into it would be wrong.+ const { conn, fetchMock } = openWith(undefined);+ await flush();++ expect(openUrl(fetchMock)).toContain('start_from=head');+ conn.stop();+ });+});++/**+ * A restored session claims the room we remembered for it.+ *+ * Normally the room arrives from the server, because the session's+ * `connect_to_room` claims it on this connection. A resumed session never+ * calls the tool again — it does not re-run its initial prompt — so nothing is+ * coming. Waiting leaves the connection room-less forever: the session is+ * silent, and the watcher spawns a duplicate for the next message.+ */+describe('repointing a restored session', () => {+ it('claims the remembered room on the existing connection', async () => {+ const fetchMock = vi.fn(async (url: string, _init?: RequestInit) => {+ if (String(url).includes('/events')) {+ return {+ ok: true,+ status: 200,+ body: new ReadableStream<Uint8Array>({ start() {} }),+ text: async (): Promise<string> => '',+ };+ }+ return {+ ok: true,+ status: 200,+ json: async () => ({}),+ text: async (): Promise<string> => '',+ };+ });+ vi.stubGlobal('fetch', fetchMock);+ const conn = new RoomConnection({+ creds,+ roomId: null,+ roomName: null,+ connectionId: 'conn-1',+ sessionId: 'session-1',+ sink: { acquire: () => ({ write: vi.fn() }) },+ injector,+ control,+ deeplinkScheme: 'switchdash',+ isHumanTyping: () => false,+ mediaDir,+ log: silentLog,+ });+ conn.start();+ await flush();++ await conn.repointTo('room-remembered', 'Remembered');++ const subscribe = fetchMock.mock.calls.find((c) =>+ String(c[0]).includes('/connection/subscribe')+ );+ expect(subscribe).toBeDefined();+ expect(String((subscribe![1] as RequestInit).body)).toContain('room-remembered');+ conn.stop();+ });++ it('does nothing when it already holds that room', async () => {+ const fetchMock = vi.fn(async (url: string, _init?: RequestInit) => {+ if (String(url).includes('/events')) {+ return {+ ok: true,+ status: 200,+ body: new ReadableStream<Uint8Array>({ start() {} }),+ text: async (): Promise<string> => '',+ };+ }+ return {+ ok: true,+ status: 200,+ json: async () => ({}),+ text: async (): Promise<string> => '',+ };+ });+ vi.stubGlobal('fetch', fetchMock);+ const conn = new RoomConnection({+ creds,+ roomId: 'room-1',+ roomName: 'Room One',+ connectionId: 'conn-1',+ sessionId: 'session-1',+ sink: { acquire: () => ({ write: vi.fn() }) },+ injector,+ control,+ deeplinkScheme: 'switchdash',+ isHumanTyping: () => false,+ mediaDir,+ log: silentLog,+ });+ conn.start();+ await flush();++ await conn.repointTo('room-1', 'Room One');++ expect(fetchMock.mock.calls.some((c) => String(c[0]).includes('/connection/subscribe'))).toBe(+ false+ );+ conn.stop();+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.tsindex 2204595a6..8f69e3711 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts@@ -1,71 +1,32 @@import * as fs from 'node:fs';import * as path from 'node:path';+import { SwitchEventStream } from '@sandbox-quantum/switch-agent-runtime';import type { AgentStatus, NotificationType } from '@shared/core/providers/agentEvents';import type { InjectionSink } from './injection-sink';import type { SessionControl } from './session-control';import {formatEventForInjection,formatAttachmentAnnotation,- type AgentBridgeEventResponse,+ type AgentBridgeEvent,type AttachmentRef,type CommandPayload,type MessagePayload,} from './switch-event-format';-const POLL_TIMEOUT_S = 10;-const INITIAL_BACKOFF_MS = 1000;-const MAX_BACKOFF_MS = 30_000;// Per-request timeouts. Without these a fetch on a half-open socket (e.g. during// a brief ALB 5xx blip) can hang forever with no response and no error, wedging-// the await-each-tick loop it runs in — the renew loop in particular, which then-// stops refreshing liveness so the session ages out (SESSION_TTL) and the agent-// silently drops the room. Every fetch is bounded so a hang aborts and the-// surrounding backoff loop continues.+// the await-each-tick loop it runs in. Every fetch is bounded so a hang aborts+// and the surrounding loop continues.//-// The long-poll waits up to POLL_TIMEOUT_S server-side, so its client bound adds-// slack on top. Renew is deliberately short — shorter than the server's ~6s-// SESSION_TTL — so a hung renew aborts and retries well inside the window that-// would otherwise drop the session.-const POLL_REQUEST_TIMEOUT_MS = POLL_TIMEOUT_S * 1000 + 5_000;-const RENEW_REQUEST_TIMEOUT_MS = 4_000;+// Liveness no longer depends on these: the event stream and its heartbeat live+// in SwitchEventStream, which owns its own timeouts and reconnect. What remains+// here is the out-of-band reporting — runtime state and media downloads.const RUNTIME_STATE_REQUEST_TIMEOUT_MS = 10_000;const MEDIA_REQUEST_TIMEOUT_MS = 30_000;-// Watchdog cadence + staleness bound for the renew loop. If no renew has-// succeeded within the threshold the loop is presumed wedged (a request stalled-// past its own timeout, or the loop otherwise stopped making progress): abort the-// in-flight renew to force an immediate fresh attempt, and warn loudly so a-// silently-dropped room is visible rather than mysterious.-//-// "Wedged" specifically means *not making progress*. A renew that fails fast —-// a refused connection to an endpoint that is simply gone — is progress: the-// loop is running, retrying, and reporting for itself. Firing the watchdog then-// would abort a request that is not in flight and warn about a stall that is not-// happening, which is how a single dead endpoint used to produce a third of a-// warning line per second, forever.-const RENEW_WATCHDOG_INTERVAL_MS = 2_000;-const RENEW_STALE_THRESHOLD_MS = 8_000;-// Backoff for the renew loops. Renews are a heartbeat, so the healthy cadence is-// fixed and short; failures back off geometrically up to this cap. Once the-// heartbeat has missed its TTL the session is already dropped server-side, so-// retrying every 2s buys nothing but noise — `renew` is an upsert, so the-// session re-establishes on the first success whenever that comes.-const RENEW_MAX_BACKOFF_MS = 30_000;// Safety net for the dialog gate: if a blocking prompt (permission/elicitation)// never reports resolution, release the gate after this long so queued messages// can't get permanently stuck. Normal turns are never gated.const BUSY_FALLBACK_MS = 60_000;-// Cadence for the room connection-liveness heartbeat. The server keeps the-// agent's session "connected" only while these renews arrive (SESSION_TTL), so-// a closed session drops to "no session" within seconds. Mirrors the connector-// channel's CONNECTION_RENEW_INTERVAL_MS.-const CONNECTION_RENEW_INTERVAL_MS = 2000;-// Cadence for the role-lease heartbeat. When the managed session assumes a room-// role, the server holds the seat only while `/leases/renew` arrives within its-// LEASE_TTL (~6s), so without this a role assumed from switchdash auto-releases-// within seconds. Renewed unconditionally: the server's touch is room-agnostic-// and a no-op when no lease is held, so it keeps a held role alive and does-// nothing otherwise. Mirrors the connector channel's LEASE_RENEW_INTERVAL_MS.-const LEASE_RENEW_INTERVAL_MS = 2000;// How long to wait before re-checking the dual-writer gate while the operator// is typing into the pane. Short enough that delivery resumes promptly once// they pause.@@ -162,8 +123,28 @@ export interface RoomConnectionLogger {export interface RoomConnectionDeps {creds: SwitchCredentials;- roomId: string;+ /**+ * The room the session is already known to be in, if we happen to know —+ * restoring after a restart, or an adopted session whose hook told us. Null+ * for a session we just launched: it has not connected to a room yet, and+ * when it does the server tells us on the stream.+ */+ roomId: string | null;roomName: string | null;+ /**+ * The connection id this session uses, minted before launch and handed to the+ * session in its environment so its tool calls land on this same connection.+ * Stable across room changes and reconnects — that is what makes the room+ * repointable instead of requiring a new connection each time.+ */+ connectionId: string;+ /**+ * Where this session's stream should begin, when head is wrong. Set when a+ * watcher spawned the session to answer a specific message: that message is+ * already behind head, so starting there would skip the one thing the+ * session exists to handle.+ */+ startCursor?: number;/** The switchdash session id of the session this connection drives, so* the deeplink can resolve to the exact session on any client (the shared* session id is the same across clients; the local room mapping is not). */@@ -190,21 +171,44 @@ export interface RoomConnectionDeps {* temp dir in the sidecar).*/mediaDir: string;+ /**+ * Called when the server reports which room this connection covers — on+ * connect, and again whenever it changes. This is how switchdash learns a+ * session's room: from Switch, on the connection the session's own+ * `connect_to_room` call landed on.+ */+ onRoomChanged?: (roomId: string | null) => void;log: RoomConnectionLogger;}/**- * One agent ↔ one Switch room: long-polls the agent bridge for room events,- * injects addressed messages / task events into the session via an- * `InjectionSink`, keeps the room connection alive with a renew heartbeat, and- * reports runtime state back to the bridge. Transport-agnostic — the local main- * process drives it with a PTY-backed sink, the remote sidecar with a- * tmux-backed one.+ * One **session's** connection to Switch: receives its room's events on the+ * agent bridge's push stream, injects addressed messages / task events into the+ * session via an `InjectionSink`, and reports runtime state back to the bridge.+ * Transport-agnostic — the local main process drives it with a PTY-backed sink,+ * the remote sidecar with a tmux-backed one.+ *+ * Delivery and liveness both belong to `SwitchEventStream`: one SSE connection+ * and one heartbeat, in place of the long-poll and the three renew loops+ * (`/connection/renew`, `/leases/renew`, `/watch/heartbeat`) this used to run.+ * The connection survives a dropped socket, so a reconnect resumes from the+ * cursor rather than losing whatever arrived while it was away — the poll had+ * no cursor at all and the server drained its queue on read.+ *+ * **The room is not fixed and is not ours to decide.** The connection belongs+ * to the session and merely points at whichever room the session is in; the+ * server says which, on this connection's own stream. When the session calls+ * `connect_to_room`, the server claims the room on the connection the call came+ * in on — this one, when the session was handed our id at launch — and tells us+ * as `subscription_changed`. Before that arrived from the server we learned the+ * room by reading the agent's tool response through a hook, which broke+ * silently the moment that response changed shape.*/export class RoomConnection {private readonly creds: SwitchCredentials;- private readonly roomId: string;- private readonly roomName: string | null;+ /** The room this session is currently in, or null before the server says. */+ private roomId: string | null;+ private roomName: string | null;private readonly sessionId: string;private readonly sink: InjectionSink;private readonly injector: PromptInjector;@@ -236,15 +240,19 @@ export class RoomConnection {private activityTicker: ReturnType<typeof setInterval> | null = null;private busyFallback: ReturnType<typeof setTimeout> | null = null;private humanGateTimer: ReturnType<typeof setTimeout> | null = null;- /** Monotonic timestamp of the last renew that succeeded — drives the watchdog. */- private lastRenewOkAt = 0;- /** Consecutive connection-renew failures; 0 while healthy. Tells the watchdog- * a loop that is failing loudly apart from one that has gone quiet. */- private renewFailures = 0;- /** Aborts just the in-flight renew request (independent of the loop's own- * per-request timeout) so the watchdog can force an immediate retry. */- private renewRequestAbort: AbortController | null = null;- private renewWatchdog: ReturnType<typeof setInterval> | null = null;+ /** The push transport: one SSE stream plus one heartbeat, replacing the+ * long-poll and the three renew loops. */+ private stream: SwitchEventStream | null = null;+ /** Minted before launch and shared with the session, so its tool calls land+ * on this connection. Reused across reconnects, so the server-side+ * connection — and with it the room slot and role lease — survives a dropped+ * socket. */+ private readonly connectionId: string;+ private readonly startCursor: number | undefined;+ /** Notified whenever the server tells us which room this session is in. */+ private readonly onRoomChanged: ((roomId: string | null) => void) | null;+ /** Unaddressed room messages filtered out since the last event we surfaced. */+ private missed = 0;constructor(deps: RoomConnectionDeps) {this.creds = deps.creds;@@ -257,21 +265,102 @@ export class RoomConnection {this.deeplinkScheme = deps.deeplinkScheme;this.isHumanTyping = deps.isHumanTyping;this.mediaDir = deps.mediaDir;+ this.connectionId = deps.connectionId;+ this.startCursor = deps.startCursor;+ this.onRoomChanged = deps.onRoomChanged ?? null;this.log = deps.log;}- /** Begin polling + renew loops and seed an idle runtime-state report. */+ /** Open the event stream and seed an idle runtime-state report. */start(): void {- void this.pollLoop();- void this.connectionRenewLoop();- void this.leaseRenewLoop();- this.renewWatchdog = setInterval(() => this.checkRenewStale(), RENEW_WATCHDOG_INTERVAL_MS);+ this.stream = new SwitchEventStream({+ creds: this.creds,+ connectionId: this.connectionId,+ // One room per session: the connection claims it, which is what stops a+ // second session of the same agent silently competing for the room.+ scope: 'single',+ filter: 'all',+ // Empty until the session connects to one. Declared here only when we+ // already know it — a restored session, or one adopted with a room.+ rooms: this.roomId ? [this.roomId] : [],+ startCursor: this.startCursor,+ onEvent: (event) => this.handleEvent(event),+ onRooms: (rooms) => this.adoptRoom(rooms),+ onGap: (info) => this.handleGap(info),+ onEvicted: (reason) =>+ this.log.warn('RoomConnection: connection evicted', {+ event: 'room_connection_evicted',+ roomId: this.roomId,+ reason,+ }),+ log: this.log,+ signal: this.abort.signal,+ });+ this.stream.start();// Seed this room's deeplink right away (an idle report carries it) so the// session's `(Open in SwitchDash)` link is available in the new room's// !status immediately on connect/switch — not only once the agent next// works. idle surfaces nothing on the bridge, so this posts no message.- void this.postRuntimeState('idle', null).catch(() => {});+ if (this.roomId) void this.postRuntimeState('idle', null).catch(() => {});+ }++ /**+ * Claim a room we already know about, without waiting to be told.+ *+ * For a **restored** session. Normally the room arrives from the server,+ * because the session's `connect_to_room` claims it on this connection — but+ * a resumed session never calls the tool again: it does not re-run its+ * initial prompt. Nothing is coming, and we are the only ones who remember+ * which room it was in, so we assert it.+ *+ * Not a return to inferring rooms. This is the one case where the knowledge+ * is genuinely ours: read back from our own persisted map for a session we+ * are restarting. Everywhere else the server still decides.+ */+ async repointTo(roomId: string, roomName: string | null): Promise<void> {+ if (this.roomId === roomId) return;+ this.roomName = roomName;+ this.log.debug('RoomConnection: claiming the remembered room for a restored session', {+ event: 'room_connection_repoint',+ sessionId: this.sessionId,+ roomId,+ previous: this.roomId,+ });+ // The server's acknowledgement comes back as `subscription_changed`, which+ // sets `roomId` through the normal path — so there is still exactly one+ // writer for it, and a claim that fails leaves us honestly room-less.+ await this.stream?.repoint(roomId);+ }++ /**+ * Take the room the server says this connection covers.+ *+ * The server is the authority: the session's `connect_to_room` claimed the+ * room on this connection, and this is that fact arriving. Nothing else is+ * allowed to set the room — inferring it anywhere else is what let switchdash+ * and Switch disagree.+ *+ * A `single`-scope connection covers at most one room, so anything else in+ * the list would be a protocol violation rather than a case to handle.+ */+ private adoptRoom(rooms: string[]): void {+ const next = rooms[0] ?? null;+ if (next === this.roomId) return;++ const previous = this.roomId;+ this.roomId = next;+ // The name is not on the wire — the renderer resolves it from the gateway's+ // room list, and falls back to a short id when it cannot.+ if (next !== previous) this.roomName = null;+ this.log.debug('RoomConnection: room set by the server', {+ event: 'room_connection_room_changed',+ sessionId: this.sessionId,+ previous,+ roomId: next,+ });+ this.onRoomChanged?.(next);+ if (next) void this.postRuntimeState('idle', null).catch(() => {});}/** Stop the loops and clear any lingering runtime-state surface. */@@ -290,14 +379,19 @@ export class RoomConnection {this.abort.abort();if (this.busyFallback) clearTimeout(this.busyFallback);if (this.humanGateTimer) clearTimeout(this.humanGateTimer);- if (this.renewWatchdog) clearInterval(this.renewWatchdog);this.stopActivityTicker();}- get room(): string {+ /** The room the session is in, or null until the server has said. */+ get room(): string | null {return this.roomId;}+ /** The connection this session's tool calls are expected to arrive on. */+ get connection(): string {+ return this.connectionId;+ }+/*** The `<scheme>://session?…` deeplink for this managed session, sent with the* runtime-state report so the bridge can link the working / awaiting-input@@ -308,7 +402,7 @@ export class RoomConnection {const params = new URLSearchParams({server: this.creds.apiEndpoint,agent: this.creds.agentId,- room: this.roomId,+ room: this.roomId ?? '',// The shared session id resolves to the exact session on any client// (a client that only adopted the session has no room mapping to match on).session: this.sessionId,@@ -378,253 +472,75 @@ export class RoomConnection {}}- /** Refresh the room connection-liveness heartbeat. Throws on a non-OK response. */- private async postConnectionRenew(requestAbort: AbortController): Promise<void> {- const resp = await this.fetchWithTimeout(- `${this.creds.apiEndpoint}/agents/${this.creds.agentId}/connection/renew`,- {- method: 'POST',- headers: {- Authorization: `Bearer ${this.creds.token}`,- 'Content-Type': 'application/json',- },- body: JSON.stringify({ room_id: this.roomId }),- },- RENEW_REQUEST_TIMEOUT_MS,- { extraSignal: requestAbort.signal }- );- if (!resp.ok) {- throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);- }- }-- /** Refresh the role-lease heartbeat. Throws on a non-OK response. */- private async postLeaseRenew(): Promise<void> {- const resp = await this.fetchWithTimeout(- `${this.creds.apiEndpoint}/agents/${this.creds.agentId}/leases/renew`,- {- method: 'POST',- headers: {- Authorization: `Bearer ${this.creds.token}`,- 'Content-Type': 'application/json',- },- },- RENEW_REQUEST_TIMEOUT_MS- );- if (!resp.ok) {- throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);- }- }-/**- * Keep the agent's session marked "connected" to the room while we poll it.- * The connect_to_room hook only fires on a live tool call, so after a restart- * (or whenever switchdash owns the session) nothing else renews this — without- * it the bridge would consider the session gone within seconds.+ * Handle one event from the stream.*- * Each renew is bounded by RENEW_REQUEST_TIMEOUT_MS (see fetchWithTimeout) so a- * hung request can never wedge this loop, and a watchdog re-aborts an in-flight- * renew that has stalled the loop past RENEW_STALE_THRESHOLD_MS. `renew` is an- * upsert server-side, so once requests flow again a TTL-expired session- * re-establishes on the next success — no explicit re-connect needed.+ * Unaddressed room messages are not surfaced; they are tallied and the count+ * is appended to the next event that IS surfaced, so the agent knows it has+ * fallen behind and can catch up with read_context.*/- private async connectionRenewLoop(): Promise<void> {- // Seed the watchdog clock so a wedge before the first success is still caught.- this.lastRenewOkAt = Date.now();- await this.renewLoop('connection', CONNECTION_RENEW_INTERVAL_MS, async () => {- const requestAbort = new AbortController();- this.renewRequestAbort = requestAbort;- try {- await this.postConnectionRenew(requestAbort);- this.lastRenewOkAt = Date.now();- } finally {- if (this.renewRequestAbort === requestAbort) this.renewRequestAbort = null;- }+ private async handleEvent(event: AgentBridgeEvent): Promise<void> {+ // Session-control commands aren't injected as text — they drive concrete+ // keystrokes (interrupt/compact/reset) against the session.+ if (event.type === 'command') {+ void this.executeCommand(event.payload as CommandPayload);+ return;+ }+ const addressed = event.type === 'message' && (event.payload as MessagePayload).addressed;+ const threadId =+ event.type === 'message' ? ((event.payload as MessagePayload).thread_id ?? null) : null;+ if (event.type === 'message' && !addressed) {+ this.missed += 1;+ }+ const text = formatEventForInjection(event, this.roomName);+ this.log.debug('RoomConnection: received event', {+ roomId: this.roomId,+ type: event.type,+ ...(event.type === 'message'+ ? { addressed: (event.payload as MessagePayload).addressed }+ : {}),+ surfaced: text !== null,});- }-- /**- * Drive one renew heartbeat until the connection stops.- *- * While renews succeed the cadence is fixed — this is a liveness signal and the- * server drops the session without it. While they fail it backs off to- * RENEW_MAX_BACKOFF_MS, and reports on a curve rather than per attempt: the- * first failure, then at exponentially sparser counts, then a line when it- * recovers. An endpoint that is permanently gone therefore costs a handful of- * lines rather than one every couple of seconds for the life of the app, while- * a failure that matters is still reported the moment it happens.- */- private async renewLoop(- kind: 'connection' | 'lease',- intervalMs: number,- attempt: () => Promise<void>- ): Promise<void> {- let failures = 0;- let failingSince = 0;-- while (!this.abort.signal.aborted) {- try {- await attempt();- if (failures > 0) {- this.log.warn(`RoomConnection: ${kind} renew recovered`, {- event: 'room_renew_recovered',- roomId: this.roomId,- failures,- outageMs: Date.now() - failingSince,- });- }- failures = 0;- if (kind === 'connection') this.renewFailures = 0;- } catch (error) {- if (this.abort.signal.aborted) return;- if (failures === 0) failingSince = Date.now();- failures += 1;- if (kind === 'connection') this.renewFailures = failures;- // Powers of two: 1st, 2nd, 4th, 8th … failure. Dense enough to catch a- // blip as it starts, sparse enough that an outage cannot flood the log.- if ((failures & (failures - 1)) === 0) {- this.log.warn(`RoomConnection: ${kind} renew error`, {- event: 'room_renew_failed',- roomId: this.roomId,- endpoint: this.creds.apiEndpoint,- failures,- failingForMs: Date.now() - failingSince,- error: String(error),- });- }+ if (!text) return;++ let annotated = text;+ if (event.type === 'message') {+ // Materialise attachments of ANY type to local files and tell the agent+ // they are there — parity with the connector channel. A download that+ // fails is named in the annotation rather than dropped, so the agent is+ // never left believing it saw everything.+ const { imagePaths, filePaths, failed } = await this.downloadAttachments(+ event.payload as MessagePayload+ );+ const annotation = formatAttachmentAnnotation(imagePaths, filePaths, failed);+ if (annotation) {+ annotated = `${annotated}\n${annotation}`;}-- const delay =- failures === 0- ? intervalMs- : Math.min(intervalMs * 2 ** (failures - 1), RENEW_MAX_BACKOFF_MS);- await new Promise((r) => setTimeout(r, delay));}+ const body =+ this.missed > 0+ ? `${annotated}\n(${this.missed} unread room message${this.missed === 1 ? '' : 's'} since your last read_context — call read_context to catch up.)`+ : annotated;+ this.missed = 0;+ this.enqueue({ text: body, addressed, threadId });}/**- * Keep any role the managed session has assumed alive. The server holds the- * seat only while `/leases/renew` arrives within its LEASE_TTL, and the- * `connect_to_room`/`assume_role` hooks fire only on the agent's own tool- * calls — nothing else renews the lease when switchdash owns the session, so- * without this a role assumed from switchdash auto-releases within seconds.+ * Tell the agent it has a hole in its history.*- * Renewed unconditionally: `touch_lease` is room-agnostic and a no-op when no- * lease is held, so this keeps a held role alive and does nothing otherwise.- * Each renew is bounded by RENEW_REQUEST_TIMEOUT_MS so a hung request cannot- * wedge the loop; the loop ends on abort, which lets the lease expire and the- * role auto-release shortly after the connection stops.+ * The server reports a gap when it cannot serve our cursor — events aged out+ * of the buffer, or the server restarted and the numbering reset. Staying+ * quiet here would leave the session believing the stream was complete, which+ * is the failure mode this transport exists to make impossible.*/- private async leaseRenewLoop(): Promise<void> {- await this.renewLoop('lease', LEASE_RENEW_INTERVAL_MS, () => this.postLeaseRenew());- }-- /**- * Detect a renew loop that has stopped making progress — no successful renew- * within RENEW_STALE_THRESHOLD_MS. Abort the in-flight request so the loop- * retries immediately instead of waiting out a stall, and warn loudly: a- * silently-dropped room should be visible, not mysterious.- *- * A loop that is failing outright is not stalled: it is looping, backing off- * and reporting on its own schedule, and there is no in-flight request to- * abort. Leave it to speak for itself — this watchdog exists for the case it- * cannot report, where a request neither returns nor rejects.- */- private checkRenewStale(): void {- if (this.abort.signal.aborted) return;- if (this.renewFailures > 0) return;- const staleMs = Date.now() - this.lastRenewOkAt;- if (staleMs <= RENEW_STALE_THRESHOLD_MS) return;- this.log.warn('RoomConnection: renew stale — forcing retry', {- event: 'room_renew_stalled',- roomId: this.roomId,- staleMs,+ private handleGap(info: { fromSequence: number; reason: string }): void {+ this.enqueue({+ text:+ `[Switch] Some room events were missed and cannot be replayed (${info.reason}). ` ++ 'Call read_context to catch up before responding.',+ addressed: true,+ threadId: null,});- this.renewRequestAbort?.abort();- }-- private async pollLoop(): Promise<void> {- let backoff = INITIAL_BACKOFF_MS;- const url = `${this.creds.apiEndpoint}/agents/${this.creds.agentId}/rooms/${this.roomId}/events?timeout=${POLL_TIMEOUT_S}`;- // Tally unaddressed room messages filtered out since the last event we DID- // surface, and annotate the next surfaced event with the count — mirroring- // the channel's missed_count so the agent knows it has fallen behind.- let missed = 0;-- while (!this.abort.signal.aborted) {- try {- const resp = await this.fetchWithTimeout(- url,- { headers: { Authorization: `Bearer ${this.creds.token}` } },- POLL_REQUEST_TIMEOUT_MS- );-- if (resp.status === 204) {- backoff = INITIAL_BACKOFF_MS;- continue;- }- if (!resp.ok) {- throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);- }-- backoff = INITIAL_BACKOFF_MS;- const data = (await resp.json()) as AgentBridgeEventResponse;- for (const event of data.events) {- // Session-control commands aren't injected as text — they drive- // concrete keystrokes (interrupt/compact/reset) against the session.- if (event.type === 'command') {- void this.executeCommand(event.payload as CommandPayload);- continue;- }- const addressed = event.type === 'message' && (event.payload as MessagePayload).addressed;- const threadId =- event.type === 'message' ? ((event.payload as MessagePayload).thread_id ?? null) : null;- if (event.type === 'message' && !addressed) {- missed += 1;- }- const text = formatEventForInjection(event, this.roomName);- this.log.debug('RoomConnection: received event', {- roomId: this.roomId,- type: event.type,- ...(event.type === 'message'- ? { addressed: (event.payload as MessagePayload).addressed }- : {}),- surfaced: text !== null,- });- if (text) {- let annotated = text;- if (event.type === 'message') {- // Materialise attachments of ANY type to local files and tell the- // agent they are there — parity with the connector channel, which- // the pollers otherwise lacked. A download that fails is named in- // the annotation rather than dropped, so the agent is never left- // believing it saw everything.- const { imagePaths, filePaths, failed } = await this.downloadAttachments(- event.payload as MessagePayload- );- const annotation = formatAttachmentAnnotation(imagePaths, filePaths, failed);- if (annotation) {- annotated = `${annotated}\n${annotation}`;- }- }- const body =- missed > 0- ? `${annotated}\n(${missed} unread room message${missed === 1 ? '' : 's'} since your last read_context — call read_context to catch up.)`- : annotated;- missed = 0;- this.enqueue({ text: body, addressed, threadId });- }- }- } catch (error) {- if (this.abort.signal.aborted) return;- this.log.warn('RoomConnection: poll error', {- roomId: this.roomId,- error: String(error),- });- await new Promise((r) => setTimeout(r, backoff));- backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);- }- }}/**@@ -936,6 +852,18 @@ export class RoomConnection {*/private async executeCommand(payload: CommandPayload): Promise<void> {const command = payload.command;+ if (!this.roomId) {+ // A control command can only have come from a room, so this means the+ // server told us about the event before it told us about the room.+ // Refusing beats guessing: `reset` re-types a connect prompt naming the+ // room, and naming the wrong one would move the session.+ this.log.warn('RoomConnection: control command before the room is known', {+ event: 'room_connection_command_without_room',+ sessionId: this.sessionId,+ command,+ });+ return;+ }const plan = this.control.plan(command, {room: this.roomName ?? this.roomId,role: payload.args || null,diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-event-format.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-event-format.tsindex 9b386dfd0..bb1fd9696 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-event-format.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-event-format.ts@@ -1,76 +1,28 @@/**- * Agent-bridge event shapes and notification formatting, mirrored from the- * Claude Code connector channel (`connectors/.../channel/server.ts`). switchdash- * polls the same `/agents/{id}/rooms/{room}/events` endpoint and injects the- * formatted text into the session's PTY instead of delivering it as an MCP- * channel notification.- */--/**- * A pointer to a media attachment on a message event. Mirrors the agent- * bridge's `AttachmentRef` (and the connector channel's) — metadata plus the- * Matrix `mxc://` URI only; the bytes are fetched on demand via the- * media-download endpoint.+ * Formatting agent-bridge events for injection into a session's terminal.+ *+ * The event *shapes* are protocol, and live in+ * `@sandbox-quantum/switch-agent-runtime`; they are re-exported here so the+ * many call sites that import both from this module keep working. What is+ * genuinely switchdash's is below: turning an event into the line a human (and+ * an agent reading its own terminal) sees.*/-export interface AttachmentRef {- filename: string;- mimetype: string;- size: number;- mxc: string;- msgtype: string;-}--export interface MessagePayload {- addressed: boolean;- sender: string;- sender_name: string;- message_id: string;- body: string;- timestamp: number;- thread_id?: string | null;- attachments?: AttachmentRef[];-}--export interface CommandPayload {- command: string;- // Command arguments. For `reset`/`compact` this carries the role name the- // agent should re-assume after its context is cleared/compacted (empty when- // it held none).- args: string;- user_id: string;- user_name: string;- // Thread root of the originating command message, so the completion notice- // can be posted back into that same thread. null when not in a thread.- thread_id?: string | null;-}--export interface RoomJoinPayload {- member: string;- member_name: string;- timestamp: number;- listening: boolean;-}--export interface TaskPayload {- task_id: string;- requester_agent_id: string;- performer_agent_id: string;- summary?: string;- description?: string;- update?: string;- outcome?: string | null;- reason?: string | null;-}--export interface AgentBridgeEvent {- type: string;- room_id: string;- payload: MessagePayload | CommandPayload | RoomJoinPayload | TaskPayload;-}-export interface AgentBridgeEventResponse {- events: AgentBridgeEvent[];-}+export type {+ AgentBridgeEvent,+ AttachmentRef,+ CommandPayload,+ MessagePayload,+ RoomJoinPayload,+ TaskPayload,+} from '@sandbox-quantum/switch-agent-runtime';+import type {+ AgentBridgeEvent,+ CommandPayload,+ MessagePayload,+ RoomJoinPayload,+ TaskPayload,+} from '@sandbox-quantum/switch-agent-runtime';/*** Format an agent-bridge event as a self-contained line to inject into thediff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.tsindex 4244a781c..72a8d045d 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto';import * as os from 'node:os';import * as path from 'node:path';import { DEEPLINK_SCHEME } from '@main/app/deeplinks';@@ -18,7 +19,7 @@ import {readSwitchAgentCredentials,readSwitchAgentCredentialsFromSettings,} from './switch-credentials';-import type { SessionRoomContext } from './switch-room-service';+import { switchRoomService, type SessionRoomContext } from './switch-room-service';/*** Polls the Switch agent bridge for room events on behalf of each live session@@ -36,16 +37,84 @@ import type { SessionRoomContext } from './switch-room-service';*/class SwitchNotificationPoller {private readonly connections = new Map<string, RoomConnection>();+ /** Agent id → buffer position the next session for it should start from. */+ private readonly pendingStart = new Map<string, number>();/**- * Begin polling the room a session just connected to (replaces any prior).- * Idempotent for the same room: a repeat connect (e.g. a hydration after a- * boot-time sweep already started the poller) is a no-op so the in-flight- * queue and renew loop are preserved.+ * Open this session's connection before it launches, and return the id to+ * hand it in its environment.+ *+ * The connection must exist first: the session's very first `connect_to_room`+ * arrives tagged with this id, and the server rejects a call naming a+ * connection that is not open. Opening here is also what makes the room+ * server-driven — the claim lands on this connection and comes back as+ * `subscription_changed`.+ *+ * Returns null when the session has no Switch credentials, which is not an+ * error: plenty of sessions are not Switch agents at all.+ */+ async ensureForSession(ctx: SessionRoomContext): Promise<string | null> {+ const existing = this.connections.get(ctx.sessionId);+ if (existing) return existing.connection;+ return await this.start(ctx, null, null);+ }++ /**+ * Where the next session opened for this agent should start reading.+ *+ * Set by the watcher just before it spawns, carrying the sequence of the+ * message that triggered the spawn. Without it the session's stream opens at+ * head — *after* that message, because the watcher already consumed it to+ * decide to spawn — and the session comes up having missed the one thing it+ * was started to answer.+ *+ * Keyed by agent rather than by room because the room is not known until the+ * session connects. Two spawns racing take the lower cursor, which replays a+ * little rather than skipping: the connection only ever receives events for+ * the room it claims, so the cost of overlap is small and the cost of a gap+ * is the bug this fixes.+ */+ noteSpawnTrigger(agentId: string, sequence: number): void {+ const start = Math.max(sequence - 1, 0);+ const pending = this.pendingStart.get(agentId);+ this.pendingStart.set(agentId, pending === undefined ? start : Math.min(pending, start));+ }++ /**+ * Point a session at a room the hook told us about.+ *+ * This is the **fallback** path. When switchdash launched the session it+ * handed over a connection id, the session's `connect_to_room` claimed the+ * room on it, and the server has already told us — so by the time this runs+ * there is nothing to do. It still matters for a session switchdash only+ * adopted, which has its own connection and never saw our id.+ *+ * Idempotent for the same room, so the common no-op stays a no-op.*/connect(ctx: SessionRoomContext, roomId: string, roomName: string | null): void {const existing = this.connections.get(ctx.sessionId);- if (existing && existing.room === roomId) return;+ if (existing) {+ if (existing.room === roomId) return;+ if (existing.room === null) {+ // Our connection is open but holds no room. Claim it on the existing+ // connection rather than tearing down and rebuilding — that keeps the+ // session's place and its cursor.+ //+ // This is what a restored session needs. It is resumed, not started+ // fresh, so it never re-runs its initial prompt and never calls+ // connect_to_room: no claim is coming from the server, and waiting for+ // one leaves the connection room-less forever, the session silent, and+ // the watcher spawning a duplicate for the next message.+ void existing.repointTo(roomId, roomName).catch((error) => {+ log.warn('SwitchNotificationPoller: failed to claim the remembered room', {+ sessionId: ctx.sessionId,+ roomId,+ error: String(error),+ });+ });+ return;+ }+ }this.disconnect(ctx.sessionId);void this.start(ctx, roomId, roomName).catch((error) => {log.warn('SwitchNotificationPoller: failed to start poller', {@@ -70,22 +139,22 @@ class SwitchNotificationPoller {private async start(ctx: SessionRoomContext,- roomId: string,+ roomId: string | null,roomName: string | null- ): Promise<void> {+ ): Promise<string | null> {const loaded = await loadSessionWithAgent(ctx.sessionId);if (!loaded) {log.warn('SwitchNotificationPoller: session not found; cannot read credentials', {sessionId: ctx.sessionId,});- return;+ return null;}const location = await getLocationById(loaded.locationId);if (!location) {log.warn('SwitchNotificationPoller: no location for session; cannot read credentials', {sessionId: ctx.sessionId,});- return;+ return null;}if (location.sshHost !== null) {// Remote agents poll from their on-host sidecar (CHOO-1059); the local@@ -94,7 +163,7 @@ class SwitchNotificationPoller {sessionId: ctx.sessionId,locationId: location.id,});- return;+ return null;}const rootPath = location.dir;@@ -117,7 +186,7 @@ class SwitchNotificationPoller {'SwitchNotificationPoller: missing Switch credentials (SWITCH_API_TOKEN/ENDPOINT/AGENT_ID) — cannot poll room',{ sessionId: ctx.sessionId, dir: rootPath, roomId, slug });- return;+ return null;}// Names for the ids these logs carry. The poller holds the joined row@@ -126,10 +195,29 @@ class SwitchNotificationPoller {noteAgentName(creds.agentId, slug);const ptySessionId = makeAgentPtySessionId(location.id, ctx.sessionId);+ const connectionId = randomUUID();+ // Consumed, not just read: it belongs to this session's launch, and a+ // later session must not rewind to a message this one already handled.+ const startCursor = this.pendingStart.get(creds.agentId);+ this.pendingStart.delete(creds.agentId);+ // The other end of the watcher's hand-off. If a spawned session comes up+ // without the message that triggered it, these two lines say whether the+ // cursor was handed over and honoured, or whether the session opened at+ // head and read past its own trigger.+ log.info('SwitchNotificationPoller: opening session connection', {+ event: 'switch_session_connection_open',+ sessionId: ctx.sessionId,+ agentId: creds.agentId,+ connectionId,+ startFrom: startCursor ?? 'head',+ roomId: roomId ?? '(await the server)',+ });const connection = new RoomConnection({creds,roomId,roomName,+ connectionId,+ startCursor,sessionId: ctx.sessionId,sink: new PtyInjectionSink(ptySessionId),injector: new PluginPromptInjector(ctx.providerId),@@ -137,6 +225,17 @@ class SwitchNotificationPoller {deeplinkScheme: DEEPLINK_SCHEME,isHumanTyping: () => isHumanInputRecent(ptySessionId),mediaDir: path.join(os.tmpdir(), 'switchdash-switch-media', ctx.sessionId),+ // The server naming this connection's room is the authoritative signal,+ // so it is what updates the session→room map the UI reads. The+ // connect_to_room hook writes the same map, and now only matters for+ // sessions that never got our connection id.+ onRoomChanged: (room) => {+ if (room) {+ void switchRoomService.setSessionRoom(ctx, room, creds.agentId, null);+ } else {+ switchRoomService.clearSession(ctx.sessionId);+ }+ },log,});this.connections.set(ctx.sessionId, connection);@@ -161,6 +260,7 @@ class SwitchNotificationPoller {},() => connection.start());+ return connectionId;}/**diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.tsindex 19bee2715..99ad8bf0b 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts@@ -38,6 +38,50 @@ type ConnectionState = SessionRoomConnection & {*/class SwitchRoomService implements IDisposable {private readonly connections = new Map<string, ConnectionState>();+ private readonly roomListeners = new Set<+ (change: { sessionId: string; roomId: string | null; agentId: string | null }) => void+ >();++ /**+ * Subscribe, **in this process**, to a session's room changing.+ *+ * Deliberately not the `events` bus. In main, `events.emit` is+ * `webContents.send` and `events.on` is `ipcMain.on` — one direction each,+ * renderer-bound. A main-process emit therefore never reaches a+ * main-process listener, so anything in main that subscribed that way+ * silently received nothing. AutoSessionWatcher did exactly that, and its+ * per-room spawn guard was consequently never cleared on connect: it sat+ * until the 120s TTL, blocking respawns for a room whose session had long+ * since arrived.+ *+ * Returns an unsubscribe function.+ */+ onSessionRoomChanged(+ listener: (change: { sessionId: string; roomId: string | null; agentId: string | null }) => void+ ): () => void {+ this.roomListeners.add(listener);+ return () => this.roomListeners.delete(listener);+ }++ private notifyRoomChanged(change: {+ sessionId: string;+ roomId: string | null;+ agentId: string | null;+ }): void {+ // To the renderer, for the UI…+ events.emit(sessionRoomChangedChannel, change);+ // …and to this process, for the logic that reacts to it.+ for (const listener of this.roomListeners) {+ try {+ listener(change);+ } catch (error) {+ log.warn('SwitchRoomService: room-change listener failed', {+ sessionId: change.sessionId,+ error: String(error),+ });+ }+ }+ }/*** Record (or replace) the room a session is connected to. A session holds at@@ -83,11 +127,7 @@ class SwitchRoomService implements IDisposable {agentId,});- events.emit(sessionRoomChangedChannel, {- sessionId: ctx.sessionId,- roomId,- agentId,- });+ this.notifyRoomChanged({ sessionId: ctx.sessionId, roomId, agentId });}/**@@ -120,24 +160,24 @@ class SwitchRoomService implements IDisposable {agentId,});- events.emit(sessionRoomChangedChannel, {- sessionId: ctx.sessionId,- roomId,- agentId,- });+ this.notifyRoomChanged({ sessionId: ctx.sessionId, roomId, agentId });}/**- * Re-establish a session's room connection and poller from persisted state.- * Called when a session's PTY (re)launches — e.g. after an app restart — so- * the agent keeps receiving addressed room events without having to call- * connect_to_room again. No-op when the session has no persisted room.+ * Re-establish a session's connection to its room from persisted state.+ *+ * Called when a session's PTY (re)launches — e.g. after an app restart. A+ * resumed session does not re-run its initial prompt, so it never calls+ * `connect_to_room` again: nobody else is going to say which room it was in,+ * and without this it comes back connected to nothing.+ *+ * No-op when the session has no persisted room.*/- async restorePoller(ctx: SessionRoomContext): Promise<void> {+ async restoreConnection(ctx: SessionRoomContext): Promise<void> {const persisted = await getPersistedRoomConnection(ctx.sessionId);if (!persisted) return;- log.info('SwitchRoomService: restoring room poller for resumed session', {+ log.info('SwitchRoomService: restoring the room connection for a resumed session', {sessionId: ctx.sessionId,roomId: persisted.roomId,});@@ -162,11 +202,7 @@ class SwitchRoomService implements IDisposable {log.info('SwitchRoomService: session disconnected from room', { sessionId });- events.emit(sessionRoomChangedChannel, {- sessionId,- roomId: null,- agentId: null,- });+ this.notifyRoomChanged({ sessionId, roomId: null, agentId: null });}/**diff --git a/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/remote-host-detail.tsx b/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/remote-host-detail.tsxindex 0deee5c38..c408a1737 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/remote-host-detail.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/remote-host-detail.tsx@@ -359,9 +359,21 @@ function DepRow({// gh reports auth separately: installed but not authenticated is still unusable.const needsGhAuth = isGh && !dep.ghAuth!.authenticated;const authed = isGh && dep.ghAuth!.authenticated;+ // Authenticated is not the same as usable. Sessions on this host fetch their+ // MCP runtime from GitHub Packages, and `gh auth login` does not request+ // read:packages — so a host that logged in before we asked for it looks+ // perfectly set up while every session it starts comes up with no tools.+ const canReadPackages = isGh && dep.ghAuth!.canReadPackages;+ const needsScope = authed && !canReadPackages;const readiness: Readiness =- dep.status === 'error' ? 'error' : !installed ? 'missing' : needsGhAuth ? 'partial' : 'ready';+ dep.status === 'error'+ ? 'error'+ : !installed+ ? 'missing'+ : needsGhAuth || needsScope+ ? 'partial'+ : 'ready';const steps: Step[] = isGh? [@@ -373,6 +385,12 @@ function DepRow({label: authed ? `Authenticated as ${dep.ghAuth!.account ?? 'you'}` : 'Authenticate',state: !installed ? 'pending' : authed ? 'done' : 'current',},+ {+ label: canReadPackages+ ? 'Can read packages'+ : 'Needs read:packages — re-run Authenticate',+ state: !authed ? 'pending' : canReadPackages ? 'done' : 'current',+ },]: [];@@ -396,9 +414,13 @@ function DepRow({{install.isPending ? 'Installing…' : 'Install'}</Button>)}- {installed && needsGhAuth && (+ {/* Also offered when the login is fine but lacks read:packages —+ telling someone to re-run Authenticate without giving them the+ button is worse than not telling them. Re-running the login is the+ fix: it now requests the scope. */}+ {installed && (needsGhAuth || needsScope) && (<Button size="sm" onClick={onAuthenticate}>- Authenticate+ {needsScope ? 'Re-authenticate' : 'Authenticate'}</Button>)}</div>diff --git a/dash/apps/switchdash-desktop/src/shared/core/npm-registry.ts b/dash/apps/switchdash-desktop/src/shared/core/npm-registry.tsnew file mode 100644index 000000000..cdb225d5c--- /dev/null+++ b/dash/apps/switchdash-desktop/src/shared/core/npm-registry.ts@@ -0,0 +1,61 @@+/**+ * Registry access for the Switch agent runtime, shared by every spawn path.+ *+ * The Claude Code plugin fetches its MCP server with+ * `npx @sandbox-quantum/switch-agent-runtime`. That package lives on GitHub+ * Packages and is private, so npm needs two things it does not know by+ * default: which registry serves the scope, and a token for it. Absent both,+ * npm asks npmjs.com, which has never heard of the package — so the failure+ * reads as a plain 404 for something that does not exist, rather than anything+ * about registries or credentials.+ *+ * Three places have to arrange this — the desktop for local sessions, the+ * sidecar for sessions it starts on a VM, and the SSH runtime for remote+ * sessions started from the desktop. They differ only in how they run `gh` and+ * write a file. Everything they must agree on lives here, because when it was+ * copied per path instead, one copy was simply missing and the symptom was a+ * 404 that named neither the cause nor the path that lacked it.+ */++export const NPM_REGISTRY_HOST = 'npm.pkg.github.com';+export const NPM_SCOPE = '@sandbox-quantum';++/**+ * The token is referenced, never written.+ *+ * npm expands `${VAR}` in an `.npmrc` as it reads it, so the file holds a+ * pointer to an environment variable rather than a credential. The value is+ * placed in the session's environment at spawn and lives only in that process.+ */+export const NPM_TOKEN_VAR = 'SWITCHDASH_GITHUB_TOKEN';++export const NPMRC_CONTENTS = [+ `${NPM_SCOPE}:registry=https://${NPM_REGISTRY_HOST}`,+ `//${NPM_REGISTRY_HOST}/:_authToken=\${${NPM_TOKEN_VAR}}`,+ '',+].join('\n');++/** How to fix a token that authenticates but cannot read packages. */+export const READ_PACKAGES_FIX = 'gh auth refresh -h github.com -s read:packages';++/**+ * Whether `gh auth status` output describes a token that cannot read packages.+ *+ * `gh auth login` asks for `gist`, `read:org`, `repo` and `workflow` — not+ * `read:packages`. A perfectly healthy default login therefore yields a token+ * the registry refuses with a 403 about "expected scopes", several layers below+ * anything that mentions `gh`.+ *+ * Returns false when no scope line is present: the output is human-readable and+ * may change, and being wrong about it must never block a session from starting.+ */+export function lacksReadPackages(ghAuthStatusOutput: string): boolean {+ return (+ ghAuthStatusOutput.includes('Token scopes:') && !ghAuthStatusOutput.includes('read:packages')+ );+}++/** The environment that points npm at a written npmrc. */+export function npmRegistryEnv(npmrcPath: string, token: string): Record<string, string> {+ return { npm_config_userconfig: npmrcPath, [NPM_TOKEN_VAR]: token };+}diff --git a/dash/apps/switchdash-desktop/src/sidecar/index.ts b/dash/apps/switchdash-desktop/src/sidecar/index.tsindex 053955be6..5b64fb8d9 100644--- a/dash/apps/switchdash-desktop/src/sidecar/index.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/index.ts@@ -14,6 +14,7 @@ import { createTmuxRun } from '@main/core/switch-rooms/tmux-injection-sink';import { type AgentLaunchSpec } from './agent-launch-spec';import { atomicWriteFile } from './atomic-file';import { NotificationWatcher, type WatcherLogger } from './notification-watcher';+import { npmRegistryAuthEnv } from './npm-registry-auth';import { InProcessSessionSpawner } from './session-spawner';import { createSidecarLogger, requireEnv } from './sidecar-logger';import {@@ -272,10 +273,16 @@ async function main(): Promise<void> {hookToken: server.getToken(),endpointFile,runtime,+ openConnectionFor: (sessionId, providerId, startCursor) =>+ runtime.ensureForSession(sessionId, providerId, startCursor),switchEnv: {SWITCH_API_ENDPOINT: creds.apiEndpoint,SWITCH_API_TOKEN: creds.token,SWITCH_AGENT_ID: creds.agentId,+ // Without this a spawned session's `npx` asks npmjs.com for a package+ // that only exists on GitHub Packages, and reports a 404 that says+ // nothing about registries or credentials.+ ...(await npmRegistryAuthEnv(repoDir, log)),},isPaneLive,log,@@ -326,7 +333,14 @@ async function main(): Promise<void> {// Hand the per-room spawn guard off to the live-room check the moment a session// connects — so a session torn down shortly after connecting does not leave the// room gated until INFLIGHT_TTL_MS (mirrors the local AutoSessionWatcher).- runtime.onRoomConnected((roomId) => watcher?.clearRoom(roomId));+ // Both spawn guards end here. The launched entry in particular must go even+ // when the session connects to a DIFFERENT room than it was started for:+ // keyed by the room it was launched for, it would otherwise keep vouching for+ // a room the session has left, and pings there would never spawn again.+ runtime.onRoomConnected((roomId, sessionId) => {+ watcher?.clearRoom(roomId);+ spawner?.drop(sessionId);+ });watcher.start();const refreshLiveness = async (): Promise<void> => {diff --git a/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts b/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.tsindex 6741fe514..53613f595 100644--- a/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts@@ -27,8 +27,10 @@ afterEach(() => {// spawnForRoom / handleNotification are private; reach them to test the spawn// decision in isolation from the long-poll loop.-function handle(watcher: NotificationWatcher, roomId: string): void {- (watcher as unknown as { handleNotification: (r: string) => void }).handleNotification(roomId);+function handle(watcher: NotificationWatcher, roomId: string, sequence?: number): void {+ (+ watcher as unknown as { handleNotification: (r: string, s?: number) => void }+ ).handleNotification(roomId, sequence);}describe('NotificationWatcher spawn decision', () => {@@ -47,7 +49,24 @@ describe('NotificationWatcher spawn decision', () => {const spawner = makeSpawner();handle(makeWatcher(spawner), 'room-x');await vi.waitFor(() => expect(spawner.launch).toHaveBeenCalledTimes(1));- expect(spawner.launch).toHaveBeenCalledWith('room-x');+ expect(spawner.launch).toHaveBeenCalledWith('room-x', undefined);+ });++ // The watcher consumed the triggering event to decide to spawn, so the+ // session it starts must rewind to it. Launched at head, the session comes up+ // having missed the one message it exists to answer.+ it('starts the spawned session one event before its trigger', async () => {+ const spawner = makeSpawner();+ handle(makeWatcher(spawner), 'room-x', 42);+ await vi.waitFor(() => expect(spawner.launch).toHaveBeenCalledTimes(1));+ expect(spawner.launch).toHaveBeenCalledWith('room-x', 41);+ });++ it('does not rewind past the start of the stream', async () => {+ const spawner = makeSpawner();+ handle(makeWatcher(spawner), 'room-x', 0);+ await vi.waitFor(() => expect(spawner.launch).toHaveBeenCalledTimes(1));+ expect(spawner.launch).toHaveBeenCalledWith('room-x', 0);});it('does not launch when a live session already attends the room', async () => {diff --git a/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.ts b/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.tsindex 5951e2d18..10fc96f7f 100644--- a/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.ts@@ -1,19 +1,23 @@+import { randomUUID } from 'node:crypto';+import { SwitchEventStream } from '@sandbox-quantum/switch-agent-runtime';import type { SwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';-import type { AgentBridgeEventResponse } from '@main/core/switch-rooms/switch-event-format';-const NOTIF_POLL_TIMEOUT_S = 10;-const INITIAL_BACKOFF_MS = 1000;-const MAX_BACKOFF_MS = 30_000;-// Refresh the "watching" heartbeat well under the server's ALWAYS_ON_TTL (90s)-// so a dormant agent reports DORMANT (and the server replies "Starting a-// session…") while the sidecar is watching on the VM.-const WATCH_HEARTBEAT_INTERVAL_MS = 30_000;+// How often the auto_session gate is re-read, so toggling it takes effect+// without restarting the sidecar. Matches the cadence the old idle loop woke+// at, so enabling auto_session still takes effect within about a second rather+// than becoming noticeably laggier. The connection's own heartbeat runs at the+// protocol's 2s cadence inside SwitchEventStream; this only decides whether+// that connection should exist at all.+const GATE_POLL_INTERVAL_MS = 1_000;const SPAWN_MAX_ATTEMPTS = 3;const SPAWN_RETRY_DELAY_MS = 2000;-// How long a room stays "spawn in flight" before the guard is cleared. Covers-// the boot+connect window; once the spawned tmux session is live, the-// live-session check no-ops further notifications anyway. If the spawn failed,-// clearing lets the next notification retry.+// How long a room stays "spawn in flight" before the guard is cleared.+//+// This covers the window the server cannot: it learns a session exists only+// when that session's connection claims the room, tens of seconds after the+// process starts. Until then the room looks unattended and every further+// addressed message would spawn again. Cleared early once the session is live;+// this TTL is the backstop for a spawn that failed.const INFLIGHT_TTL_MS = 120_000;export interface WatcherLogger {@@ -48,8 +52,16 @@ function sleep(ms: number, signal: AbortSignal): Promise<void> {export interface SessionSpawner {/** True when a session this watcher started is already attending the room. */isRoomLive(roomId: string): Promise<boolean>;- /** Launch one fresh session bound to the room. Throws on failure so the watcher can retry. */- launch(roomId: string): Promise<void>;+ /**+ * Launch one fresh session bound to the room. Throws on failure so the+ * watcher can retry.+ *+ * `startCursor` is where the new session's own connection should begin+ * reading. The watcher has already consumed the triggering event — that is+ * how it knows to spawn — so a session opening at head comes up having+ * missed the very message it exists to answer.+ */+ launch(roomId: string, startCursor?: number): Promise<void>;}/** Post a message to a room on the agent's behalf (the spawn-failure notice). Throws on non-OK. */@@ -66,19 +78,6 @@ async function postRoomMessage(if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);}-/** Refresh the agent's "watching" heartbeat. Throws on non-OK. */-async function postWatchHeartbeat(- creds: SwitchAgentCredentials,- signal: AbortSignal-): Promise<void> {- const resp = await fetch(`${creds.apiEndpoint}/agents/${creds.agentId}/watch/heartbeat`, {- method: 'POST',- headers: { Authorization: `Bearer ${creds.token}`, 'Content-Type': 'application/json' },- signal,- });- if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);-}-/*** The VM-side port of switchdash's `AutoSessionWatcher`: long-polls the Switch* agent-bridge notification stream and, whenever the agent is addressed in a@@ -96,6 +95,10 @@ export class NotificationWatcher {/** Room ids with a spawn in flight (booting / connecting) → guards against* duplicate spawns while a notification storm lands during the boot window. */private readonly inFlight = new Map<string, ReturnType<typeof setTimeout>>();+ /** Chosen once so the connection survives a dropped socket. */+ private readonly connectionId = randomUUID();+ /** Aborts the watch connection when auto_session is toggled off. */+ private streamAbort: AbortController | null = null;constructor(private readonly deps: {@@ -115,82 +118,89 @@ export class NotificationWatcher {start(): void {const { creds, log } = this.deps;log.info('NotificationWatcher: started', { agentId: creds.agentId });- void this.notificationLoop();- void this.watchHeartbeatLoop();+ void this.gateLoop();}stop(): void {this.abort.abort();+ this.closeStream();for (const timer of this.inFlight.values()) clearTimeout(timer);this.inFlight.clear();this.deps.log.info('NotificationWatcher: stopped');}- private async watchHeartbeatLoop(): Promise<void> {- const { creds, watchEnabled, log } = this.deps;+ /**+ * Hold the watch connection open exactly while auto_session is enabled.+ *+ * The connection carries both jobs the two old loops did: it delivers the+ * addressed events that trigger a spawn, and its heartbeat is what makes the+ * agent report DORMANT so the server answers "Starting a session…". Tying+ * both to the gate keeps that promise honest — a sidecar that will not start+ * a session should not be advertising that it will.+ */+ private async gateLoop(): Promise<void> {+ const { watchEnabled } = this.deps;const { signal } = this.abort;while (!signal.aborted) {- if (!watchEnabled()) {- await sleep(WATCH_HEARTBEAT_INTERVAL_MS, signal);- continue;- }- try {- await postWatchHeartbeat(creds, signal);- } catch (error) {- if (signal.aborted) return;- log.warn('NotificationWatcher: watch heartbeat error', {- agentId: creds.agentId,- error: String(error),- });- }- await sleep(WATCH_HEARTBEAT_INTERVAL_MS, signal);+ if (watchEnabled()) this.openStream();+ else this.closeStream();+ await sleep(GATE_POLL_INTERVAL_MS, signal);}}- private async notificationLoop(): Promise<void> {- const { creds, watchEnabled, log } = this.deps;- const { signal } = this.abort;- const url = `${creds.apiEndpoint}/agents/${creds.agentId}/notifications?timeout=${NOTIF_POLL_TIMEOUT_S}`;- let backoff = INITIAL_BACKOFF_MS;- log.debug('NotificationWatcher: notification loop started', { agentId: creds.agentId, url });-- while (!signal.aborted) {- // Auto_session disabled → do not poll (the stream is a destructive queue,- // so draining it while we won't act would swallow events). Idle instead.- if (!watchEnabled()) {- await sleep(INITIAL_BACKOFF_MS, signal);- continue;- }- try {- const resp = await fetch(url, {- headers: { Authorization: `Bearer ${creds.token}` },- signal,+ private openStream(): void {+ if (this.streamAbort) return;+ const { creds, log } = this.deps;+ const streamAbort = new AbortController();+ this.streamAbort = streamAbort;+ log.info('NotificationWatcher: opening watch connection', {+ agentId: creds.agentId,+ connectionId: this.connectionId,+ });+ new SwitchEventStream({+ creds: { agentId: creds.agentId, apiEndpoint: creds.apiEndpoint, token: creds.token },+ connectionId: this.connectionId,+ // Every room the agent belongs to except those a session's connection has+ // claimed — the server, not this process, decides which those are.+ scope: 'all',+ filter: 'addressed',+ rooms: [],+ // Same promise as switchdash's watcher: this process will spawn.+ spawnCapable: true,+ onEvent: (event) => {+ if (event.room_id) this.handleNotification(event.room_id, event.sequence);+ },+ onGap: (info) => {+ log.warn('NotificationWatcher: gap — may have missed a spawn trigger', {+ agentId: creds.agentId,+ fromSequence: info.fromSequence,+ reason: info.reason,});- if (resp.status === 204) {- backoff = INITIAL_BACKOFF_MS;- continue;- }- if (!resp.ok) throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);-- backoff = INITIAL_BACKOFF_MS;- const data = (await resp.json()) as AgentBridgeEventResponse;- for (const event of data.events) {- this.handleNotification(event.room_id);- }- } catch (error) {- if (signal.aborted) return;- log.warn('NotificationWatcher: notification poll error', {+ },+ onEvicted: (reason) => {+ log.warn('NotificationWatcher: watch connection evicted', {agentId: creds.agentId,- error: String(error),+ reason,});- await sleep(backoff, signal);- backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);- }- }+ },+ log: {+ debug: (message, meta) => log.debug(message, meta),+ warn: (message, meta) => log.warn(message, meta),+ error: (message, meta) => log.warn(message, meta),+ },+ signal: AbortSignal.any([streamAbort.signal, this.abort.signal]),+ }).start();+ }++ private closeStream(): void {+ if (!this.streamAbort) return;+ this.streamAbort.abort();+ this.streamAbort = null;+ this.deps.log.info('NotificationWatcher: watch connection closed (auto_session off)');}/** Decide whether to spawn for a notified room, with a per-room in-flight guard. */- private handleNotification(roomId: string): void {+ private handleNotification(roomId: string, sequence?: number): void {if (this.inFlight.has(roomId)) {this.deps.log.info('NotificationWatcher: notification for room with a spawn already in flight — skipping duplicate spawn',@@ -202,7 +212,12 @@ export class NotificationWatcher {const timer = setTimeout(() => this.inFlight.delete(roomId), INFLIGHT_TTL_MS);this.inFlight.set(roomId, timer);- void this.spawnForRoom(roomId).catch((error) => {+ // One before the trigger, so the session's stream replays it. Overlapping+ // by an event is cheap — a connection only receives events for the room it+ // claims — where a gap is the bug this exists to prevent.+ const startCursor = sequence === undefined ? undefined : Math.max(sequence - 1, 0);++ void this.spawnForRoom(roomId, startCursor).catch((error) => {this.deps.log.warn('NotificationWatcher: spawn failed', { roomId, error: String(error) });});}@@ -217,7 +232,7 @@ export class NotificationWatcher {this.clearInFlight(roomId);}- private async spawnForRoom(roomId: string): Promise<void> {+ private async spawnForRoom(roomId: string, startCursor?: number): Promise<void> {const { spawner, creds, log } = this.deps;// A session this watcher started is already attending the room — its own@@ -231,10 +246,16 @@ export class NotificationWatcher {for (let attempt = 1; attempt <= SPAWN_MAX_ATTEMPTS; attempt += 1) {if (this.abort.signal.aborted) return;try {- await spawner.launch(roomId);+ await spawner.launch(roomId, startCursor);+ // Half of a hand-off logged at both ends, so a session that comes up+ // without its triggering message can be diagnosed from the log alone:+ // this says where the session should start reading, and the runtime's+ // `switch_session_connection_open` says where it actually started.log.info('NotificationWatcher: spawned session for room', {+ event: 'auto_session_spawned',agentId: creds.agentId,roomId,+ startFrom: startCursor ?? 'head',});return;} catch (error) {diff --git a/dash/apps/switchdash-desktop/src/sidecar/npm-registry-auth.ts b/dash/apps/switchdash-desktop/src/sidecar/npm-registry-auth.tsnew file mode 100644index 000000000..ce4869735--- /dev/null+++ b/dash/apps/switchdash-desktop/src/sidecar/npm-registry-auth.ts@@ -0,0 +1,117 @@+import { execFile } from 'node:child_process';+import { mkdir, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { promisify } from 'node:util';+import {+ lacksReadPackages,+ NPMRC_CONTENTS,+ npmRegistryEnv,+ READ_PACKAGES_FIX,+} from '@shared/core/npm-registry';+import type { WatcherLogger } from './notification-watcher';++const execFileAsync = promisify(execFile);++/**+ * Registry access for sessions this sidecar starts on the VM.+ *+ * The Claude Code plugin fetches its MCP server with+ * `npx @sandbox-quantum/switch-agent-runtime`. That package is on GitHub+ * Packages and private, so npm needs to be told which registry serves the+ * scope and how to authenticate. Told neither, it asks npmjs.com, which has+ * never heard of it — the failure reads as a plain 404 for a package that does+ * not exist, rather than anything about registries or credentials.+ *+ * This is the VM-side counterpart of switchdash's `npmRegistryAuthEnv`. Same+ * two settings, same env-var indirection so no token is written to disk; the+ * only difference is that the token comes from the VM's own `gh`, which is a+ * core host dependency, rather than the desktop's.+ */++async function ghToken(log: WatcherLogger): Promise<string | null> {+ try {+ const { stdout } = await execFileAsync('gh', ['auth', 'token'], { timeout: 10_000 });+ const token = stdout.trim();+ return token.length > 0 ? token : null;+ } catch (error) {+ log.warn('npmRegistryAuth: `gh auth token` failed on this host', {+ event: 'npm_registry_auth_no_gh',+ error: String(error),+ });+ return null;+ }+}++/**+ * Warn when the token cannot read packages.+ *+ * `gh auth login` asks for `gist`, `read:org`, `repo` and `workflow` — not+ * `read:packages`. So the default, perfectly healthy login produces a token+ * that authenticates fine and is then refused by the registry with a 403 about+ * "expected scopes", several layers below anything that mentions `gh`.+ *+ * Checked here so the cause is stated at spawn, where it is actionable, rather+ * than inferred later from an npx failure. Only a warning: the scope list is+ * parsed from human-readable output, and being wrong about it must not stop a+ * session starting.+ */+async function warnIfCannotReadPackages(log: WatcherLogger): Promise<void> {+ try {+ // `gh auth status` prints scopes on stderr.+ const { stdout, stderr } = await execFileAsync('gh', ['auth', 'status'], { timeout: 10_000 });+ if (!lacksReadPackages(`${stdout}${stderr}`)) return;+ log.warn('npmRegistryAuth: the GitHub token cannot read packages', {+ event: 'npm_registry_auth_missing_scope',+ fix: READ_PACKAGES_FIX,+ detail:+ 'gh auth login does not request read:packages, so the registry will refuse ' ++ 'with 403 and the session will start without its MCP tools',+ });+ } catch {+ // Never fatal — this is a diagnostic, not a gate.+ }+}++/**+ * Write the npmrc and return the environment that points npm at it.+ *+ * Returns an empty environment when the host has no usable `gh`. The session+ * still starts: it will fail to fetch the runtime and come up without tools,+ * which is bad, but strictly better than not starting at all — and the warning+ * here names the cause, which a bare npm 404 would not.+ */+export async function npmRegistryAuthEnv(+ repoDir: string,+ log: WatcherLogger+): Promise<Record<string, string>> {+ const token = await ghToken(log);+ if (!token) {+ log.warn('npmRegistryAuth: no GitHub token — the agent runtime will not resolve', {+ event: 'npm_registry_auth_missing_token',+ hint: 'run `gh auth login` on this host; the package is private and reads as 404 without it',+ });+ return {};+ }++ await warnIfCannotReadPackages(log);++ const dir = path.join(repoDir, '.switchdash');+ const npmrc = path.join(dir, 'npmrc');+ try {+ await mkdir(dir, { recursive: true });+ await writeFile(npmrc, NPMRC_CONTENTS, { mode: 0o600 });+ } catch (error) {+ log.warn('npmRegistryAuth: could not write npmrc', {+ event: 'npm_registry_auth_write_failed',+ path: npmrc,+ error: String(error),+ });+ return {};+ }++ log.info('npmRegistryAuth: registry access configured for spawned sessions', {+ event: 'npm_registry_auth_ready',+ npmrc,+ });+ return npmRegistryEnv(npmrc, token);+}diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.tsindex eb0acf606..9ac6dbbe2 100644--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts@@ -158,4 +158,29 @@ describe('InProcessSessionSpawner.drop', () => {expect(spawner.spawnedSessions()).toHaveLength(1);});++ // A session started for room A that moves to room B leaves A uncovered, and a+ // ping there must spawn again. The launched entry is keyed by the room the+ // session was started for and its pane is still alive in room B, so left in+ // place it vouches for A forever and A becomes permanently unspawnable.+ it('frees the original room once its session has moved elsewhere', async () => {+ const rooms = new Map<string, string>();+ const runtime = {+ hasLiveRoom: vi.fn((r: string) => [...rooms.values()].includes(r)),+ };+ const { spawner } = makeSpawner({ isPaneLive: () => true, runtime });++ await spawner.launch('room-a');+ const sessionId = spawner.spawnedSessions()[0]!.sessionId;++ // Connects to the room it was started for: still covered.+ rooms.set(sessionId, 'room-a');+ spawner.drop(sessionId);+ await expect(spawner.isRoomLive('room-a')).resolves.toBe(true);++ // Re-targets to another room. Its pane is still live — that is the trap.+ rooms.set(sessionId, 'room-b');+ await expect(spawner.isRoomLive('room-b')).resolves.toBe(true);+ await expect(spawner.isRoomLive('room-a')).resolves.toBe(false);+ });});diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.tsindex 8a08dd1bc..801b184ab 100644--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts@@ -26,6 +26,17 @@ export interface InProcessSessionSpawnerDeps {endpointFile: string;/** The multi-session runtime — a room it already serves needs no new session. */runtime: RoomLivenessSource;+ /**+ * Open a connection for a session about to launch and return its id, so the+ * session's tool calls land on the connection this sidecar is reading. Same+ * hand-off switchdash does locally; without it the session opens its own and+ * the sidecar is back to inferring the room from a hook.+ */+ openConnectionFor?: (+ sessionId: string,+ providerId: string,+ startCursor?: number+ ) => string | null;/** The agent's Switch identity as `SWITCH_*` env, injected into every* auto-started session so it authenticates as this agent — a `--settings` env* block is not reliably propagated to the spawned MCP server (CHOO-1440). */@@ -69,9 +80,16 @@ export class InProcessSessionSpawner implements SessionSpawner {}/**- * Forget a launched session by its session id (switchdash deleted it), so- * it is no longer reported as pending/spawned and a fresh room notification can- * spawn a new one. No-op if we never launched this session.+ * Forget a launched session by its session id, so it is no longer reported as+ * pending/spawned and a fresh room notification can spawn a new one. No-op if+ * we never launched this session.+ *+ * Called both when switchdash deletes a session and when one connects to a+ * room. The entry only covers the boot window — between launch and the first+ * `connect_to_room` — and once the runtime knows the session, its room map is+ * the accurate answer. Keeping the entry past that point makes it vouch for+ * the room the session was *started for* rather than the one it is in, so a+ * session that moves rooms leaves its old room permanently unspawnable.*/drop(sessionId: string): void {for (const [roomId, session] of this.launched) {@@ -127,12 +145,18 @@ export class InProcessSessionSpawner implements SessionSpawner {return false;}- async launch(roomId: string): Promise<void> {+ async launch(roomId: string, startCursor?: number): Promise<void> {const { hookPort, hookToken, endpointFile, log } = this.deps;const spec = this.spec;const sessionId = randomUUID();const tmuxTarget = makeAgentTmuxSessionName(sessionId);+ // Open the session's connection before launching it: its first+ // connect_to_room arrives tagged with this id, and the server refuses a+ // call naming a connection that is not open.+ const connectionId =+ this.deps.openConnectionFor?.(sessionId, spec.providerId, startCursor) ?? null;+const hookEnv = {...this.deps.switchEnv,...buildAgentHookEnv({@@ -141,6 +165,7 @@ export class InProcessSessionSpawner implements SessionSpawner {token: hookToken,endpointFile,}),+ ...(connectionId ? { SWITCH_CONNECTION_ID: connectionId } : {}),};const command = materializeAgentCommand(spec, {sessionId,diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.tsindex 5c97b76dc..3d82a68bd 100644--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts@@ -16,7 +16,7 @@ vi.mock('@main/core/providers/plugin-registry', () => ({getPlugin: () => ({ behavior: { hooks: undefined }, capabilities: { prompt: { kind: 'argv' } } }),}));-const silentLog = { debug: vi.fn(), warn: vi.fn(), error: vi.fn() };+const silentLog = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };function fakeConnection(): ManagedConnection {return { start: vi.fn(), stop: vi.fn(), onAgentStatusChange: vi.fn() };@@ -89,6 +89,26 @@ describe('SidecarRuntime (multi-session)', () => {expect(created[0].conn.start).toHaveBeenCalledTimes(1);});+ // The receiving half of the watcher's hand-off. The watcher already consumed+ // the event that made it spawn, so the session's own connection has to rewind+ // to it — opened at head, the session misses the message it exists to answer.+ it('opens a spawned session at the cursor the watcher handed over', () => {+ const { runtime, created } = makeRuntime();++ runtime.ensureForSession('session-a', 'codex', 41);++ expect(created).toHaveLength(1);+ expect(created[0].deps.startCursor).toBe(41);+ });++ it('opens a session at head when no cursor was handed over', () => {+ const { runtime, created } = makeRuntime();++ runtime.ensureForSession('session-a', 'codex');++ expect(created[0].deps.startCursor).toBeUndefined();+ });+it('records every hooked session (hasSeen) so /sessions can scope tmux to this agent', async () => {const { runtime } = makeRuntime();expect(runtime.hasSeen('session-a')).toBe(false);@@ -200,6 +220,23 @@ describe('SidecarRuntime (multi-session)', () => {expect(connected).toEqual(['room-1', 'room-1']);});+ // The spawner's launched entry is keyed by session, not room, so the listener+ // has to carry the session id — without it the entry cannot be dropped, and it+ // keeps vouching for the room the session was started for after it has moved.+ it('tells the listener which session connected, on first connect and on a move', async () => {+ const { runtime } = makeRuntime();+ const connected: Array<[string, string]> = [];+ runtime.onRoomConnected((roomId, sessionId) => connected.push([roomId, sessionId]));++ await runtime.handleHook(switchRoomHook('room-1', PTY_A));+ await runtime.handleHook(switchRoomHook('room-2', PTY_A));++ expect(connected).toEqual([+ ['room-1', 'session-a'],+ ['room-2', 'session-a'],+ ]);+ });+it('roomIdForSession returns the attended room, or null when unknown', async () => {const { runtime } = makeRuntime();await runtime.handleHook(switchRoomHook('room-1', PTY_A));diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.tsindex 08542383a..c6e16d37a 100644--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto';import * as os from 'node:os';import * as path from 'node:path';import { deriveAgentStatus } from '@main/core/agent-hooks/derive-agent-status';@@ -82,7 +83,7 @@ export class SidecarRuntime {/** Notified when a session connects to a room, so the notification watcher can* hand its per-room in-flight guard off to the live-room check (mirrors the* local AutoSessionWatcher's room-connection subscription). */- private roomConnectedListener: ((roomId: string) => void) | null = null;+ private roomConnectedListener: ((roomId: string, sessionId: string) => void) | null = null;constructor(private readonly deps: SidecarRuntimeDeps) {this.resolveContext = async (ptyId) => {@@ -96,8 +97,17 @@ export class SidecarRuntime {};}- /** Register the room-connected listener (the notification watcher's guard hand-off). */- onRoomConnected(listener: (roomId: string) => void): void {+ /**+ * Register the room-connected listener (the notification watcher's guard+ * hand-off).+ *+ * Carries the session id as well as the room because the spawn guards are+ * keyed differently: the watcher's in-flight guard by room, the spawner's+ * launched-session entry by session. Both end at the moment a session+ * connects, and after that the runtime's own room map is the only thing that+ * should decide whether a room is covered.+ */+ onRoomConnected(listener: (roomId: string, sessionId: string) => void): void {this.roomConnectedListener = listener;}@@ -154,6 +164,21 @@ export class SidecarRuntime {// has no database to update.}+ /**+ * Open a session's connection before it launches, and return the id to hand+ * it in its environment. Mirrors switchdash's `ensureForSession`.+ *+ * The connection must exist before the session's first `connect_to_room`,+ * which arrives tagged with this id. It also makes the room server-driven+ * here too: the claim lands on this connection and comes back as+ * `subscription_changed`, so the sidecar stops depending on parsing the hook.+ */+ ensureForSession(sessionId: string, providerId: string, startCursor?: number): string {+ const existing = this.sessions.get(sessionId);+ if (existing) return existing.connection.connection;+ return this.openConnection(sessionId, providerId, null, null, startCursor);+ }+private connectRoom(sessionId: string,providerId: string,@@ -165,7 +190,17 @@ export class SidecarRuntime {// in-flight queue and renew loop are preserved — but still hand off the// watcher's spawn guard (idempotent), since a session is attending the room.if (existing && existing.roomId === roomId) {- this.roomConnectedListener?.(roomId);+ this.roomConnectedListener?.(roomId, sessionId);+ return;+ }+ if (existing && existing.roomId === null) {+ // We opened this connection at launch and the server has not named a+ // room yet. The claim is in flight; trust it rather than rebuilding.+ this.deps.log.debug('SidecarRuntime: hook named a room before the server did', {+ sessionId,+ roomId,+ });+ this.roomConnectedListener?.(roomId, sessionId);return;}// A session re-targeting to a new room supersedes ITS OWN prior room only —@@ -173,11 +208,25 @@ export class SidecarRuntime {// connect_to_room re-targeting independently).if (existing) existing.connection.stop();+ this.openConnection(sessionId, providerId, roomId, roomName);+ this.roomConnectedListener?.(roomId, sessionId);+ }++ private openConnection(+ sessionId: string,+ providerId: string,+ roomId: string | null,+ roomName: string | null,+ startCursor?: number+ ): string {const tmuxTarget = makeAgentTmuxSessionName(sessionId);+ const connectionId = randomUUID();const connection = this.deps.createConnection({creds: this.deps.creds,roomId,roomName,+ connectionId,+ startCursor,sessionId,sink: new TmuxInjectionSink(tmuxTarget, this.deps.tmuxRun, () =>this.deps.isPaneLive(tmuxTarget)@@ -190,13 +239,33 @@ export class SidecarRuntime {// can't gate on human typing yet — a known follow-up for the attached case.isHumanTyping: () => false,mediaDir: path.join(os.tmpdir(), 'switchdash-switch-media', sessionId),+ // The server naming this connection's room is what records it here, so a+ // session that moves rooms is followed without re-reading a hook.+ onRoomChanged: (room) => {+ const entry = this.sessions.get(sessionId);+ if (entry) entry.roomId = room;+ if (room) {+ this.deps.registry.record({ sessionId, roomId: room, providerId, tmuxTarget });+ this.roomConnectedListener?.(room, sessionId);+ }+ },log: this.deps.log,});this.sessions.set(sessionId, { connection, roomId, tmuxTarget });- this.deps.registry.record({ sessionId, roomId, providerId, tmuxTarget });- this.deps.log.debug('SidecarRuntime: room connected', { sessionId, roomId, roomName });+ if (roomId) this.deps.registry.record({ sessionId, roomId, providerId, tmuxTarget });+ // The other end of the watcher's hand-off. If a spawned session comes up+ // without the message that triggered it, this says whether a cursor was+ // handed over and honoured, or whether it opened at head and read past it.+ this.deps.log.info('SidecarRuntime: connection opened', {+ event: 'switch_session_connection_open',+ sessionId,+ roomId,+ roomName,+ connectionId,+ startFrom: startCursor ?? 'head',+ });connection.start();- this.roomConnectedListener?.(roomId);+ return connectionId;}/**diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.tsindex 4480957ac..a479a659d 100644--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts@@ -19,7 +19,7 @@* Bump policy: `x` on a wire break (and only then), `y` on every release that* changes the sidecar.*/-export const SIDECAR_VERSION = '1.0';+export const SIDECAR_VERSION = '1.3';/*** Oldest major this client can still speak to. Raise it only when support for andiff --git a/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db b/dash/apps/switchdash-desktop/tooling/fixtures/baseline.dbindex c11b06ed3..1d69ce577 100644Binary files a/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db and b/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db differdiff --git a/dash/apps/switchdash-desktop/tooling/fixtures/empty.db b/dash/apps/switchdash-desktop/tooling/fixtures/empty.dbindex 5f86d6ba0..708c15bce 100644Binary files a/dash/apps/switchdash-desktop/tooling/fixtures/empty.db and b/dash/apps/switchdash-desktop/tooling/fixtures/empty.db differdiff --git a/dash/packages/switch-agent-runtime/package.json b/dash/packages/switch-agent-runtime/package.jsonnew file mode 100644index 000000000..e849560e1--- /dev/null+++ b/dash/packages/switch-agent-runtime/package.json@@ -0,0 +1,53 @@+{+ "name": "@sandbox-quantum/switch-agent-runtime",+ "version": "0.1.2",+ "description": "Switch agent protocol client, and the local MCP runtime built on it",+ "license": "Apache-2.0",+ "author": {+ "name": "Switch Contributors"+ },+ "repository": {+ "type": "git",+ "url": "git+https://github.com/sandbox-quantum/switch.git",+ "directory": "dash/packages/switch-agent-runtime"+ },+ "bin": {+ "switch-agent-runtime": "./dist/bin.mjs"+ },+ "files": [+ "dist"+ ],+ "type": "module",+ "sideEffects": false,+ "exports": {+ ".": {+ "types": "./dist/index.d.mts",+ "default": "./dist/index.mjs"+ },+ "./package.json": "./package.json"+ },+ "publishConfig": {+ "registry": "https://npm.pkg.github.com"+ },+ "scripts": {+ "dev": "tsdown --watch",+ "build": "tsdown",+ "test": "vitest run",+ "lint": "sh -c 'root=$(cd ../.. && pwd); cd \"$root/apps/switchdash-desktop\" && pnpm exec oxlint --config .oxlintrc.json \"$root/packages/switch-agent-runtime\"'",+ "format": "oxfmt",+ "format:check": "oxfmt --check",+ "typecheck": "tsgo --noEmit -p tsconfig.json"+ },+ "dependencies": {+ "@modelcontextprotocol/sdk": "^1.0.0"+ },+ "devDependencies": {+ "@types/node": "^20.19.42",+ "@typescript/native-preview": "7.0.0-dev.20260609.1",+ "tsdown": "^0.22.2",+ "vitest": "^4.1.0"+ },+ "engines": {+ "node": ">=20"+ }+}diff --git a/dash/packages/switch-agent-runtime/src/bin.shebang.test.ts b/dash/packages/switch-agent-runtime/src/bin.shebang.test.tsnew file mode 100644index 000000000..de6732f9f--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/bin.shebang.test.ts@@ -0,0 +1,35 @@+import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';++/**+ * The interpreter this is published against.+ *+ * `npx` runs the `bin` under node, always — that is what npx is. A shebang+ * naming anything else makes the package unstartable on every host that does+ * not happen to have that interpreter, and the failure is `exit 127` from+ * `/usr/bin/env`, which says nothing about which package or why.+ *+ * This is not hypothetical: 0.1.1 shipped `#!/usr/bin/env bun`, left behind+ * when the server moved from `Bun.serve` to `node:http`. The code was correct+ * and the artifact would not start.+ */+const SHEBANG = '#!/usr/bin/env node';++const PKG_ROOT = join(import.meta.dirname, '..');++describe('bin shebang', () => {+ it('names node in source', () => {+ const source = readFileSync(join(PKG_ROOT, 'src/bin.ts'), 'utf8');+ expect(source.split('\n', 1)[0]).toBe(SHEBANG);+ });++ // The built artifact is what actually ships, so check it when it exists —+ // it always does in CI, which builds before publishing. Absent locally, the+ // source assertion above already covers the mistake anyone is likely to make.+ it('carries the shebang through the build', () => {+ const dist = join(PKG_ROOT, 'dist/bin.mjs');+ if (!existsSync(dist)) return;+ expect(readFileSync(dist, 'utf8').split('\n', 1)[0]).toBe(SHEBANG);+ });+});diff --git a/dash/packages/switch-agent-runtime/src/bin.ts b/dash/packages/switch-agent-runtime/src/bin.tsnew file mode 100644index 000000000..a3286fc58--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/bin.ts@@ -0,0 +1,1348 @@+#!/usr/bin/env node+/**+ * Switch channel for Claude Code.+ *+ * Holds a push connection to the Switch Agent Bridge (server-sent events) and+ * pushes addressed messages and task events into the Claude Code session as+ * channel notifications.+ *+ * The room is set by the PostToolUse hook on connect_to_room, which+ * POSTs the room id to a localhost port this server exposes. The port is+ * advertised at `${CLAUDE_PLUGIN_DATA}/sessions/${ppid}/port`, where ppid is+ * this process's parent PID (the Claude Code session). The hook resolves the+ * same path from its own getppid(), so each session's hook reaches its own+ * channel without any cross-session coordination.+ *+ * Config comes from env vars set via .mcp.json env block (SWITCH_*).+ */++import { randomUUID } from 'node:crypto';+import * as fs from 'node:fs';+import * as http from 'node:http';+import * as os from 'node:os';+import * as path from 'node:path';+import { Server } from '@modelcontextprotocol/sdk/server/index.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';+import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';+import { readSse, type SseFrame } from './sse';++const API_ENDPOINT = process.env.SWITCH_API_ENDPOINT ?? '';+const API_TOKEN = process.env.SWITCH_API_TOKEN ?? '';+const AGENT_ID = process.env.SWITCH_AGENT_ID ?? '';++// When this session is managed by switchdash, switchdash reads the agent+// bridge itself and injects addressed messages into the PTY. Reads are no+// longer destructive, so both can read the same events without stealing from+// each other — but the agent would be told twice. So we still hold the+// connection (it is what correlates every tool call and proves this session is+// reachable) and simply do not surface events as notifications.+// Env var name kept for compatibility with switchdash releases in the wild.+const SUPPRESS_NOTIFICATIONS = process.env.SWITCH_CHANNEL_DISABLE_POLL === '1';++// Claude Code may spawn this server twice on startup: once before settings.env+// expansion (vars literal as `${SWITCH_*}`) and once with real values. Reject+// the unresolved spawn so it doesn't race the real one for the port file.+function looksUnresolved(value: string): boolean {+ return value.startsWith('${') && value.endsWith('}');+}++if (+ !API_ENDPOINT ||+ !API_TOKEN ||+ !AGENT_ID ||+ looksUnresolved(API_ENDPOINT) ||+ looksUnresolved(API_TOKEN) ||+ looksUnresolved(AGENT_ID)+) {+ process.stderr.write(+ `switch: missing or unresolved config — need SWITCH_API_ENDPOINT, SWITCH_API_TOKEN, and SWITCH_AGENT_ID\n` ++ ` endpoint=${API_ENDPOINT || 'MISSING'}\n` ++ ` token=${API_TOKEN ? 'set' : 'MISSING'}\n` ++ ` agent_id=${AGENT_ID || 'MISSING'}\n` ++ `If these look like \`\${SWITCH_*}\`, the env block in \`.claude/settings.local.json\` has not been expanded — run the \`configure\` skill.\n`+ );+ process.exit(1);+}++const SESSION_PPID = process.ppid;+const SESSION_DIR = path.join(os.homedir(), '.switch', 'sessions', String(SESSION_PPID));+const PORT_FILE = path.join(SESSION_DIR, 'port');+process.stderr.write(`switch: ppid=${SESSION_PPID} session_dir=${SESSION_DIR}\n`);++process.on('unhandledRejection', (err) => {+ process.stderr.write(`switch: unhandled rejection: ${err}\n`);+});+process.on('uncaughtException', (err) => {+ process.stderr.write(`switch: uncaught exception: ${err}\n`);+});++// -- Types matching core/switch_core/bridges/agent/events.py ----------------------++type AttachmentRef = {+ filename: string;+ mimetype: string;+ size: number;+ mxc: string;+ msgtype: string;+};++type MessagePayload = {+ addressed: boolean;+ sender: string;+ sender_name: string;+ message_id: string;+ body: string;+ timestamp: number;+ thread_id?: string | null;+ attachments?: AttachmentRef[];+};++type CommandPayload = {+ command: string;+ target: string | null;+ user_id: string;+ user_name: string;+};++type RoomJoinPayload = {+ member: string;+ member_name: string;+ timestamp: number;+ listening: boolean;+};++type TaskDelegatePayload = {+ task_id: string;+ requester_agent_id: string;+ performer_agent_id: string;+ summary: string;+ description: string;+};++type TaskAcceptPayload = {+ task_id: string;+ requester_agent_id: string;+ performer_agent_id: string;+};++type TaskUpdatePayload = {+ task_id: string;+ requester_agent_id: string;+ performer_agent_id: string;+ update: string;+};++type TaskFinalisePayload = {+ task_id: string;+ requester_agent_id: string;+ performer_agent_id: string;+ outcome: string | null;+};++type TaskCancelPayload = {+ task_id: string;+ requester_agent_id: string;+ performer_agent_id: string;+ reason: string | null;+};++type AgentEvent = {+ type: string;+ room_id: string;+ bridge_id: string | null;+ channel_type: string | null;+ payload:+ | MessagePayload+ | CommandPayload+ | RoomJoinPayload+ | TaskDelegatePayload+ | TaskAcceptPayload+ | TaskUpdatePayload+ | TaskFinalisePayload+ | TaskCancelPayload;+};++// -- Connection state --------------------------------------------------------+//+// The client picks its own connection id and reuses it when reconnecting, so a+// dropped stream reattaches to the same server-side connection instead of+// creating a new one. That is what lets a brief network drop cost a gap in+// delivery rather than this session's room slot.++// A supervisor that spawned this session may hand it a connection to share+// (switchdash does: it opens the stream, then passes the id in the+// environment). Then this process holds no stream and no heartbeat of its own —+// it only tags its tool calls with the id, so the server can tell which session+// is calling and which room that session is in.+//+// The point is that `connect_to_room` then claims the room on the *supervisor's*+// connection, which is the one delivering events. Two connections for one+// session is what made the supervisor unable to see its own agent's room, and+// left it scraping tool responses to find out.+//+// Absent the hand-off — a bare terminal session, or one the supervisor merely+// attached to — this process owns its connection exactly as before.+//+// It is read from the ambient environment and NOT declared in the plugin's+// .mcp.json. Host env vars reach a spawned MCP server anyway, and declaring it+// there made it mandatory: a `${VAR}` in that block that resolves to nothing+// fails the whole server with "Missing environment variables", so every session+// without a supervisor — the standalone case — lost its tools entirely.+function borrowedConnectionId(): string | null {+ const raw = process.env.SWITCH_CONNECTION_ID?.trim();+ if (!raw) return null;+ // An unexpanded `${...}` means someone declared this in a config file and the+ // host did not substitute it. Using it as an id would tag every tool call+ // with a connection that cannot exist, which the server rejects — and the+ // reason would be invisible from here. Ignore it and own the connection.+ if (raw.includes('${')) {+ process.stderr.write(+ `switch: ignoring unexpanded SWITCH_CONNECTION_ID (${raw}) — opening our own connection\n`+ );+ return null;+ }+ return raw;+}++const BORROWED_CONNECTION_ID = borrowedConnectionId();+const CONNECTION_ID = BORROWED_CONNECTION_ID ?? randomUUID();+const OWNS_CONNECTION = BORROWED_CONNECTION_ID === null;++let pollingRoomId: string | null = null;+let streamAbort: AbortController | null = null;+let leaseAbort: AbortController | null = null;+let heartbeatAbort: AbortController | null = null;++// Highest sequence number processed. Sent back on reconnect (as Last-Event-ID)+// to resume exactly where we stopped, and on every heartbeat so the server can+// trim what we have seen.+let cursor = 0;++// Whether the currently open stream declared a room when it opened.+let streamHasRoom = false;++// Unaddressed room messages are filtered out (never reach Claude as a+// notification), so the agent silently falls behind on room chatter. We tally+// how many we've dropped since the agent last read context and surface that+// count on every notification we DO emit, so the agent knows when to call+// read_context to catch up. Reset to 0 when the agent reads context (signalled+// by the /read-context hook) and when polling switches rooms.+let missedSinceRead = 0;++// -- MCP server --------------------------------------------------------------++const mcp = new Server(+ { name: 'switch', version: '0.1.0' },+ {+ capabilities: {+ tools: {},+ experimental: {+ 'claude/channel': {},+ },+ },+ instructions: [+ 'Events from Switch rooms arrive as <channel source="plugin:switch-connector:switch" room_id="..." event_type="..." ...>.',+ 'Only addressed messages, room_join events, and task events are delivered — unaddressed room chatter is filtered out.',+ '',+ 'A room_join event fires when a user or agent joins a room — but you are only notified for rooms where you are configured to receive join events (per-room, per-agent; off by default, set via the join_event_listeners option on create_room / update_room or the gateway). The meta carries member (their matrix id) and member_name (their display name). React if it is relevant — e.g. a welcome agent greets the new arrival and explains the room via post_message, or send_targeted_message to address them directly. Your own join does not produce a room_join event.',+ '',+ 'Every notification carries a `missed_count` in its meta: the number of unaddressed room messages filtered out since you last called read_context. When it is above 0 the one-line body is annotated with it. A growing count means the room is active around you and you have fallen behind — call read_context (widen `since` to cover the gap) to catch up on what you missed. The count resets to 0 when you call read_context.',+ '',+ 'Delivery is automatic: when you call connect_to_room on the switch MCP server, a PostToolUse hook pushes the room id to this channel over a localhost port. The channel claims that room on its connection and events are pushed to you as they happen. No separate tool call is needed.',+ '',+ 'If you receive a `gap` event, some room events were dropped and cannot be replayed — call read_context before responding rather than assuming you have the full picture.',+ '',+ 'When you receive a message event:',+ '1. Call read_context with the since parameter set to a timestamp a few minutes before the event timestamp to get recent conversation context without re-reading the full history.',+ '2. Understand what is being asked or discussed.',+ '3. Respond by calling post_message (or send_targeted_message if addressing a specific agent).',+ '',+ 'If a message event has an image_path attribute, the sender attached one or more images. Each path is a local file already downloaded for you (comma-separated if several) — Read it to see the image before responding.',+ 'If it has a file_path attribute, the sender attached one or more non-image files (.md, .csv, .pdf, logs, code — comma-separated if several), already downloaded for you. Read them before responding.',+ 'A failed_attachments attribute lists files the sender attached that could NOT be retrieved. Do not pretend you saw them — say so.',+ '',+ "To view a file that appears in read_context history but did NOT arrive with an image_path/file_path (e.g. an unaddressed file posted earlier), call the download_attachment tool with the attachment's mxc (from the read_context attachments field). It writes the file locally and returns the path — then Read that path.",+ 'To send files into the room, call the send_attachment tool with `path` (one file) or `paths` (several, delivered as ONE message) plus an optional caption/thread_id. Any file type works. They post as native room attachments and bridged platforms (Slack, Mattermost) receive them as real file uploads.',+ '',+ 'When you receive a task_delegate event (only delivered if your integration profile has can_accept=true):',+ '1. Call accept_task with the task_id to move it to ongoing.',+ '2. Call read_context with since to understand the conversation context.',+ '3. Perform the work described in the task. Optionally call update_task(task_id, update) with progress messages as you work — these are persisted.',+ '4. Call finalise_task(task_id, outcome) with a one-string description of what happened (success or failure).',+ '',+ 'When you receive task_accept, task_update, or task_finalise events for tasks you delegated, review the progress/outcome and continue your work accordingly.',+ 'When you receive a task_cancel event, the task is dead — do not finalise it.',+ '',+ 'You must be connected to the room (via connect_to_room) before calling read_context, post_message, send_targeted_message, or any task tool.',+ ].join('\n'),+ }+);++// Addressed images are auto-downloaded and surfaced as image_path on the+// notification. This tool lets the agent fetch ANY attachment on demand — e.g.+// an image seen in read_context history that arrived unaddressed (no+// notification, so no image_path). It writes the bytes to a local file and+// returns the path, which the agent then Reads.+const DOWNLOAD_ATTACHMENT_TOOL = {+ name: 'download_attachment',+ description:+ 'Download a room attachment (by its mxc:// URI, as returned in an ' ++ "attachment's `mxc` field from read_context) to a local file and return " ++ 'the path. Works for any file type. Use this to view a file from history ' ++ 'that did not arrive with an image_path/file_path. Operates on the ' ++ 'currently connected room unless ' ++ 'room_id is given.',+ inputSchema: {+ type: 'object',+ properties: {+ mxc: {+ type: 'string',+ description: "The attachment's mxc:// URI (from a read_context attachment).",+ },+ filename: {+ type: 'string',+ description: 'Optional original filename, used to name the local file.',+ },+ room_id: {+ type: 'string',+ description: 'Optional Switch room id. Defaults to the currently polling room.',+ },+ },+ required: ['mxc'],+ },+};++// The outbound counterpart of download_attachment: the agent names a local+// file (e.g. a screenshot it produced) and the channel uploads the bytes to+// the agent bridge, which posts them into the room as an m.image / m.file+// event — from there the collaboration bridges relay it out to Slack /+// Mattermost like any other room message.+const SEND_ATTACHMENT_TOOL = {+ name: 'send_attachment',+ description:+ 'Send one or more local files of ANY type (image, .md, .csv, .pdf, log, ' ++ 'code) into the connected Switch room as attachments. They enter the room ' ++ 'as native image/file events and bridged platforms (Slack, Mattermost) ' ++ 'receive them as real file uploads. Several files sent in one call arrive ' ++ 'as ONE message carrying all of them. Pass `path` for a single file or ' ++ '`paths` for several. Oversize or unreadable files fail the whole call — ' ++ 'nothing is sent silently. Operates on the currently connected room unless ' ++ 'room_id is given.',+ inputSchema: {+ type: 'object',+ properties: {+ path: {+ type: 'string',+ description: 'Absolute path of the local file to send.',+ },+ paths: {+ type: 'array',+ items: { type: 'string' },+ description:+ 'Absolute paths of several local files to send as one message. ' ++ 'Use instead of `path` for a multi-attachment message.',+ },+ caption: {+ type: 'string',+ description: 'Optional text to accompany the attachment.',+ },+ thread_id: {+ type: 'string',+ description:+ 'Optional message id to reply into, making this a threaded reply ' ++ '(normalised to the thread root).',+ },+ room_id: {+ type: 'string',+ description: 'Optional Switch room id. Defaults to the currently polling room.',+ },+ },+ },+};++// -- Switch operations, served locally --------------------------------------+//+// The agent's whole tool surface is served from this process. Each tool is one+// of Switch's operations, fetched from the server at startup so the two cannot+// drift, and each call becomes POST /ops/{name} on THIS process's connection.+//+// That last part is the point: because the stream and the tool surface live in+// the same process, a tool call is correlated to a connection structurally —+// the connection id never has to travel through the agent or its config, and+// cannot be forgotten, leaked, or attached to the wrong session.++type SwitchOperation = {+ name: string;+ description: string;+ input_schema: Record<string, unknown>;+};++let operations: SwitchOperation[] = [];++async function loadOperations(): Promise<void> {+ const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/ops`, {+ headers: { Authorization: `Bearer ${API_TOKEN}` },+ });+ if (!resp.ok) {+ // Without the operation list this process cannot serve the agent at all.+ // Fail loudly at startup rather than presenting an empty tool surface that+ // looks like "Switch has nothing to offer".+ throw new Error(`cannot load Switch operations: HTTP ${resp.status}: ${await resp.text()}`);+ }+ const data = (await resp.json()) as {+ operations: Record<string, { description: string; input_schema: Record<string, unknown> }>;+ };+ operations = Object.entries(data.operations).map(([name, op]) => ({+ name,+ description: op.description,+ input_schema: op.input_schema,+ }));+ process.stderr.write(`switch: serving ${operations.length} operations locally\n`);+}++async function callOperation(+ name: string,+ args: Record<string, unknown>+): Promise<{+ isError?: boolean;+ content: { type: 'text'; text: string }[];+ structuredContent?: Record<string, unknown>;+}> {+ try {+ const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/ops/${name}`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${API_TOKEN}`,+ 'Content-Type': 'application/json',+ // Correlation, supplied by the process that owns the connection.+ 'X-Switch-Connection-Id': CONNECTION_ID,+ },+ body: JSON.stringify(args),+ });+ const text = await resp.text();+ if (!resp.ok) {+ return { isError: true, content: [{ type: 'text', text: `${resp.status}: ${text}` }] };+ }+ const data = JSON.parse(text) as { result?: unknown };+ const result = data.result ?? null;+ return {+ content: [+ {+ type: 'text',+ text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),+ },+ ],+ // Object results are also returned as structured content. The remote MCP+ // server produced this for free (FastMCP derives it from the return+ // type), and hosts read the tool's *fields* from it — switchdash's+ // connect_to_room hook takes room_id and agent_id straight off the tool+ // response. Text alone leaves them with a blob they cannot address, so+ // the session silently never gets bound to its room.+ ...(result !== null && typeof result === 'object' && !Array.isArray(result)+ ? { structuredContent: result as Record<string, unknown> }+ : {}),+ };+ } catch (err) {+ return { isError: true, content: [{ type: 'text', text: `${name} failed: ${err}` }] };+ }+}++mcp.setRequestHandler(ListToolsRequestSchema, async () => ({+ tools: [+ ...operations.map((op) => ({+ name: op.name,+ description: op.description,+ inputSchema: op.input_schema,+ })),+ DOWNLOAD_ATTACHMENT_TOOL,+ SEND_ATTACHMENT_TOOL,+ ],+}));++mcp.setRequestHandler(CallToolRequestSchema, async (req) => {+ const name = req.params.name;+ if (name === 'download_attachment') {+ return handleDownloadAttachment(req.params.arguments ?? {});+ }+ if (name === 'send_attachment') {+ return handleSendAttachment(req.params.arguments ?? {});+ }+ if (operations.some((op) => op.name === name)) {+ const result = await callOperation(name, req.params.arguments ?? {});+ // connect_to_room binds the room to this connection; keep the local view+ // in step so attachments and missed-counts target the right room.+ if (name === 'connect_to_room' && !result.isError) {+ const roomId = (req.params.arguments ?? {}).room_id;+ if (typeof roomId === 'string') setConnectedRoom(roomId);+ }+ return result;+ }+ throw new Error(`Unknown tool: ${name}`);+});++async function handleDownloadAttachment(rawArgs: Record<string, unknown>) {+ const args = rawArgs as {+ mxc?: string;+ filename?: string;+ room_id?: string;+ };+ const mxc = typeof args.mxc === 'string' ? args.mxc : '';+ if (!mxc) {+ return { isError: true, content: [{ type: 'text', text: 'mxc is required' }] };+ }+ const roomId = args.room_id ?? pollingRoomId;+ if (!roomId) {+ return {+ isError: true,+ content: [+ {+ type: 'text',+ text: 'Not connected to a room — call connect_to_room first or pass room_id.',+ },+ ],+ };+ }+ const mediaId = mxc.split('/').pop() || 'attachment';+ const destName = `${sanitiseName(mediaId)}-${sanitiseName(args.filename ?? '')}`;+ try {+ const path = await fetchMediaToFile(roomId, mxc, destName);+ return { content: [{ type: 'text', text: path }] };+ } catch (err) {+ return {+ isError: true,+ content: [{ type: 'text', text: `Download failed: ${err}` }],+ };+ }+}++// Extension → mimetype map. Anything unlisted goes up as+// application/octet-stream, which still relays fine — the mapping exists to+// preserve type fidelity so platforms render/preview the file properly.+const MIME_BY_EXT: Record<string, string> = {+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.gif': 'image/gif',+ '.webp': 'image/webp',+ '.svg': 'image/svg+xml',+ '.bmp': 'image/bmp',+ '.pdf': 'application/pdf',+ '.txt': 'text/plain',+ '.md': 'text/markdown',+ '.csv': 'text/csv',+ '.tsv': 'text/tab-separated-values',+ '.log': 'text/plain',+ '.json': 'application/json',+ '.yaml': 'application/yaml',+ '.yml': 'application/yaml',+ '.toml': 'application/toml',+ '.xml': 'application/xml',+ '.html': 'text/html',+ '.css': 'text/css',+ '.js': 'text/javascript',+ '.mjs': 'text/javascript',+ '.ts': 'text/x-typescript',+ '.tsx': 'text/x-typescript',+ '.jsx': 'text/javascript',+ '.py': 'text/x-python',+ '.rs': 'text/x-rust',+ '.go': 'text/x-go',+ '.java': 'text/x-java',+ '.c': 'text/x-c',+ '.h': 'text/x-c',+ '.cpp': 'text/x-c++',+ '.sh': 'application/x-sh',+ '.sql': 'application/sql',+ '.zip': 'application/zip',+ '.gz': 'application/gzip',+ '.tar': 'application/x-tar',+};++async function handleSendAttachment(rawArgs: Record<string, unknown>) {+ const args = rawArgs as {+ path?: string;+ paths?: unknown;+ caption?: string;+ thread_id?: string;+ room_id?: string;+ };+ const filePaths: string[] = [];+ if (typeof args.path === 'string' && args.path) filePaths.push(args.path);+ if (Array.isArray(args.paths)) {+ for (const p of args.paths) if (typeof p === 'string' && p) filePaths.push(p);+ }+ if (filePaths.length === 0) {+ return {+ isError: true,+ content: [{ type: 'text', text: 'path (or paths) is required' }],+ };+ }+ const roomId = args.room_id ?? pollingRoomId;+ if (!roomId) {+ return {+ isError: true,+ content: [+ {+ type: 'text',+ text: 'Not connected to a room — call connect_to_room first or pass room_id.',+ },+ ],+ };+ }++ // Read every file up front: one unreadable path fails the whole call rather+ // than posting a partial message.+ const files: { name: string; bytes: Buffer; mimetype: string }[] = [];+ for (const filePath of filePaths) {+ let bytes: Buffer;+ try {+ bytes = fs.readFileSync(filePath);+ } catch (err) {+ return {+ isError: true,+ content: [{ type: 'text', text: `Cannot read ${filePath}: ${err}` }],+ };+ }+ files.push({+ name: path.basename(filePath),+ bytes,+ mimetype: MIME_BY_EXT[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream',+ });+ }++ const form = new FormData();+ for (const file of files) {+ form.append('files', new Blob([file.bytes], { type: file.mimetype }), file.name);+ }+ if (typeof args.caption === 'string' && args.caption) form.append('caption', args.caption);+ if (typeof args.thread_id === 'string' && args.thread_id)+ form.append('thread_id', args.thread_id);++ try {+ const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/rooms/${roomId}/media`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${API_TOKEN}` },+ body: form,+ });+ if (!resp.ok) {+ throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);+ }+ const data = (await resp.json()) as { event_id?: string };+ const names = files.map((f) => f.name).join(', ');+ return {+ content: [+ {+ type: 'text',+ text:+ `Sent ${files.length === 1 ? names : `${files.length} files (${names})`} ` ++ `to the room (event_id: ${data.event_id ?? 'unknown'}).`,+ },+ ],+ };+ } catch (err) {+ return {+ isError: true,+ content: [{ type: 'text', text: `Send failed: ${err}` }],+ };+ }+}++// -- Event stream (SSE) ------------------------------------------------------+//+// One long-lived HTTP request the server writes events into as they happen.+// Catch-up from our cursor comes first, then live delivery. On any drop we+// reopen with the same connection id and Last-Event-ID, and the server resumes+// from where we stopped — the gap fills itself rather than being lost.++function stopStream() {+ if (streamAbort) {+ streamAbort.abort();+ streamAbort = null;+ }+ pollingRoomId = null;+}++function startStream() {+ // A borrowed connection belongs to the supervisor: it holds the stream and+ // the heartbeat. Opening a second stream on the same id would take the+ // connection over — the server treats a reopen as the client returning — and+ // the supervisor would stop receiving anything.+ if (!OWNS_CONNECTION) return;+ if (streamAbort) return;+ const abort = new AbortController();+ streamAbort = abort;++ void (async () => {+ let backoff = 1000;++ while (!abort.signal.aborted) {+ try {+ const params = new URLSearchParams({+ connection_id: CONNECTION_ID,+ scope: 'single',+ filter: 'all',+ start_from: cursor > 0 ? String(cursor) : 'head',+ });+ // Declare the room when opening, not after: catch-up runs immediately,+ // and a room subscribed afterwards would arrive too late for the+ // buffered events this reconnect exists to recover.+ //+ // Not when switchdash is managing this session, though. It runs its own+ // connection for the room and claims the slot; a second claim from here+ // would be refused, and whichever of us lost would sit in a reconnect+ // loop delivering nothing. Suppressing the *notification* was never+ // enough — the claim has to be suppressed too.+ if (pollingRoomId && !SUPPRESS_NOTIFICATIONS) {+ params.set('rooms', pollingRoomId);+ }+ const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/events?${params}`, {+ headers: {+ Authorization: `Bearer ${API_TOKEN}`,+ Accept: 'text/event-stream',+ ...(cursor > 0 ? { 'Last-Event-ID': String(cursor) } : {}),+ },+ signal: abort.signal,+ });++ if (!resp.ok || !resp.body) {+ throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);+ }++ backoff = 1000;+ process.stderr.write(+ `switch: stream open (connection ${CONNECTION_ID}, cursor ${cursor})\n`+ );++ for await (const frame of readSse(resp.body, abort.signal)) {+ if (frame.id) cursor = Math.max(cursor, Number(frame.id) || 0);+ await handleFrame(frame);+ }+ } catch (err) {+ if (abort.signal.aborted) return;+ process.stderr.write(`switch: stream error: ${err}, reconnecting in ${backoff / 1000}s\n`);+ await new Promise((r) => setTimeout(r, backoff));+ backoff = Math.min(backoff * 2, 30000);+ }+ }+ })();+}++async function handleFrame(frame: SseFrame): Promise<void> {+ switch (frame.event) {+ case 'connection_state':+ process.stderr.write(+ `switch: connection established (rooms=${JSON.stringify(frame.data.rooms)})\n`+ );+ return;++ case 'subscription_changed':+ process.stderr.write(`switch: subscription now ${JSON.stringify(frame.data.rooms)}\n`);+ return;++ case 'gap':+ // Never silent: tell the agent it has a hole in its history rather than+ // letting it carry on as though the stream were complete.+ process.stderr.write(+ `switch: GAP — missed events before sequence ${frame.data.from_sequence}\n`+ );+ await emitNotification(+ 'Some room events were missed and cannot be replayed. Call read_context ' ++ 'to catch up before responding.',+ {+ room_id: pollingRoomId ?? '',+ event_type: 'gap',+ from_sequence: String(frame.data.from_sequence ?? ''),+ }+ );+ return;++ case 'evicted':+ process.stderr.write(`switch: evicted — ${frame.data.reason}\n`);+ return;++ default:+ if (SUPPRESS_NOTIFICATIONS) {+ // Consumed, not surfaced: the cursor still advances, so resuming after+ // a drop stays correct even though switchdash is doing the telling.+ return;+ }+ await handleEvent(frame.data as unknown as AgentEvent);+ }+}++// -- Room reconciliation ------------------------------------------------------++// There is no subscribeRoom any more: `connect_to_room` claims the room on the+// calling connection server-side, so a client-side follow-up would be a second+// way to say the same thing — and, on a managed session, a way to take a slot+// that belongs to the supervisor. Releasing is still explicit, below.++async function unsubscribeRoom(roomId: string): Promise<void> {+ try {+ await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/connection/unsubscribe`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${API_TOKEN}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ connection_id: CONNECTION_ID, room_id: roomId }),+ });+ } catch (err) {+ process.stderr.write(`switch: unsubscribe failed for ${roomId}: ${err}\n`);+ }+}++function setConnectedRoom(target: string | null) {+ if (target === pollingRoomId) return;++ const previous = pollingRoomId;++ if (previous) {+ process.stderr.write(`switch: leaving room ${previous}\n`);+ // Only release a slot we hold. On a borrowed connection the claim belongs+ // to the supervisor's stream, and connect_to_room repoints it for us —+ // releasing here would blank the supervisor's room between the two calls.+ if (OWNS_CONNECTION) void unsubscribeRoom(previous);+ pollingRoomId = null;+ }++ if (target) {+ pollingRoomId = target;+ missedSinceRead = 0;++ process.stderr.write(+ `switch: joining room ${target}` ++ (OWNS_CONNECTION ? '' : ' (connection shared with the supervisor)') ++ (SUPPRESS_NOTIFICATIONS ? ' (notifications suppressed: switchdash-managed)' : '') ++ '\n'+ );++ if (!OWNS_CONNECTION) {+ // The supervisor holds the stream on this connection, and the server has+ // already claimed the room on it — connect_to_room does that now. So the+ // supervisor has been told, and there is nothing for us to open, claim or+ // reopen. This branch is the whole point of sharing the connection.+ return;+ }++ startStream();+ startHeartbeat();+ if (SUPPRESS_NOTIFICATIONS) {+ // Managed session on an older supervisor that did not hand us an id: it+ // runs its own connection for this room and owns the slot, so ours must+ // not compete for a room it is not serving. Kept for switchdash releases+ // in the wild; the shared-connection path above replaces it.+ return;+ }+ // The room is already claimed server-side by connect_to_room. What is left+ // is catch-up: the stream may have opened before the room was known, in+ // which case it skipped that room's buffered events. Reopening declares the+ // room up front and resumes from our cursor — which is still behind those+ // events, because we never received them.+ if (streamAbort && !streamHasRoom) {+ streamHasRoom = true;+ restartStream();+ }+ }+}++// -- Connection heartbeat ----------------------------------------------------+//+// One tick, every 2s, carrying the cursor. It proves this client is alive AND+// consuming — strictly stronger than the server observing an open socket — and+// tells the server how far we have read. The server drops the connection when+// these stop, releasing its room slot; it rejects them when no stream is+// attached, so a session that is somehow acting without receiving is told+// rather than left believing it is connected.++const HEARTBEAT_INTERVAL_MS = 2000;++function stopHeartbeat() {+ if (heartbeatAbort) {+ heartbeatAbort.abort();+ heartbeatAbort = null;+ }+}++function startHeartbeat() {+ // The supervisor beats for a borrowed connection. Two heartbeats would not+ // conflict, but they would disagree about the cursor: ours only advances on+ // events we receive, and on a borrowed connection we receive none — so ours+ // would keep reporting 0 and undo the supervisor's progress.+ if (!OWNS_CONNECTION) return;+ if (heartbeatAbort) return;+ const abort = new AbortController();+ heartbeatAbort = abort;++ void (async () => {+ while (!abort.signal.aborted) {+ try {+ const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/connection/beat`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${API_TOKEN}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ connection_id: CONNECTION_ID, cursor }),+ signal: abort.signal,+ });+ if (resp.status === 409 || resp.status === 404) {+ // Either the stream is gone or the connection expired. Both mean we+ // are not receiving; reopening resumes from the cursor.+ process.stderr.write(+ `switch: heartbeat rejected (HTTP ${resp.status}) — reopening stream\n`+ );+ stopStreamKeepingRoom();+ startStream();+ // No re-claim here. When we own the connection and serve the room,+ // reopening declares it on the URL; when the supervisor serves it,+ // the slot is the supervisor's and claiming would take it away.+ }+ } catch (err) {+ if (abort.signal.aborted) return;+ process.stderr.write(`switch: heartbeat error: ${err}\n`);+ }+ await new Promise((r) => setTimeout(r, HEARTBEAT_INTERVAL_MS));+ }+ })();+}++function restartStream() {+ stopStreamKeepingRoom();+ startStream();+}++function stopStreamKeepingRoom() {+ const room = pollingRoomId;+ stopStream();+ pollingRoomId = room;+}++// -- Role lease renewal ------------------------------------------------------+//+// While this session holds a room-role, renew the lease on a fast cadence so an+// (exclusive) seat stays held. The server frees a lease shortly after renewals+// stop (TTL), so a crashed/closed session auto-releases. release_role and a+// clean disconnect stop the loop immediately.++const LEASE_RENEW_INTERVAL_MS = 2000;++function stopLeaseRenew() {+ if (leaseAbort) {+ leaseAbort.abort();+ leaseAbort = null;+ }+}++function startLeaseRenew() {+ if (leaseAbort) return; // already renewing+ const abort = new AbortController();+ leaseAbort = abort;++ void (async () => {+ while (!abort.signal.aborted) {+ try {+ const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/leases/renew`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${API_TOKEN}` },+ signal: abort.signal,+ });+ if (resp.ok) {+ const data = (await resp.json()) as { held?: boolean };+ // The server says we hold no lease — nothing to renew, stop the loop.+ if (data.held === false) {+ stopLeaseRenew();+ return;+ }+ }+ } catch (err) {+ if (abort.signal.aborted) return;+ process.stderr.write(`switch: lease renew error: ${err}\n`);+ }+ await new Promise((r) => setTimeout(r, LEASE_RENEW_INTERVAL_MS));+ }+ })();+}++// -- Hook listener: localhost-only port advertised via PORT_FILE ------------++function publishPort(port: number) {+ fs.mkdirSync(SESSION_DIR, { recursive: true });+ fs.writeFileSync(PORT_FILE, String(port));+}++function unpublishPort() {+ try {+ fs.rmSync(SESSION_DIR, { recursive: true, force: true });+ } catch (err) {+ process.stderr.write(`switch: failed to clean up ${SESSION_DIR}: ${err}\n`);+ }+}++/**+ * The hook routes, as a Web-standard handler.+ *+ * Kept in Request/Response terms rather than node's (req, res): it is the+ * clearer shape for routing, and it is what this was written against. The+ * node:http bridge below is the only thing that had to change when the runtime+ * stopped requiring Bun.+ */+async function handleHookRequest(req: Request): Promise<Response> {+ const url = new URL(req.url);+ if (req.method !== 'POST') {+ return new Response('method not allowed', { status: 405 });+ }++ if (url.pathname === '/connect') {+ let body: { room_id?: unknown };+ try {+ body = (await req.json()) as { room_id?: unknown };+ } catch {+ return new Response('bad json', { status: 400 });+ }+ const roomId = typeof body.room_id === 'string' ? body.room_id : null;+ if (!roomId) {+ return new Response('missing room_id', { status: 400 });+ }+ setConnectedRoom(roomId);+ return new Response('ok');+ }++ if (url.pathname === '/disconnect') {+ setConnectedRoom(null);+ stopLeaseRenew();+ return new Response('ok');+ }++ if (url.pathname === '/assume-role') {+ startLeaseRenew();+ return new Response('ok');+ }++ if (url.pathname === '/release-role') {+ stopLeaseRenew();+ return new Response('ok');+ }++ if (url.pathname === '/read-context') {+ // The agent called read_context, so it has caught up on room history —+ // clear the missed-message backlog we've been tallying.+ missedSinceRead = 0;+ return new Response('ok');+ }++ if (url.pathname === '/turn-end') {+ // The Claude Code turn finished. Clear the "thinking" indicator in case+ // the agent ended without posting a reply — Slack's faked indicator is+ // a real message that lingers until explicitly deleted (the reply path+ // clears it server-side, but a no-reply turn would otherwise leave it).+ if (pollingRoomId) void setTyping(pollingRoomId, false);+ return new Response('ok');+ }++ return new Response('not found', { status: 404 });+}++function startHookListener() {+ const server = http.createServer((nodeReq, nodeRes) => {+ void (async () => {+ try {+ const chunks: Buffer[] = [];+ for await (const chunk of nodeReq) chunks.push(chunk as Buffer);+ const req = new Request(`http://127.0.0.1${nodeReq.url ?? '/'}`, {+ method: nodeReq.method ?? 'GET',+ // A GET/HEAD with a body is a TypeError, and every route here is a+ // POST, but the guard keeps a stray probe from crashing the listener.+ body: chunks.length > 0 ? Buffer.concat(chunks) : undefined,+ });+ const res = await handleHookRequest(req);+ nodeRes.writeHead(res.status);+ nodeRes.end(await res.text());+ } catch (err) {+ // The hooks are how the session tells us it changed room. Failing one+ // silently would leave us serving the wrong room with no sign why.+ process.stderr.write(`switch: hook request failed: ${err}\n`);+ if (!nodeRes.headersSent) nodeRes.writeHead(500);+ nodeRes.end('hook failed');+ }+ })();+ });++ server.listen(0, '127.0.0.1', () => {+ const address = server.address();+ const port = typeof address === 'object' && address !== null ? address.port : 0;+ publishPort(port);+ process.stderr.write(+ `switch: hook listener on http://127.0.0.1:${port} (published to ${PORT_FILE})\n`+ );+ });+}++// -- Event handling ----------------------------------------------------------++async function handleEvent(event: AgentEvent) {+ const { type, room_id, payload } = event;++ if (type === 'message') {+ const msg = payload as MessagePayload;+ if (!msg.addressed) {+ // Unaddressed chatter: filtered out, no notification. Tally it so the+ // next notification can tell the agent how far behind it has fallen.+ missedSinceRead++;+ return;+ }++ // Surface receipt feedback: tell the room's bridged channel that this+ // agent is "typing" so the human knows the message landed and we're+ // working on a reply. Fire-and-forget — typing feedback must never block+ // or fail event delivery. The indicator is cleared when the agent posts+ // its reply, and on turn end via the Stop hook (`/turn-end`) for the case+ // where the agent finishes without replying.+ void setTyping(room_id, true);++ // Materialise every attachment to a local file so Claude can Read it,+ // whatever the type. Images are surfaced as image_path (Claude renders+ // them); everything else as file_path. A download that fails is reported+ // as failed_attachment rather than being dropped quietly.+ const imagePaths: string[] = [];+ const filePaths: string[] = [];+ const failedAttachments: string[] = [];+ const attachments = msg.attachments ?? [];+ for (let i = 0; i < attachments.length; i++) {+ const att = attachments[i];+ const localPath = await downloadAttachment(room_id, att, msg.message_id, i);+ if (!localPath) {+ failedAttachments.push(att.filename);+ continue;+ }+ if (att.mimetype.startsWith('image/')) imagePaths.push(localPath);+ else filePaths.push(localPath);+ }++ const ts = new Date(msg.timestamp).toISOString();+ await emitNotification(`[${msg.sender_name}]: ${msg.body}`, {+ room_id,+ event_type: type,+ sender: msg.sender,+ sender_name: msg.sender_name,+ message_id: msg.message_id,+ timestamp: ts,+ // Lets an addressed agent reply back into the same thread.+ ...(msg.thread_id ? { thread_id: msg.thread_id } : {}),+ ...(imagePaths.length ? { image_path: imagePaths.join(',') } : {}),+ ...(filePaths.length ? { file_path: filePaths.join(',') } : {}),+ ...(failedAttachments.length ? { failed_attachments: failedAttachments.join(',') } : {}),+ });+ return;+ }++ if (type === 'command') {+ const cmd = payload as CommandPayload;+ await emitNotification(`Command: ${cmd.command}${cmd.target ? ` target=${cmd.target}` : ''}`, {+ room_id,+ event_type: type,+ user_id: cmd.user_id,+ user_name: cmd.user_name,+ });+ return;+ }++ if (type === 'room_join') {+ const join = payload as RoomJoinPayload;+ // This agent is opted out of join events in this room — deliver nothing.+ if (!join.listening) {+ return;+ }+ await emitNotification(`${join.member_name} joined the room`, {+ room_id,+ event_type: type,+ member: join.member,+ member_name: join.member_name,+ timestamp: new Date(join.timestamp).toISOString(),+ });+ return;+ }++ if (type === 'task_delegate') {+ const task = payload as TaskDelegatePayload;+ await emitNotification(`Task delegated: ${task.summary} — ${task.description}`, {+ room_id,+ event_type: type,+ task_id: task.task_id,+ requester_agent_id: task.requester_agent_id,+ performer_agent_id: task.performer_agent_id,+ summary: task.summary,+ });+ return;+ }++ if (type === 'task_accept') {+ const task = payload as TaskAcceptPayload;+ await emitNotification(`Task accepted by ${task.performer_agent_id}`, {+ room_id,+ event_type: type,+ task_id: task.task_id,+ requester_agent_id: task.requester_agent_id,+ performer_agent_id: task.performer_agent_id,+ });+ return;+ }++ if (type === 'task_update') {+ const task = payload as TaskUpdatePayload;+ await emitNotification(`Task update: ${task.update}`, {+ room_id,+ event_type: type,+ task_id: task.task_id,+ requester_agent_id: task.requester_agent_id,+ performer_agent_id: task.performer_agent_id,+ });+ return;+ }++ if (type === 'task_finalise') {+ const task = payload as TaskFinalisePayload;+ await emitNotification(`Task finalised: ${task.outcome ?? '(no outcome provided)'}`, {+ room_id,+ event_type: type,+ task_id: task.task_id,+ requester_agent_id: task.requester_agent_id,+ performer_agent_id: task.performer_agent_id,+ });+ return;+ }++ if (type === 'task_cancel') {+ const task = payload as TaskCancelPayload;+ await emitNotification(`Task cancelled${task.reason ? `: ${task.reason}` : ''}`, {+ room_id,+ event_type: type,+ task_id: task.task_id,+ requester_agent_id: task.requester_agent_id,+ performer_agent_id: task.performer_agent_id,+ });+ return;+ }++ process.stderr.write(`switch: unknown event type: ${type}\n`);+}++const MEDIA_DIR = path.join(SESSION_DIR, 'media');++// Download an inbound attachment from the agent bridge to a local file so+// Claude can Read it. The bridge proxies the bytes out of the Matrix media+// repo (the channel holds only the bridge API token, not Matrix creds).+// Returns the local path, or null on failure (logged, never throws).+function sanitiseName(name: string): string {+ return name.replace(/[^a-zA-Z0-9._-]/g, '_') || 'attachment';+}++// Fetch an attachment's bytes from the agent bridge (which proxies the Matrix+// media repo) and write them to a local file under MEDIA_DIR. Throws on error.+async function fetchMediaToFile(roomId: string, mxc: string, destName: string): Promise<string> {+ const url =+ `${API_ENDPOINT}/agents/${AGENT_ID}/rooms/${roomId}/media` + `?mxc=${encodeURIComponent(mxc)}`;+ const resp = await fetch(url, {+ headers: { Authorization: `Bearer ${API_TOKEN}` },+ });+ if (!resp.ok) {+ throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);+ }+ const bytes = Buffer.from(await resp.arrayBuffer());+ fs.mkdirSync(MEDIA_DIR, { recursive: true });+ const dest = path.join(MEDIA_DIR, destName);+ fs.writeFileSync(dest, bytes);+ return dest;+}++// Notification path: best-effort download (failures are logged, never thrown,+// so they can't break event delivery). Returns the local path or null.+async function downloadAttachment(+ roomId: string,+ att: AttachmentRef,+ messageId: string,+ index: number+): Promise<string | null> {+ try {+ const destName = `${messageId.replace(/[^a-zA-Z0-9]/g, '_')}-${index}-${sanitiseName(att.filename)}`;+ return await fetchMediaToFile(roomId, att.mxc, destName);+ } catch (err) {+ process.stderr.write(`switch: attachment download error: ${err}\n`);+ return null;+ }+}++async function setTyping(roomId: string, isTyping: boolean) {+ try {+ const url = `${API_ENDPOINT}/agents/${AGENT_ID}/typing`;+ const resp = await fetch(url, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${API_TOKEN}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({ room_id: roomId, is_typing: isTyping }),+ });+ if (!resp.ok) {+ process.stderr.write(+ `switch: set typing failed: HTTP ${resp.status}: ${await resp.text()}\n`+ );+ }+ } catch (err) {+ process.stderr.write(`switch: set typing error: ${err}\n`);+ }+}++async function emitNotification(content: string, meta: Record<string, string>) {+ // Surface the unaddressed-message backlog on every notification. meta values+ // are strings; missed_count is always present (0 when caught up). When it's+ // non-zero, annotate the one-line body so the agent sees it without having+ // to inspect meta, and knows to widen read_context's `since` to catch up.+ const missed = missedSinceRead;+ const enriched = { ...meta, missed_count: String(missed) };+ const body =+ missed > 0+ ? `${content}\n⚠️ ${missed} unread room message${missed === 1 ? '' : 's'} since your last read_context — call read_context (widen \`since\`) to catch up on what you missed.`+ : content;+ await mcp+ .notification({+ method: 'notifications/claude/channel',+ params: { content: body, meta: enriched },+ })+ .catch((err) => {+ process.stderr.write(`switch: failed to deliver event to Claude: ${err}\n`);+ });+}++// -- Connect and start -------------------------------------------------------++const transport = new StdioServerTransport();++transport.onclose = () => {+ stopStream();+ stopHeartbeat();+ stopLeaseRenew();+ unpublishPort();+ process.exit(0);+};++// Wipe any stale port file left by a crashed previous process for the same ppid.+// Safe: the previous process for this ppid is gone (we are it now); a live+// sibling would be a different ppid.+unpublishPort();++// Load the operation list before serving: a tool surface that is empty+// because a fetch failed is worse than a process that refuses to start.+await loadOperations();++await mcp.connect(transport);++startHookListener();++// The connection exists for the life of this process, not just while a room is+// attached: it is what correlates every tool call, and what the server uses to+// know this agent is reachable at all.+startStream();+startHeartbeat();++process.stderr.write(`switch: running (agent_id=${AGENT_ID})\n`);diff --git a/dash/packages/switch-agent-runtime/src/event-stream.ts b/dash/packages/switch-agent-runtime/src/event-stream.tsnew file mode 100644index 000000000..55c65fe9d--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/event-stream.ts@@ -0,0 +1,345 @@+import { readSse, type SseFrame } from './sse';+import type { AgentBridgeEvent, SwitchCredentials } from './types';++/**+ * The agent bridge's push transport (CHOO-1857), client side.+ *+ * Replaces the long-poll: one SSE stream carries events, one heartbeat proves+ * we are alive, and both are tied to a connection id we choose. The connection+ * outlives its socket — losing the stream stops delivery but does not end the+ * connection, so reopening within the heartbeat TTL keeps the room slot and the+ * role lease and resumes from the cursor.+ *+ * Two things this buys that the poll could not:+ *+ * - **Resume.** Every event carries a sequence number; we reopen with+ * `Last-Event-ID` and get exactly what we missed. The poll had no cursor at+ * all — the server drained the queue on read, so anything delivered while we+ * were away was simply gone.+ * - **One heartbeat instead of three.** `/connection/renew`, `/leases/renew`+ * and `/watch/heartbeat` collapse into `/connection/beat`.+ *+ * A gap is never silent. If the server cannot serve our cursor it says so, and+ * `onGap` fires so the caller can tell the agent to re-read context rather than+ * carry on believing it saw everything.+ */++/** Cadence of the connection heartbeat. Must stay well inside the server's+ * 6s TTL — the server declares the connection dead without it. */+export const BEAT_INTERVAL_MS = 2000;+const BEAT_REQUEST_TIMEOUT_MS = 4000;+const INITIAL_BACKOFF_MS = 1000;+const MAX_BACKOFF_MS = 30_000;++export type StreamScope = 'single' | 'all';+export type DeliveryFilter = 'all' | 'addressed';++export interface EventStreamLogger {+ debug(message: string, meta?: Record<string, unknown>): void;+ warn(message: string, meta?: Record<string, unknown>): void;+ error(message: string, meta?: Record<string, unknown>): void;+}++export interface SwitchEventStreamDeps {+ creds: SwitchCredentials;+ /** Chosen by us and reused across reconnects — that is what makes the+ * connection survive a dropped socket. */+ connectionId: string;+ scope: StreamScope;+ filter: DeliveryFilter;+ /**+ * Declares that this connection will start a session for a room on demand.+ *+ * The server keys the "Starting a session…" reply and the DORMANT status off+ * this rather than off the agent's configured `connection_model`, so a+ * watcher must say so — otherwise an addressed message in an unattended room+ * is answered with "my connector isn't reporting in" while this connection is+ * sitting right here, about to spawn.+ */+ spawnCapable?: boolean;+ /**+ * Where to begin, when it must not be "whatever happens next".+ *+ * A session spawned to answer a message needs the buffer position *before*+ * that message: the watcher already consumed it to decide to spawn, so+ * opening at head starts the session after the very thing it was started+ * for. Omitted for every other case, where head is right.+ */+ startCursor?: number;+ /** Rooms declared when the stream opens. Declared at open rather than+ * subscribed afterwards: catch-up runs immediately, and a room claimed a+ * moment later arrives too late for the buffered events a reconnect exists+ * to recover — they would be skipped as "not covered" AND the cursor+ * advanced past them. */+ rooms: string[];+ onEvent(event: AgentBridgeEvent): Promise<void> | void;+ /**+ * The rooms the server says this connection covers — on connect, and again+ * whenever they change. The server is the authority here: a room claimed by+ * the session's own `connect_to_room` arrives this way, which is what lets a+ * supervisor learn its session's room from Switch rather than by watching+ * the agent's tool calls.+ */+ onRooms?: (rooms: string[]) => void;+ /** Fired when the server reports missed events it cannot replay. */+ onGap(info: { fromSequence: number; reason: string }): void;+ /** Fired when another stream took this connection over, or it was closed. */+ onEvicted(reason: string): void;+ log: EventStreamLogger;+ /** Aborts the stream and the heartbeat together. */+ signal: AbortSignal;+}++export class SwitchEventStream {+ private readonly deps: SwitchEventStreamDeps;+ /** Highest sequence number received. Sent on every beat and used as+ * `Last-Event-ID` when reopening. Seeded from `startCursor` when the caller+ * needs to begin behind head rather than at it. */+ private cursor: number;+ /** Aborts only the current socket, so a reconnect can replace it without+ * tearing down the connection. */+ private socketAbort: AbortController | null = null;+ private rooms: string[];++ constructor(deps: SwitchEventStreamDeps) {+ this.deps = deps;+ this.rooms = [...deps.rooms];+ this.cursor = deps.startCursor ?? 0;+ }++ get position(): number {+ return this.cursor;+ }++ start(): void {+ void this.streamLoop();+ void this.beatLoop();+ }++ /** Repoint the stream at a different room without dropping the connection.+ * The room is claimed server-side first, then the socket is reopened so the+ * new room's buffered events are part of catch-up. */+ async repoint(roomId: string): Promise<void> {+ this.rooms = [roomId];+ await this.subscribe(roomId);+ this.reopen();+ }++ private reopen(): void {+ this.socketAbort?.abort();+ }++ /**+ * Pass the server's room list on, and keep our own copy in step.+ *+ * The local copy matters on reconnect: it is what gets declared on the open+ * URL, so a room the server claimed while we were connected is still ours+ * after a drop. Without it a reconnect would re-open with the room we were+ * first told about — or none — and quietly stop receiving.+ */+ private reportRooms(raw: unknown): void {+ if (!Array.isArray(raw)) return;+ const rooms = raw.filter((r): r is string => typeof r === 'string');+ this.rooms = rooms;+ this.deps.onRooms?.(rooms);+ }++ private async subscribe(roomId: string): Promise<void> {+ const resp = await this.post('connection/subscribe', {+ connection_id: this.deps.connectionId,+ room_id: roomId,+ });+ if (!resp.ok) {+ // 409 means another live connection of this agent already holds the room+ // — usually a stale session. Loud: quietly carrying on would leave us+ // attached to a stream that will never deliver that room's events.+ throw new Error(`subscribe to ${roomId} failed: HTTP ${resp.status}`);+ }+ }++ private post(path: string, body: unknown, timeoutMs = BEAT_REQUEST_TIMEOUT_MS) {+ const { creds } = this.deps;+ return fetch(`${creds.apiEndpoint}/agents/${creds.agentId}/${path}`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${creds.token}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(body),+ signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), this.deps.signal]),+ });+ }++ private async streamLoop(): Promise<void> {+ const { creds, connectionId, scope, filter, log, signal } = this.deps;+ let backoff = INITIAL_BACKOFF_MS;++ while (!signal.aborted) {+ const socketAbort = new AbortController();+ this.socketAbort = socketAbort;+ try {+ const params = new URLSearchParams({+ connection_id: connectionId,+ scope,+ filter,+ start_from: this.cursor > 0 ? String(this.cursor) : 'head',+ });+ if (this.deps.spawnCapable) params.set('spawn_capable', 'true');+ if (this.rooms.length) params.set('rooms', this.rooms.join(','));++ const resp = await fetch(`${creds.apiEndpoint}/agents/${creds.agentId}/events?${params}`, {+ headers: {+ Authorization: `Bearer ${creds.token}`,+ Accept: 'text/event-stream',+ ...(this.cursor > 0 ? { 'Last-Event-ID': String(this.cursor) } : {}),+ },+ signal: AbortSignal.any([socketAbort.signal, signal]),+ });++ if (!resp.ok || !resp.body) {+ throw new Error(`HTTP ${resp.status}: ${await resp.text()}`);+ }++ backoff = INITIAL_BACKOFF_MS;+ log.debug('SwitchEventStream: stream open', {+ event: 'switch_stream_open',+ connectionId,+ cursor: this.cursor,+ rooms: this.rooms,+ });++ for await (const frame of readSse(resp.body, socketAbort.signal)) {+ if (frame.id) this.cursor = Math.max(this.cursor, Number(frame.id) || 0);+ await this.handleFrame(frame);+ }+ } catch (error) {+ if (signal.aborted) return;+ // A deliberate reopen (repoint) aborts the socket; that is not an error.+ if (!socketAbort.signal.aborted) {+ log.warn('SwitchEventStream: stream error', {+ event: 'switch_stream_error',+ error: String(error),+ backoffMs: backoff,+ });+ await new Promise((r) => setTimeout(r, backoff));+ backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);+ }+ }+ }+ }++ private async handleFrame(frame: SseFrame): Promise<void> {+ const { log, onGap, onEvicted, onEvent } = this.deps;+ switch (frame.event) {+ case 'connection_state':+ log.debug('SwitchEventStream: connection established', {+ event: 'switch_stream_connected',+ rooms: frame.data.rooms,+ });+ this.reportRooms(frame.data.rooms);+ return;+ case 'subscription_changed':+ log.debug('SwitchEventStream: subscription changed', {+ event: 'switch_stream_subscription',+ rooms: frame.data.rooms,+ });+ this.reportRooms(frame.data.rooms);+ return;+ case 'gap':+ log.warn('SwitchEventStream: gap — events missed', {+ event: 'switch_stream_gap',+ fromSequence: frame.data.from_sequence,+ reason: frame.data.reason,+ });+ onGap({+ fromSequence: Number(frame.data.from_sequence ?? 0),+ reason: String(frame.data.reason ?? 'events were missed'),+ });+ return;+ case 'evicted':+ log.warn('SwitchEventStream: evicted', {+ event: 'switch_stream_evicted',+ reason: frame.data.reason,+ });+ onEvicted(String(frame.data.reason ?? 'connection closed'));+ return;+ default:+ await onEvent(frame.data as unknown as AgentBridgeEvent);+ }+ }++ /**+ * The single heartbeat. Proves we are alive and reports the cursor.+ *+ * A 404 or 409 means we are not receiving — the connection expired, or it has+ * no stream attached. Both are recovered by reopening, which resumes from the+ * cursor. Failing quietly here is the one thing that must not happen: a client+ * that has stopped receiving while believing it is connected is exactly the+ * bug this transport exists to remove.+ *+ * While beats succeed the cadence is fixed and short — the server declares the+ * connection dead without them. While they fail it backs off, because a beat+ * that has already missed the TTL cannot save the connection: reopening the+ * stream is what re-establishes it, and that loop is doing its own retrying.+ * Hammering a dead endpoint every two seconds forever is what this avoids —+ * an endpoint that is simply gone (a managed server's port after the stack was+ * destroyed) should cost a trickle of requests and a handful of log lines, not+ * a permanent stream of both.+ */+ private async beatLoop(): Promise<void> {+ const { log, signal, connectionId } = this.deps;+ let failures = 0;+ let backoff = BEAT_INTERVAL_MS;++ const fail = (error: unknown): void => {+ failures += 1;+ // Report the first failure, then on a curve: powers of two, so a+ // permanent outage costs a handful of lines rather than one per beat.+ if ((failures & (failures - 1)) === 0) {+ log.warn('SwitchEventStream: heartbeat failed', {+ event: 'switch_beat_failed',+ endpoint: this.deps.creds.apiEndpoint,+ failures,+ error: String(error),+ });+ }+ backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);+ };++ while (!signal.aborted) {+ try {+ const resp = await this.post('connection/beat', {+ connection_id: connectionId,+ cursor: this.cursor,+ });+ if (resp.status === 404 || resp.status === 409) {+ // Not an outage: the server answered. We are simply not attached, so+ // reopen at the normal cadence rather than backing off.+ log.warn('SwitchEventStream: heartbeat rejected — reopening', {+ event: 'switch_beat_rejected',+ status: resp.status,+ connectionId,+ });+ this.reopen();+ failures = 0;+ backoff = BEAT_INTERVAL_MS;+ } else if (!resp.ok) {+ fail(new Error(`HTTP ${resp.status}`));+ } else {+ if (failures > 0) {+ log.warn('SwitchEventStream: heartbeat recovered', {+ event: 'switch_beat_recovered',+ afterFailures: failures,+ });+ }+ failures = 0;+ backoff = BEAT_INTERVAL_MS;+ }+ } catch (error) {+ if (signal.aborted) return;+ fail(error);+ }+ await new Promise((r) => setTimeout(r, backoff));+ }+ }+}diff --git a/dash/packages/switch-agent-runtime/src/index.ts b/dash/packages/switch-agent-runtime/src/index.tsnew file mode 100644index 000000000..9d2a6f3ba--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/index.ts@@ -0,0 +1,36 @@+/**+ * The Switch agent protocol client.+ *+ * One connection to Switch: an SSE stream carrying events, a heartbeat proving+ * the client is alive, and a cursor so a reconnect resumes exactly where it+ * stopped. Everything a process needs to be reachable as an agent, and nothing+ * about what it then does with the events — injecting them into a terminal,+ * surfacing them as MCP notifications, or deciding to start a session are all+ * the consumer's business.+ *+ * Imported by switchdash (which delivers into a session's pane) and by this+ * package's own MCP runtime (which serves them next to the agent). It exists+ * because those two had a copy each and the copies drifted within a day.+ *+ * The MCP runtime is a separate entry point (`./bin`) so importing the client+ * does not drag in the MCP SDK.+ */++export {+ BEAT_INTERVAL_MS,+ SwitchEventStream,+ type DeliveryFilter,+ type EventStreamLogger,+ type StreamScope,+ type SwitchEventStreamDeps,+} from './event-stream';+export { readSse, type SseFrame } from './sse';+export type {+ AgentBridgeEvent,+ AttachmentRef,+ CommandPayload,+ MessagePayload,+ RoomJoinPayload,+ SwitchCredentials,+ TaskPayload,+} from './types';diff --git a/dash/packages/switch-agent-runtime/src/sse.test.ts b/dash/packages/switch-agent-runtime/src/sse.test.tsnew file mode 100644index 000000000..7235ab9f9--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/sse.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from 'vitest';+import { readSse, type SseFrame } from './sse';++/**+ * The wire format, pinned.+ *+ * These moved here with the parser. They used to sit beside a drift check that+ * compared two copies of this file; the copies are gone, so the check is too,+ * but the behaviour it protected still needs testing — and now testing it once+ * genuinely covers every client, which was the point of the move.+ */++function stream(chunks: string[]): ReadableStream<Uint8Array> {+ const encoder = new TextEncoder();+ return new ReadableStream<Uint8Array>({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));+ controller.close();+ },+ });+}++async function parse(chunks: string[]): Promise<SseFrame[]> {+ const frames: SseFrame[] = [];+ for await (const frame of readSse(stream(chunks), new AbortController().signal)) {+ frames.push(frame);+ }+ return frames;+}++describe('SSE framing', () => {+ it('parses event, id and data', async () => {+ const frames = await parse(['id: 7\nevent: message\ndata: {"body":"hi"}\n\n']);+ expect(frames).toEqual([{ event: 'message', id: '7', data: { body: 'hi' } }]);+ });++ it('defaults the event name to message when absent', async () => {+ const frames = await parse(['data: {"a":1}\n\n']);+ expect(frames[0].event).toBe('message');+ });++ it('leaves id undefined when the server sends none', async () => {+ // Control frames carry no sequence — treating a missing id as 0 would drag+ // the cursor backwards and replay the whole buffer on reconnect.+ const frames = await parse(['event: connection_state\ndata: {"rooms":[]}\n\n']);+ expect(frames[0].id).toBeUndefined();+ });++ it('skips keepalive comments without emitting a frame', async () => {+ const frames = await parse([': keepalive\n\n', 'event: gap\ndata: {"from_sequence":3}\n\n']);+ expect(frames).toHaveLength(1);+ expect(frames[0].event).toBe('gap');+ });++ it('reassembles a frame split across chunk boundaries', async () => {+ // The network splits wherever it likes; a frame torn mid-JSON must not be+ // dropped or parsed twice.+ const frames = await parse(['id: 1\nevent: mes', 'sage\ndata: {"bo', 'dy":"split"}\n\n']);+ expect(frames).toEqual([{ event: 'message', id: '1', data: { body: 'split' } }]);+ });++ it('emits several frames arriving in one chunk', async () => {+ const frames = await parse([+ 'id: 1\nevent: message\ndata: {"n":1}\n\nid: 2\nevent: message\ndata: {"n":2}\n\n',+ ]);+ expect(frames.map((f) => f.data.n)).toEqual([1, 2]);+ });++ it('joins multi-line data fields', async () => {+ const frames = await parse(['event: message\ndata: {"a":\ndata: 1}\n\n']);+ expect(frames[0].data).toEqual({ a: 1 });+ });++ it('ignores a frame with no data lines', async () => {+ const frames = await parse(['event: message\nid: 4\n\n']);+ expect(frames).toEqual([]);+ });++ it('throws on unparseable JSON rather than skipping it', async () => {+ // A frame we cannot read is a frame we have lost. Silently dropping it+ // would advance nothing and hide the loss.+ await expect(parse(['event: message\ndata: {not json}\n\n'])).rejects.toThrow();+ });++ it('stops when the signal aborts', async () => {+ const abort = new AbortController();+ abort.abort();+ const frames: SseFrame[] = [];+ for await (const frame of readSse(stream(['data: {"a":1}\n\n']), abort.signal)) {+ frames.push(frame);+ }+ expect(frames).toEqual([]);+ });+});diff --git a/dash/packages/switch-agent-runtime/src/sse.ts b/dash/packages/switch-agent-runtime/src/sse.tsnew file mode 100644index 000000000..fd2a8b4dd--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/sse.ts@@ -0,0 +1,56 @@+/**+ * The agent bridge's SSE framing.+ *+ * One implementation, imported by everything that speaks the protocol: the+ * local MCP runtime next to the agent, and switchdash. It used to exist twice —+ * separate deployables, no shared package — and the copies drifted within a day+ * of being made. This package is what removed the excuse.+ *+ * Deliberately free of imports and of anything specific to a host: it is the+ * wire format and nothing else. Reporting, reconnection, heartbeats and cursors+ * belong to the caller, which is where clients legitimately differ.+ */++export type SseFrame = { event: string; id?: string; data: Record<string, unknown> };++/** Parse an SSE byte stream into frames, ending when the stream or signal does. */+export async function* readSse(+ body: ReadableStream<Uint8Array>,+ signal: AbortSignal+): AsyncGenerator<SseFrame> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let buffered = '';++ try {+ while (!signal.aborted) {+ const { done, value } = await reader.read();+ if (done) return;+ buffered += decoder.decode(value, { stream: true });++ let split: number;+ while ((split = buffered.indexOf('\n\n')) !== -1) {+ const raw = buffered.slice(0, split);+ buffered = buffered.slice(split + 2);++ let event = 'message';+ let id: string | undefined;+ const dataLines: string[] = [];+ for (const line of raw.split('\n')) {+ // A comment line is the server's keepalive: it stops proxies timing+ // the stream out for idleness and carries nothing.+ if (line.startsWith(':')) continue;+ if (line.startsWith('event: ')) event = line.slice(7);+ else if (line.startsWith('id: ')) id = line.slice(4);+ else if (line.startsWith('data: ')) dataLines.push(line.slice(6));+ }+ if (!dataLines.length) continue;+ // A frame we cannot parse is a frame we have lost. Surface it rather+ // than skipping quietly; the caller decides how loud to be.+ yield { event, id, data: JSON.parse(dataLines.join('\n')) };+ }+ }+ } finally {+ void reader.cancel().catch(() => {});+ }+}diff --git a/dash/packages/switch-agent-runtime/src/types.ts b/dash/packages/switch-agent-runtime/src/types.tsnew file mode 100644index 000000000..4f2313315--- /dev/null+++ b/dash/packages/switch-agent-runtime/src/types.ts@@ -0,0 +1,89 @@+/**+ * The wire shapes of the agent bridge's events.+ *+ * Protocol types, so they live with the protocol client rather than in any one+ * consumer. Formatting an event for a human, or for injection into a terminal,+ * is a consumer's business and stays there.+ */++/**+ * A pointer to a media attachment on a message event. Mirrors the agent+ * bridge's `AttachmentRef` (and the connector channel's) — metadata plus the+ * Matrix `mxc://` URI only; the bytes are fetched on demand via the+ * media-download endpoint.+ */+export interface AttachmentRef {+ filename: string;+ mimetype: string;+ size: number;+ mxc: string;+ msgtype: string;+}++export interface MessagePayload {+ addressed: boolean;+ sender: string;+ sender_name: string;+ message_id: string;+ body: string;+ timestamp: number;+ thread_id?: string | null;+ attachments?: AttachmentRef[];+}++export interface CommandPayload {+ command: string;+ // Command arguments. For `reset`/`compact` this carries the role name the+ // agent should re-assume after its context is cleared/compacted (empty when+ // it held none).+ args: string;+ user_id: string;+ user_name: string;+ // Thread root of the originating command message, so the completion notice+ // can be posted back into that same thread. null when not in a thread.+ thread_id?: string | null;+}++export interface RoomJoinPayload {+ member: string;+ member_name: string;+ timestamp: number;+ listening: boolean;+}++export interface TaskPayload {+ task_id: string;+ requester_agent_id: string;+ performer_agent_id: string;+ summary?: string;+ description?: string;+ update?: string;+ outcome?: string | null;+ reason?: string | null;+}++export interface AgentBridgeEvent {+ type: string;+ room_id: string;+ payload: MessagePayload | CommandPayload | RoomJoinPayload | TaskPayload;+ /**+ * The event's position in the agent's buffer. Present on the push transport,+ * absent on the legacy poll.+ *+ * Load-bearing when a watcher spawns a session: the session's connection has+ * to start from *before* the message that triggered the spawn, or the very+ * message the session was started to answer is behind it.+ */+ sequence?: number;+}++export interface AgentBridgeEventResponse {+ events: AgentBridgeEvent[];+}++/** The credentials an agent uses to talk to its Switch instance. */+export interface SwitchCredentials {+ agentId: string;+ apiEndpoint: string;+ token: string;+}diff --git a/dash/packages/switch-agent-runtime/tsconfig.json b/dash/packages/switch-agent-runtime/tsconfig.jsonnew file mode 100644index 000000000..f4dd63e9d--- /dev/null+++ b/dash/packages/switch-agent-runtime/tsconfig.json@@ -0,0 +1,19 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "skipLibCheck": true,+ "esModuleInterop": true,+ "isolatedModules": true,+ "declaration": true,+ "noEmit": true,+ "forceConsistentCasingInFileNames": true,+ "jsx": "react",+ "lib": ["ES2022"],+ "types": ["node"]+ },+ "include": ["**/*.ts", "**/*.tsx"],+ "exclude": ["node_modules", "dist"]+}diff --git a/dash/packages/switch-agent-runtime/tsdown.config.ts b/dash/packages/switch-agent-runtime/tsdown.config.tsnew file mode 100644index 000000000..4732fdf33--- /dev/null+++ b/dash/packages/switch-agent-runtime/tsdown.config.ts@@ -0,0 +1,13 @@+import { defineConfig } from 'tsdown';++export default defineConfig({+ // Two entry points, deliberately separate. `index` is the protocol client+ // switchdash imports; `bin` is the MCP server npx runs. Splitting them keeps+ // the MCP SDK out of anything that only wants to talk to Switch.+ entry: { index: 'src/index.ts', bin: 'src/bin.ts' },+ format: ['esm'],+ dts: true,+ deps: {},+ sourcemap: true,+ clean: true,+});diff --git a/dash/pnpm-lock.yaml b/dash/pnpm-lock.yamlindex a3ebf1bb6..96cac42d1 100644--- a/dash/pnpm-lock.yaml+++ b/dash/pnpm-lock.yaml@@ -13,6 +13,9 @@ importers:'@parcel/watcher':specifier: ^2.5.6version: 2.5.6+ '@sandbox-quantum/switch-agent-runtime':+ specifier: workspace:*+ version: link:../../packages/switch-agent-runtime'@switchdash/core':specifier: workspace:*version: link:../../packages/core@@ -365,6 +368,25 @@ importers:specifier: ^4.1.0version: 4.1.8(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ packages/switch-agent-runtime:+ dependencies:+ '@modelcontextprotocol/sdk':+ specifier: ^1.0.0+ version: 1.30.0([email protected])+ devDependencies:+ '@types/node':+ specifier: ^20.19.42+ version: 20.19.42+ '@typescript/native-preview':+ specifier: 7.0.0-dev.20260609.1+ version: 7.0.0-dev.20260609.1+ tsdown:+ specifier: ^0.22.2+ vitest:+ specifier: ^4.1.0+ version: 4.1.8(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+packages:'@antfu/[email protected]':@@ -1125,6 +1147,12 @@ packages:'@floating-ui/[email protected]':resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==}+ '@hono/[email protected]':+ resolution: {integrity: sha512-eWpQYr67tqJLeaSUl0Q+TquuYfUdTibpOJlUMV2FfUP7+KqCC5TufnwnlXL6mobZBJbGAYRd7ZvEBDCbLInjhg==}+ engines: {node: '>=20'}+ peerDependencies:+ hono: ^4+'@iconify/[email protected]':resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==}@@ -1162,6 +1190,16 @@ packages:'@mermaid-js/[email protected]':resolution: {integrity: sha512-VuHdsYMK1bT6X2JbcAaWAhugTRvRBRyuZgd+c22swUeI9g/ntaxF7CY7dYarhZovofCbUNO0G7JesfmNtjYOCw==}+ '@modelcontextprotocol/[email protected]':+ resolution: {integrity: sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==}+ engines: {node: '>=18'}+ peerDependencies:+ '@cfworker/json-schema': ^4.1.1+ zod: ^3.25 || ^4.0+ peerDependenciesMeta:+ '@cfworker/json-schema':+ optional: true+'@monaco-editor/[email protected]':resolution: {integrity: sha512-gIwR1HrJrrx+vfyOhYmCZ0/JcWqG5kbfG7+d3f/C1LXk2EvzAbHSg3MQ5lO2sMlo9izoAZ04shohfKLVT6crVA==}@@ -2525,10 +2563,22 @@ packages:resolution: {integrity: sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==}engines: {node: ^20.17.0 || >=22.9.0}+ resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}engines: {node: '>= 14'}+ resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}+ peerDependencies:+ ajv: ^8.0.0+ peerDependenciesMeta:+ ajv:+ optional: true+resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}@@ -2643,6 +2693,10 @@ packages:resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==}+ resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==}deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.@@ -2683,6 +2737,10 @@ packages:resolution: {integrity: sha512-dUx+HxVbiNsNQ4mGe1PyoC/tBmsHwBNDLdBuqWCj+rhHFE9lHgrXiGYKAM1uNlznhAaUSyMlms84VeSSr3gOBA==}engines: {node: '>=14.0.0'}+ resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-U1Z/ob71V/bXfVABvNr/Kumf5VyeQRBEm6Txb0PQ6S7V5GpBM3w4Cbqz/xPDicR5tN0uvDifng8C+5qECeGwyQ==}engines: {node: '>=6.0.0'}@@ -2707,6 +2765,10 @@ packages:resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}+ engines: {node: '>= 0.4'}+resolution: {integrity: sha512-l8xKG+gwAIExZGl9FrF7KUwuOmk6wbEPC9Xoy/RtnWv1XG0Q4LFlagaLpUv3Kiza3W/wm27zy0yWJEieYKAP6w==}@@ -2840,12 +2902,36 @@ packages:engines: {node: ^14.13.0 || >=16.0.0}hasBin: true+ resolution: {integrity: sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}+ resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==}+ engines: {node: '>=6.6.0'}++ resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}+ resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}+ engines: {node: '>= 0.10'}+resolution: {integrity: sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==}@@ -3097,6 +3183,10 @@ packages:resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}engines: {node: '>=0.4.0'}+ resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}engines: {node: '>=6'}@@ -3256,6 +3346,9 @@ packages:resolution: {integrity: sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==}+ resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}+resolution: {integrity: sha512-/RInbCy1d4P6Zdfa+TMVsf/ufZVotat5hCw3QXmWtjU+3pFEOvOQ7ibo3aIxyCJw2leIeAMjmPj+1SLJiCpdrQ==}engines: {node: '>=12.0.0'}@@ -3309,6 +3402,10 @@ packages:resolution: {integrity: sha512-YGRs8knHhKHVShLkFET/rWAU8kmHbOV5LwN938RHI0pljAJ1Gf6SzXsSmRaEzcXTtOOmVqJ5+WtQPL5uigY50Q==}engines: {node: '>=14'}+ resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}@@ -3378,6 +3475,9 @@ packages:resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}engines: {node: '>=6'}+ resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==}+resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}engines: {node: '>=10'}@@ -3392,9 +3492,21 @@ packages:resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}+ resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}+ resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==}+ engines: {node: '>=18.0.0'}++ resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==}+ engines: {node: '>=18.0.0'}+resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==}engines: {node: '>=6'}@@ -3406,6 +3518,16 @@ packages:resolution: {integrity: sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==}+ resolution: {integrity: sha512-0D493aP61w0TJ2A0wy27riRsO7FMQ7FK+KUHOKCSfPvYo0R55aiC6emCVgFUeShH0fq0ICPVzNcgoS+BsbXQCA==}+ engines: {node: '>= 16'}+ peerDependencies:+ express: '>= 4.11'++ resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==}+ engines: {node: '>= 18'}+resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}@@ -3441,6 +3563,10 @@ packages:resolution: {integrity: sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==}+ resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==}+ engines: {node: '>= 18.0.0'}+resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==}engines: {node: '>= 6'}@@ -3449,6 +3575,10 @@ packages:resolution: {integrity: sha512-wzsgA6WOq+09wrU1tsJ09udeR/YZRaeArL9e1wPbFg3GG2yDnC2ldKpxs4xunpFF9DgqCqOIra3bc1HWrJ37Ww==}engines: {node: '>=0.4.x'}+ resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-uaBd3qC1v3KQqBEjwTUd183K6PbS+j0yR9w9VmEOLWA/tnUcSn8Xa3uck7t4dgpDoUss8xQTcj8W2L07lrnLFg==}peerDependencies:@@ -3463,6 +3593,10 @@ packages:react-dom:optional: true+ resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}@@ -3640,6 +3774,10 @@ packages:resolution: {integrity: sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA==}+ resolution: {integrity: sha512-GqXJqY/xJkJmuloTrnV1ZEXG3fqte+VjkUqoRNZXcrUidiUOP4fMSIHHY4tsqZBK++kVyWmt/AAfSUuy57/eSA==}+ engines: {node: '>=16.9.0'}+resolution: {integrity: sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ==}@@ -3660,6 +3798,10 @@ packages:resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==}+ resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}engines: {node: '>= 14'}@@ -3680,6 +3822,10 @@ packages:resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==}+ engines: {node: '>=0.10.0'}+resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}@@ -3714,6 +3860,14 @@ packages:resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==}engines: {node: '>=12'}+ resolution: {integrity: sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==}+ engines: {node: '>= 12'}++ resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}+ engines: {node: '>= 0.10'}+resolution: {integrity: sha512-DwzsA04LQ10FHTZuL0/grVDk4rFoVH1pjAToYwBrHSxcrBIGQuXrQMtD5U1b0U2XVgKZCTLLP8u2Qxqhy3l2Vg==}@@ -3757,6 +3911,9 @@ packages:resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}+ resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}+resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==}@@ -3788,6 +3945,9 @@ packages:resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}hasBin: true+ resolution: {integrity: sha512-hq1OB1bALKfydZNoViyg6hPVGV4i93ny9Op+n4zP5RSf7SCZEXa/TsG2O3IEr7+WlHRTPnpqDmHfMH6qXAD60w==}+resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}@@ -3818,6 +3978,9 @@ packages:resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}+ resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==}+resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==}@@ -4055,6 +4218,14 @@ packages:resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}+ resolution: {integrity: sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-pTMbcf3rWdtLiYGpmoTjHEpeY8seiy6sR+9nD7LOs8KfUbHE4lOUAprTRqRAcWSQ6MQpdX+YEsxShtGsINtPtw==}@@ -4149,10 +4320,18 @@ packages:resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==}engines: {node: '>=4.0.0'}@@ -4260,6 +4439,10 @@ packages:resolution: {integrity: sha512-MBymFqWDxu1sQd6kQX5SJUvyIyCQVgyAUCoIsSGNGf8I6JFL2s5VUMiRZTNwLQK5BUg7LpxRzPGNTvXWrDnooA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==}+ engines: {node: '>= 0.6'}+resolution: {integrity: sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==}engines: {node: '>=10'}@@ -4298,6 +4481,14 @@ packages:resolution: {integrity: sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==}engines: {node: '>=10'}+ resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==}+ engines: {node: '>= 0.4'}+resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}engines: {node: '>= 0.4'}@@ -4306,6 +4497,10 @@ packages:resolution: {integrity: sha512-AWGB9WFcRXOQs48Z/udjI5ZcZMHXwX8XPByNpOydgcGsDLIzjGizhoMWJyKAWze7AVW/2W1i+/gPX4YtKe5cyg==}engines: {node: '>=12.20.0'}+ resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}@@ -4359,6 +4554,10 @@ packages:resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==}+ resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==}@@ -4374,6 +4573,9 @@ packages:resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==}engines: {node: 18 || 20 || >=22}+ resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==}+resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}@@ -4399,6 +4601,10 @@ packages:resolution: {integrity: sha512-yCH2dtLHfEBnzlHUJymR/Z1nN2ePG3m392Mv8TFlTP1B0xkpMQNHAnfkY0n2tAi6ceKO6YWhxYfZ96V4vVkh/g==}engines: {node: '>=18'}+ resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==}+ engines: {node: '>=16.20.0'}+resolution: {integrity: sha512-emEcLuomt2j03vxD54giVB4SxTjnsqkU692xZOZXHDVoYyypEm+b3jpiTcc+Cf+myooc+/Ly0z01jqeNHVgJGw==}engines: {node: '>=16.0.0'}@@ -4478,6 +4684,10 @@ packages:resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==}+ resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}+ engines: {node: '>= 0.10'}+resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}@@ -4492,6 +4702,10 @@ packages:resolution: {integrity: sha512-KTqnxsgGiQ6ZAzZCVlJH5eOjSnvlyEgx1m8bkRJfOhmGRqfo5KLvmAlACQkrjEtOQ4B7wF9TdSLIs9O90MX9xA==}engines: {node: '>=16.0.0'}+ resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==}+ engines: {node: '>=0.6'}+resolution: {integrity: sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==}@@ -4499,6 +4713,14 @@ packages:resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==}engines: {node: '>=10'}+ resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}+ engines: {node: '>= 0.10'}+resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==}hasBin: true@@ -4683,6 +4905,10 @@ packages:resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==}+ resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}+ engines: {node: '>= 18'}+resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==}@@ -4742,10 +4968,21 @@ packages:engines: {node: '>=10'}hasBin: true+ resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==}+ engines: {node: '>= 18'}+resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==}engines: {node: '>=10'}+ resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}+resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}engines: {node: '>=8'}@@ -4758,6 +4995,22 @@ packages:resolution: {integrity: sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==}+ engines: {node: '>= 0.4'}+resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}@@ -4825,6 +5078,10 @@ packages:resolution: {integrity: sha512-HTEHMNieakEnoe33shBYcZ7NX83ACUjCu8c40iOGEZsngj9zRnkqS9j1pqQPXwobB0ZcVTk27REb7COQ0UR59w==}+ resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}@@ -4967,6 +5224,10 @@ packages:resolution: {integrity: sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==}engines: {node: '>=14.14'}+ resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}+ engines: {node: '>=0.6'}+resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==}engines: {node: '>=6'}@@ -5051,6 +5312,10 @@ packages:resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==}engines: {node: '>=10'}+ resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==}+ engines: {node: '>= 18'}+resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==}engines: {node: '>=14.17'}@@ -5111,6 +5376,10 @@ packages:resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}engines: {node: '>= 10.0.0'}+ resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-PZ8hTS+AqcGxsaQntl3IRBw65QrBI6lxzqDEL7IAo/XCEqRTKGfOX56Vea5TH9SZczRVxuzk1re04z/YjuYCJA==}@@ -5161,6 +5430,10 @@ packages:resolution: {integrity: sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg==}hasBin: true+ resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}+ engines: {node: '>= 0.8'}+resolution: {integrity: sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg==}@@ -5408,6 +5681,11 @@ packages:resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}engines: {node: '>=10'}+ resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==}+ peerDependencies:+ zod: ^3.25.28 || ^4+resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}@@ -6029,6 +6307,10 @@ snapshots:'@floating-ui/[email protected]': {}+ '@hono/[email protected]([email protected])':+ dependencies:+ hono: 4.12.34+'@iconify/[email protected]': {}'@iconify/[email protected]':@@ -6077,6 +6359,28 @@ snapshots:dependencies:'@chevrotain/types': 11.1.2+ '@modelcontextprotocol/[email protected]([email protected])':+ dependencies:+ '@hono/node-server': 2.0.12([email protected])+ ajv: 8.20.0+ ajv-formats: 3.0.1([email protected])+ content-type: 1.0.5+ cors: 2.8.6+ cross-spawn: 7.0.6+ eventsource: 3.0.7+ eventsource-parser: 3.1.0+ express: 5.2.1+ express-rate-limit: 8.6.1([email protected])+ hono: 4.12.34+ jose: 6.2.7+ json-schema-typed: 8.0.2+ pkce-challenge: 5.0.1+ raw-body: 3.0.2+ zod: 4.4.3+ zod-to-json-schema: 3.25.2([email protected])+ transitivePeerDependencies:+ - supports-color+'@monaco-editor/[email protected]':dependencies:state-local: 1.0.7@@ -7189,8 +7493,17 @@ snapshots:+ dependencies:+ mime-types: 3.0.2+ negotiator: 1.0.0++ optionalDependencies:+ ajv: 8.20.0+dependencies:fast-deep-equal: 3.1.3@@ -7342,6 +7655,20 @@ snapshots:+ dependencies:+ bytes: 3.1.2+ content-type: 2.0.0+ debug: 4.4.3+ http-errors: 2.0.1+ iconv-lite: 0.7.3+ on-finished: 2.4.1+ qs: 6.15.3+ raw-body: 3.0.2+ type-is: 2.1.0+ transitivePeerDependencies:+ - supports-color+optional: true@@ -7404,6 +7731,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+@@ -7427,6 +7756,11 @@ snapshots:es-errors: 1.3.0function-bind: 1.1.2+ dependencies:+ call-bind-apply-helpers: 1.0.2+ get-intrinsic: 1.3.0+@@ -7547,10 +7881,25 @@ snapshots:tree-kill: 1.2.2yargs: 17.7.2+ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ object-assign: 4.1.1+ vary: 1.1.2+dependencies:layout-base: 1.0.2@@ -7826,6 +8175,8 @@ snapshots:+ [email protected]: {}+@@ -7898,6 +8249,8 @@ snapshots:dependencies:readable-stream: 2.3.8+ [email protected]: {}+@@ -7994,6 +8347,8 @@ snapshots:+ [email protected]: {}+dependencies:once: 1.4.0@@ -8120,6 +8475,8 @@ snapshots:+ [email protected]: {}+optional: true@@ -8131,14 +8488,63 @@ snapshots:dependencies:'@types/estree': 1.0.9+ [email protected]: {}++ [email protected]: {}++ dependencies:+ eventsource-parser: 3.1.0++ dependencies:+ debug: 4.4.3+ express: 5.2.1+ ip-address: 10.4.0+ transitivePeerDependencies:+ - supports-color++ dependencies:+ accepts: 2.0.0+ body-parser: 2.3.0+ content-disposition: 1.1.0+ content-type: 1.0.5+ cookie: 0.7.2+ cookie-signature: 1.2.2+ debug: 4.4.3+ depd: 2.0.0+ encodeurl: 2.0.0+ escape-html: 1.0.3+ etag: 1.8.1+ finalhandler: 2.1.1+ fresh: 2.0.0+ http-errors: 2.0.1+ merge-descriptors: 2.0.0+ mime-types: 3.0.2+ on-finished: 2.4.1+ once: 1.4.0+ parseurl: 1.3.3+ proxy-addr: 2.0.7+ qs: 6.15.3+ range-parser: 1.3.0+ router: 2.2.0+ send: 1.2.1+ serve-static: 2.2.1+ statuses: 2.0.2+ type-is: 2.1.0+ vary: 1.1.2+ transitivePeerDependencies:+ - supports-color+@@ -8173,6 +8579,17 @@ snapshots:dependencies:minimatch: 5.1.9+ dependencies:+ debug: 4.4.3+ encodeurl: 2.0.0+ escape-html: 1.0.3+ on-finished: 2.4.1+ parseurl: 1.3.3+ statuses: 2.0.2+ transitivePeerDependencies:+ - supports-color+dependencies:asynckit: 0.4.0@@ -8183,6 +8600,8 @@ snapshots:+ [email protected]: {}+dependencies:motion-dom: 12.40.0@@ -8192,6 +8611,8 @@ snapshots:react: 19.2.7react-dom: 19.2.7([email protected])+ [email protected]: {}+@@ -8469,6 +8890,8 @@ snapshots:+ [email protected]: {}+@@ -8487,6 +8910,14 @@ snapshots:+ dependencies:+ depd: 2.0.0+ inherits: 2.0.4+ setprototypeof: 1.2.0+ statuses: 2.0.2+ toidentifier: 1.0.1+dependencies:agent-base: 7.1.4@@ -8512,6 +8943,10 @@ snapshots:dependencies:safer-buffer: 2.1.2+ dependencies:+ safer-buffer: 2.1.2+@@ -8535,6 +8970,10 @@ snapshots:+ [email protected]: {}++ [email protected]: {}+@@ -8569,6 +9008,8 @@ snapshots:+ [email protected]: {}+@@ -8589,6 +9030,8 @@ snapshots:+ [email protected]: {}+@@ -8629,6 +9072,8 @@ snapshots:+ [email protected]: {}+optional: true@@ -8934,6 +9379,10 @@ snapshots:+ [email protected]: {}++ [email protected]: {}+dependencies:'@braintree/sanitize-url': 7.1.2@@ -9161,10 +9610,16 @@ snapshots:+ [email protected]: {}+dependencies:mime-db: 1.52.0+ dependencies:+ mime-db: 1.54.0+@@ -9247,6 +9702,8 @@ snapshots:compromise: 14.15.1stopword: 3.1.5+ [email protected]: {}+dependencies:semver: 7.8.5@@ -9288,11 +9745,19 @@ snapshots:+ [email protected]: {}++ [email protected]: {}+optional: true+ dependencies:+ ee-first: 1.1.1+dependencies:wrappy: 1.0.2@@ -9388,6 +9853,8 @@ snapshots:dependencies:entities: 8.0.0+ [email protected]: {}+@@ -9399,6 +9866,8 @@ snapshots:lru-cache: 11.5.1minipass: 7.1.3+ [email protected]: {}+@@ -9415,6 +9884,8 @@ snapshots:dependencies:safe-buffer: 5.2.1+ [email protected]: {}+dependencies:'@noble/hashes': 1.4.0@@ -9506,6 +9977,11 @@ snapshots:+ dependencies:+ forwarded: 0.2.0+ ipaddr.js: 1.9.1+dependencies:end-of-stream: 1.4.5@@ -9519,10 +9995,24 @@ snapshots:+ dependencies:+ es-define-property: 1.0.1+ side-channel: 1.1.1++ [email protected]: {}++ dependencies:+ bytes: 3.1.2+ http-errors: 2.0.1+ iconv-lite: 0.7.3+ unpipe: 1.0.0+dependencies:deep-extend: 0.6.0@@ -9810,6 +10300,16 @@ snapshots:points-on-curve: 0.2.0points-on-path: 0.2.1+ dependencies:+ debug: 4.4.3+ depd: 2.0.0+ is-promise: 4.0.0+ parseurl: 1.3.3+ path-to-regexp: 8.4.2+ transitivePeerDependencies:+ - supports-color+@@ -9849,11 +10349,38 @@ snapshots:+ dependencies:+ debug: 4.4.3+ encodeurl: 2.0.0+ escape-html: 1.0.3+ etag: 1.8.1+ fresh: 2.0.0+ http-errors: 2.0.1+ mime-types: 3.0.2+ ms: 2.1.3+ on-finished: 2.4.1+ range-parser: 1.3.0+ statuses: 2.0.2+ transitivePeerDependencies:+ - supports-color+dependencies:type-fest: 0.13.1optional: true+ dependencies:+ encodeurl: 2.0.0+ escape-html: 1.0.3+ parseurl: 1.3.3+ send: 1.2.1+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}+dependencies:shebang-regex: 3.0.0@@ -9862,6 +10389,34 @@ snapshots:+ dependencies:+ es-errors: 1.3.0+ object-inspect: 1.13.4++ dependencies:+ call-bound: 1.0.4+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ object-inspect: 1.13.4++ dependencies:+ call-bound: 1.0.4+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ object-inspect: 1.13.4+ side-channel-map: 1.0.1++ dependencies:+ es-errors: 1.3.0+ object-inspect: 1.13.4+ side-channel-list: 1.0.1+ side-channel-map: 1.0.1+ side-channel-weakmap: 1.0.2+@@ -9923,6 +10478,8 @@ snapshots:+ [email protected]: {}+@@ -10064,6 +10621,8 @@ snapshots:+ [email protected]: {}+@@ -10131,6 +10690,12 @@ snapshots:optional: true+ dependencies:+ content-type: 2.0.0+ media-typer: 1.1.1+ mime-types: 3.0.2+@@ -10197,6 +10762,8 @@ snapshots:+ [email protected]: {}+dependencies:bluebird: 3.7.2@@ -10241,6 +10808,8 @@ snapshots:+ [email protected]: {}+dependencies:'@types/unist': 3.0.3@@ -10482,6 +11051,10 @@ snapshots:+ dependencies:+ zod: 4.4.3+diff --git a/docs/api/AGENT_PROTOCOL.md b/docs/api/AGENT_PROTOCOL.mdnew file mode 100644index 000000000..778723cdc--- /dev/null+++ b/docs/api/AGENT_PROTOCOL.md@@ -0,0 +1,816 @@+# Agent Bridge Protocol++Status: **design, under review** (CHOO-1857)++This document specifies the protocol between an agent and Switch: how an agent+connects, what it receives, what it sends, and what happens when things break.+It replaces the long-poll delivery described in `ARCHITECTURE.md` §4.3.++---++## 1. Why this changes++Four problems in the current model, all structural rather than incidental.++**Two sources of truth for "which session is in which room."** `connect_to_room`+is an MCP tool that writes a row keyed on the MCP transport session id, while+events are fetched over an unrelated HTTP request that never mentions it. The+thing that joined the room and the thing receiving that room's events are two+independent connections sharing only an agent id. Neither notices when the+other dies. Clients then keep their own copies — switchdash persists a+session→room map to SQLite, the remote reconciler mirrors it, the sidecar keeps+a third — so the same fact is stored four times and reconciled nowhere.++**Events are held in memory and destroyed on read.** The event queue is a+per-agent, per-room `asyncio.Queue`. A poll *removes* what it returns, so only+one consumer can exist (hence `SWITCH_CHANNEL_DISABLE_POLL`, which switchdash+sets to stop the connector stealing its events). Nothing survives a restart,+and there is no way to ask "what did I miss?" because no record is kept.++**Liveness is guessed from timestamps by every reader independently.** Three+heartbeat endpoints with three cadences and three TTLs exist because there are+three connection models. Each caller compares `last_seen_at` against a TTL at+read time; nobody owns the answer. There is no session-close signal at all, so+bindings linger until they expire.++**Connection models leak agent implementation details into the server.**+`always_on` / `session_addressable` / `session_passive` / `auto_session` is+branched on in 22 places, but almost all of those reduce to "is there a live+connection, and what does it cover" — facts the server could observe rather+than be told.++### Non-goals++- Horizontal scaling. `switch-core` is single-process by construction (the Helm+ chart refuses `replicaCount != 1` because Matrix sync sessions live in+ memory). This design assumes one process and notes the seams where that+ assumption is load-bearing.+- Replacing MCP. MCP remains the agent's tool surface.+- AG-UI (CHOO-1685). This design should not make it harder to land; it does not+ attempt it.++---++## 2. Model++### 2.1 The connection++A **connection** is the unit of everything. It is created by opening the event+stream and it owns:++- **scope** — which rooms it covers+- **filter** — which events within those rooms+- **cursor** — how far the client has consumed+- **liveness** — its heartbeat+- **room slots** — its exclusive right to act as the agent in a room+- **role lease** — the room role it holds, if any++A connection belongs to exactly one agent. An agent may have several.++The connection is held **in memory only**. It cannot outlive the server+process (its socket and buffer cannot), so persisting it would recreate the+staleness bug. Every question of the form "is this agent reachable in room R?"+is answered from the live connection set, not from a table.++### 2.2 Scope++Declared when the stream opens, mutable while it is open.++| scope | meaning | typical client |+|---|---|---|+| `single` | at most one room at a time; subscribing to a new room drops the previous | a terminal coding session |+| `all` | every room the agent belongs to, including rooms joined later | a supervising daemon, an always-on agent |++`single` is `all` with a limit of one. The limit is enforced server-side, so+"one room at a time" is a guarantee rather than a convention in a skill.++Scope is always a subset of the rooms the agent is already a member of.+Subscribing is not joining; membership is checked per subscribe.++### 2.3 Filter++Also declared at open. Orthogonal to scope: scope selects *rooms*, filter+selects *events within them*.++| filter | delivers |+|---|---|+| `all` | every event in subscribed rooms, each carrying `addressed` |+| `addressed` | only addressed messages, task events, and opted-in room joins |++A session uses `single` + `all` — it needs unaddressed traffic for context and+for missed-message counts. A daemon uses `all` + `addressed` — it is watching+for a reason to start a session, not following conversations. This replaces+the separate `/notifications` endpoint and collapses the two notification+builders (CHOO-1810) into one.++### 2.4 Room slots++**At most one connection per (agent, room) may act as that agent in that room.**++- A `single`-scope connection **claims** the slot for its room.+- An `all`-scope connection covers every room **not** claimed by another+ connection of the same agent.+- When a `single` connection claims room R, the `all` connection **goes fully+ dark on R** — it receives nothing for R until the claim is released.+- When the claiming connection dies, coverage returns to the `all` connection+ automatically.++Exactly one recipient per room at all times: no duplicate delivery, no+coordination needed for handoff in either direction.++This rule already exists — implemented client-side in+`auto-session-watcher.ts`, which skips a room when switchdash's own map says a+session covers it. Moving it into the protocol is the split-brain fix.++**Collision.** If a `single` connection tries to claim a room already claimed+by a live connection of the same agent, the claim is **rejected** with an error+naming the incumbent. The common cause is an accident (a stale process, a+double launch) and rejecting surfaces it. An explicit takeover flag forces the+claim, evicting the incumbent, which is told why.++### 2.5 Sessions are not a server concept++Switch models connections, not sessions. Whether a client runs one PTY or ten+behind a connection is its own business.++A daemon that spawns sessions does not relay events to them: each spawned+session opens **its own** `single`-scope connection. Consequences: correlation+stays structural (each session's stream and MCP live in one process), failure+is isolated (the daemon dying does not disconnect running sessions), and a bare+terminal session with no daemon works identically.++A client may later multiplex sessions behind one connection. Switch does not+need to change for that.++---++## 3. Transport++**SSE for server→agent, ordinary HTTP for agent→server.**++The two directions have different shapes. Downward is a stream: events happen+whenever, the agent listens. Upward is request/response: each action wants a+result. SSE plus HTTP uses each for what it already does, rather than+rebuilding request semantics inside a WebSocket frame protocol.++Reasons, in order of weight:++1. **Resume is specified.** SSE tags events with ids and clients reconnect with+ `Last-Event-ID` automatically. Gap recovery after a laptop sleeps is the+ spec, not something we invent.+2. **It survives the network.** SSE is plain HTTP, so proxies, K8s ingress,+ corporate networks and SSH port-forwards pass it through. WebSocket's+ upgrade handshake is a class of "works on my machine" failure we would own.+3. **It is debuggable.** `curl -N .../events` shows the live stream.++Both are client-initiated, so agents work behind NAT with only outbound HTTPS.+**Switch can never wake a disconnected agent** — with no connection, events+queue. Anything resembling "Switch starts a session on demand" must be done by+something already connected and local.++**Accepted cost:** two channels can fail independently. §5.3 binds them.++---++## 4. The event buffer++### 4.1 Shape++Per agent, an ordered buffer of recent events, each with a monotonically+increasing **sequence number**. Events are appended when produced and removed+only when confirmed or aged out — **never on read**.++Delivery becomes a read, which makes it repeatable, resumable and verifiable.+It also permits more than one reader, which is what allows+`SWITCH_CHANNEL_DISABLE_POLL` to be deleted.++The buffer is **in memory** for the first implementation. Restart loses+undelivered events — accepted, and made loud (§5.5). It sits behind a narrow+interface (`append`, `read_from`, `confirm`, `prune`) so it can be moved to+Postgres later without anything above it changing.++> **Why not Kafka / Redis Streams / NATS?** Event volume is human chat scale —+> order of one event per second aggregate. A broker's central benefit is+> decoupling producers from consumers for independent scaling, which+> `switch-core` cannot use while it is pinned to one replica. Against that: a+> new stateful service in the Helm chart, in compose, in CI and in every dev+> setup, plus a "committed to the DB, failed to publish" failure mode we do not+> have today. If the buffer ever needs to leave the process, Postgres first+> (`LISTEN/NOTIFY` for the wakeup), Redis Streams second — its stream ids are+> the same cursor concept.++### 4.2 Bounding and gaps++The current queue is unbounded: an agent that never connects accumulates+forever in RAM. The buffer is **capped per agent**. On overflow the oldest+events are dropped and the agent is flagged as having a **gap**.++A gap is never silent. The next connection for that agent is told it missed+events and must re-read room context. The same applies when a client asks to+start from a sequence number older than the buffer retains: that is an+**error**, not a fast-forward to head.++### 4.3 Confirmation++Two mechanisms, both free:++- **On reconnect** — `Last-Event-ID` states what the client processed. This is+ what makes resume correct.+- **Piggybacked** — the heartbeat and every agent→server call carry the+ client's current sequence number, so the buffer trims during long-lived+ connections rather than growing to the cap.++The cursor is **monotonic per connection**. A client may not move it backwards+to force replay; history is `read_context`'s job, not the stream's.++### 4.4 Starting position++Chosen once, at open:++- **head** (default) — only events from now on. Correct for a session a human+ started; nobody is waiting on a specific event.+- **from a given sequence number** — used on reconnect, and by a spawner.++When a daemon spawns a session in response to an event, it passes that event's+sequence number to the session, which opens its connection just below it. The+session therefore receives exactly the message that woke it, and nothing else,+without relying on the agent thinking to go looking.++The trigger event is consequently delivered twice — once to the daemon that+used it to decide to spawn, once to the session that acts on it. This is+intended.++---++## 5. Connection lifecycle++### 5.1 Opening++```+GET /agents/{agent_id}/events+Authorization: Bearer <agent token>+Accept: text/event-stream++ connection_id client-generated UUID+ scope single | all+ filter all | addressed+ start_from head | <sequence number> (default head)+ spawn_capable bool (default false)+ protocol protocol version+```++The client generates the connection id, which makes opening **idempotent**: a+timed-out request can be retried without creating a second connection. The id+identifies, it does not authorise — the agent token does that — so it need not+be treated as a secret. An id belonging to a different agent is rejected.++The server responds with an open `text/event-stream` and sends the connection's+state as the first event.++**Protocol version is checked at open.** An incompatible client is refused with+a message telling the user to update. The runtime lives on the user's machine+and Switch moves independently; silent degradation is not acceptable.++### 5.2 Heartbeat++```+POST /agents/{agent_id}/connection/beat+ connection_id+ cursor last sequence number processed+```++Every **2 s**; TTL **6 s**. One heartbeat for every kind of connection. It+replaces all three of today's: `/connection/renew`, `/watch/heartbeat` and+`/leases/renew`.++It does two jobs: proves the client is alive *and* consuming (strictly stronger+than a server-side write succeeding), and confirms the cursor so the buffer can+trim.++The server also writes a keepalive comment down the stream periodically. That+is only to stop proxies timing out an idle connection — it is **not** the+liveness signal.++### 5.3 The two signals++A connection has two independent signals: whether a **stream is attached**, and+whether the **heartbeat is fresh**.++| stream | heartbeat | state |+|---|---|---|+| attached | fresh | **healthy** — events flow |+| detached | fresh | **alive, not receiving** — keeps slot and lease; events buffer; heartbeat is *rejected* with "no stream attached, reopen" |+| attached | stale | **dead** — half-open socket; drop stream, release slot and lease |+| detached | stale | **dead** |++**The connection dies when the heartbeat goes stale. Losing the stream does not+kill it; it only stops delivery.**++This is what makes a 6 s TTL safe. A brief network drop detaches the stream,+the connection survives, the client reattaches with the same connection id and+resumes from its cursor — keeping its room slot and role lease. Without the+grace window, a wifi hiccup would drop an agent's role.++Reconnecting with an id that is already live **takes over**: the previous+stream is dropped with an explicit reason. "Same client returning" and "same+client duplicated" are indistinguishable, and takeover is right for both.++### 5.4 Binding the two channels++Every agent→server call carries the `connection_id`. The server checks it+against the live connection set:++- live → accept+- unknown or dead → **reject** with "your stream is not connected; reconnect and+ resume from your cursor"++This is the coupling a single WebSocket would give for free, obtained with one+field. It means an agent whose stream died cannot keep acting as though+connected: it is told on its very next action.++Correlation is always **derived** by the server — from the credential or the+local socket — never accepted as a claim in a request body.++### 5.5 Restart++On restart there are zero connections; every client reconnects. This is the+truth, and the server must not pretend otherwise.++The server marks a fresh start. A client resuming with a cursor from a previous+process is told its cursor is meaningless and it must re-read context. Never a+quiet resume that looks healthy.++### 5.6 Closing++- Stream closes → detach, grace window per §5.3.+- Heartbeat lapses → connection dies: slots released, role lease released,+ buffer for that connection discarded.++---++## 6. Events (server → agent)++Wire format is SSE. Each event carries `id` (the sequence number), `event`+(the type) and `data` (JSON).++```+id: 4813+event: message+data: {"type":"message","room_id":"…","bridge_id":"…","channel_type":"channel_public",+ "payload":{…}}+```++### 6.1 Envelope++| field | type | notes |+|---|---|---|+| `type` | string | one of the types below |+| `room_id` | string | Switch room id |+| `room_name` | string | *new* — `all`-scope clients receive events for rooms they never explicitly connected to |+| `bridge_id` | string \| null | collaboration bridge, if any |+| `channel_type` | string \| null | `channel_public`, `channel_private`, `direct` |+| `payload` | object | per type |++### 6.2 `message`++```json+{ "addressed": true, "sender": "@switch-slack-alice:switch.local",+ "sender_name": "alice", "message_id": "$abc…", "body": "…",+ "timestamp": 1785569372682, "thread_id": "$root…",+ "attachments": [ { "filename": "diagram.png", "mimetype": "image/png",+ "size": 20481, "mxc": "mxc://…", "msgtype": "m.image" } ] }+```++`addressed` is computed server-side: true for a `direct` channel, an `@name` or+`@alias` mention, or an `@role` mention whose role this agent holds. The+addressing policy is applied at this point — a mention from a sender not+permitted to address this agent is demoted to unaddressed.++Attachments carry a pointer, never bytes; fetch via the media endpoint.++### 6.3 `command`++```json+{ "command": "reset", "args": "", "user_id": "…", "user_name": "alice",+ "thread_id": "$root…" }+```++### 6.4 `room_join`++```json+{ "member": "@alice:switch.local", "member_name": "alice",+ "timestamp": 1785569372682, "listening": true }+```++`listening` reflects the per-room, per-agent opt-in. Under `filter: addressed`,+joins are delivered only when `listening` is true.++### 6.5 Task events++All five carry `task_id`, `requester_agent_id`, `performer_agent_id`, plus:++| type | extra |+|---|---|+| `task_delegate` | `summary`, `description` |+| `task_accept` | — |+| `task_update` | `update` |+| `task_finalise` | `outcome` |+| `task_cancel` | `reason` |++Task events are always notifiable and are delivered under both filters.++### 6.6 Control events++New, carried on the same stream:++| type | payload | meaning |+|---|---|---|+| `connection_state` | `connection_id`, `scope`, `filter`, `rooms`, `cursor`, `protocol` | first event on every stream |+| `subscription_changed` | `rooms`, `reason` | scope changed — including a room going dark because another connection claimed it |+| `gap` | `from_sequence`, `reason` | events were dropped; re-read context |+| `evicted` | `reason` | this connection lost its slot or was taken over; it must stop acting |++`gap` and `evicted` exist so that degradation is always visible. A client that+has missed events must never appear healthy.++---++## 7. Operations (agent → server)++Every agent operation is reachable through **two front doors that dispatch into+one registry**:++- **MCP** — the tool surface an agent model calls.+- **HTTP** — `POST /agents/{agent_id}/ops/{operation}`, arguments as the JSON+ body, `X-Switch-Connection-Id` naming the caller's connection.++**Operation names are the MCP tool names verbatim.** A runtime translating+between the two is `POST /ops/${toolName}` and nothing more — no mapping table+to maintain, and no second vocabulary to keep in step.++Parity is **structural, not maintained**: operations live in a registry that+neither door owns. The HTTP endpoint dispatches into it; the MCP server+registers its tools from it. An operation is therefore reachable through both+doors the moment it exists, and **retiring a door is deleting a file** rather+than refactoring everything underneath. This is what makes a local runtime+possible at all (§9.1) and closes the overlap with CHOO-490.++An operation is a plain async function taking its arguments and nothing else.+Who is calling, and which connection or session they are bound to, comes from+a **call context** each front door establishes before dispatching — so no+transport type appears in an operation's signature, and the operations layer+imports nothing from either door.++`GET /agents/{agent_id}/ops` lists every operation and its JSON-schema+parameters, read straight off the registry.++### 7.1 What the caller supplies++An operation needs two things about its caller: **which agent** (the bearer+token) and **which session or connection** it belongs to. Over MCP the latter+is the transport session; over HTTP it is the connection id. Both are derived+by the server — from the credential and the header — never taken from the+request body.++A connection id belonging to a different agent, or to one that has died, is+**refused**, not silently treated as "no connection".++### 7.2 The operations++**Rooms** — `connect_to_room`, `read_context`, `list_participants`,+`list_rooms`, `list_all_rooms`, `get_room_detail`, `update_room`,+`create_room`, `archive_room`, `unarchive_room`, `invite_agent_to_room`,+`add_users_to_room`, `list_linked_rooms`, `link_rooms`, `unlink_rooms`,+`list_room_groups`, `create_room_group`, `get_room_group_detail`.++`connect_to_room` remains a single call that both subscribes and returns+instructions, participants, references, roles and linked rooms. Internally+subscription and payload are separate concerns; they are not split in the+agent-facing API, because an agent must not be able to subscribe to a room+without being told what the room is about.++**Messaging** — `post_message`, `send_targeted_message`.++**Tasks** — `delegate_task`, `accept_task`, `update_task`, `finalise_task`,+`cancel_task`, `list_tasks`.++**Roles** — `list_roles`, `get_role_detail`, `define_role`, `edit_role`,+`delete_role`, `assume_role`, `release_role`.++**Resources** — `list_references`, `list_reference_types`, `create_reference`,+`attach_reference_to_room`, `load_internal_documents`, `create_room_document`,+`update_room_document`, `delete_room_document`.++**Agents and bridges** — `list_agents`, `get_agent_detail`,+`update_agent_detail`, `list_bridges`.++### 7.3 What stays ordinary REST++Not agent operations, and shaped wrongly by RPC over JSON:++- **Media** — upload and download are multipart and binary.+- **The event stream** and **connection lifecycle** (`beat`, `subscribe`,+ `unsubscribe`) — these are the transport, not things done *through* it.+- **Mediation hooks**, **registration**, **runtime state**, **typing**.++## 8. Connection profiles replace agent profiles++`connection_model` is removed. What the server needs is observable from+connections; what it does not need was never its business.++| today | becomes |+|---|---|+| `always_on` | a connection with `scope: all` |+| `session_addressable` | a connection with `scope: single` |+| `auto_session` | a connection with `scope: all`, `spawn_capable: true` |+| `session_passive` | *no connection* — the agent can act, but receives nothing |++### 8.1 Statuses++Three, derived:++| status | condition |+|---|---|+| `LIVE` | a connection covers this room |+| `DORMANT` | no connection covers this room, but the agent has a live `spawn_capable` connection |+| `DISCONNECTED` | no connection covers this room |++`NO_SESSION` and `AWAITING_MANUAL_POLL` are removed: both describe what an+agent was *declared* to be, not what is true. The explanatory nuance humans+see ("this agent is started manually" vs "this agent is offline") moves into+the auto-reply text, read from the agent's configuration at reply time.++`DORMANT` currently renders with a blank emoji in `!status` — fixed here.++### 8.2 Role leases++The lease moves onto the connection.++- Keyed on the connection, not globally on the agent.+- Kept alive by the connection heartbeat; `/leases/renew` is removed.+- Released when the connection dies — for a reason, not on a timer.+- One role per connection replaces one role per agent, so an agent with two+ sessions may hold different roles in different rooms.++Leases still survive room hops, because the connection does.++---++## 9. MCP++MCP remains the tool surface. Two ways to reach it, converging on **one+connection object** — the stream registers it, calls validate against it, the+heartbeat maintains it, its death releases everything.++**Only the stream can create a connection.** Calls through either door attach+to one; they never conjure one "to be helpful", which would reintroduce two+things that can disagree.++**Switch hosting an MCP server is the legacy path.** It remains supported, but+the direction of travel is a local runtime (§9.1): MCP the *protocol* is how an+agent calls tools and is not going anywhere; Switch being the one to *host* it+is what recedes.++### 9.1 Local MCP (recommended)++One process holds the stream and serves MCP over stdio. A tool call arrives+**inside the process that owns the connection**, so correlation is a variable+in memory — nothing to transmit, leak or get wrong. The connection id never+appears in a prompt or a config file, and the process can refuse a tool call+immediately when its own stream is down.++**This is what ships now.** The runtime lives in the plugin at+`connectors/claude-code-plugin/runtime`. It holds the stream, serves the whole+operation surface over stdio, and turns each tool call into+`POST /ops/{operation}` carrying its own connection id — so an agent never+talks to Switch directly and correlation is structural.++**Distribution is not solved yet.** A marketplace installs a plugin from its+own subtree (`source: ./connectors/claude-code-plugin`), so the runtime has to+sit *inside* the plugin to be installed with it — a sibling directory is not+copied and the path dangles. With a second connector plugin that means a+second copy, which is the thing worth avoiding. The answer is to publish the+runtime as a package each plugin depends on (the launcher already runs an+install step, so this is a small change), and that should happen before the+Codex plugin ships rather than after.++The operation list is fetched from the server at startup rather than hardcoded,+so the tool surface is whatever the server actually offers. If that fetch+fails the runtime refuses to start: an empty tool surface would look like+"Switch has nothing to offer" rather than a broken connection.++Planned second mode off the same code: *daemon* (long-lived, `scope: all`,+`spawn_capable`) alongside today's *session* mode (child of the agent,+`scope: single`).++- **Claude Code** — plugin `.mcp.json` at the plugin root, `${CLAUDE_PLUGIN_ROOT}`+ for the path, `${VAR}` expansion for endpoint and token.+- **Codex** — Codex expands neither, so switchdash registers the server on argv+ at launch. It controls the launch, so it can also inject per-session+ credentials.++### 9.2 Remote MCP (fallback)++Some hosts cannot run a local process — ChatGPT-style platforms require a+remote, publicly reachable HTTPS endpoint. They land on a reduced tier:++**Remote MCP with the agent's static token** — can act; holds no connection, no+room slot, no liveness, receives no pushed events. This is what `session_passive`+becomes, and it falls out of the model rather than being special-cased.++Correlating a remote MCP client to a stream is possible by minting a token per+connection and injecting it at launch, but that is deferred: it serves only the+fallback tier and costs minting, expiry, rotation and injection.++---++## 10. Client topologies++### 10.1 How a client knows which room a session is in++It asks; it does not observe.++Today switchdash learns a session's room by watching: a `PostToolUse` hook+fires after `connect_to_room` succeeds and switchdash records the room in its+own map, persisted to SQLite. The hook is accurate — the flaw is the *copy*. A+copy drifts when the session dies, when the connection fails after the tool+returned, when the server restarts, or when the room is deleted.++Under this design the session's own connection carries its subscription, and+that is authoritative. A client reads it from the local runtime it spawned+(same process as the connection) or from Switch. **The hook, the persisted+session→room blob, and the remote mirror all go away.**++Cross-checking a room against incoming events becomes unnecessary: a+connection only receives events for rooms it is subscribed to, and any change+— including a room going dark because another connection claimed it — arrives+as `subscription_changed`.++### 10.2 One connection per session, or one per agent++A connection is a socket, and a socket belongs to one process. Two terminal+sessions are two processes and therefore two connections; the count follows+from the topology, not from policy.++**Default: one connection per session.** A spawned session opens its own+`single`-scope connection; the daemon holds an `all`-scope one and only+notices uncovered rooms and spawns. This is the shape that already exists, it+isolates failure (the daemon dying does not disconnect running sessions), and+it keeps correlation structural.++**Optional later: one connection per agent.** A daemon may multiplex sessions+behind a single connection, serving them a local MCP endpoint and minting a+per-session token at spawn so it knows which session is calling. Switch does+not change: it sees one `all`-scope connection either way, and reachability+questions are answered from scope. This is a client-side optimisation, not a+protocol migration — but nothing else should hard-code one-socket-per-session+assumptions.++## 11. Backward compatibility++Polling clients must keep working. Both paths read the **same buffer**, so they+cannot diverge while both exist.++The old poll endpoint sends no cursor, so **the server keeps one on its+behalf**: "everything after the last thing I gave you, and record that I gave+it." Behaviour is unchanged for the old client — it polls, gets new events,+never sees a duplicate — but events are no longer destroyed for anyone else.++Two consequences, stated rather than hidden:++- Old clients keep **at-most-once** delivery, as today: the server advances the+ cursor on send, so a lost response loses those events. New clients get+ **at-least-once**, because they confirm.+- An old client that restarts has no cursor and cannot ask what it missed. It+ resumes wherever the server's cursor sits. Left honestly broken; the fix is+ to migrate the client.++`SWITCH_CHANNEL_DISABLE_POLL` can be deleted as soon as reads are+non-destructive — before SSE exists.++Polling endpoints are removed in a later, separate release.++---++## 12. Failure handling++Fail loud, never fake. Concretely:++| situation | behaviour |+|---|---|+| resume from a cursor older than the buffer | error: missed events, re-read context |+| buffer overflow | drop oldest, flag gap, `gap` event on next connection |+| heartbeat with no stream attached | reject: reopen the stream |+| call with unknown/dead `connection_id` | reject: reconnect and resume |+| `connection_id` belonging to another agent | reject |+| room slot already claimed | reject, naming the incumbent |+| slot taken over | incumbent receives `evicted` and stops |+| server restart | cursors invalidated; clients told to re-read |+| incompatible protocol version | refuse at open with an upgrade message |+| per-agent connection cap exceeded | reject loudly |++A connection that has silently missed events must never appear healthy.++---++## 13. Delivery plan++**Stage A — server plus one client.** *(implemented)*++1. Sequence numbers on events; bounded buffer with gap flag; old poll+ endpoints served from the buffer with a server-held cursor. No client+ changes.+2. Connection object, SSE endpoint, heartbeat, scope, filter, slots, the state+ machine of §5.3. Polling still works. Testable with `curl`.+3. Claude Code connector on the stream: connection id, resume by cursor, one+ heartbeat, room claimed on the connection.++4. HTTP operations front door (§7): every MCP tool reachable at+ `POST /ops/{operation}`, dispatched from the same registry so parity cannot+ drift. Unblocks the local runtime and closes the overlap with CHOO-490.++ **Still to do — merging the two MCP servers into one local runtime.** Now+ possible: the runtime serves the tool surface over stdio and translates each+ call to `POST /ops/${toolName}` on its own connection. Until it lands the+ plugin keeps registering the remote `switch` MCP server alongside the local+ channel.++**Stage B — migrate the clients. Nothing is removed.**++The server stays backward compatible until the clients are known to have moved,+so everything here is additive: a client still polling and still sending the+three renews is unaffected and unaware.++4. **Presence is the union of the heartbeat rows and the live connections.**+ *(implemented)* Presence was read only from `agent_sessions` and+ `role_leases` — the rows the pre-connection clients kept warm with+ `/connection/renew`, `/watch/heartbeat` and `/leases/renew`. A client on the+ single connection heartbeat sends none of those, so it would show+ DISCONNECTED and lose its role within six seconds of migrating, while alive+ on its stream. That, not the transport, is what blocks the client work.++ Every reader now takes both arms:++ | reader | connection arm |+ |---|---|+ | `compute_agent_statuses` | `live_agents` / `live_agents_in_room` OR-ed into each liveness set |+ | `AgentClient._is_available` | a covering connection means reachable |+ | `AgentClient` "sessions elsewhere" / `bound_here` | connection rooms merged with the bound rooms |+ | `auto_session` spawn reply | any live connection counts as watching |+ | `room_role_store` (6 predicates + `acquire_lease`) | `last_seen_at` fresh **OR** `agent_id` in `alive_agent_ids` |+ | `assemble_agent_detail` | connections listed as sessions, `lifecycle: "connection"` |++ Neither arm alone is correct while both kinds of client exist. Stage C+ deletes the DB arm and what remains is this code minus one branch — which is+ why the union goes in now rather than a write-shim that would be thrown away.++ `connections` is a **required** argument on `compute_agent_statuses` and+ `assemble_agent_detail`: a call site that forgot it would report a migrated+ agent as offline, and nothing at the call site would show it. Pass an empty+ registry to mean "DB arm only". The store-level predicates default+ `alive_agent_ids` to empty, since the store is a query layer with no registry+ to hand and its own tests exercise the freshness rule directly.++ One registry is created in `main.py` and injected into `AgentClient`,+ `AdminClient` and the bridge app — the Matrix clients are wired before the+ bridge, so the bridge could no longer own it.++5. switchdash (`RoomConnection` → session-grained connection that repoints+ rooms; daemon mode) and the sidecar, which reuses the same class verbatim —+ `sidecar-runtime.ts` constructs `RoomConnection` directly, so the two migrate+ together rather than separately. The `auto_session` watcher's+ `/notifications` poll folds into an `all`-scope connection, and its three+ heartbeat loops collapse into one beat.++ Note `RoomConnection` has no client-side cursor today: the poll URL carries+ only `timeout` and the server drains the queue on read. Resume is something+ this migration *adds*, not something it has to preserve.++**Stage C — the removals. Gated on the clients having transitioned.**++6. Remove `connection_model`; derive statuses from connections alone; move role+ leases onto the connection; delete the three renew endpoints and the DB arm+ of every union above.+7. Remove the polling endpoints.++Opportunistic, both relevant to this work: the `DORMANT` display bug, and+`read_context`'s deep-history pagination, which discards Matrix's continuation+token and so cannot page past roughly `limit * 5` events — this matters more+once "re-read context" is the documented recovery path for a gap.++Both connector skills (`claude-code-plugin`, `codex-plugin`) and both plugin+versions must be updated when the agent-facing contract changes.++---++## 14. Related work++- **CHOO-490** — HTTP protocol parity. Overlaps directly; this document is the+ contract both should serve.+- **CHOO-1810** — two notification builders. Closed by §2.3: one delivery path+ with a declared filter.+- **CHOO-1685** — AG-UI. Not addressed; the event envelope is versioned and+ additive so it stays landable.+- **CHOO-1101 / CHOO-1366 / CHOO-1811** — bugs caused by the polling model.+ Useful as tests of whether this design makes them impossible rather than+ merely fixed.