diff --git a/README.md b/README.md index e32bf821c..0308d304f 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ | Install nanobot with no terminal/config background | [Start Without Technical Background](./docs/start-without-technical-background.md) | | Install quickly and get one CLI reply | [Install](#-install) and [Quick Start](#-quick-start) | | Open the bundled browser UI | [WebUI](#-webui) | -| Connect Telegram, Discord, WeChat, Slack, Email, Mattermost, or another chat app | [Chat Apps](./docs/chat-apps.md) | +| Connect Telegram, Discord, WeChat, Slack, Email, Mattermost, Linear, or another channel | [Chat Apps](./docs/chat-apps.md) | | Configure providers, fallback models, Langfuse, MCP, web tools, or security | [Docs](./docs/README.md) and [Configuration](./docs/configuration.md) | | Understand or extend the internals | [Architecture](./docs/architecture.md) and [Development](./docs/development.md) | | Deploy to the cloud or keep nanobot running as a service | [Deployment](./docs/deployment.md) | @@ -53,7 +53,7 @@ nanobot is a self-hosted personal AI agent runtime. It can: - run in a browser WebUI or terminal -- connect to Telegram, Discord, Slack, WeChat, Email, Mattermost, and other chat apps +- connect to Telegram, Discord, Slack, WeChat, Email, Mattermost, Linear, and other channels - use tools such as files, shell, web search, web fetch, MCP, cron, image generation, and subagents - keep session history and long-term memory through Dream - run long-horizon goals and scheduled automations @@ -63,7 +63,7 @@ nanobot is a self-hosted personal AI agent runtime. It can: ## 💡 Why nanobot - **Persistent workflows**: goals, memory, tools, and chat context survive long-running work. -- **Chat-native reach**: WebUI, API, Telegram, Feishu, Slack, Discord, Teams, email, and Mattermost. +- **Chat-native reach**: WebUI, API, Telegram, Feishu, Slack, Discord, Teams, email, Mattermost, and Linear. - **Model freedom**: OpenAI-compatible APIs, local LLMs, image generation, search, and fallbacks. - **Small core**: readable internals with MCP, memory, deployment, and automation built in. - **Own your stack**: inspect, customize, self-host, and extend without a giant platform. diff --git a/docs/chat-apps.md b/docs/chat-apps.md index 91f8dd53d..e87dcac8a 100644 --- a/docs/chat-apps.md +++ b/docs/chat-apps.md @@ -1,6 +1,6 @@ # Chat Apps for Self-Hosted AI Agents -Connect nanobot to Telegram, Discord, Slack, WeChat, Email, Mattermost, and +Connect nanobot to Telegram, Discord, Slack, WeChat, Email, Mattermost, Linear, and other chat platforms. This page is the full chat-channel reference. If you want a focused setup path for one platform, start with a guide: @@ -15,6 +15,7 @@ a focused setup path for one platform, start with a guide: | QQ | [Build a QQ AI Agent with nanobot](./guides/qq-ai-agent.md) | | Email | [Build an Email AI Agent with nanobot](./guides/email-ai-agent.md) | | Mattermost | [Build a Mattermost AI Agent with nanobot](./guides/mattermost-ai-agent.md) | +| Linear | [Use nanobot as a native Linear agent](./guides/linear-agent.md) | Want to build your own channel? See the [Channel Package Guide](./channel-package-guide.md). @@ -105,6 +106,32 @@ If `nanobot channels status` does not show the channel as enabled, the config sn | **Microsoft Teams** | App ID + App Password + public HTTPS endpoint | | **Mochat** | Claw token (auto-setup available) | | **Signal** | signal-cli daemon + phone number | +| **Linear** | Private OAuth app + public HTTPS callback URL | + +
+Linear + +Linear is a native Agent channel rather than a comment bot. A user starts a task +by explicitly mentioning the installed nanobot app in an issue. Follow-up prompts +inside that Agent Session continue the same nanobot session without another +mention. Ordinary issue comments do not invoke nanobot. + +The native Agent API is webhook-based. Linear must reach a stable HTTPS URL, but +the machine running nanobot does not need its own public IP address: a reverse +proxy, Cloudflare Tunnel, Tailscale Funnel, or another HTTPS tunnel can forward +the public URL to nanobot's local listener. + +The recommended setup is **Settings → Channels → Linear**. Save the public URL +first to reveal a prefilled private OAuth app link, create the app, copy its Client +ID, Client Secret, and Webhook Signing Secret back into nanobot, save again, then +choose **Connect Linear**. OAuth requests only `read`, `write`, and +`app:mentionable`; it deliberately does not request `app:assignable` so a new task +must begin with an @mention. + +See the [native Linear agent guide](./guides/linear-agent.md) for the complete +setup, tunnel examples, security model, and troubleshooting. + +
Telegram diff --git a/docs/guides/README.md b/docs/guides/README.md index a21c3951e..8bc53bb6b 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -28,6 +28,7 @@ Use **Settings → Channels** in the WebUI for guided setup. These guides explai | Connect QQ | [QQ AI agent](./qq-ai-agent.md) | | Connect Email | [Email AI agent](./email-ai-agent.md) | | Connect Mattermost | [Mattermost AI agent](./mattermost-ai-agent.md) | +| Connect Linear | [Native Linear agent](./linear-agent.md) | ## Integrate from Code diff --git a/docs/guides/linear-agent.md b/docs/guides/linear-agent.md new file mode 100644 index 000000000..9400905cb --- /dev/null +++ b/docs/guides/linear-agent.md @@ -0,0 +1,265 @@ +# Connect nanobot as a Native Linear Agent + +This guide takes you from an empty Linear channel configuration to a working +@mention in an issue. The recommended path uses the nanobot WebUI and a +pre-filled Linear app manifest, so you do not need to enter callback URLs or +webhook subscriptions by hand. + +> [!NOTE] +> Linear's Agent APIs are currently a Developer Preview. Their schema may +> change. Keep nanobot current when you use this channel. + +## What this channel does + +- A new task starts only when someone explicitly @mentions the installed app. +- An ordinary issue comment does not invoke nanobot. +- A follow-up inside the existing Agent Session continues the same nanobot + session without another @mention. +- Linear's stop control cancels the active nanobot turn. +- nanobot reports its acknowledgement, tool activity, reasoning, and final + answer as native Linear Agent Activities. + +The OAuth request includes `app:mentionable` and deliberately excludes +`app:assignable`. Do not add `app:assignable` if every new task must start with +an @mention. + +Linear MCP is optional. Add it when the agent also needs tools for searching or +changing Linear issues. MCP does not replace this channel's OAuth installation, +webhook, or Agent Session transport. + +## Before you start + +Prepare these four things: + +| Requirement | What you need | +|---|---| +| Working nanobot | `nanobot agent -m "Hello"` returns a response | +| Linear access | Permission to create a private OAuth app; a workspace admin must approve its installation | +| Public HTTPS origin | A stable address such as `https://nanobot.example.com` | +| Local route | The public address forwards to nanobot's Linear listener, which defaults to port `3979` | + +The public address is an **origin**, not a complete endpoint. Enter +`https://nanobot.example.com`, not +`https://nanobot.example.com/linear/webhook`. + +The four network fields have different jobs: + +| nanobot field | Who uses it | Recommended value | +|---|---|---| +| **Public HTTPS URL** | Linear calls this address over the internet | Your stable HTTPS origin | +| **Listen host** | nanobot binds this local interface | `127.0.0.1` for a same-machine proxy; `0.0.0.0` when a container or another host must reach it | +| **Listen port** | The proxy or tunnel forwards to this local port | Keep `3979` unless it conflicts with another service | +| **Webhook/OAuth paths** | nanobot distinguishes webhook delivery from OAuth callbacks | Keep the defaults unless your proxy requires different paths | + +### Webhook and networking requirements + +The native Linear Agent transport requires a webhook; there is no polling mode. +The OAuth callback also needs to reach the same nanobot instance. + +You do **not** need a public IP address. A reverse proxy or HTTPS tunnel can +forward a public hostname to `127.0.0.1:3979`. Cloudflare Tunnel, Tailscale +Funnel, Caddy, nginx, and similar tools can all provide this route. Use a stable +hostname for normal use: if the hostname changes, you must update both URLs in +the Linear app. + +Choose the simplest option that matches your deployment: + +| Your deployment | Recommended route | +|---|---| +| Home server, laptop, or a network behind NAT | A named HTTPS tunnel with a fixed hostname | +| VPS with a domain and existing HTTPS proxy | Add a reverse-proxy route to `127.0.0.1:3979` | +| Docker or Kubernetes | Route the ingress or proxy to the container's port `3979`; keep the public URL on the ingress | +| Short local test | A temporary HTTPS tunnel works, but you must recreate or edit the Linear app when its hostname changes | + +With the default paths, the route must preserve these two requests: + +```text +https://nanobot.example.com/linear/oauth/callback -> 127.0.0.1:3979 +https://nanobot.example.com/linear/webhook -> 127.0.0.1:3979 +``` + +If the proxy or tunnel runs on the same machine, set the advanced **Listen +host** field to `127.0.0.1` so the listener is not exposed directly on the local +network. Containers and separate reverse-proxy hosts may require `0.0.0.0`. +The Linear listener serves plain HTTP locally; terminate HTTPS at the proxy or +tunnel instead of exposing port `3979` directly to the internet. + +## Recommended setup in the WebUI + +Keep `nanobot webui` running throughout the setup. + +### 1. Save the public address + +1. Open **Settings → Channels → Linear**. +2. Enter your stable origin in **Public HTTPS URL**, for example + `https://nanobot.example.com`. +3. Leave the three OAuth credential fields empty for now. +4. Select **Save settings**. nanobot saves the partial configuration and shows + **Create prefilled Linear app**. + +Saving a partial configuration at this point is expected. You will create the +credentials in the next step. + +### 2. Create the Linear app + +1. Select **Create prefilled Linear app**. Sign in to the Linear workspace in + which you want to create the app. +2. Review the pre-filled form. It should describe a **private** app and contain: + + ```text + Redirect URI: https://nanobot.example.com/linear/oauth/callback + Webhook URL: https://nanobot.example.com/linear/webhook + Webhook types: AgentSessionEvent, PermissionChange, OAuthAuthorization + ``` + +3. Choose a short, recognizable app name and icon if you want to customize how + nanobot appears in Linear. +4. Create the app. + +Do not add a `Comment` webhook subscription. Linear delivers new @mentions and +Agent Session follow-ups through `AgentSessionEvent`; subscribing to comments +would add events that this channel intentionally ignores. + +### 3. Copy the three credentials into nanobot + +In the new Linear app's settings, copy these values: + +| Linear value | nanobot field | +|---|---| +| Client ID | **OAuth client ID** | +| Client Secret | **OAuth client secret** | +| Webhook signing secret | **Webhook signing secret** | + +Return to **Settings → Channels → Linear**, paste all three values, and select +**Save settings** again. A successful validation lists the complete webhook and +OAuth callback URLs. + +Treat the Client Secret and Webhook signing secret like passwords. They belong +only in the nanobot configuration and the Linear application settings. + +### 4. Authorize the workspace + +1. Select **Connect Linear**. +2. Open the displayed authorization link, or scan the QR code. +3. Choose the workspace and approve the installation as a workspace admin. +4. Return to nanobot and wait for **Linear is connected**. + +nanobot enables the channel automatically after authorization. The gateway must +remain running so Linear can deliver webhooks. To replace an authorization, use +the reconnect action and approve it again. + +The pre-filled manifest creates a private app for the current workspace. A +distributable OAuth app can authorize additional workspaces; nanobot stores and +refreshes each workspace installation separately. + +### 5. Test the first task + +1. Open an issue in the connected Linear workspace. +2. Add a comment that @mentions the app and includes a request, for example: + + ```text + @nanobot summarize the likely cause and suggest the next diagnostic step + ``` + +3. Open the Agent Session. You should first see a starting acknowledgement, + followed by agent activity and a final response. +4. Send a follow-up inside that Agent Session. You do not need to @mention the + app again there. + +If **Allowed Linear users** is empty, the first mention returns a nanobot pairing +code. Approve the pending request in the WebUI pairing dialog, then repeat the +prompt in the same Agent Session. For a static allowlist, enter Linear user IDs +in **Allowed Linear users**. Enter `*` only if every member of every connected +workspace should be able to invoke the agent. + +## Verify the setup + +The setup is complete when all of these checks pass: + +- **Settings → Channels → Linear** shows the channel as on with no runtime error. +- While the channel is running, opening + `http://127.0.0.1:3979/linear/health` on the nanobot machine returns + `{"ok":true}`. Use your configured host and port if you changed them. +- A new comment with an explicit @mention creates an Agent Session and receives + a response. +- A normal issue comment without an @mention does nothing. +- A follow-up inside the Agent Session receives a response without another + @mention. + +## Manual configuration + +Use this path when deployment tooling manages `~/.nanobot/config.json` directly. +The WebUI path above is easier because it generates the Linear app definition +and completes OAuth for you. + +Merge this section into `~/.nanobot/config.json`: + +```json +{ + "channels": { + "linear": { + "enabled": true, + "clientId": "YOUR_LINEAR_CLIENT_ID", + "clientSecret": "YOUR_LINEAR_CLIENT_SECRET", + "webhookSigningSecret": "YOUR_LINEAR_WEBHOOK_SIGNING_SECRET", + "publicBaseUrl": "https://nanobot.example.com", + "host": "127.0.0.1", + "port": 3979, + "webhookPath": "/linear/webhook", + "oauthCallbackPath": "/linear/oauth/callback", + "allowFrom": ["YOUR_LINEAR_USER_ID"] + } + } +} +``` + +Register these exact URLs in the Linear OAuth app: + +```text +OAuth callback: https://nanobot.example.com/linear/oauth/callback +Webhook: https://nanobot.example.com/linear/webhook +``` + +Subscribe the webhook to exactly `AgentSessionEvent`, `PermissionChange`, and +`OAuthAuthorization`. Do not subscribe to `Comment`. The OAuth connection step +in the WebUI is still required: it installs the app and stores the +workspace-scoped access and refresh tokens. + +## Security and reliability + +- OAuth uses authorization code flow, PKCE, a short-lived CSRF state, and the + Linear app actor. +- Webhooks are verified against `Linear-Signature` using the raw request body + before JSON parsing. nanobot also checks the delivery timestamp and configured + OAuth Client ID. +- `Linear-Delivery` IDs are deduplicated. +- Verified events are committed to a local SQLite queue before nanobot returns + HTTP 200. Pending work resumes after a restart. +- Access and rotating refresh tokens are stored in the Linear channel state + database, not in `config.json` or the browser. +- OAuth revocation removes the affected workspace installation locally. + +Back up the nanobot instance data directory as carefully as other credentials. +Do not publish `linear/state.sqlite3`, the Client Secret, or the Webhook signing +secret. + +## Troubleshooting + +| Symptom | What to check | +|---|---| +| **Create prefilled Linear app** is missing | Enter only the public HTTPS origin in **Public HTTPS URL**, then select **Save settings**. | +| Linear rejects the callback or webhook URL | Use a stable public `https://` hostname. Do not use HTTP, localhost, a private IP, or a path in **Public HTTPS URL**. | +| OAuth opens but cannot finish | Keep `nanobot webui` running. Confirm the proxy forwards `/linear/oauth/callback` to the configured listen host and port. Then start **Connect Linear** again. | +| OAuth finishes in Linear but nanobot keeps waiting | The callback reached a different nanobot process or URL. Compare the app's Redirect URI with the callback URL shown by nanobot. | +| The local health URL does not load | Start **Connect Linear** or enable the connected channel, then check the configured listen host and port. | +| An @mention gets no response | Confirm `AgentSessionEvent` is subscribed, the Client ID and signing secret match the same app, and the workspace authorization has not been revoked. Run `nanobot gateway logs` for the exact error. | +| The first @mention returns a pairing code | Approve it in the WebUI pairing dialog, then repeat the prompt in the same Agent Session. Alternatively, configure a narrow **Allowed Linear users** list. | +| Normal comments do nothing | This is intentional. Start a task by @mentioning the app, or continue inside an existing Agent Session. | +| Issues can be delegated to the app without an @mention | Remove `app:assignable`, reconnect the workspace, and use nanobot's built-in OAuth flow, which requests only `read`, `write`, and `app:mentionable`. | +| Authorization reports missing scopes | Reconnect from nanobot. Do not reuse an authorization URL that omits `read`, `write`, or `app:mentionable`. | + +For Linear's platform-side behavior, see the official +[Agents guide](https://linear.app/developers/agents), +[OAuth app manifest reference](https://linear.app/developers/oauth-app-manifests), +[OAuth guide](https://linear.app/developers/oauth-2-0-authentication), and +[webhook reference](https://linear.app/developers/webhooks). diff --git a/nanobot/channels/linear/__init__.py b/nanobot/channels/linear/__init__.py new file mode 100644 index 000000000..c921582fc --- /dev/null +++ b/nanobot/channels/linear/__init__.py @@ -0,0 +1 @@ +"""Native Linear Agent channel.""" diff --git a/nanobot/channels/linear/client.py b/nanobot/channels/linear/client.py new file mode 100644 index 000000000..543ac4498 --- /dev/null +++ b/nanobot/channels/linear/client.py @@ -0,0 +1,324 @@ +"""Minimal async Linear OAuth and GraphQL client.""" + +from __future__ import annotations + +import asyncio +import time +from typing import Any, cast + +import httpx + +from nanobot.channels.linear.config import LinearConfig +from nanobot.channels.linear.oauth import LINEAR_SCOPES +from nanobot.channels.linear.state import LinearInstallation, LinearStateStore + +LINEAR_GRAPHQL_URL = "https://api.linear.app/graphql" +LINEAR_TOKEN_URL = "https://api.linear.app/oauth/token" + + +class LinearApiError(RuntimeError): + """Linear returned a transport, authentication, or GraphQL error.""" + + def __init__( + self, + message: str, + *, + retryable: bool = False, + retry_after: float | None = None, + ) -> None: + super().__init__(message) + self.retryable = retryable + self.retry_after = retry_after + + +class LinearClient: + def __init__( + self, + config: LinearConfig, + state: LinearStateStore, + http: httpx.AsyncClient | None = None, + ) -> None: + self.config = config + self.state = state + self._http = http or httpx.AsyncClient(timeout=30.0) + self._owns_http = http is None + self._refresh_locks: dict[str, asyncio.Lock] = {} + + async def close(self) -> None: + if self._owns_http: + await self._http.aclose() + + async def exchange_code(self, code: str, verifier: str) -> LinearInstallation: + token = await self._token_request( + { + "grant_type": "authorization_code", + "code": code, + "redirect_uri": self.config.redirect_uri, + "client_id": self.config.client_id, + "client_secret": self.config.client_secret, + "code_verifier": verifier, + } + ) + access_token = _required_string(token, "access_token") + identity = await self._graphql_with_token( + access_token, + "query NanobotLinearIdentity { viewer { id organization { id name } } }", + {}, + ) + viewer = _required_mapping(identity, "viewer") + organization = _required_mapping(viewer, "organization") + scopes = _scopes(token.get("scope")) + missing_scopes = set(LINEAR_SCOPES) - set(scopes) + if missing_scopes: + raise LinearApiError( + "Linear authorization is missing required scope(s): " + + ", ".join(sorted(missing_scopes)) + ) + installation = LinearInstallation( + organization_id=_required_string(organization, "id"), + oauth_client_id=self.config.client_id, + organization_name=str(organization.get("name") or ""), + app_user_id=_required_string(viewer, "id"), + access_token=access_token, + refresh_token=_required_string(token, "refresh_token"), + expires_at=time.time() + _expires_in(token), + scope=scopes, + ) + self.state.save_installation(installation) + return installation + + async def graphql( + self, + organization_id: str, + query: str, + variables: dict[str, Any], + ) -> dict[str, Any]: + installation = await self._fresh_installation(organization_id) + try: + return await self._graphql_with_token(installation.access_token, query, variables) + except LinearApiError as exc: + if "authentication" not in str(exc).lower(): + raise + installation = await self._refresh(organization_id, force=True) + return await self._graphql_with_token(installation.access_token, query, variables) + + async def create_activity( + self, + organization_id: str, + agent_session_id: str, + content: dict[str, Any], + *, + activity_id: str, + ephemeral: bool = False, + ) -> None: + data = await self.graphql( + organization_id, + """ + mutation NanobotAgentActivityCreate($input: AgentActivityCreateInput!) { + agentActivityCreate(input: $input) { success agentActivity { id } } + } + """, + { + "input": { + "id": activity_id, + "agentSessionId": agent_session_id, + "content": content, + "ephemeral": ephemeral, + } + }, + ) + result = _required_mapping(data, "agentActivityCreate") + if result.get("success") is not True: + raise LinearApiError("Linear did not accept the agent activity") + + async def _fresh_installation(self, organization_id: str) -> LinearInstallation: + installation = self.state.installation(organization_id) + if installation is None: + raise LinearApiError( + f"No Linear OAuth installation for organization {organization_id}" + ) + if installation.oauth_client_id != self.config.client_id: + raise LinearApiError( + "The Linear workspace was authorized for a different OAuth Client ID; reconnect it" + ) + if installation.expires_at <= time.time() + 60: + return await self._refresh(organization_id) + return installation + + async def _refresh(self, organization_id: str, *, force: bool = False) -> LinearInstallation: + lock = self._refresh_locks.setdefault(organization_id, asyncio.Lock()) + async with lock: + installation = self.state.installation(organization_id) + if installation is None: + raise LinearApiError( + f"No Linear OAuth installation for organization {organization_id}" + ) + if not force and installation.expires_at > time.time() + 60: + return installation + token = await self._token_request( + { + "grant_type": "refresh_token", + "refresh_token": installation.refresh_token, + "client_id": self.config.client_id, + "client_secret": self.config.client_secret, + } + ) + refreshed = LinearInstallation( + organization_id=installation.organization_id, + oauth_client_id=installation.oauth_client_id, + organization_name=installation.organization_name, + app_user_id=installation.app_user_id, + access_token=_required_string(token, "access_token"), + refresh_token=_required_string(token, "refresh_token"), + expires_at=time.time() + _expires_in(token), + scope=_scopes(token.get("scope")) or installation.scope, + ) + missing_scopes = set(LINEAR_SCOPES) - set(refreshed.scope) + if missing_scopes: + raise LinearApiError( + "Refreshed Linear authorization is missing required scope(s): " + + ", ".join(sorted(missing_scopes)) + ) + self.state.save_installation(refreshed) + return refreshed + + async def _token_request(self, form: dict[str, str]) -> dict[str, Any]: + try: + response = await self._http.post(LINEAR_TOKEN_URL, data=form) + except httpx.HTTPError as exc: + raise LinearApiError(f"Linear OAuth request failed: {exc}", retryable=True) from exc + payload = _response_object(response) + if response.is_error: + detail = str(payload.get("error_description") or payload.get("error") or response.status_code) + raise LinearApiError( + f"Linear OAuth request failed: {detail}", + retryable=response.status_code == 429 or response.status_code >= 500, + retry_after=_retry_after_seconds(response), + ) + return payload + + async def _graphql_with_token( + self, + access_token: str, + query: str, + variables: dict[str, Any], + ) -> dict[str, Any]: + try: + response = await self._http.post( + LINEAR_GRAPHQL_URL, + headers={"Authorization": f"Bearer {access_token}"}, + json={"query": query, "variables": variables}, + ) + except httpx.HTTPError as exc: + raise LinearApiError(f"Linear API request failed: {exc}", retryable=True) from exc + if response.status_code in {401, 403}: + raise LinearApiError("Linear authentication failed") + payload = _response_object(response) + errors = payload.get("errors") + if isinstance(errors, list) and errors: + messages: list[str] = [] + retryable = False + for raw_error in cast(list[object], errors): + if isinstance(raw_error, dict): + error = cast(dict[str, Any], raw_error) + message = str(error.get("message") or "GraphQL error") + messages.append(message) + extensions = error.get("extensions") + code = ( + str(cast(dict[str, Any], extensions).get("code") or "").upper() + if isinstance(extensions, dict) + else "" + ) + retryable = retryable or code in { + "INTERNAL_ERROR", + "INTERNAL_SERVER_ERROR", + "RATELIMITED", + "SERVICE_UNAVAILABLE", + } or "internal" in message.lower() + message = "; ".join(messages) or "GraphQL error" + raise LinearApiError( + message, + retryable=retryable, + retry_after=_retry_after_seconds(response) if retryable else None, + ) + if response.is_error: + raise LinearApiError( + f"Linear API request failed with HTTP {response.status_code}", + retryable=response.status_code == 429 or response.status_code >= 500, + retry_after=_retry_after_seconds(response), + ) + data = payload.get("data") + if not isinstance(data, dict): + raise LinearApiError("Linear API response did not contain data") + return cast(dict[str, Any], data) + + +def _response_object(response: httpx.Response) -> dict[str, Any]: + retryable = response.status_code == 429 or response.status_code >= 500 + try: + value: object = response.json() + except ValueError as exc: + raise LinearApiError( + "Linear returned a non-JSON response", + retryable=retryable, + retry_after=_retry_after_seconds(response) if retryable else None, + ) from exc + if not isinstance(value, dict): + raise LinearApiError( + "Linear returned an invalid JSON response", + retryable=retryable, + retry_after=_retry_after_seconds(response) if retryable else None, + ) + return cast(dict[str, Any], value) + + +def _retry_after_seconds(response: httpx.Response) -> float | None: + raw_retry_after = response.headers.get("Retry-After", "").strip() + try: + retry_after = float(raw_retry_after) + except ValueError: + retry_after = -1.0 + if retry_after >= 0: + return retry_after + for header in ( + "X-RateLimit-Endpoint-Requests-Reset", + "X-RateLimit-Requests-Reset", + "X-RateLimit-Complexity-Reset", + ): + raw_reset = response.headers.get(header, "").strip() + try: + reset = float(raw_reset) + except ValueError: + continue + reset_seconds = reset / 1000 if reset > 10_000_000_000 else reset + return max(0.0, reset_seconds - time.time()) + return None + + +def _required_mapping(value: dict[str, Any], key: str) -> dict[str, Any]: + item = value.get(key) + if not isinstance(item, dict): + raise LinearApiError(f"Linear response is missing {key}") + return cast(dict[str, Any], item) + + +def _required_string(value: dict[str, Any], key: str) -> str: + item = value.get(key) + if not isinstance(item, str) or not item: + raise LinearApiError(f"Linear response is missing {key}") + return item + + +def _expires_in(value: dict[str, Any]) -> float: + expires = value.get("expires_in") + if isinstance(expires, int | float) and not isinstance(expires, bool): + return max(60.0, float(expires)) + return 86400.0 + + +def _scopes(value: object) -> tuple[str, ...]: + if isinstance(value, str): + return tuple(item for item in value.replace(",", " ").split() if item) + if isinstance(value, list): + return tuple(str(item) for item in cast(list[object], value)) + return () diff --git a/nanobot/channels/linear/config.py b/nanobot/channels/linear/config.py new file mode 100644 index 000000000..809ffb59e --- /dev/null +++ b/nanobot/channels/linear/config.py @@ -0,0 +1,100 @@ +"""Configuration and URL validation for the native Linear channel.""" + +from __future__ import annotations + +import ipaddress +from urllib.parse import urlparse + +from pydantic import Field, field_validator, model_validator + +from nanobot.config_base import Base + +DEFAULT_PORT = 3979 +DEFAULT_WEBHOOK_PATH = "/linear/webhook" +DEFAULT_OAUTH_CALLBACK_PATH = "/linear/oauth/callback" + + +class LinearConfig(Base): + """Linear OAuth app and local webhook listener settings.""" + + enabled: bool = False + client_id: str = "" + client_secret: str = "" + webhook_signing_secret: str = "" + public_base_url: str = "" + host: str = "0.0.0.0" + port: int = Field(default=DEFAULT_PORT, ge=1, le=65535) + webhook_path: str = DEFAULT_WEBHOOK_PATH + oauth_callback_path: str = DEFAULT_OAUTH_CALLBACK_PATH + allow_from: list[str] = Field(default_factory=list) + send_progress: bool = True + send_tool_hints: bool = True + show_reasoning: bool = True + + @field_validator("webhook_path", "oauth_callback_path") + @classmethod + def validate_path(cls, value: str) -> str: + path = value.strip() + if not path.startswith("/") or "?" in path or "#" in path: + raise ValueError("must be an absolute URL path without a query or fragment") + return path.rstrip("/") or "/" + + @field_validator("public_base_url") + @classmethod + def normalize_public_base_url(cls, value: str) -> str: + raw = value.strip() + return validate_public_base_url(raw) if raw else "" + + @model_validator(mode="after") + def validate_distinct_paths(self) -> LinearConfig: + if self.webhook_path == self.oauth_callback_path: + raise ValueError("Linear webhookPath and oauthCallbackPath must be different") + return self + + def validate_runtime(self) -> None: + missing = [ + label + for label, value in ( + ("clientId", self.client_id), + ("clientSecret", self.client_secret), + ("webhookSigningSecret", self.webhook_signing_secret), + ("publicBaseUrl", self.public_base_url), + ) + if not value.strip() + ] + if missing: + raise ValueError("Missing Linear setting(s): " + ", ".join(missing)) + + @property + def redirect_uri(self) -> str: + return self.public_base_url.rstrip("/") + self.oauth_callback_path + + @property + def webhook_url(self) -> str: + return self.public_base_url.rstrip("/") + self.webhook_path + + +def validate_public_base_url(value: str) -> str: + """Require the externally reachable HTTPS origin Linear expects.""" + raw = value.strip() + parsed = urlparse(raw) + if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password: + raise ValueError("publicBaseUrl must be an HTTPS origin, for example https://bot.example.com") + if parsed.path not in {"", "/"} or parsed.query or parsed.fragment: + raise ValueError("publicBaseUrl must not include a path, query, or fragment") + try: + parsed.port + except ValueError as exc: + raise ValueError("publicBaseUrl contains an invalid port") from exc + if parsed.netloc.endswith(":") or any(character.isspace() for character in parsed.netloc): + raise ValueError("publicBaseUrl contains an invalid host or port") + host = parsed.hostname.lower() + if host == "localhost" or host.endswith(".localhost"): + raise ValueError("publicBaseUrl must be public; localhost is not accepted by Linear") + try: + address = ipaddress.ip_address(host) + except ValueError: + address = None + if address is not None and not address.is_global: + raise ValueError("publicBaseUrl must not use a private or loopback IP address") + return raw.rstrip("/") diff --git a/nanobot/channels/linear/connect.py b/nanobot/channels/linear/connect.py new file mode 100644 index 000000000..8029aedc1 --- /dev/null +++ b/nanobot/channels/linear/connect.py @@ -0,0 +1,175 @@ +"""WebUI OAuth connection flow for Linear workspace installations.""" + +from __future__ import annotations + +import asyncio +import time +from dataclasses import dataclass, field +from typing import Any, cast + +from nanobot.channels.connect import ChannelConnectError, QueryParams, query_first +from nanobot.channels.linear.client import LinearApiError, LinearClient +from nanobot.channels.linear.config import LinearConfig +from nanobot.channels.linear.oauth import ( + FLOW_TTL_SECONDS, + OAUTH_FLOWS, + LinearOAuthFlow, + authorization_url, +) +from nanobot.channels.linear.server import LinearServerLease, acquire_http_server +from nanobot.channels.linear.state import LinearStateStore +from nanobot.config.loader import load_config + + +@dataclass(slots=True) +class LinearConnectSession: + flow: LinearOAuthFlow + config: LinearConfig + state: LinearStateStore + server: LinearServerLease + completion_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False) + + +class LinearConnectStore: + """Keep short-lived OAuth browser sessions in the gateway process.""" + + def __init__(self) -> None: + self._sessions: dict[str, LinearConnectSession] = {} + + async def handle(self, action: str, query: QueryParams) -> dict[str, Any]: + await self._cleanup() + if action == "start": + return await self.start(force=_query_bool(query, "force")) + session_id = (query_first(query, "session_id") or "").strip() + if not session_id: + raise ChannelConnectError("missing Linear connect session") + if action == "poll": + return await self.poll(session_id) + if action == "cancel": + return await self.cancel(session_id) + raise ChannelConnectError(f"unsupported Linear connect action: {action}", status=404) + + async def start(self, *, force: bool = False) -> dict[str, Any]: + config = _load_linear_config() + try: + config.validate_runtime() + except ValueError as exc: + raise ChannelConnectError(str(exc)) from exc + state = LinearStateStore() + if state.has_installations(config.client_id) and not force: + return { + "session_id": "", + "status": "succeeded", + "message": "Linear is already connected. Use reconnect to add or replace a workspace.", + } + flow = OAUTH_FLOWS.create() + try: + lease = await asyncio.to_thread(acquire_http_server, config, state) + except (OSError, RuntimeError) as exc: + OAUTH_FLOWS.remove(flow) + raise ChannelConnectError( + f"Unable to start the Linear callback listener on {config.host}:{config.port}: {exc}", + status=502, + ) from exc + self._sessions[flow.session_id] = LinearConnectSession( + flow=flow, + config=config, + state=state, + server=lease, + ) + return { + "session_id": flow.session_id, + "status": "pending", + "authorization_url": authorization_url(config, flow), + "qr_url": authorization_url(config, flow), + "redirect_uri": config.redirect_uri, + "webhook_url": config.webhook_url, + "interval_ms": 1500, + "expires_at_ms": int((flow.created_at + FLOW_TTL_SECONDS) * 1000), + "message": "Authorize the nanobot app in Linear.", + } + + async def poll(self, session_id: str) -> dict[str, Any]: + session = self._sessions.get(session_id) + if session is None: + return _terminal(session_id, "expired", "This Linear authorization has expired.") + async with session.completion_lock: + if self._sessions.get(session_id) is not session: + return _terminal(session_id, "cancelled", "Linear authorization cancelled.") + flow = session.flow + if time.monotonic() >= flow.deadline: + await self._close_session(session_id) + return _terminal(session_id, "expired", "This Linear authorization has expired.") + if flow.error: + message = "Linear authorization was cancelled." + await self._close_session(session_id) + return _terminal(session_id, "failed", message) + if not flow.code: + return { + "session_id": session_id, + "status": "pending", + "interval_ms": 1500, + "expires_at_ms": int((flow.created_at + FLOW_TTL_SECONDS) * 1000), + "message": "Waiting for Linear authorization.", + } + + client = LinearClient(session.config, session.state) + try: + installation = await client.exchange_code(flow.code, flow.verifier) + except LinearApiError as exc: + await self._close_session(session_id) + return _terminal( + session_id, + "failed", + f"Linear authorization could not be completed: {exc}", + ) + finally: + await client.close() + await self._close_session(session_id) + return { + "session_id": session_id, + "status": "succeeded", + "message": "Linear is connected.", + "organization_id": installation.organization_id, + "organization_name": installation.organization_name, + } + + async def cancel(self, session_id: str) -> dict[str, Any]: + session = self._sessions.get(session_id) + if session is not None: + async with session.completion_lock: + await self._close_session(session_id) + return _terminal(session_id, "cancelled", "Linear authorization cancelled.") + + async def _cleanup(self) -> None: + expired = [ + session_id + for session_id, session in self._sessions.items() + if time.monotonic() >= session.flow.deadline + ] + for session_id in expired: + await self.cancel(session_id) + + async def _close_session(self, session_id: str) -> None: + session = self._sessions.pop(session_id, None) + if session is None: + return + OAUTH_FLOWS.remove(session.flow) + await asyncio.to_thread(session.server.close) + + +def _load_linear_config() -> LinearConfig: + config = load_config() + extras: dict[str, Any] = config.channels.model_extra or {} + raw: object = extras.get("linear", {}) + if not isinstance(raw, dict): + raw = {} + return LinearConfig.model_validate(cast(dict[str, Any], raw)) + + +def _query_bool(query: QueryParams, key: str) -> bool: + return (query_first(query, key) or "").strip().lower() in {"1", "true", "yes"} + + +def _terminal(session_id: str, status: str, message: str) -> dict[str, Any]: + return {"session_id": session_id, "status": status, "message": message} diff --git a/nanobot/channels/linear/manifest.py b/nanobot/channels/linear/manifest.py new file mode 100644 index 000000000..066f73ee2 --- /dev/null +++ b/nanobot/channels/linear/manifest.py @@ -0,0 +1,38 @@ +"""Dependency-free management contract for the native Linear Agent channel.""" + +from nanobot.channels._manifest import field, required_fields +from nanobot.channels.contracts import ChannelManagementSpec, ChannelSetupSpec +from nanobot.channels.linear.state import local_state_present +from nanobot.channels.linear.validation import validate +from nanobot.channels.plugin import ChannelPlugin + +SETUP_SPEC = ChannelSetupSpec( + fields={ + "clientId": field(), + "clientSecret": field("secret"), + "webhookSigningSecret": field("secret"), + "publicBaseUrl": field(), + "host": field(default="0.0.0.0"), + "port": field("int", default=3979), + "webhookPath": field(default="/linear/webhook"), + "oauthCallbackPath": field(default="/linear/oauth/callback"), + "allowFrom": field("list"), + }, + required=required_fields( + "clientId", + "clientSecret", + "webhookSigningSecret", + "publicBaseUrl", + ), + validator=validate, +) + +PLUGIN = ChannelPlugin( + name="linear", + display_name="Linear", + runtime=f"{__package__}.runtime:LinearChannel", + connector=f"{__package__}.connect:LinearConnectStore", + setup=SETUP_SPEC, + management=ChannelManagementSpec(local_state_present=local_state_present), + webui="webui/index.tsx", +) diff --git a/nanobot/channels/linear/oauth.py b/nanobot/channels/linear/oauth.py new file mode 100644 index 000000000..d54e3e33b --- /dev/null +++ b/nanobot/channels/linear/oauth.py @@ -0,0 +1,92 @@ +"""PKCE OAuth flow state for Linear app installations.""" + +from __future__ import annotations + +import base64 +import hashlib +import secrets +import threading +import time +from dataclasses import dataclass +from urllib.parse import urlencode + +from nanobot.channels.linear.config import LinearConfig + +LINEAR_AUTHORIZE_URL = "https://linear.app/oauth/authorize" +LINEAR_SCOPES = ("read", "write", "app:mentionable") +FLOW_TTL_SECONDS = 600 + + +@dataclass(slots=True) +class LinearOAuthFlow: + session_id: str + state: str + verifier: str + created_at: float + deadline: float + code: str | None = None + error: str | None = None + + +class LinearOAuthFlows: + """Process-local, short-lived OAuth state shared with the callback server.""" + + def __init__(self) -> None: + self._guard = threading.RLock() + self._by_state: dict[str, LinearOAuthFlow] = {} + + def create(self) -> LinearOAuthFlow: + now = time.monotonic() + flow = LinearOAuthFlow( + session_id=secrets.token_urlsafe(18), + state=secrets.token_urlsafe(32), + verifier=secrets.token_urlsafe(64), + created_at=time.time(), + deadline=now + FLOW_TTL_SECONDS, + ) + with self._guard: + self._cleanup_locked(now) + self._by_state[flow.state] = flow + return flow + + def complete(self, state: str, *, code: str | None, error: str | None) -> bool: + with self._guard: + self._cleanup_locked(time.monotonic()) + flow = self._by_state.get(state) + if flow is None or flow.code is not None or flow.error is not None: + return False + flow.code = code + flow.error = error + return True + + def remove(self, flow: LinearOAuthFlow) -> None: + with self._guard: + if self._by_state.get(flow.state) is flow: + self._by_state.pop(flow.state, None) + + def _cleanup_locked(self, now: float) -> None: + expired = [state for state, flow in self._by_state.items() if now >= flow.deadline] + for state in expired: + self._by_state.pop(state, None) + + +OAUTH_FLOWS = LinearOAuthFlows() + + +def authorization_url(config: LinearConfig, flow: LinearOAuthFlow) -> str: + digest = hashlib.sha256(flow.verifier.encode()).digest() + challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode() + query = urlencode( + { + "client_id": config.client_id, + "redirect_uri": config.redirect_uri, + "response_type": "code", + "scope": ",".join(LINEAR_SCOPES), + "actor": "app", + "prompt": "consent", + "state": flow.state, + "code_challenge": challenge, + "code_challenge_method": "S256", + } + ) + return f"{LINEAR_AUTHORIZE_URL}?{query}" diff --git a/nanobot/channels/linear/runtime.py b/nanobot/channels/linear/runtime.py new file mode 100644 index 000000000..0f90a73c7 --- /dev/null +++ b/nanobot/channels/linear/runtime.py @@ -0,0 +1,400 @@ +"""Native Linear Agent channel runtime.""" + +from __future__ import annotations + +import asyncio +import json +import uuid +from contextlib import suppress +from typing import Any, cast + +from nanobot.bus.events import OutboundMessage +from nanobot.bus.outbound_events import ProgressEvent, RetryWaitEvent, outbound_event_from_message +from nanobot.bus.queue import MessageBus +from nanobot.channels.base import BaseChannel +from nanobot.channels.linear.client import LinearApiError, LinearClient +from nanobot.channels.linear.config import LinearConfig +from nanobot.channels.linear.server import LinearServerLease, acquire_http_server +from nanobot.channels.linear.state import LinearStateStore, QueuedWebhook + + +class LinearPayloadError(ValueError): + """A signed webhook has an unsupported or malformed payload.""" + + +class LinearChannel(BaseChannel): + """Receive @mention Agent Sessions and publish native Agent Activities.""" + + name = "linear" + display_name = "Linear" + + @classmethod + def default_config(cls) -> dict[str, Any]: + return LinearConfig().model_dump(mode="json", by_alias=True) + + def __init__(self, config: Any, bus: MessageBus): + if isinstance(config, dict): + config = LinearConfig.model_validate(config) + super().__init__(config, bus) + self.config: LinearConfig = config + self._state = LinearStateStore() + self._client: LinearClient | None = None + self._server: LinearServerLease | None = None + self._reasoning: dict[tuple[str, str], list[str]] = {} + self._routes: dict[str, dict[str, Any]] = {} + + def progress_transport_defaults(self) -> tuple[bool, bool] | None: + return self.config.send_progress, self.config.send_tool_hints + + async def start(self) -> None: + self.config.validate_runtime() + if not self._state.has_installations(self.config.client_id): + raise RuntimeError("Connect at least one Linear workspace with OAuth before enabling") + self._state.recover_processing_webhooks() + self._client = LinearClient(self.config, self._state) + try: + self._server = await asyncio.to_thread( + acquire_http_server, + self.config, + self._state, + ) + except Exception: + await self._client.close() + self._client = None + raise + self._running = True + self.logger.info( + "Linear webhook listening on http://{}:{}{} (public URL: {})", + self.config.host, + self.config.port, + self.config.webhook_path, + self.config.webhook_url, + ) + while self._running: + events = await asyncio.to_thread(self._state.claim_webhooks) + if not events: + await asyncio.sleep(0.2) + continue + for event in events: + await self._process_queued_webhook(event) + + async def stop(self) -> None: + self._running = False + if self._server is not None: + await asyncio.to_thread(self._server.close) + self._server = None + if self._client is not None: + await self._client.close() + self._client = None + self._reasoning.clear() + self._routes.clear() + + def start_error_message(self, error: Exception) -> str | None: + return f"Linear channel failed to start: {error}" + + async def send(self, msg: OutboundMessage) -> None: + event = outbound_event_from_message(msg) + if isinstance(event, ProgressEvent): + if event.tool_events: + for item in event.tool_events: + await self._send_tool_event(msg, item) + return + if msg.content: + await self._create_activity( + msg.chat_id, + msg.metadata, + {"type": "thought", "body": msg.content}, + key=f"progress:{hash(msg.content)}", + ephemeral=True, + ) + return + if isinstance(event, RetryWaitEvent): + await self._create_activity( + msg.chat_id, + msg.metadata, + {"type": "thought", "body": msg.content}, + key=f"retry:{hash(msg.content)}", + ephemeral=True, + ) + return + if not msg.content: + return + await self._create_activity( + msg.chat_id, + msg.metadata, + {"type": "response", "body": msg.content}, + key="response", + ) + + async def send_reasoning_delta( + self, + chat_id: str, + delta: str, + metadata: dict[str, Any] | None = None, + *, + stream_id: str | None = None, + ) -> None: + key = (chat_id, stream_id or "default") + self._reasoning.setdefault(key, []).append(delta) + + async def send_reasoning_end( + self, + chat_id: str, + metadata: dict[str, Any] | None = None, + *, + stream_id: str | None = None, + ) -> None: + key = (chat_id, stream_id or "default") + body = "".join(self._reasoning.pop(key, [])).strip() + if body: + await self._create_activity( + chat_id, + metadata or {}, + {"type": "thought", "body": body}, + key=f"reasoning:{stream_id or 'default'}", + ) + + async def send_file_edit_events( + self, + chat_id: str, + edits: list[dict[str, Any]], + metadata: dict[str, Any] | None = None, + ) -> None: + for index, edit in enumerate(edits): + path = str(edit.get("path") or edit.get("file") or "file") + result = str(edit.get("status") or edit.get("phase") or "updated") + await self._create_activity( + chat_id, + metadata or {}, + { + "type": "action", + "action": "Edit file", + "parameter": path, + "result": result, + }, + key=f"file:{path}:{index}:{result}", + ) + + async def _send_tool_event(self, msg: OutboundMessage, item: dict[str, Any]) -> None: + name = str(item.get("name") or "tool") + phase = str(item.get("phase") or "start") + call_id = str(item.get("call_id") or uuid.uuid4()) + arguments = item.get("arguments") + parameter = json.dumps(arguments, ensure_ascii=False, default=str)[:2000] + content: dict[str, Any] = { + "type": "action", + "action": name, + "parameter": parameter, + } + if phase == "end": + content["result"] = _compact_result(item.get("result")) + elif phase == "error": + content["result"] = str(item.get("error") or "Tool execution failed") + await self._create_activity( + msg.chat_id, + msg.metadata, + content, + key=f"tool:{call_id}:{phase}", + ) + + async def _create_activity( + self, + chat_id: str, + metadata: dict[str, Any], + content: dict[str, Any], + *, + key: str, + ephemeral: bool = False, + ) -> None: + client = self._client + if client is None: + raise RuntimeError("Linear HTTP client is not initialized") + route = _linear_route(metadata) or self._routes.get(chat_id) + if route is None: + raise RuntimeError("Linear outbound message is missing route metadata") + metadata.setdefault("linear", route) + session_id = str(route.get("agent_session_id") or chat_id) + organization_id = _required_text(route, "organization_id") + activity_ids_raw = metadata.setdefault("_linear_activity_ids", {}) + if not isinstance(activity_ids_raw, dict): + activity_ids_raw = {} + metadata["_linear_activity_ids"] = activity_ids_raw + activity_ids = cast(dict[str, Any], activity_ids_raw) + activity_id = str(activity_ids.setdefault(key, str(uuid.uuid4()))) + await client.create_activity( + organization_id, + session_id, + content, + activity_id=activity_id, + ephemeral=ephemeral, + ) + + async def _process_queued_webhook(self, event: QueuedWebhook) -> None: + try: + await self._process_webhook(event.delivery_id, event.payload) + except LinearPayloadError as exc: + self.logger.warning("Dropping invalid Linear webhook {}: {}", event.delivery_id, exc) + await asyncio.to_thread(self._state.complete_webhook, event.delivery_id) + except LinearApiError as exc: + self.logger.warning("Linear webhook {} failed: {}", event.delivery_id, exc) + if exc.retryable: + await asyncio.to_thread( + self._state.retry_webhook, + event.delivery_id, + str(exc), + event.attempts, + exc.retry_after, + ) + else: + await asyncio.to_thread(self._state.complete_webhook, event.delivery_id) + except Exception as exc: + self.logger.exception("Linear webhook {} failed", event.delivery_id) + await asyncio.to_thread( + self._state.retry_webhook, + event.delivery_id, + str(exc), + event.attempts, + ) + else: + await asyncio.to_thread(self._state.complete_webhook, event.delivery_id) + + async def _process_webhook(self, delivery_id: str, payload: dict[str, Any]) -> None: + event_type = payload.get("type") + if event_type in {"OAuthApp", "OAuthAuthorization", "PermissionChange"}: + self._process_lifecycle_event(payload) + return + if event_type != "AgentSessionEvent": + raise LinearPayloadError("unsupported event type") + action = _required_text(payload, "action") + if action not in {"created", "prompted"}: + return + session = _required_object(payload, "agentSession") + agent_session_id = _required_text(session, "id") + organization_id = _required_text(payload, "organizationId") + if str(session.get("organizationId") or organization_id) != organization_id: + raise LinearPayloadError("organization mismatch") + installation = self._state.installation(organization_id) + if installation is None: + raise LinearPayloadError("organization is not installed") + activity = _optional_object(payload.get("agentActivity")) + if activity and str(activity.get("userId") or "") == installation.app_user_id: + return + signal = str(activity.get("signal") or "") if activity else "" + sender_id = str( + (activity or {}).get("userId") + or session.get("creatorId") + or "" + ).strip() + if not sender_id: + raise LinearPayloadError("missing sender identity") + content = "/stop" if signal == "stop" else _prompt_text(payload, session, activity, action) + if not content: + if signal in {"auth", "continue", "select"}: + content = _signal_text(signal, activity) + if not content: + return + metadata = { + "message_id": delivery_id, + "linear": { + "organization_id": organization_id, + "agent_session_id": agent_session_id, + "issue_id": str(session.get("issueId") or ""), + "comment_id": str(session.get("commentId") or ""), + "app_user_id": installation.app_user_id, + "oauth_client_id": str(payload.get("oauthClientId") or ""), + "action": action, + "signal": signal, + "delivery_id": delivery_id, + }, + } + self._routes[agent_session_id] = cast(dict[str, Any], metadata["linear"]) + if len(self._routes) > 1000: + self._routes.pop(next(iter(self._routes))) + await self._create_activity( + agent_session_id, + metadata, + {"type": "thought", "body": "Starting…"}, + key="accepted", + ephemeral=True, + ) + await self._handle_message( + sender_id=sender_id, + chat_id=agent_session_id, + content=content, + metadata=metadata, + session_key=f"linear:{organization_id}:{agent_session_id}", + is_dm=True, + ) + + def _process_lifecycle_event(self, payload: dict[str, Any]) -> None: + action = str(payload.get("action") or "").lower() + organization_id = str(payload.get("organizationId") or "").strip() + if organization_id and action in {"remove", "removed", "revoke", "revoked"}: + self._state.delete_installation(organization_id) + self.logger.info("Removed revoked Linear workspace installation {}", organization_id) + + +def _linear_route(metadata: dict[str, Any]) -> dict[str, Any] | None: + value = metadata.get("linear") + return cast(dict[str, Any], value) if isinstance(value, dict) else None + + +def _required_text(value: dict[str, Any], key: str) -> str: + item = value.get(key) + if not isinstance(item, str) or not item.strip(): + raise LinearPayloadError(f"missing {key}") + return item.strip() + + +def _required_object(value: dict[str, Any], key: str) -> dict[str, Any]: + item = value.get(key) + if not isinstance(item, dict): + raise LinearPayloadError(f"missing {key}") + return cast(dict[str, Any], item) + + +def _optional_object(value: object) -> dict[str, Any]: + return cast(dict[str, Any], value) if isinstance(value, dict) else {} + + +def _prompt_text( + payload: dict[str, Any], + session: dict[str, Any], + activity: dict[str, Any], + action: str, +) -> str: + value: object + if action == "created": + value = payload.get("promptContext") + else: + value = activity.get("body") or activity.get("content") + return _text_from_value(value) or _text_from_value(session.get("comment")) + + +def _text_from_value(value: object) -> str: + if isinstance(value, str): + return value.strip() + if isinstance(value, dict): + mapping = cast(dict[str, Any], value) + for key in ("body", "text", "prompt", "content"): + text = _text_from_value(mapping.get(key)) + if text: + return text + if isinstance(value, list): + parts = [_text_from_value(item) for item in cast(list[object], value)] + return "\n".join(part for part in parts if part) + return "" + + +def _signal_text(signal: str, activity: dict[str, Any]) -> str: + metadata = activity.get("signalMetadata") + text = _text_from_value(metadata) + return text or f"Linear agent signal: {signal}" + + +def _compact_result(value: object) -> str: + if isinstance(value, str): + return value[:2000] + with suppress(TypeError, ValueError): + return json.dumps(value, ensure_ascii=False, default=str)[:2000] + return str(value)[:2000] diff --git a/nanobot/channels/linear/server.py b/nanobot/channels/linear/server.py new file mode 100644 index 000000000..9e00608e9 --- /dev/null +++ b/nanobot/channels/linear/server.py @@ -0,0 +1,282 @@ +"""Shared local HTTP listener for Linear webhooks and OAuth callbacks.""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import threading +import time +from datetime import datetime +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any, cast +from urllib.parse import parse_qs, urlparse + +from loguru import logger + +from nanobot.channels.linear.config import LinearConfig +from nanobot.channels.linear.oauth import OAUTH_FLOWS +from nanobot.channels.linear.state import LinearStateStore + +MAX_WEBHOOK_BYTES = 1024 * 1024 +MAX_WEBHOOK_AGE_SECONDS = 60 +WEBHOOK_TYPES = { + "AgentSessionEvent", + "OAuthApp", + "OAuthAuthorization", + "PermissionChange", +} + + +class LinearWebhookError(ValueError): + def __init__(self, message: str, status: HTTPStatus = HTTPStatus.BAD_REQUEST) -> None: + super().__init__(message) + self.status = status + + +class _ReusableThreadingHTTPServer(ThreadingHTTPServer): + allow_reuse_address = True + daemon_threads = True + + +class SharedLinearHttpServer: + def __init__(self, config: LinearConfig, state: LinearStateStore) -> None: + self.config = config + self.state = state + self._references = 0 + self._server: ThreadingHTTPServer | None = None + self._thread: threading.Thread | None = None + + @property + def identity(self) -> tuple[str, int, str, str, str, str]: + return ( + self.config.host, + self.config.port, + self.config.client_id, + self.config.webhook_signing_secret, + self.config.webhook_path, + self.config.oauth_callback_path, + ) + + def start(self) -> None: + owner = self + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def do_GET(self) -> None: # noqa: N802 + parsed = urlparse(self.path) + if parsed.path == owner.config.oauth_callback_path: + owner._handle_oauth_callback(self, parse_qs(parsed.query)) + return + if parsed.path == "/linear/health": + self._send(HTTPStatus.OK, b'{"ok":true}', "application/json") + return + self._send(HTTPStatus.NOT_FOUND, b"not found", "text/plain; charset=utf-8") + + def do_POST(self) -> None: # noqa: N802 + parsed = urlparse(self.path) + if parsed.path != owner.config.webhook_path: + self._send(HTTPStatus.NOT_FOUND, b"not found", "text/plain; charset=utf-8") + return + try: + owner._handle_webhook(self) + except LinearWebhookError as exc: + logger.bind(channel="linear").warning("Rejected Linear webhook: {}", exc) + self._send(exc.status, str(exc).encode(), "text/plain; charset=utf-8") + except Exception: + logger.bind(channel="linear").exception( + "Could not persist a verified Linear webhook" + ) + self._send( + HTTPStatus.INTERNAL_SERVER_ERROR, + b"webhook persistence failed", + "text/plain; charset=utf-8", + ) + + def _send(self, status: HTTPStatus, body: bytes, content_type: str) -> None: + self.send_response(status.value) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: Any) -> None: + return + + self._server = _ReusableThreadingHTTPServer( + (self.config.host, self.config.port), + Handler, + ) + self._thread = threading.Thread( + target=self._server.serve_forever, + name="nanobot-linear", + daemon=True, + ) + self._thread.start() + + def close(self) -> None: + if self._server is not None: + self._server.shutdown() + self._server.server_close() + self._server = None + if self._thread is not None and self._thread.is_alive(): + self._thread.join(timeout=2) + self._thread = None + + def _handle_oauth_callback( + self, + handler: BaseHTTPRequestHandler, + query: dict[str, list[str]], + ) -> None: + state = _query_first(query, "state") + code = _query_first(query, "code") + error = _query_first(query, "error") + if not state or (not code and not error): + _handler_response(handler, HTTPStatus.BAD_REQUEST, _oauth_html(False)) + return + completed = OAUTH_FLOWS.complete(state, code=code, error=error) + _handler_response( + handler, + HTTPStatus.OK if completed else HTTPStatus.BAD_REQUEST, + _oauth_html(completed), + ) + + def _handle_webhook(self, handler: BaseHTTPRequestHandler) -> None: + raw_length = handler.headers.get("Content-Length") + try: + length = int(raw_length or "") + except ValueError as exc: + raise LinearWebhookError("invalid content length") from exc + if length <= 0 or length > MAX_WEBHOOK_BYTES: + raise LinearWebhookError("invalid content length", HTTPStatus.REQUEST_ENTITY_TOO_LARGE) + raw = handler.rfile.read(length) + signature = handler.headers.get("Linear-Signature", "").strip() + expected = hmac.new( + self.config.webhook_signing_secret.encode(), + raw, + hashlib.sha256, + ).hexdigest() + if not signature or not hmac.compare_digest(signature.lower(), expected): + raise LinearWebhookError("invalid signature", HTTPStatus.UNAUTHORIZED) + delivery_id = handler.headers.get("Linear-Delivery", "").strip() + if not delivery_id or len(delivery_id) > 200: + raise LinearWebhookError("missing delivery id") + try: + value: object = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise LinearWebhookError("invalid JSON") from exc + if not isinstance(value, dict): + raise LinearWebhookError("webhook body must be an object") + payload = cast(dict[str, Any], value) + timestamp = _webhook_timestamp(payload.get("webhookTimestamp")) + if timestamp is None or abs(time.time() - timestamp) > MAX_WEBHOOK_AGE_SECONDS: + raise LinearWebhookError("stale webhook", HTTPStatus.UNAUTHORIZED) + event_type = payload.get("type") + if event_type not in WEBHOOK_TYPES: + _handler_response(handler, HTTPStatus.OK, b'{"ok":true,"ignored":true}', "application/json") + return + oauth_client_id = payload.get("oauthClientId") + if oauth_client_id != self.config.client_id: + raise LinearWebhookError("webhook belongs to another OAuth app", HTTPStatus.FORBIDDEN) + self.state.enqueue_webhook(delivery_id, payload) + _handler_response(handler, HTTPStatus.OK, b'{"ok":true}', "application/json") + + +class LinearServerLease: + def __init__(self, server: SharedLinearHttpServer) -> None: + self._server = server + self._closed = False + + def close(self) -> None: + if self._closed: + return + self._closed = True + _release_server(self._server) + + +_SERVER_GUARD = threading.RLock() +_shared_server: SharedLinearHttpServer | None = None + + +def acquire_http_server(config: LinearConfig, state: LinearStateStore) -> LinearServerLease: + global _shared_server + with _SERVER_GUARD: + candidate = SharedLinearHttpServer(config, state) + if _shared_server is None: + candidate.start() + _shared_server = candidate + elif _shared_server.identity != candidate.identity: + raise RuntimeError( + "A Linear callback listener is already running with different settings" + ) + _shared_server._references += 1 # pyright: ignore[reportPrivateUsage] + return LinearServerLease(_shared_server) + + +def _release_server(server: SharedLinearHttpServer) -> None: + global _shared_server + with _SERVER_GUARD: + if _shared_server is not server: + return + server._references -= 1 # pyright: ignore[reportPrivateUsage] + if server._references <= 0: # pyright: ignore[reportPrivateUsage] + server.close() + _shared_server = None + + +def _handler_response( + handler: BaseHTTPRequestHandler, + status: HTTPStatus, + body: bytes, + content_type: str = "text/html; charset=utf-8", +) -> None: + handler.send_response(status.value) + handler.send_header("Content-Type", content_type) + handler.send_header("Content-Length", str(len(body))) + handler.send_header("Cache-Control", "no-store") + handler.send_header("X-Content-Type-Options", "nosniff") + handler.end_headers() + handler.wfile.write(body) + + +def _oauth_html(success: bool) -> bytes: + title = "Linear connected" if success else "Linear connection failed" + detail = ( + "Authorization received. You can close this window and return to nanobot." + if success + else "The authorization request is invalid or expired. Return to nanobot and try again." + ) + return ( + "" + + title + + "

" + + title + + "

" + + detail + + "

" + ).encode() + + +def _query_first(query: dict[str, list[str]], key: str) -> str | None: + values = query.get(key) + return values[0] if values and values[0] else None + + +def _webhook_timestamp(value: object) -> float | None: + if isinstance(value, int | float) and not isinstance(value, bool): + timestamp = float(value) + return timestamp / 1000 if timestamp > 10_000_000_000 else timestamp + if not isinstance(value, str) or not value: + return None + try: + timestamp = float(value) + except ValueError: + try: + return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() + except ValueError: + return None + return timestamp / 1000 if timestamp > 10_000_000_000 else timestamp diff --git a/nanobot/channels/linear/state.py b/nanobot/channels/linear/state.py new file mode 100644 index 000000000..df1e1e818 --- /dev/null +++ b/nanobot/channels/linear/state.py @@ -0,0 +1,275 @@ +"""Durable installation and webhook state owned by the Linear channel.""" + +from __future__ import annotations + +import json +import os +import sqlite3 +import threading +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, cast + +from nanobot.config.paths import get_config_path, get_runtime_subdir + + +@dataclass(frozen=True, slots=True) +class LinearInstallation: + organization_id: str + oauth_client_id: str + app_user_id: str + access_token: str + refresh_token: str + expires_at: float + scope: tuple[str, ...] = () + organization_name: str = "" + + +@dataclass(frozen=True, slots=True) +class QueuedWebhook: + delivery_id: str + payload: dict[str, Any] + attempts: int + + +class LinearStateStore: + """Small SQLite store so webhook acknowledgement is durable and idempotent.""" + + def __init__(self, path: Path | None = None) -> None: + self.path = path or (get_runtime_subdir("linear") / "state.sqlite3") + self.path.parent.mkdir(parents=True, exist_ok=True) + self._guard = threading.RLock() + self._initialize() + try: + os.chmod(self.path.parent, 0o700) + os.chmod(self.path, 0o600) + except OSError: + pass + + def _connect(self) -> sqlite3.Connection: + connection = sqlite3.connect(self.path, timeout=10) + connection.row_factory = sqlite3.Row + connection.execute("PRAGMA journal_mode=WAL") + connection.execute("PRAGMA synchronous=FULL") + return connection + + def _initialize(self) -> None: + with self._guard, self._connect() as connection: + connection.executescript( + """ + CREATE TABLE IF NOT EXISTS installations ( + organization_id TEXT PRIMARY KEY, + oauth_client_id TEXT NOT NULL, + app_user_id TEXT NOT NULL, + access_token TEXT NOT NULL, + refresh_token TEXT NOT NULL, + expires_at REAL NOT NULL, + scope_json TEXT NOT NULL, + organization_name TEXT NOT NULL, + updated_at REAL NOT NULL + ); + CREATE TABLE IF NOT EXISTS webhook_events ( + delivery_id TEXT PRIMARY KEY, + payload_json TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + attempts INTEGER NOT NULL DEFAULT 0, + next_attempt_at REAL NOT NULL DEFAULT 0, + last_error TEXT, + created_at REAL NOT NULL + ); + CREATE TABLE IF NOT EXISTS webhook_receipts ( + delivery_id TEXT PRIMARY KEY, + received_at REAL NOT NULL + ); + """ + ) + columns = { + str(row["name"]) + for row in connection.execute("PRAGMA table_info(installations)").fetchall() + } + if "oauth_client_id" not in columns: + connection.execute( + "ALTER TABLE installations ADD COLUMN oauth_client_id TEXT NOT NULL DEFAULT ''" + ) + connection.execute( + "DELETE FROM webhook_receipts WHERE received_at < ?", + (time.time() - 30 * 24 * 60 * 60,), + ) + + def has_installations(self, oauth_client_id: str | None = None) -> bool: + with self._guard, self._connect() as connection: + if oauth_client_id is None: + row = connection.execute("SELECT 1 FROM installations LIMIT 1").fetchone() + else: + row = connection.execute( + "SELECT 1 FROM installations WHERE oauth_client_id = ? LIMIT 1", + (oauth_client_id,), + ).fetchone() + return row is not None + + def save_installation(self, installation: LinearInstallation) -> None: + with self._guard, self._connect() as connection: + connection.execute( + """ + INSERT INTO installations ( + organization_id, oauth_client_id, app_user_id, access_token, refresh_token, + expires_at, scope_json, organization_name, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(organization_id) DO UPDATE SET + oauth_client_id=excluded.oauth_client_id, + app_user_id=excluded.app_user_id, + access_token=excluded.access_token, + refresh_token=excluded.refresh_token, + expires_at=excluded.expires_at, + scope_json=excluded.scope_json, + organization_name=excluded.organization_name, + updated_at=excluded.updated_at + """, + ( + installation.organization_id, + installation.oauth_client_id, + installation.app_user_id, + installation.access_token, + installation.refresh_token, + installation.expires_at, + json.dumps(installation.scope), + installation.organization_name, + time.time(), + ), + ) + + def installation(self, organization_id: str) -> LinearInstallation | None: + with self._guard, self._connect() as connection: + row = connection.execute( + "SELECT * FROM installations WHERE organization_id = ?", + (organization_id,), + ).fetchone() + return _installation_from_row(row) if row is not None else None + + def delete_installation(self, organization_id: str) -> None: + with self._guard, self._connect() as connection: + connection.execute( + "DELETE FROM installations WHERE organization_id = ?", + (organization_id,), + ) + + def enqueue_webhook(self, delivery_id: str, payload: dict[str, Any]) -> bool: + serialized = json.dumps(payload, separators=(",", ":"), ensure_ascii=False) + with self._guard, self._connect() as connection: + connection.execute("BEGIN IMMEDIATE") + receipt = connection.execute( + "INSERT OR IGNORE INTO webhook_receipts (delivery_id, received_at) VALUES (?, ?)", + (delivery_id, time.time()), + ) + if receipt.rowcount != 1: + return False + connection.execute( + """ + INSERT INTO webhook_events ( + delivery_id, payload_json, status, next_attempt_at, created_at + ) VALUES (?, ?, 'pending', 0, ?) + """, + (delivery_id, serialized, time.time()), + ) + return True + + def claim_webhooks(self, limit: int = 20) -> list[QueuedWebhook]: + now = time.time() + claimed: list[QueuedWebhook] = [] + with self._guard, self._connect() as connection: + connection.execute("BEGIN IMMEDIATE") + rows = connection.execute( + """ + SELECT delivery_id, payload_json, attempts + FROM webhook_events + WHERE status = 'pending' AND next_attempt_at <= ? + ORDER BY created_at + LIMIT ? + """, + (now, limit), + ).fetchall() + for row in rows: + connection.execute( + "UPDATE webhook_events SET status = 'processing' WHERE delivery_id = ?", + (row["delivery_id"],), + ) + value: object = json.loads(str(row["payload_json"])) + if isinstance(value, dict): + claimed.append( + QueuedWebhook( + delivery_id=str(row["delivery_id"]), + payload=cast(dict[str, Any], value), + attempts=int(row["attempts"]), + ) + ) + return claimed + + def complete_webhook(self, delivery_id: str) -> None: + with self._guard, self._connect() as connection: + connection.execute( + "DELETE FROM webhook_events WHERE delivery_id = ?", + (delivery_id,), + ) + + def retry_webhook( + self, + delivery_id: str, + error: str, + attempts: int, + retry_after: float | None = None, + ) -> None: + retry_count = attempts + 1 + if retry_count >= 10: + status = "failed" + next_attempt_at = 0.0 + else: + status = "pending" + backoff = min(300.0, 2.0**retry_count) + delay = max(backoff, min(86400.0, retry_after or 0.0)) + next_attempt_at = time.time() + delay + with self._guard, self._connect() as connection: + connection.execute( + """ + UPDATE webhook_events + SET status = ?, attempts = ?, next_attempt_at = ?, last_error = ? + WHERE delivery_id = ? + """, + (status, retry_count, next_attempt_at, error[:2000], delivery_id), + ) + + def recover_processing_webhooks(self) -> None: + with self._guard, self._connect() as connection: + connection.execute( + "UPDATE webhook_events SET status = 'pending' WHERE status = 'processing'" + ) + + +def _installation_from_row(row: sqlite3.Row) -> LinearInstallation: + raw_scope: object = json.loads(str(row["scope_json"])) + scope = ( + tuple(str(item) for item in cast(list[object], raw_scope)) + if isinstance(raw_scope, list) + else () + ) + return LinearInstallation( + organization_id=str(row["organization_id"]), + oauth_client_id=str(row["oauth_client_id"]), + app_user_id=str(row["app_user_id"]), + access_token=str(row["access_token"]), + refresh_token=str(row["refresh_token"]), + expires_at=float(row["expires_at"]), + scope=scope, + organization_name=str(row["organization_name"]), + ) + + +def local_state_present(_section: Any) -> bool: + """Report OAuth installation state without importing the channel runtime.""" + path = get_config_path().parent / "linear" / "state.sqlite3" + if not path.is_file(): + return False + try: + return LinearStateStore(path).has_installations() + except (OSError, sqlite3.Error): + return False diff --git a/nanobot/channels/linear/tests/__init__.py b/nanobot/channels/linear/tests/__init__.py new file mode 100644 index 000000000..8088cbda9 --- /dev/null +++ b/nanobot/channels/linear/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for the native Linear channel.""" diff --git a/nanobot/channels/linear/tests/test_linear.py b/nanobot/channels/linear/tests/test_linear.py new file mode 100644 index 000000000..5cc873603 --- /dev/null +++ b/nanobot/channels/linear/tests/test_linear.py @@ -0,0 +1,534 @@ +from __future__ import annotations + +import hashlib +import hmac +import http.client +import json +import socket +import time +from dataclasses import replace +from pathlib import Path +from typing import Any +from urllib.parse import parse_qs, urlparse + +import httpx +import pytest + +from nanobot.bus.events import OutboundMessage +from nanobot.bus.outbound_events import ProgressEvent +from nanobot.bus.queue import MessageBus +from nanobot.channels.linear.client import LinearApiError, LinearClient +from nanobot.channels.linear.config import LinearConfig, validate_public_base_url +from nanobot.channels.linear.oauth import OAUTH_FLOWS, authorization_url +from nanobot.channels.linear.runtime import LinearChannel +from nanobot.channels.linear.server import acquire_http_server +from nanobot.channels.linear.state import LinearInstallation, LinearStateStore + + +def _config(port: int = 3979) -> LinearConfig: + return LinearConfig( + client_id="client-id", + client_secret="client-secret", + webhook_signing_secret="webhook-secret", + public_base_url="https://nanobot.example.com", + host="127.0.0.1", + port=port, + allow_from=["*"], + ) + + +def _installation() -> LinearInstallation: + return LinearInstallation( + organization_id="org-1", + oauth_client_id="client-id", + organization_name="Example", + app_user_id="app-user-1", + access_token="access", + refresh_token="refresh", + expires_at=time.time() + 3600, + scope=("read", "write", "app:mentionable"), + ) + + +def _free_port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + +def _post_webhook( + port: int, + payload: dict[str, Any], + *, + signature: str | None = None, + delivery: str = "delivery-1", +) -> tuple[int, bytes]: + raw = json.dumps(payload, separators=(",", ":")).encode() + actual_signature = signature or hmac.new(b"webhook-secret", raw, hashlib.sha256).hexdigest() + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=3) + connection.request( + "POST", + "/linear/webhook", + raw, + { + "Content-Type": "application/json", + "Linear-Signature": actual_signature, + "Linear-Delivery": delivery, + }, + ) + response = connection.getresponse() + body = response.read() + connection.close() + return response.status, body + + +def _agent_webhook(*, action: str = "created", signal: str = "") -> dict[str, Any]: + activity: dict[str, Any] | None = None + if action == "prompted": + activity = { + "id": "activity-1", + "agentSessionId": "session-1", + "content": {"type": "prompt", "body": "continue the work"}, + "signal": signal or None, + "userId": "user-1", + } + return { + "type": "AgentSessionEvent", + "action": action, + "oauthClientId": "client-id", + "organizationId": "org-1", + "webhookTimestamp": int(time.time() * 1000), + "promptContext": "please investigate this issue", + "agentActivity": activity, + "agentSession": { + "id": "session-1", + "organizationId": "org-1", + "creatorId": "user-1", + "issueId": "issue-1", + "commentId": "comment-1", + }, + } + + +def test_linear_config_requires_public_https_origin() -> None: + assert validate_public_base_url("https://nanobot.example.com") == "https://nanobot.example.com" + assert LinearConfig(public_base_url=" https://nanobot.example.com/ ").public_base_url == ( + "https://nanobot.example.com" + ) + for value in ( + "http://nanobot.example.com", + "https://localhost:3979", + "https://127.0.0.1", + "https://nanobot.example.com/linear", + "https://nanobot.example.com:invalid", + "https://nanobot.example.com:", + ): + with pytest.raises(ValueError): + validate_public_base_url(value) + + +def test_linear_config_rejects_overlapping_callback_paths() -> None: + with pytest.raises(ValueError, match="must be different"): + LinearConfig( + webhook_path="/linear/events/", + oauth_callback_path="/linear/events", + ) + + +def test_oauth_authorization_uses_app_actor_pkce_and_mention_scope() -> None: + flow = OAUTH_FLOWS.create() + try: + parsed = urlparse(authorization_url(_config(), flow)) + query = parsed.query + assert parsed.scheme == "https" + assert "actor=app" in query + assert "code_challenge_method=S256" in query + assert "app%3Amentionable" in query + assert "app%3Aassignable" not in query + assert f"state={flow.state}" in query + finally: + OAUTH_FLOWS.remove(flow) + + +def test_state_store_persists_installations_and_deduplicates_webhooks(tmp_path: Path) -> None: + store = LinearStateStore(tmp_path / "linear.sqlite3") + installation = _installation() + store.save_installation(installation) + second_installation = replace( + installation, + organization_id="org-2", + organization_name="Second workspace", + app_user_id="app-user-2", + access_token="second-access", + refresh_token="second-refresh", + ) + store.save_installation(second_installation) + + assert store.installation("org-1") == installation + assert store.installation("org-2") == second_installation + assert store.enqueue_webhook("delivery-1", _agent_webhook()) is True + assert store.enqueue_webhook("delivery-1", _agent_webhook()) is False + + events = store.claim_webhooks() + assert len(events) == 1 + assert events[0].delivery_id == "delivery-1" + store.complete_webhook("delivery-1") + assert store.claim_webhooks() == [] + assert store.enqueue_webhook("delivery-1", _agent_webhook()) is False + + +def test_webhook_server_verifies_signature_deduplicates_and_ignores_comments( + tmp_path: Path, +) -> None: + port = _free_port() + config = _config(port) + store = LinearStateStore(tmp_path / "linear.sqlite3") + lease = acquire_http_server(config, store) + try: + status, _ = _post_webhook(port, _agent_webhook(), signature="invalid") + assert status == 401 + + status, _ = _post_webhook(port, _agent_webhook()) + assert status == 200 + status, _ = _post_webhook(port, _agent_webhook()) + assert status == 200 + assert len(store.claim_webhooks()) == 1 + + comment = _agent_webhook() + comment["type"] = "Comment" + comment.pop("oauthClientId") + status, body = _post_webhook(port, comment, delivery="comment-1") + assert status == 200 + assert b"ignored" in body + finally: + lease.close() + + +def test_webhook_server_rejects_stale_or_wrong_app_events(tmp_path: Path) -> None: + port = _free_port() + store = LinearStateStore(tmp_path / "linear.sqlite3") + lease = acquire_http_server(_config(port), store) + try: + stale = _agent_webhook() + stale["webhookTimestamp"] = int((time.time() - 120) * 1000) + assert _post_webhook(port, stale)[0] == 401 + + other_app = _agent_webhook() + other_app["oauthClientId"] = "other-client" + assert _post_webhook(port, other_app, delivery="other-app")[0] == 403 + finally: + lease.close() + + +def test_oauth_callback_completes_only_registered_state(tmp_path: Path) -> None: + port = _free_port() + lease = acquire_http_server( + _config(port), + LinearStateStore(tmp_path / "linear.sqlite3"), + ) + flow = OAUTH_FLOWS.create() + try: + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=3) + connection.request( + "GET", + f"/linear/oauth/callback?state={flow.state}&code=authorization-code", + ) + response = connection.getresponse() + response.read() + connection.close() + assert response.status == 200 + assert flow.code == "authorization-code" + finally: + OAUTH_FLOWS.remove(flow) + lease.close() + + +@pytest.mark.asyncio +async def test_oauth_exchange_saves_workspace_app_identity_and_required_scopes( + tmp_path: Path, +) -> None: + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response( + 200, + json={ + "access_token": "access", + "refresh_token": "refresh", + "expires_in": 86400, + "scope": "read write app:mentionable", + }, + ) + return httpx.Response( + 200, + json={ + "data": { + "viewer": { + "id": "app-user-1", + "organization": {"id": "org-1", "name": "Example"}, + } + } + }, + ) + + state = LinearStateStore(tmp_path / "linear.sqlite3") + http = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + client = LinearClient(_config(), state, http) + try: + installation = await client.exchange_code("code", "verifier") + finally: + await http.aclose() + + assert installation.app_user_id == "app-user-1" + assert installation.organization_id == "org-1" + assert state.installation("org-1") == installation + + +@pytest.mark.asyncio +async def test_oauth_exchange_rejects_missing_mention_scope(tmp_path: Path) -> None: + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + return httpx.Response( + 200, + json={ + "access_token": "access", + "refresh_token": "refresh", + "expires_in": 86400, + "scope": "read write", + }, + ) + return httpx.Response( + 200, + json={ + "data": { + "viewer": { + "id": "app-user-1", + "organization": {"id": "org-1", "name": "Example"}, + } + } + }, + ) + + state = LinearStateStore(tmp_path / "linear.sqlite3") + http = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + client = LinearClient(_config(), state, http) + try: + with pytest.raises(LinearApiError, match="app:mentionable"): + await client.exchange_code("code", "verifier") + finally: + await http.aclose() + + assert state.has_installations() is False + + +@pytest.mark.asyncio +async def test_graphql_non_json_server_error_is_retryable(tmp_path: Path) -> None: + def handler(_request: httpx.Request) -> httpx.Response: + return httpx.Response(503, text="temporarily unavailable") + + state = LinearStateStore(tmp_path / "linear.sqlite3") + state.save_installation(_installation()) + http = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + client = LinearClient(_config(), state, http) + try: + with pytest.raises(LinearApiError) as error: + await client.graphql("org-1", "query Test { viewer { id } }", {}) + finally: + await http.aclose() + + assert error.value.retryable is True + + +@pytest.mark.asyncio +async def test_graphql_rate_limit_error_is_retryable(tmp_path: Path) -> None: + reset_at = int((time.time() + 60) * 1000) + + def handler(_request: httpx.Request) -> httpx.Response: + return httpx.Response( + 400, + headers={"X-RateLimit-Requests-Reset": str(reset_at)}, + json={ + "errors": [{ + "message": "Request limit exceeded", + "extensions": {"code": "RATELIMITED"}, + }] + }, + ) + + state = LinearStateStore(tmp_path / "linear.sqlite3") + state.save_installation(_installation()) + http = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + client = LinearClient(_config(), state, http) + try: + with pytest.raises(LinearApiError, match="Request limit exceeded") as error: + await client.graphql("org-1", "query Test { viewer { id } }", {}) + finally: + await http.aclose() + + assert error.value.retryable is True + assert error.value.retry_after is not None + assert 50 <= error.value.retry_after <= 60 + + +@pytest.mark.asyncio +async def test_expired_workspace_token_is_refreshed_and_rotated(tmp_path: Path) -> None: + seen_refresh_form: dict[str, list[str]] = {} + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path == "/oauth/token": + seen_refresh_form.update(parse_qs(request.content.decode())) + return httpx.Response( + 200, + json={ + "access_token": "rotated-access", + "refresh_token": "rotated-refresh", + "expires_in": 86400, + "scope": "read write app:mentionable", + }, + ) + assert request.headers["Authorization"] == "Bearer rotated-access" + return httpx.Response(200, json={"data": {"viewer": {"id": "app-user-1"}}}) + + state = LinearStateStore(tmp_path / "linear.sqlite3") + state.save_installation(replace(_installation(), expires_at=time.time() - 1)) + http = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + client = LinearClient(_config(), state, http) + try: + data = await client.graphql("org-1", "query Test { viewer { id } }", {}) + finally: + await http.aclose() + + assert data["viewer"] == {"id": "app-user-1"} + assert seen_refresh_form["grant_type"] == ["refresh_token"] + assert seen_refresh_form["refresh_token"] == ["refresh"] + refreshed = state.installation("org-1") + assert refreshed is not None + assert refreshed.access_token == "rotated-access" + assert refreshed.refresh_token == "rotated-refresh" + + +class _FakeLinearClient: + def __init__(self) -> None: + self.activities: list[dict[str, Any]] = [] + + async def create_activity( + self, + organization_id: str, + agent_session_id: str, + content: dict[str, Any], + *, + activity_id: str, + ephemeral: bool = False, + ) -> None: + self.activities.append( + { + "organization_id": organization_id, + "agent_session_id": agent_session_id, + "content": content, + "activity_id": activity_id, + "ephemeral": ephemeral, + } + ) + + +def _runtime(tmp_path: Path) -> tuple[LinearChannel, _FakeLinearClient]: + channel = LinearChannel(_config(), MessageBus()) + state = LinearStateStore(tmp_path / "linear.sqlite3") + state.save_installation(_installation()) + fake = _FakeLinearClient() + channel._state = state # pyright: ignore[reportPrivateUsage] + channel._client = fake # type: ignore[assignment] # pyright: ignore[reportPrivateUsage] + return channel, fake + + +@pytest.mark.asyncio +async def test_created_agent_session_publishes_only_the_mention_prompt(tmp_path: Path) -> None: + channel, client = _runtime(tmp_path) + await channel._process_webhook("delivery-1", _agent_webhook()) # pyright: ignore[reportPrivateUsage] + + inbound = await channel.bus.consume_inbound() + assert inbound.content == "please investigate this issue" + assert inbound.sender_id == "user-1" + assert inbound.chat_id == "session-1" + assert inbound.session_key == "linear:org-1:session-1" + assert inbound.metadata["linear"]["issue_id"] == "issue-1" + assert client.activities[0]["content"] == {"type": "thought", "body": "Starting…"} + + +@pytest.mark.asyncio +async def test_prompted_stop_signal_becomes_priority_stop_command(tmp_path: Path) -> None: + channel, _ = _runtime(tmp_path) + await channel._process_webhook( # pyright: ignore[reportPrivateUsage] + "delivery-2", + _agent_webhook(action="prompted", signal="stop"), + ) + + inbound = await channel.bus.consume_inbound() + assert inbound.content == "/stop" + assert inbound.metadata["linear"]["signal"] == "stop" + + +@pytest.mark.asyncio +async def test_app_authored_activity_is_not_echoed_back(tmp_path: Path) -> None: + channel, _ = _runtime(tmp_path) + payload = _agent_webhook(action="prompted") + payload["agentActivity"]["userId"] = "app-user-1" + + await channel._process_webhook("delivery-3", payload) # pyright: ignore[reportPrivateUsage] + + assert channel.bus.inbound.empty() + + +@pytest.mark.asyncio +async def test_outbound_response_and_tool_progress_use_native_activity_shapes( + tmp_path: Path, +) -> None: + channel, client = _runtime(tmp_path) + metadata = { + "linear": { + "organization_id": "org-1", + "agent_session_id": "session-1", + } + } + response = OutboundMessage( + channel="linear", + chat_id="session-1", + content="Done", + metadata=metadata, + ) + await channel.send(response) + activity_id = client.activities[-1]["activity_id"] + await channel.send(response) + + tool = OutboundMessage( + channel="linear", + chat_id="session-1", + content="", + metadata=metadata, + event=ProgressEvent( + tool_events=[{ + "phase": "end", + "call_id": "call-1", + "name": "linear_get_issue", + "arguments": {"id": "issue-1"}, + "result": {"title": "Bug"}, + }] + ), + ) + await channel.send(tool) + + assert client.activities[0]["content"] == {"type": "response", "body": "Done"} + assert client.activities[1]["activity_id"] == activity_id + assert client.activities[2]["content"]["type"] == "action" + assert client.activities[2]["content"]["action"] == "linear_get_issue" + + +def test_revocation_removes_workspace_installation(tmp_path: Path) -> None: + channel, _ = _runtime(tmp_path) + channel._process_lifecycle_event( # pyright: ignore[reportPrivateUsage] + { + "type": "OAuthApp", + "action": "revoked", + "organizationId": "org-1", + } + ) + assert channel._state.installation("org-1") is None # pyright: ignore[reportPrivateUsage] diff --git a/nanobot/channels/linear/validation.py b/nanobot/channels/linear/validation.py new file mode 100644 index 000000000..4cf002ce9 --- /dev/null +++ b/nanobot/channels/linear/validation.py @@ -0,0 +1,40 @@ +"""Setup validation for Linear's public callback requirements.""" + +from typing import Any + +from pydantic import ValidationError + +from nanobot.channels.contracts import ChannelValidationContext +from nanobot.channels.linear.config import LinearConfig +from nanobot.channels.validation import check, required_checks, status_from_checks + + +def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]: + checks, missing = required_checks("linear", values) + try: + config = LinearConfig.model_validate(values) + config.validate_runtime() + except (ValidationError, ValueError) as exc: + checks.append(check("callbacks", "Public callbacks", "fail", str(exc))) + else: + checks.append( + check( + "callbacks", + "Public callbacks", + "pass", + f"Webhook: {config.webhook_url}; OAuth callback: {config.redirect_uri}", + ) + ) + checks.append( + check( + "linear_app", + "Linear OAuth app", + "skipped", + "OAuth credentials and scopes are verified when you connect; " + "webhook delivery is verified by the first event.", + ) + ) + return status_from_checks("linear", checks, missing) + + +__all__ = ["validate"] diff --git a/nanobot/channels/linear/webui/LinearConnectFlow.tsx b/nanobot/channels/linear/webui/LinearConnectFlow.tsx new file mode 100644 index 000000000..558424cdd --- /dev/null +++ b/nanobot/channels/linear/webui/LinearConnectFlow.tsx @@ -0,0 +1,118 @@ +import { ExternalLink } from "lucide-react"; +import { useTranslation } from "react-i18next"; + +import { channelTranslator } from "@/channel-plugins/i18n"; +import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow"; +import { Button } from "@/components/ui/button"; +import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types"; + +export function LinearConnectFlow({ + token, + feature, + idleLabel, + connectRequestId, + onFeaturesUpdate, +}: ChannelPluginConnectFlowProps) { + const { t } = useTranslation(); + const tx = channelTranslator(t, "linear"); + const publicBaseUrl = feature.config_values?.["channels.linear.publicBaseUrl"]?.replace(/\/$/, ""); + const webhookPath = feature.config_values?.["channels.linear.webhookPath"] || "/linear/webhook"; + const callbackPath = feature.config_values?.["channels.linear.oauthCallbackPath"] || "/linear/oauth/callback"; + const manifestUrl = publicBaseUrl + ? linearManifestUrl(publicBaseUrl, webhookPath, callbackPath) + : null; + + return ( +
+ {manifestUrl ? ( +
+ +
+ ) : null} + ( +
+
+ + {tx("custom.waiting", "Waiting for Linear authorization...")} +
+ {connect.qr_url ? ( + + ) : null} +
+ )} + /> +
+ ); +} + +export function linearManifestUrl( + publicBaseUrl: string, + webhookPath: string, + callbackPath: string, +): string { + const manifest = { + $schema: "https://linear.app/.well-known/oauth-app-manifest.schema.json", + schemaVersion: "1.0.0", + distribution: "private", + display: { + description: "Use nanobot as a native issue agent.", + }, + developer: { name: "nanobot" }, + oauth: { + client_name: "nanobot Agent", + client_uri: publicBaseUrl, + redirect_uris: [`${publicBaseUrl}${callbackPath}`], + grant_types: ["authorization_code"], + }, + webhook: { + enabled: true, + url: `${publicBaseUrl}${webhookPath}`, + resourceTypes: [ + "AgentSessionEvent", + "PermissionChange", + "OAuthAuthorization", + ], + }, + }; + return `https://linear.app/settings/api/applications/new?${new URLSearchParams({ + manifest: JSON.stringify(manifest), + })}`; +} diff --git a/nanobot/channels/linear/webui/index.tsx b/nanobot/channels/linear/webui/index.tsx new file mode 100644 index 000000000..a1d298151 --- /dev/null +++ b/nanobot/channels/linear/webui/index.tsx @@ -0,0 +1,37 @@ +import { lazy } from "react"; + +import type { ChannelUiContribution } from "@/channel-plugins/types"; +import { chatAppGuideUrl } from "@/components/settings/channels/catalog"; + +const LinearConnectFlow = lazy(() => + import("./LinearConnectFlow").then(({ LinearConnectFlow: component }) => ({ + default: component, + })), +); + +export default { + ConnectFlow: LinearConnectFlow, + presentation: { + displayName: "Linear", + initials: "LI", + color: "#5E6AD2", + logoUrl: "https://linear.app/favicon.ico", + setup: { + mode: "connect", + docsUrl: chatAppGuideUrl("linear"), + fields: [ + { key: "channels.linear.clientId" }, + { key: "channels.linear.clientSecret" }, + { key: "channels.linear.webhookSigningSecret" }, + { key: "channels.linear.publicBaseUrl" }, + ], + manualFields: [ + { key: "channels.linear.host" }, + { key: "channels.linear.port" }, + { key: "channels.linear.webhookPath" }, + { key: "channels.linear.oauthCallbackPath" }, + { key: "channels.linear.allowFrom" }, + ], + }, + }, +} satisfies ChannelUiContribution; diff --git a/nanobot/channels/linear/webui/locales/en.json b/nanobot/channels/linear/webui/locales/en.json new file mode 100644 index 000000000..846bbabc0 --- /dev/null +++ b/nanobot/channels/linear/webui/locales/en.json @@ -0,0 +1,71 @@ +{ + "description": "Work with nanobot from Linear issues through native Agent Sessions.", + "requirements": "A private Linear OAuth app and a stable public HTTPS callback URL", + "setup": { + "docsLabel": "Open Linear setup guide", + "officialLabel": "Create Linear OAuth app", + "tryIt": "Mention the app in an issue comment. Follow-ups inside its Agent Session do not need another mention.", + "summary": "Create a private Linear OAuth app, save its credentials and public URL, then authorize each workspace. New sessions require an explicit @mention; ordinary comments are ignored.", + "steps": [ + "Expose this nanobot instance through a stable HTTPS URL (a tunnel is fine).", + "Create a private OAuth app in Linear with read, write, and app:mentionable scopes. Do not add app:assignable.", + "Subscribe the app webhook to AgentSessionEvent, PermissionChange, and OAuthAuthorization using the generated webhook URL.", + "Save settings, connect the workspace with OAuth, then @mention the app on an issue." + ], + "fields": { + "clientId": { + "label": "OAuth client ID", + "placeholder": "Linear OAuth client ID", + "help": "Copy it from the private OAuth app in Linear." + }, + "clientSecret": { + "label": "OAuth client secret", + "placeholder": "••••••", + "help": "Stored only by this nanobot instance." + }, + "webhookSigningSecret": { + "label": "Webhook signing secret", + "placeholder": "••••••", + "help": "Used to verify Linear-Signature before any webhook body is parsed." + }, + "publicBaseUrl": { + "label": "Public HTTPS URL", + "placeholder": "https://nanobot.example.com", + "help": "A stable HTTPS origin routed to the listener below; do not include a path." + }, + "host": { + "label": "Listen host", + "placeholder": "0.0.0.0" + }, + "port": { + "label": "Listen port", + "placeholder": "3979" + }, + "webhookPath": { + "label": "Webhook path", + "placeholder": "/linear/webhook" + }, + "oauthCallbackPath": { + "label": "OAuth callback path", + "placeholder": "/linear/oauth/callback" + }, + "allowFrom": { + "label": "Allowed Linear users", + "placeholder": "Linear user IDs, comma separated", + "help": "Leave empty to use nanobot pairing, or use * to allow every user in connected workspaces." + } + } + }, + "custom": { + "qrAlt": "Linear authorization QR code", + "authorizeTitle": "Authorize in Linear", + "authorizeDescription": "Open Linear in this browser or scan the QR code. nanobot enables the channel after authorization.", + "waiting": "Waiting for Linear authorization...", + "connected": "Linear is connected.", + "stopped": "Authorization stopped.", + "connecting": "Connecting...", + "reconnect": "Connect another workspace", + "connect": "Connect Linear", + "openLinear": "Continue in Linear" + } +} diff --git a/nanobot/channels/linear/webui/locales/es.json b/nanobot/channels/linear/webui/locales/es.json new file mode 100644 index 000000000..eb5deb090 --- /dev/null +++ b/nanobot/channels/linear/webui/locales/es.json @@ -0,0 +1,71 @@ +{ + "description": "Trabaja con nanobot desde incidencias de Linear mediante sesiones de agente nativas.", + "requirements": "Una aplicación OAuth privada de Linear y una URL HTTPS pública y estable para las devoluciones de llamada", + "setup": { + "docsLabel": "Abrir la guía de configuración de Linear", + "officialLabel": "Crear una aplicación OAuth de Linear", + "tryIt": "Menciona la aplicación en un comentario de una incidencia. Las respuestas dentro de su sesión de agente no necesitan otra mención.", + "summary": "Crea una aplicación OAuth privada de Linear, guarda sus credenciales y la URL pública y, después, autoriza el espacio de trabajo. Cada sesión nueva requiere una @mención explícita; los comentarios normales se ignoran.", + "steps": [ + "Expón esta instancia de nanobot mediante una URL HTTPS estable (puedes usar un túnel).", + "Crea una aplicación OAuth privada en Linear con los permisos read, write y app:mentionable. No añadas app:assignable.", + "Suscribe el webhook de la aplicación a AgentSessionEvent, PermissionChange y OAuthAuthorization con la URL generada.", + "Guarda la configuración, conecta el espacio de trabajo mediante OAuth y @menciona la aplicación en una incidencia." + ], + "fields": { + "clientId": { + "label": "ID de cliente OAuth", + "placeholder": "ID de cliente OAuth de Linear", + "help": "Cópialo de la aplicación OAuth privada en Linear." + }, + "clientSecret": { + "label": "Secreto de cliente OAuth", + "placeholder": "••••••", + "help": "Solo se guarda en esta instancia de nanobot." + }, + "webhookSigningSecret": { + "label": "Secreto de firma del webhook", + "placeholder": "••••••", + "help": "Se usa para verificar Linear-Signature antes de analizar el cuerpo del webhook." + }, + "publicBaseUrl": { + "label": "URL HTTPS pública", + "placeholder": "https://nanobot.example.com", + "help": "Un origen HTTPS estable dirigido al listener indicado abajo; no incluyas una ruta." + }, + "host": { + "label": "Host de escucha", + "placeholder": "0.0.0.0" + }, + "port": { + "label": "Puerto de escucha", + "placeholder": "3979" + }, + "webhookPath": { + "label": "Ruta del webhook", + "placeholder": "/linear/webhook" + }, + "oauthCallbackPath": { + "label": "Ruta de devolución OAuth", + "placeholder": "/linear/oauth/callback" + }, + "allowFrom": { + "label": "Usuarios de Linear permitidos", + "placeholder": "ID de usuarios de Linear separados por comas", + "help": "Déjalo vacío para usar el emparejamiento de nanobot, o usa * para permitir a todos los usuarios de los espacios conectados." + } + } + }, + "custom": { + "qrAlt": "Código QR de autorización de Linear", + "authorizeTitle": "Autorizar en Linear", + "authorizeDescription": "Abre Linear en este navegador o escanea el código QR. nanobot habilitará el canal después de la autorización.", + "waiting": "Esperando la autorización de Linear...", + "connected": "Linear está conectado.", + "stopped": "La autorización se detuvo.", + "connecting": "Conectando...", + "reconnect": "Conectar otro espacio de trabajo", + "connect": "Conectar Linear", + "openLinear": "Continuar en Linear" + } +} diff --git a/nanobot/channels/linear/webui/locales/fr.json b/nanobot/channels/linear/webui/locales/fr.json new file mode 100644 index 000000000..53742c966 --- /dev/null +++ b/nanobot/channels/linear/webui/locales/fr.json @@ -0,0 +1,71 @@ +{ + "description": "Utilisez nanobot depuis les tickets Linear grâce aux sessions d’agent natives.", + "requirements": "Une application OAuth Linear privée et une URL de rappel HTTPS publique et stable", + "setup": { + "docsLabel": "Ouvrir le guide de configuration Linear", + "officialLabel": "Créer une application OAuth Linear", + "tryIt": "Mentionnez l’application dans un commentaire de ticket. Les messages suivants dans sa session d’agent ne nécessitent pas de nouvelle mention.", + "summary": "Créez une application OAuth Linear privée, enregistrez ses identifiants et son URL publique, puis autorisez l’espace de travail. Chaque nouvelle session exige une @mention explicite ; les commentaires ordinaires sont ignorés.", + "steps": [ + "Exposez cette instance nanobot avec une URL HTTPS stable (un tunnel convient).", + "Créez une application OAuth privée dans Linear avec les autorisations read, write et app:mentionable. N’ajoutez pas app:assignable.", + "Abonnez le webhook de l’application à AgentSessionEvent, PermissionChange et OAuthAuthorization avec l’URL générée.", + "Enregistrez les paramètres, connectez l’espace de travail avec OAuth, puis @mentionnez l’application dans un ticket." + ], + "fields": { + "clientId": { + "label": "ID client OAuth", + "placeholder": "ID client OAuth Linear", + "help": "Copiez-le depuis l’application OAuth privée dans Linear." + }, + "clientSecret": { + "label": "Secret client OAuth", + "placeholder": "••••••", + "help": "Enregistré uniquement sur cette instance nanobot." + }, + "webhookSigningSecret": { + "label": "Secret de signature du webhook", + "placeholder": "••••••", + "help": "Utilisé pour vérifier Linear-Signature avant toute analyse du contenu du webhook." + }, + "publicBaseUrl": { + "label": "URL HTTPS publique", + "placeholder": "https://nanobot.example.com", + "help": "Une origine HTTPS stable acheminée vers l’écouteur ci-dessous ; n’incluez pas de chemin." + }, + "host": { + "label": "Hôte d’écoute", + "placeholder": "0.0.0.0" + }, + "port": { + "label": "Port d’écoute", + "placeholder": "3979" + }, + "webhookPath": { + "label": "Chemin du webhook", + "placeholder": "/linear/webhook" + }, + "oauthCallbackPath": { + "label": "Chemin de rappel OAuth", + "placeholder": "/linear/oauth/callback" + }, + "allowFrom": { + "label": "Utilisateurs Linear autorisés", + "placeholder": "ID utilisateur Linear séparés par des virgules", + "help": "Laissez vide pour utiliser l’association nanobot, ou saisissez * pour autoriser tous les utilisateurs des espaces connectés." + } + } + }, + "custom": { + "qrAlt": "Code QR d’autorisation Linear", + "authorizeTitle": "Autoriser dans Linear", + "authorizeDescription": "Ouvrez Linear dans ce navigateur ou scannez le code QR. nanobot activera le canal après l’autorisation.", + "waiting": "En attente de l’autorisation Linear...", + "connected": "Linear est connecté.", + "stopped": "L’autorisation a été interrompue.", + "connecting": "Connexion...", + "reconnect": "Connecter un autre espace de travail", + "connect": "Connecter Linear", + "openLinear": "Continuer dans Linear" + } +} diff --git a/nanobot/channels/linear/webui/locales/id.json b/nanobot/channels/linear/webui/locales/id.json new file mode 100644 index 000000000..d00e5907c --- /dev/null +++ b/nanobot/channels/linear/webui/locales/id.json @@ -0,0 +1,71 @@ +{ + "description": "Gunakan nanobot dari issue Linear melalui Agent Session native.", + "requirements": "Aplikasi OAuth Linear privat dan URL callback HTTPS publik yang stabil", + "setup": { + "docsLabel": "Buka panduan penyiapan Linear", + "officialLabel": "Buat aplikasi OAuth Linear", + "tryIt": "Mention aplikasi dalam komentar issue. Pesan lanjutan di Agent Session tidak memerlukan mention lagi.", + "summary": "Buat aplikasi OAuth Linear privat, simpan kredensial dan URL publiknya, lalu otorisasi workspace. Setiap sesi baru memerlukan @mention eksplisit; komentar biasa akan diabaikan.", + "steps": [ + "Ekspos instans nanobot ini melalui URL HTTPS yang stabil (tunnel dapat digunakan).", + "Buat aplikasi OAuth privat di Linear dengan scope read, write, dan app:mentionable. Jangan tambahkan app:assignable.", + "Daftarkan webhook aplikasi untuk AgentSessionEvent, PermissionChange, dan OAuthAuthorization menggunakan URL yang dibuat.", + "Simpan pengaturan, hubungkan workspace melalui OAuth, lalu @mention aplikasi pada issue." + ], + "fields": { + "clientId": { + "label": "ID klien OAuth", + "placeholder": "ID klien OAuth Linear", + "help": "Salin dari aplikasi OAuth privat di Linear." + }, + "clientSecret": { + "label": "Secret klien OAuth", + "placeholder": "••••••", + "help": "Hanya disimpan oleh instans nanobot ini." + }, + "webhookSigningSecret": { + "label": "Secret penandatanganan webhook", + "placeholder": "••••••", + "help": "Digunakan untuk memverifikasi Linear-Signature sebelum isi webhook diurai." + }, + "publicBaseUrl": { + "label": "URL HTTPS publik", + "placeholder": "https://nanobot.example.com", + "help": "Origin HTTPS stabil yang diarahkan ke listener di bawah; jangan sertakan path." + }, + "host": { + "label": "Host listener", + "placeholder": "0.0.0.0" + }, + "port": { + "label": "Port listener", + "placeholder": "3979" + }, + "webhookPath": { + "label": "Path webhook", + "placeholder": "/linear/webhook" + }, + "oauthCallbackPath": { + "label": "Path callback OAuth", + "placeholder": "/linear/oauth/callback" + }, + "allowFrom": { + "label": "Pengguna Linear yang diizinkan", + "placeholder": "ID pengguna Linear, dipisahkan koma", + "help": "Biarkan kosong untuk memakai pairing nanobot, atau gunakan * untuk mengizinkan semua pengguna di workspace yang terhubung." + } + } + }, + "custom": { + "qrAlt": "Kode QR otorisasi Linear", + "authorizeTitle": "Otorisasi di Linear", + "authorizeDescription": "Buka Linear di browser ini atau pindai kode QR. nanobot akan mengaktifkan channel setelah otorisasi.", + "waiting": "Menunggu otorisasi Linear...", + "connected": "Linear telah terhubung.", + "stopped": "Otorisasi dihentikan.", + "connecting": "Menghubungkan...", + "reconnect": "Hubungkan workspace lain", + "connect": "Hubungkan Linear", + "openLinear": "Lanjutkan di Linear" + } +} diff --git a/nanobot/channels/linear/webui/locales/ja.json b/nanobot/channels/linear/webui/locales/ja.json new file mode 100644 index 000000000..847799155 --- /dev/null +++ b/nanobot/channels/linear/webui/locales/ja.json @@ -0,0 +1,71 @@ +{ + "description": "Linear の issue からネイティブ Agent Session を通じて nanobot を利用します。", + "requirements": "非公開の Linear OAuth アプリと、安定した公開 HTTPS コールバック URL", + "setup": { + "docsLabel": "Linear セットアップガイドを開く", + "officialLabel": "Linear OAuth アプリを作成", + "tryIt": "issue のコメントでアプリをメンションしてください。Agent Session 内の続きのメッセージでは、再度メンションする必要はありません。", + "summary": "非公開の Linear OAuth アプリを作成し、認証情報と公開 URL を保存してからワークスペースを認証します。新しいセッションの開始には明示的な @メンションが必要で、通常のコメントは無視されます。", + "steps": [ + "この nanobot インスタンスを安定した HTTPS URL で公開します(トンネルも利用できます)。", + "Linear で read、write、app:mentionable スコープを持つ非公開 OAuth アプリを作成します。app:assignable は追加しないでください。", + "生成された URL を使い、アプリの webhook を AgentSessionEvent、PermissionChange、OAuthAuthorization に登録します。", + "設定を保存し、OAuth でワークスペースを接続してから、issue でアプリを @メンションします。" + ], + "fields": { + "clientId": { + "label": "OAuth クライアント ID", + "placeholder": "Linear OAuth クライアント ID", + "help": "Linear の非公開 OAuth アプリからコピーします。" + }, + "clientSecret": { + "label": "OAuth クライアントシークレット", + "placeholder": "••••••", + "help": "この nanobot インスタンス内にのみ保存されます。" + }, + "webhookSigningSecret": { + "label": "Webhook 署名シークレット", + "placeholder": "••••••", + "help": "Webhook の本文を解析する前に Linear-Signature を検証するために使います。" + }, + "publicBaseUrl": { + "label": "公開 HTTPS URL", + "placeholder": "https://nanobot.example.com", + "help": "下のリスナーへ転送される安定した HTTPS オリジンを指定します。パスは含めないでください。" + }, + "host": { + "label": "リッスンホスト", + "placeholder": "0.0.0.0" + }, + "port": { + "label": "リッスンポート", + "placeholder": "3979" + }, + "webhookPath": { + "label": "Webhook パス", + "placeholder": "/linear/webhook" + }, + "oauthCallbackPath": { + "label": "OAuth コールバックパス", + "placeholder": "/linear/oauth/callback" + }, + "allowFrom": { + "label": "許可する Linear ユーザー", + "placeholder": "Linear ユーザー ID(カンマ区切り)", + "help": "nanobot のペアリングを使う場合は空欄にします。接続済みワークスペースの全ユーザーを許可する場合のみ * を指定してください。" + } + } + }, + "custom": { + "qrAlt": "Linear 認証 QR コード", + "authorizeTitle": "Linear で認証", + "authorizeDescription": "このブラウザで Linear を開くか、QR コードを読み取ってください。認証後、nanobot がチャンネルを有効にします。", + "waiting": "Linear の認証を待っています...", + "connected": "Linear に接続しました。", + "stopped": "認証を中止しました。", + "connecting": "接続しています...", + "reconnect": "別のワークスペースを接続", + "connect": "Linear に接続", + "openLinear": "Linear で続行" + } +} diff --git a/nanobot/channels/linear/webui/locales/ko.json b/nanobot/channels/linear/webui/locales/ko.json new file mode 100644 index 000000000..34bf8cbdb --- /dev/null +++ b/nanobot/channels/linear/webui/locales/ko.json @@ -0,0 +1,71 @@ +{ + "description": "Linear 이슈에서 네이티브 Agent Session을 통해 nanobot을 사용합니다.", + "requirements": "비공개 Linear OAuth 앱과 안정적인 공개 HTTPS 콜백 URL", + "setup": { + "docsLabel": "Linear 설정 가이드 열기", + "officialLabel": "Linear OAuth 앱 만들기", + "tryIt": "이슈 댓글에서 앱을 멘션하세요. Agent Session 안의 후속 메시지에는 다시 멘션할 필요가 없습니다.", + "summary": "비공개 Linear OAuth 앱을 만들고 인증 정보와 공개 URL을 저장한 다음 워크스페이스를 승인하세요. 새 세션은 명시적인 @멘션으로만 시작되며 일반 댓글은 무시됩니다.", + "steps": [ + "이 nanobot 인스턴스를 안정적인 HTTPS URL로 공개하세요(터널을 사용할 수 있습니다).", + "Linear에서 read, write, app:mentionable 범위가 있는 비공개 OAuth 앱을 만드세요. app:assignable은 추가하지 마세요.", + "생성된 URL로 앱 webhook을 AgentSessionEvent, PermissionChange, OAuthAuthorization에 구독하세요.", + "설정을 저장하고 OAuth로 워크스페이스를 연결한 다음 이슈에서 앱을 @멘션하세요." + ], + "fields": { + "clientId": { + "label": "OAuth 클라이언트 ID", + "placeholder": "Linear OAuth 클라이언트 ID", + "help": "Linear의 비공개 OAuth 앱에서 복사하세요." + }, + "clientSecret": { + "label": "OAuth 클라이언트 시크릿", + "placeholder": "••••••", + "help": "이 nanobot 인스턴스에만 저장됩니다." + }, + "webhookSigningSecret": { + "label": "Webhook 서명 시크릿", + "placeholder": "••••••", + "help": "Webhook 본문을 파싱하기 전에 Linear-Signature를 검증하는 데 사용됩니다." + }, + "publicBaseUrl": { + "label": "공개 HTTPS URL", + "placeholder": "https://nanobot.example.com", + "help": "아래 리스너로 연결되는 안정적인 HTTPS 오리진입니다. 경로는 포함하지 마세요." + }, + "host": { + "label": "수신 호스트", + "placeholder": "0.0.0.0" + }, + "port": { + "label": "수신 포트", + "placeholder": "3979" + }, + "webhookPath": { + "label": "Webhook 경로", + "placeholder": "/linear/webhook" + }, + "oauthCallbackPath": { + "label": "OAuth 콜백 경로", + "placeholder": "/linear/oauth/callback" + }, + "allowFrom": { + "label": "허용된 Linear 사용자", + "placeholder": "쉼표로 구분한 Linear 사용자 ID", + "help": "nanobot 페어링을 사용하려면 비워 두세요. 연결된 워크스페이스의 모든 사용자를 허용하려면 *를 사용하세요." + } + } + }, + "custom": { + "qrAlt": "Linear 승인 QR 코드", + "authorizeTitle": "Linear에서 승인", + "authorizeDescription": "이 브라우저에서 Linear를 열거나 QR 코드를 스캔하세요. 승인 후 nanobot이 채널을 활성화합니다.", + "waiting": "Linear 승인을 기다리는 중...", + "connected": "Linear가 연결되었습니다.", + "stopped": "승인이 중지되었습니다.", + "connecting": "연결 중...", + "reconnect": "다른 워크스페이스 연결", + "connect": "Linear 연결", + "openLinear": "Linear에서 계속" + } +} diff --git a/nanobot/channels/linear/webui/locales/pt-BR.json b/nanobot/channels/linear/webui/locales/pt-BR.json new file mode 100644 index 000000000..caa01e3d7 --- /dev/null +++ b/nanobot/channels/linear/webui/locales/pt-BR.json @@ -0,0 +1,71 @@ +{ + "description": "Use o nanobot em issues do Linear por meio de Agent Sessions nativas.", + "requirements": "Um aplicativo OAuth privado do Linear e uma URL pública HTTPS estável para callbacks", + "setup": { + "docsLabel": "Abrir o guia de configuração do Linear", + "officialLabel": "Criar aplicativo OAuth do Linear", + "tryIt": "Mencione o aplicativo em um comentário da issue. As mensagens seguintes dentro da Agent Session não precisam de outra menção.", + "summary": "Crie um aplicativo OAuth privado do Linear, salve as credenciais e a URL pública e autorize o workspace. Cada nova sessão exige uma @menção explícita; comentários comuns são ignorados.", + "steps": [ + "Exponha esta instância do nanobot por uma URL HTTPS estável (um túnel pode ser usado).", + "Crie um aplicativo OAuth privado no Linear com os escopos read, write e app:mentionable. Não adicione app:assignable.", + "Inscreva o webhook do aplicativo em AgentSessionEvent, PermissionChange e OAuthAuthorization usando a URL gerada.", + "Salve as configurações, conecte o workspace com OAuth e @mencione o aplicativo em uma issue." + ], + "fields": { + "clientId": { + "label": "ID do cliente OAuth", + "placeholder": "ID do cliente OAuth do Linear", + "help": "Copie do aplicativo OAuth privado no Linear." + }, + "clientSecret": { + "label": "Segredo do cliente OAuth", + "placeholder": "••••••", + "help": "Armazenado somente nesta instância do nanobot." + }, + "webhookSigningSecret": { + "label": "Segredo de assinatura do webhook", + "placeholder": "••••••", + "help": "Usado para verificar Linear-Signature antes de interpretar o conteúdo do webhook." + }, + "publicBaseUrl": { + "label": "URL HTTPS pública", + "placeholder": "https://nanobot.example.com", + "help": "Uma origem HTTPS estável encaminhada ao listener abaixo; não inclua um caminho." + }, + "host": { + "label": "Host de escuta", + "placeholder": "0.0.0.0" + }, + "port": { + "label": "Porta de escuta", + "placeholder": "3979" + }, + "webhookPath": { + "label": "Caminho do webhook", + "placeholder": "/linear/webhook" + }, + "oauthCallbackPath": { + "label": "Caminho do callback OAuth", + "placeholder": "/linear/oauth/callback" + }, + "allowFrom": { + "label": "Usuários do Linear permitidos", + "placeholder": "IDs de usuário do Linear separados por vírgulas", + "help": "Deixe vazio para usar o pareamento do nanobot ou use * para permitir todos os usuários dos workspaces conectados." + } + } + }, + "custom": { + "qrAlt": "Código QR de autorização do Linear", + "authorizeTitle": "Autorizar no Linear", + "authorizeDescription": "Abra o Linear neste navegador ou escaneie o código QR. O nanobot habilitará o canal após a autorização.", + "waiting": "Aguardando autorização do Linear...", + "connected": "O Linear está conectado.", + "stopped": "A autorização foi interrompida.", + "connecting": "Conectando...", + "reconnect": "Conectar outro workspace", + "connect": "Conectar Linear", + "openLinear": "Continuar no Linear" + } +} diff --git a/nanobot/channels/linear/webui/locales/vi.json b/nanobot/channels/linear/webui/locales/vi.json new file mode 100644 index 000000000..9f68506d0 --- /dev/null +++ b/nanobot/channels/linear/webui/locales/vi.json @@ -0,0 +1,71 @@ +{ + "description": "Sử dụng nanobot từ issue Linear thông qua Agent Session gốc.", + "requirements": "Ứng dụng OAuth Linear riêng tư và URL callback HTTPS công khai, ổn định", + "setup": { + "docsLabel": "Mở hướng dẫn thiết lập Linear", + "officialLabel": "Tạo ứng dụng OAuth Linear", + "tryIt": "Nhắc đến ứng dụng trong bình luận của issue. Tin nhắn tiếp theo trong Agent Session không cần nhắc lại.", + "summary": "Tạo ứng dụng OAuth Linear riêng tư, lưu thông tin xác thực và URL công khai, rồi cấp quyền cho workspace. Mỗi phiên mới cần @mention rõ ràng; bình luận thông thường sẽ bị bỏ qua.", + "steps": [ + "Công khai phiên bản nanobot này qua URL HTTPS ổn định (có thể dùng tunnel).", + "Tạo ứng dụng OAuth riêng tư trong Linear với các scope read, write và app:mentionable. Không thêm app:assignable.", + "Đăng ký webhook của ứng dụng cho AgentSessionEvent, PermissionChange và OAuthAuthorization bằng URL được tạo.", + "Lưu cài đặt, kết nối workspace qua OAuth, rồi @mention ứng dụng trong một issue." + ], + "fields": { + "clientId": { + "label": "ID máy khách OAuth", + "placeholder": "ID máy khách OAuth Linear", + "help": "Sao chép từ ứng dụng OAuth riêng tư trong Linear." + }, + "clientSecret": { + "label": "Mã bí mật máy khách OAuth", + "placeholder": "••••••", + "help": "Chỉ được lưu trên phiên bản nanobot này." + }, + "webhookSigningSecret": { + "label": "Mã bí mật ký webhook", + "placeholder": "••••••", + "help": "Dùng để xác minh Linear-Signature trước khi phân tích nội dung webhook." + }, + "publicBaseUrl": { + "label": "URL HTTPS công khai", + "placeholder": "https://nanobot.example.com", + "help": "Origin HTTPS ổn định được chuyển tiếp tới listener bên dưới; không bao gồm path." + }, + "host": { + "label": "Host lắng nghe", + "placeholder": "0.0.0.0" + }, + "port": { + "label": "Cổng lắng nghe", + "placeholder": "3979" + }, + "webhookPath": { + "label": "Đường dẫn webhook", + "placeholder": "/linear/webhook" + }, + "oauthCallbackPath": { + "label": "Đường dẫn callback OAuth", + "placeholder": "/linear/oauth/callback" + }, + "allowFrom": { + "label": "Người dùng Linear được phép", + "placeholder": "ID người dùng Linear, phân tách bằng dấu phẩy", + "help": "Để trống để dùng ghép đôi nanobot, hoặc dùng * để cho phép mọi người dùng trong các workspace đã kết nối." + } + } + }, + "custom": { + "qrAlt": "Mã QR cấp quyền Linear", + "authorizeTitle": "Cấp quyền trong Linear", + "authorizeDescription": "Mở Linear trong trình duyệt này hoặc quét mã QR. nanobot sẽ bật channel sau khi được cấp quyền.", + "waiting": "Đang chờ cấp quyền Linear...", + "connected": "Linear đã được kết nối.", + "stopped": "Đã dừng cấp quyền.", + "connecting": "Đang kết nối...", + "reconnect": "Kết nối workspace khác", + "connect": "Kết nối Linear", + "openLinear": "Tiếp tục trong Linear" + } +} diff --git a/nanobot/channels/linear/webui/locales/zh-CN.json b/nanobot/channels/linear/webui/locales/zh-CN.json new file mode 100644 index 000000000..4326166d5 --- /dev/null +++ b/nanobot/channels/linear/webui/locales/zh-CN.json @@ -0,0 +1 @@ +{"description":"通过 Linear 原生 Agent Session 在 issue 中使用 nanobot。","requirements":"一个私有 Linear OAuth 应用和稳定的公网 HTTPS 回调地址","setup":{"docsLabel":"打开 Linear 配置指南","officialLabel":"创建 Linear OAuth 应用","tryIt":"在 issue 评论中 @ 应用;进入 Agent Session 后,后续对话无需重复 @。","summary":"创建私有 Linear OAuth 应用,保存凭据和公网地址,再授权工作区。新会话必须显式 @ 应用,普通评论会被忽略。","steps":["用稳定的 HTTPS 地址暴露此 nanobot 实例(可以使用隧道)。","在 Linear 创建私有 OAuth 应用,启用 read、write 和 app:mentionable;不要启用 app:assignable。","将应用 webhook 订阅 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,并填写生成的 webhook 地址。","保存设置、通过 OAuth 连接工作区,然后在 issue 中 @ 应用。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"从 Linear 私有 OAuth 应用中复制。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只保存在此 nanobot 实例中。"},"webhookSigningSecret":{"label":"Webhook 签名密钥","placeholder":"••••••","help":"在解析 webhook 内容前验证 Linear-Signature。"},"publicBaseUrl":{"label":"公网 HTTPS 地址","placeholder":"https://nanobot.example.com","help":"稳定且能转发到下方监听端口的 HTTPS 源地址,不要包含路径。"},"host":{"label":"监听地址","placeholder":"0.0.0.0"},"port":{"label":"监听端口","placeholder":"3979"},"webhookPath":{"label":"Webhook 路径","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回调路径","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允许的 Linear 用户","placeholder":"用逗号分隔 Linear 用户 ID","help":"留空使用 nanobot 配对;填写 * 允许已连接工作区内的所有用户。"}}},"custom":{"qrAlt":"Linear 授权二维码","authorizeTitle":"在 Linear 中授权","authorizeDescription":"在当前浏览器打开 Linear 或扫描二维码;授权后 nanobot 会自动启用 channel。","waiting":"正在等待 Linear 授权……","connected":"Linear 已连接。","stopped":"授权已停止。","connecting":"正在连接……","reconnect":"连接另一个工作区","connect":"连接 Linear","openLinear":"前往 Linear"}} diff --git a/nanobot/channels/linear/webui/locales/zh-TW.json b/nanobot/channels/linear/webui/locales/zh-TW.json new file mode 100644 index 000000000..fefe5e27a --- /dev/null +++ b/nanobot/channels/linear/webui/locales/zh-TW.json @@ -0,0 +1 @@ +{"description":"透過 Linear 原生 Agent Session 在 issue 中使用 nanobot。","requirements":"一個私有 Linear OAuth 應用程式和穩定的公網 HTTPS 回呼網址","setup":{"docsLabel":"開啟 Linear 設定指南","officialLabel":"建立 Linear OAuth 應用程式","tryIt":"在 issue 評論中 @ 應用程式;進入 Agent Session 後,後續對話無需重複 @。","summary":"建立私有 Linear OAuth 應用程式,儲存憑證和公網網址,再授權工作區。新會話必須明確 @ 應用程式,普通評論會被忽略。","steps":["用穩定的 HTTPS 網址公開此 nanobot 實例(可以使用隧道)。","在 Linear 建立私有 OAuth 應用程式,啟用 read、write 和 app:mentionable;不要啟用 app:assignable。","將應用程式 webhook 訂閱 AgentSessionEvent、PermissionChange 和 OAuthAuthorization,並填入產生的 webhook 網址。","儲存設定、透過 OAuth 連接工作區,然後在 issue 中 @ 應用程式。"],"fields":{"clientId":{"label":"OAuth Client ID","placeholder":"Linear OAuth Client ID","help":"從 Linear 私有 OAuth 應用程式中複製。"},"clientSecret":{"label":"OAuth Client Secret","placeholder":"••••••","help":"只儲存在此 nanobot 實例中。"},"webhookSigningSecret":{"label":"Webhook 簽署密鑰","placeholder":"••••••","help":"在解析 webhook 內容前驗證 Linear-Signature。"},"publicBaseUrl":{"label":"公網 HTTPS 網址","placeholder":"https://nanobot.example.com","help":"穩定且能轉送到下方監聽連接埠的 HTTPS 來源網址,不要包含路徑。"},"host":{"label":"監聽位址","placeholder":"0.0.0.0"},"port":{"label":"監聽連接埠","placeholder":"3979"},"webhookPath":{"label":"Webhook 路徑","placeholder":"/linear/webhook"},"oauthCallbackPath":{"label":"OAuth 回呼路徑","placeholder":"/linear/oauth/callback"},"allowFrom":{"label":"允許的 Linear 使用者","placeholder":"以逗號分隔 Linear 使用者 ID","help":"留空使用 nanobot 配對;填寫 * 允許已連接工作區內的所有使用者。"}}},"custom":{"qrAlt":"Linear 授權 QR code","authorizeTitle":"在 Linear 中授權","authorizeDescription":"在目前瀏覽器開啟 Linear 或掃描 QR code;授權後 nanobot 會自動啟用 channel。","waiting":"正在等待 Linear 授權……","connected":"Linear 已連接。","stopped":"授權已停止。","connecting":"正在連接……","reconnect":"連接另一個工作區","connect":"連接 Linear","openLinear":"前往 Linear"}} diff --git a/tests/channels/test_channel_plugins.py b/tests/channels/test_channel_plugins.py index aadce9c44..c99045e58 100644 --- a/tests/channels/test_channel_plugins.py +++ b/tests/channels/test_channel_plugins.py @@ -281,7 +281,18 @@ def test_channels_config_keeps_shared_delivery_defaults(): @pytest.mark.parametrize( "name", - ["websocket", "telegram", "discord", "slack", "email", "feishu", "matrix", "weixin", "whatsapp"], + [ + "websocket", + "telegram", + "discord", + "slack", + "email", + "feishu", + "linear", + "matrix", + "weixin", + "whatsapp", + ], ) def test_special_setup_validation_is_owned_by_channel_package(name: str): plugin = load_channel_package(name) @@ -292,7 +303,7 @@ def test_special_setup_validation_is_owned_by_channel_package(name: str): assert plugin.setup.validator.__module__ == f"nanobot.channels.{name}.validation" -@pytest.mark.parametrize("name", ["feishu", "weixin", "whatsapp"]) +@pytest.mark.parametrize("name", ["feishu", "linear", "weixin", "whatsapp"]) def test_interactive_connector_is_owned_by_channel_package(name: str): plugin = load_channel_package(name) @@ -2667,6 +2678,7 @@ def test_optional_dependency_metadata_for_enable(): "dingtalk", "discord", "feishu", + "linear", "matrix", "mochat", "msteams", diff --git a/tests/channels/test_channel_setup.py b/tests/channels/test_channel_setup.py index 2cbb2277c..fb2a9c49e 100644 --- a/tests/channels/test_channel_setup.py +++ b/tests/channels/test_channel_setup.py @@ -18,6 +18,7 @@ EXPECTED_CHANNELS = { "discord", "email", "feishu", + "linear", "matrix", "mattermost", "mochat", diff --git a/webui/src/tests/channel-locale-registry.test.ts b/webui/src/tests/channel-locale-registry.test.ts index c1a47e4c7..5af0a9c11 100644 --- a/webui/src/tests/channel-locale-registry.test.ts +++ b/webui/src/tests/channel-locale-registry.test.ts @@ -10,6 +10,7 @@ const expectedChannels = [ "discord", "email", "feishu", + "linear", "matrix", "mattermost", "mochat", diff --git a/webui/src/tests/linear-channel-ui.test.ts b/webui/src/tests/linear-channel-ui.test.ts new file mode 100644 index 000000000..895f4c629 --- /dev/null +++ b/webui/src/tests/linear-channel-ui.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest"; + +import { linearManifestUrl } from "../../../nanobot/channels/linear/webui/LinearConnectFlow"; + +describe("Linear channel UI", () => { + it("creates a private mention-only Agent app manifest with exact callback routes", () => { + const url = new URL( + linearManifestUrl( + "https://nanobot.example.com", + "/linear/webhook", + "/linear/oauth/callback", + ), + ); + const manifest = JSON.parse(url.searchParams.get("manifest") ?? "{}") as { + distribution?: string; + oauth?: { redirect_uris?: string[] }; + webhook?: { url?: string; resourceTypes?: string[] }; + }; + + expect(url.origin + url.pathname).toBe( + "https://linear.app/settings/api/applications/new", + ); + expect(manifest.distribution).toBe("private"); + expect(manifest.oauth?.redirect_uris).toEqual([ + "https://nanobot.example.com/linear/oauth/callback", + ]); + expect(manifest.webhook?.url).toBe( + "https://nanobot.example.com/linear/webhook", + ); + expect(manifest.webhook?.resourceTypes).toEqual([ + "AgentSessionEvent", + "PermissionChange", + "OAuthAuthorization", + ]); + expect(manifest.webhook?.resourceTypes).not.toContain("Comment"); + }); +}); diff --git a/webui/src/tests/settings-channels.test.tsx b/webui/src/tests/settings-channels.test.tsx index a241bd551..a53d2239f 100644 --- a/webui/src/tests/settings-channels.test.tsx +++ b/webui/src/tests/settings-channels.test.tsx @@ -31,7 +31,7 @@ function channelSetupField( } function channelSetupContract( - channel: "discord" | "email" | "feishu" | "matrix" | "qq", + channel: "discord" | "email" | "feishu" | "linear" | "matrix" | "qq", ): ChannelSetupContract { const field = ( name: string, @@ -108,6 +108,22 @@ function channelSetupContract( { alternatives: [["channels.feishu.appSecret"]] }, ], }; + case "linear": + return { + fields: [ + field("clientId", "string", { required: true }), + field("clientSecret", "secret", { required: true }), + field("webhookSigningSecret", "secret", { required: true }), + field("publicBaseUrl", "string", { required: true }), + field("host", "string", { defaultValue: "0.0.0.0" }), + field("port", "int", { defaultValue: "3979" }), + field("webhookPath", "string", { defaultValue: "/linear/webhook" }), + field("oauthCallbackPath", "string", { + defaultValue: "/linear/oauth/callback", + }), + field("allowFrom", "list"), + ], + }; case "matrix": return { official_url: "https://matrix.org/ecosystem/clients/", @@ -859,6 +875,103 @@ describe("Settings channels", () => { expect(await screen.findByText("Scan with Feishu")).toBeInTheDocument(); }); + it("saves a Linear public URL before OAuth credentials and reveals the app manifest", async () => { + const linearFeature = { + name: "linear", + display_name: "Linear", + webui: "webui/index.tsx", + type: "channel", + enabled: false, + configured: false, + installed: true, + ready: false, + status: "not_enabled", + install_supported: true, + requires_restart: false, + setup: channelSetupContract("linear"), + }; + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url === "/api/settings") return jsonResponse(settingsPayload()); + if (url === "/api/settings/cli-apps") { + return jsonResponse({ apps: [], installed_count: 0 }); + } + if (url === "/api/settings/mcp-presets") { + return jsonResponse({ presets: [], installed_count: 0 }); + } + if (url === "/api/settings/nanobot-features") { + return jsonResponse({ features: [linearFeature], enabled_count: 0 }); + } + return { ok: false, status: 404, json: async () => ({}) } as Response; + }), + ); + requestMutationMock + .mockResolvedValueOnce({ + name: "linear", + status: "needs_setup", + checks: [], + missing_fields: [ + "channels.linear.clientId", + "channels.linear.clientSecret", + "channels.linear.webhookSigningSecret", + ], + can_enable: false, + requires_restart: false, + message: "Missing Linear credentials.", + }) + .mockResolvedValueOnce({ + name: "linear", + saved: true, + saved_keys: ["channels.linear.publicBaseUrl"], + nanobot_features: { + features: [{ + ...linearFeature, + config_values: { + "channels.linear.publicBaseUrl": "https://nanobot.example.com", + "channels.linear.host": "0.0.0.0", + "channels.linear.port": "3979", + "channels.linear.webhookPath": "/linear/webhook", + "channels.linear.oauthCallbackPath": "/linear/oauth/callback", + }, + configured_fields: ["channels.linear.publicBaseUrl"], + }], + enabled_count: 0, + requires_restart: false, + }, + }); + + renderSettingsView({ initialSection: "channels" }); + + expect(await screen.findByRole("button", { name: "View Linear settings" })).toBeInTheDocument(); + fireEvent.change(screen.getByPlaceholderText("https://nanobot.example.com"), { + target: { value: "https://nanobot.example.com" }, + }); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + + await waitFor(() => + expect(requestMutationMock).toHaveBeenCalledWith( + "settings.channel.configure", + expect.objectContaining({ + name: "linear", + values: expect.objectContaining({ + "channels.linear.publicBaseUrl": "https://nanobot.example.com", + }), + }), + 150_000, + ), + ); + expect( + await screen.findByText( + "Partial settings saved. Complete the required fields before connecting.", + ), + ).toBeInTheDocument(); + expect( + await screen.findByRole("button", { name: "Create prefilled Linear app" }), + ).toBeInTheDocument(); + }); + it("enables configured Feishu assistant without starting a new connect flow", async () => { const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const url = String(input);