mirror of
https://github.com/Sea-Haven-Industries/open-swe.git
synced 2026-09-30 12:43:16 +00:00
* chore: bake sfw binary into sandbox image (#1611) sfw only ships a launcher that fetches its real binary at first run and does a daily update check against api.github.com/repos/SocketDev/sfw-free. Both fail in the sandbox (restricted egress; the proxy injects the GitHub App installation token, which lacks access to that repo), so `sfw yarn install` errors with "could not fetch its binary". Pin sfw 2.0.6, warm + verify the binary cache at build, and set SFW_SKIP_UPDATE_CHECK=1 so runs use the baked binary offline. * feat: editable plan mode + fix review-plan banner overlap (#1610) * feat: editable plan mode + fix review-plan banner overlap Lets the thread owner edit the plan markdown by hand from the plan-review page (Edit -> textarea -> Save) via a new PUT /dashboard/api/plan/{id} endpoint that re-publishes the plan and mirrors it into the sandbox plan.md, so approve hands the edited plan to the agent as the source of truth. Also fixes the collapsed git-panel's floating expand button covering the "Review plan ->" banner by reserving space for it. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: abort plan approval when the published plan read fails get_plan_content() swallowed store errors and returned None, so a transient failure during approve would still mark the plan approved and dispatch the generic fallback text — silently dropping an owner's edited plan. Read the plan strictly (raise_on_error=True) so approval aborts instead, matching the comment read. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: show message timestamps (#1609) * feat: show message timestamps Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: suppress fallback message timestamps Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: stable message + tool-call hover timestamps Stamp a stable client-side arrival time per message and tool call (keyed by id, persisted to localStorage). Messages render the timestamp inline; tool rows reveal a dim timestamp chip on hover. Real backend created_at still takes precedence when present. * fix: hide client-stamped message timestamps Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: add PR trace resolution (#1612) * feat: add PR trace resolution Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: inject reviewer trace context as JSON Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: address review on PR trace resolution Use the documented LangSmith metadata filter syntax (and(eq(metadata_key,...), eq(metadata_value,...))) instead of has(metadata, '{...}'), which does not match runs — _list_thread_runs was silently returning nothing. Bound full-text searches to a 90-day window so they don't hit LangSmith's large-window rate limit. Also folds in the best-effort branch->head-sha resolver (dropping the weighted scoring/threshold + repo/file evidence + GitHub hydration), sandbox JSON injection, and the admin "Resolve trace" dry-run endpoint. The IDOR findings are moot: resolve_pr_to_threads/summarize_agent_session were removed; resolution now runs deterministically from the trusted run config with no model-controlled pr_url or thread_id. * fix: scope branch trace search to the repo Branch names like fix-tests aren't unique across repos (or older PRs) in a shared tracing project, so an unscoped branch hit could resolve to an unrelated thread and write its runs into the reviewer sandbox. Require the repo slug to co-occur with the branch in matched runs; the full head SHA stays unscoped since it is globally unique. Addresses open-swe review on PR #1612. --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: include plan links in PR descriptions (#1613) Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: gate workflow pushes with approval (#1614) * feat: gate workflow pushes with approval Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: preserve proxy refresh test compatibility Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: bind workflow approvals to pushed ref Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: recover thread work as patch (#1615) * feat: recover thread work as patch Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: search sandbox cwd for recovery patches Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: omit plan link in PR description when no plan exists (#1618) Plan links in PR descriptions were always built from the thread id, so runs that never produced a plan linked to an empty plan-review page. Now the plan content store is consulted first; the link is only added when a plan with non-empty markdown actually exists. A transient store failure degrades gracefully (no link) rather than blocking PR creation. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: add filter & grouping menu to agents threads sidebar (#1617) Add a Cursor-style control to the agents sidebar that groups (None/Date/ Status/Project), filters (ownership, status, source, pull request, model, repo, include-resolved), and compacts the threads list. All client-side over already-fetched sidebar threads; preferences persist in localStorage. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * chore: update langsmith sdk to 0.9.3 (#1616) Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: clickable shared PR header in git panel and reviews (#1620) * feat: clickable shared PR header in git panel and reviews Replace the standalone "View PR" button in the agent git panel with a clickable PR title, matching the reviews view. Extract a shared PrHeader component reused by both the git panel and the review main body. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * refactor: drop PrHeader wrapper, use shared component directly The review-side PrHeader was just a thin adapter mapping detail -> the shared component's props. Inline it at the call site and use the shared PrHeader directly so there's a single component. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * refactor: durable interrupt dispatch + completion webhook (#1621) * wip(rebuild): core reliability spine - remove PR-babysitting (ci_autofix + ci_monitor graph + webhook wiring) - dispatch core: agent/dispatch.py with multitask_strategy=interrupt + durability=sync + completion webhook; reroute all webhook + plan triggers; drop the racy in-process lock + is_thread_active busy-check - completion webhook: agent/completion.py + /webhooks/run-complete loopback route for failure/timeout replies (idempotent) Co-authored-by: open-swe[bot] * feat(rebuild): async tools, reconcile, shared http timeouts, assembly tuning Parallel batch on top of the reliability spine: - async-ify all 24 tools (drop asyncio.run; requests->httpx); re-implement the http_request/fetch_url SSRF + DNS-rebinding defense httpx-natively and harden the IP check to 'not is_global' (+ IPv4-mapped unwrap) - reconcile.py: stale pending-run sweep (threads.search -> per-thread runs.list -> cancel_many), wired into the scheduler graph via task='reconcile' - shared DEFAULT_HTTP_TIMEOUT (agent/utils/http.py) on every bare httpx.AsyncClient() across utils/dashboard/webapp/middleware - run budget: MODEL_CALL_RECURSION_LIMIT 5000->250 - fix stale OpenAI->Anthropic fallback id (claude-opus-4-5 -> 4-8) - drop redundant custom repair middleware (deepagents auto-adds PatchToolCalls) - confirm tool-result eviction + summarization auto-wired via backend - slim system prompt ~8% (full harness-profile rewrite deferred) Co-authored-by: open-swe[bot] * feat(rebuild): harness-profile prompt + split webhooks out of webapp - prompt.py: own the system prompt via a registered harness profile (OPEN_SWE_SHARED_BASE, kept neutral so the read-only reviewer/analyzer that share it stay safe), registered across all 4 providers; per-thread values stay in construct_system_prompt. Assembled main-agent prompt ~6.8k -> ~3.1k tokens (~55% smaller); de-duped PR/commit/suite/force-push guidance; dropped ALL-CAPS markers. - webapp.py 3325 -> 1890 LOC: moved 14 per-source handlers into agent/webhooks/{linear,slack,github}.py; webapp re-exports them for the routes + tests; moved handlers reach shared helpers via the webapp namespace to preserve the test suite's monkeypatch targets. Full suite: 1168 passing, lint clean. Co-authored-by: open-swe[bot] * Restore MODEL_CALL_RECURSION_LIMIT to 5000 for long-running tasks Reverts the 250 cap from the run-budget change — long-running tasks legitimately need many model calls. The notify_step_limit_reached safety net still fires if a run does hit the cap, so runs end with a signal either way. Co-authored-by: open-swe[bot] * fix: address PR review (auth, SSRF, interrupted status, redirect headers) - completion.py: drop `interrupted` from failure statuses — with multitask_strategy=interrupt a follow-up ends the prior run as interrupted, which is healthy, not a failure to report. [open-swe] - /webhooks/run-complete: shared-secret auth — dispatch appends ?token= when RUN_COMPLETE_WEBHOOK_SECRET is set; route verifies via hmac.compare_digest. [corridor-security] - SSRF: extract the URL validator to agent/utils/url_safety.py and apply it before server-side image fetches in multimodal.fetch_image_block. [corridor-security] - http_request: preserve caller headers/extensions across redirect hops instead of dropping them on the first hop. [open-swe] Co-authored-by: open-swe[bot] * chore: remove REBUILD_PLAN.md (planning doc, not needed in the repo) Co-authored-by: open-swe[bot] * fix: fail closed on run-complete webhook auth when secret unset Corridor follow-up: verify_run_complete_token returns False (not True) when RUN_COMPLETE_WEBHOOK_SECRET is unset, so the public route is never unauthenticated. Logs a startup warning when the secret is absent, and dispatch skips registering the webhook when there's no secret (no rejected callbacks). Co-authored-by: open-swe[bot] --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: restore forced tool call to prevent premature run stops (#1622) Restore the ensure_no_empty_msg middleware and the always-call-a-tool system-prompt instruction that #1535 removed. When the model emits a message with no tool call (and hasn't already messaged the user or confirmed completion), the middleware re-injects a no_op / confirming_completion tool call so the run continues instead of ending mid-task. Shipping to test whether it fixes runs that stop halfway through. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * chore(deps): bump langgraph-checkpoint from 4.1.0 to 4.1.1 (#1619) Bumps [langgraph-checkpoint](https://github.com/langchain-ai/langgraph) from 4.1.0 to 4.1.1. - [Release notes](https://github.com/langchain-ai/langgraph/releases) - [Commits](https://github.com/langchain-ai/langgraph/compare/checkpoint==4.1.0...checkpoint==4.1.1) --- updated-dependencies: - dependency-name: langgraph-checkpoint dependency-version: 4.1.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * fix: post reviewer resolution notes verbatim (#1624) * fix: post reviewer resolution notes verbatim Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: stabilize dashboard follow-up e2e Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: preserve dashboard attribution in e2e Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: make e2e attribution marker durable Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: only echo found e2e attribution Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: check live dashboard attribution in e2e Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * hotfix: stop prompting agent/reviewer to wrap installs in sfw (#1625) Installs hung when prefixed with sfw inside the sandbox (trace 019f0608 stalled on a pending `sfw npm install` execute, never returned). Strip the Socket Firewall guidance from the agent and reviewer prompts so installs run through the project's package manager directly. sfw stays in the Docker image; nothing invokes it now. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: make plan view mobile friendly (#1636) Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: fall back to vision model for image threads (#1626) Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: surface Slack thread errors (#1627) * fix: surface Slack thread errors Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: don't set failure_reply_posted on Slack preprocessing errors The preprocessing error handler was setting failure_reply_posted=True, the same idempotency flag handle_run_completion checks to suppress duplicate run-failure replies. Since preprocessing failures happen before any run exists but the flag persists on the thread, a subsequent run failure on the same thread would be silently ignored. The preprocessing handler already posts its own Slack reply, so the run-completion idempotency flag should not be set here. --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * chore: avoid recapping Slack replies (#1629) * chore: avoid recapping Slack replies Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * chore: simplify Slack reply prompt wording Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> --------- Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: update Slack trace reply on web handoff (#1630) * fix: update Slack trace reply on web handoff Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: trigger web handoff on dashboard starts Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: format web handoff as contextual fragment Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: preserve trace_message_ts when overwriting Slack run mapping When store_slack_run_mapping is called without trace_message_ts (e.g. on follow-up Slack mentions), it was unconditionally overwriting the thread-level mapping and clobbering the timestamp captured from the initial trace reply. After that, _notify_slack_web_handoff could not find the original message, so a subsequent move to Web silently skipped the Slack trace update. Now, when trace_message_ts is not passed, the existing thread mapping is read first and its trace_message_ts is preserved. * style: ruff format --------- Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> Co-authored-by: Johannes du Plessis <51395795+johannes117@users.noreply.github.com> Co-authored-by: Johannes du Plessis <johannes@langchain.dev> * fix: pre-bundle shiki/@pierre deps to stop dev dynamic-import failures (#1643) * fix(ui): pre-bundle shiki/@pierre deps to stop dev dynamic-import failures shiki lazy-imports a grammar per language and these libs only live inside lazy route components, so Vite's startup scanner never sees them. They get discovered on first thread navigation, triggering a dep re-optimize + force-reload that aborts the in-flight route-chunk import, surfacing as "Failed to fetch dynamically imported module: .../$threadId.tsx". Pre-bundle them (and the github themes + common code-block languages) via optimizeDeps.include so the optimize happens once at startup. Dev-only; production bundles are unaffected. * fix: pre-bundle canonical shiki docker/make langs instead of aliases --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: show queued dashboard follow-ups (#1631) * feat: show queued dashboard follow-ups Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: de-dupe queued follow-ups while streaming --------- Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> Co-authored-by: Johannes du Plessis <johannes@langchain.dev> * feat: notify Slack on plan approval (#1632) * feat: notify Slack on plan approval Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: post Slack approval notice after successful dispatch Move the _maybe_post_plan_approved_to_slack call until after _dispatch_followup succeeds so the Slack thread is not told implementation is beginning before the LangGraph run is created. Addresses PR review comment. --------- Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> Co-authored-by: Johannes du Plessis <johannes@langchain.dev> * feat: include Slack channel context in prompts (#1633) Add cached Slack channel metadata enrichment for Slack-triggered runs so prompts can include channel names and descriptions without duplicate conversations.info calls.\n\nCo-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> * chore: keep plan guidance high-level (#1634) Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: publish plans from sandbox files (#1635) * feat: publish plans from sandbox files Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: avoid fixed plan filenames Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: virtualize local sandbox file paths Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: preserve plan_file_path across set_plan_status set_plan_status was rewriting the content record with only markdown and status, dropping plan_file_path. After a reject, the owner's dashboard edit would mirror to a different file than the agent's original, and the next save_plan could republish the stale file. Preserve plan_file_path when updating status. --------- Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: return to thread after plan approval (#1637) Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: add Slack breakout thread tool (#1638) * feat: add Slack breakout thread tool Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * chore: make fake LLM scripts declarative Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: exclude slack_start_new_thread from plan mode The breakout tool can dispatch a fresh agent run that starts outside the current plan-mode state, bypassing the approval flow. Add it to PLAN_MODE_EXCLUDED_TOOLS so it's hidden alongside the other mutating tools while planning. --------- Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * chore: require bun for ui agent work (#1639) Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: request actions read for sandbox logs (#1642) * fix: request actions read for sandbox logs Request optional Actions read permission for sandbox proxy tokens, with fallback for installations that have not approved it yet. Update setup docs and prompt guidance for safe GitHub Actions log usage. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: restore actions:read scope after workflow push After an approved workflow push, the guard was restoring the proxy with BASE_RUNTIME_PROXY_TOKEN_PERMISSIONS, which excludes the actions: read scope this PR adds. Restore with RUNTIME_PROXY_TOKEN_PERMISSIONS (which includes actions: read) and fall back to BASE if the install hasn't granted Actions read — mirroring the pattern in _create_sandbox_with_proxy. Addresses review comment on PR #1642. --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * fix: widen split review diffs (#1647) Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * chore: install missing deps before verification (#1646) Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * chore: switch ui to pnpm (#1645) * chore: require pnpm for ui agent work Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * chore: switch ui to pnpm Replace Bun and Yarn lockfiles with pnpm lockfile and update UI/Vercel commands to use pnpm. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * ci: use corepack for ui pnpm e2e build Run pnpm through Corepack in the E2E global setup so CI can use the pinned package manager without a separate pnpm install step. Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * feat: add Sonnet 5 to model picker (#1651) * chore: update Sonnet examples to Sonnet 5 Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * chore: add Sonnet 5 to model picker Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> --------- Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> * Remove dead breakout-thread e2e scenario after dropping the tool The merge resolution deferred upstream's Slack breakout-thread tool (slack_start_new_thread, #1638) since it depends on the #1621 dispatch module, but the e2e harness still scripted it. Removing the tool name from fake_llm.py's _tool_step call left a malformed scenario, crashing the langgraph-dev web server at import (TypeError: _tool_step() missing 'call_id') and failing Playwright E2E. Drop the "breakout" script scenario, its _is_breakout_request helper + ScriptRule, and the corresponding full_flow.spec.ts test. * Revert upstream pnpm switch; keep bun for the UI build The merge auto-adopted upstream's pnpm switch (#1645) in tests/e2e/ global-setup.ts and ui/package.json, but our fork builds the UI with bun (vercel.json + the E2E workflow's setup-bun). That left the Playwright globalSetup running `corepack pnpm install --frozen-lockfile` with no pnpm-lock.yaml, failing E2E at UI build time. Revert global-setup.ts and ui/package.json to the dev (bun) baseline, drop the merge-added ui/pnpm-lock.yaml, and remove the re-added ui/AGENTS.md (our fork had deleted it). * Align plan-review e2e + UI with the HEAD (pre-#1635) backend The merge left a split plan vertical: the backend save_plan/plan_api are HEAD (we deferred the editable-plan/sandbox-publish features #1610/#1635/ #1637 per #80), but the plan UI and e2e harness were upstream's. The fake_llm scenario called save_plan(plan_file_path=...) — upstream's file-based #1635 contract — while HEAD save_plan takes plan_markdown, so the plan never saved and PlanReview never rendered (E2E failure on the plan-review locator). Pass plan_markdown to save_plan, and revert PlanReview.tsx / plan.ts / $threadId_.plan.tsx / plan_review.spec.ts to the dev baseline so the whole plan flow (save -> render -> approve -> implement) is consistent with the HEAD backend. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Johannes du Plessis <johannes@langchain.dev> Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com> Co-authored-by: Ramon Nogueira <ramon.nogueira@langchain.dev> Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com> Co-authored-by: Caroline di Vittorio <43390382+carolinedivittorio@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Johannes du Plessis <51395795+johannes117@users.noreply.github.com> Co-authored-by: Ankush Gola <9536492+agola11@users.noreply.github.com> Co-authored-by: Mukil Loganathan <mukil@langchain.dev>
489 lines
20 KiB
Python
489 lines
20 KiB
Python
"""GitHub OAuth and LangSmith authentication utilities."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
from datetime import UTC, datetime, timedelta
|
|
from typing import Any, Literal
|
|
|
|
import httpx
|
|
import jwt
|
|
from langgraph.config import get_config
|
|
from langgraph.graph.state import RunnableConfig
|
|
from langgraph_sdk import get_client
|
|
|
|
from .github_app import get_github_app_installation_token_with_expiry
|
|
from .github_token import cache_github_token_for_thread, get_github_token_from_thread
|
|
from .http import DEFAULT_HTTP_TIMEOUT
|
|
from .linear import comment_on_linear_issue
|
|
from .slack import post_slack_thread_reply
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
client = get_client()
|
|
|
|
|
|
class GitHubUserAuthRequired(RuntimeError):
|
|
"""Raised when a mapped user has no valid GitHub OAuth token.
|
|
|
|
Signals that the run cannot proceed on the user's behalf and that the user
|
|
must (re-)authenticate. The Slack webhook blocks before creating a run, so
|
|
this is a defense-in-depth signal at execution time.
|
|
"""
|
|
|
|
def __init__(self, source: str, github_login: str | None) -> None:
|
|
self.source = source
|
|
self.github_login = github_login
|
|
super().__init__(f"GitHub authentication required for {source} user '{github_login}'")
|
|
|
|
|
|
LANGSMITH_API_KEY = os.environ.get("LANGSMITH_API_KEY_PROD", "")
|
|
LANGSMITH_API_URL = os.environ.get("LANGSMITH_ENDPOINT", "https://api.smith.langchain.com")
|
|
LANGSMITH_HOST_API_URL = os.environ.get("LANGSMITH_HOST_API_URL", "https://api.host.langchain.com")
|
|
GITHUB_OAUTH_PROVIDER_ID = os.environ.get("GITHUB_OAUTH_PROVIDER_ID", "")
|
|
X_SERVICE_AUTH_JWT_SECRET = os.environ.get("X_SERVICE_AUTH_JWT_SECRET", "")
|
|
USER_ID_API_KEY_MAP = os.environ.get("USER_ID_API_KEY_MAP", "")
|
|
|
|
logger.debug(
|
|
"Auth env snapshot: LANGSMITH_API_KEY_PROD=%s LANGSMITH_ENDPOINT=%s "
|
|
"LANGSMITH_HOST_API_URL=%s GITHUB_OAUTH_PROVIDER_ID=%s",
|
|
"set" if LANGSMITH_API_KEY else "missing",
|
|
"set" if LANGSMITH_API_URL else "missing",
|
|
"set" if LANGSMITH_HOST_API_URL else "missing",
|
|
"set" if GITHUB_OAUTH_PROVIDER_ID else "missing",
|
|
)
|
|
|
|
|
|
def is_bot_token_only_mode() -> bool:
|
|
"""Check if we're in bot-token-only mode.
|
|
|
|
This is the case when LANGSMITH_API_KEY_PROD is set (deployed) but neither
|
|
X_SERVICE_AUTH_JWT_SECRET nor USER_ID_API_KEY_MAP is configured, meaning we
|
|
can't resolve per-user GitHub OAuth tokens. In this mode the GitHub App
|
|
installation token is used for all git operations instead.
|
|
"""
|
|
return bool(LANGSMITH_API_KEY and not X_SERVICE_AUTH_JWT_SECRET and not USER_ID_API_KEY_MAP)
|
|
|
|
|
|
def _retry_instruction(source: str) -> str:
|
|
if source == "slack":
|
|
return "Once authenticated, mention me again in this Slack thread to retry."
|
|
return "Once authenticated, reply to this issue mentioning @openswe to retry."
|
|
|
|
|
|
def _source_account_label(source: str) -> str:
|
|
if source == "slack":
|
|
return "Slack"
|
|
return "Linear"
|
|
|
|
|
|
def _auth_link_text(source: str, auth_url: str) -> str:
|
|
if source == "slack":
|
|
return auth_url
|
|
return f"[Authenticate with GitHub]({auth_url})"
|
|
|
|
|
|
def _work_item_label(source: str) -> str:
|
|
if source == "slack":
|
|
return "thread"
|
|
return "issue"
|
|
|
|
|
|
def get_secret_key_for_user(
|
|
user_id: str, tenant_id: str, expiration_seconds: int = 300
|
|
) -> tuple[str, Literal["service", "api_key"]]:
|
|
"""Create a short-lived service JWT for authenticating as a specific user."""
|
|
if not X_SERVICE_AUTH_JWT_SECRET:
|
|
msg = "X_SERVICE_AUTH_JWT_SECRET is not configured. Cannot generate service keys."
|
|
raise ValueError(msg)
|
|
|
|
payload = {
|
|
"sub": "unspecified",
|
|
"exp": datetime.now(UTC) + timedelta(seconds=expiration_seconds),
|
|
"user_id": user_id,
|
|
"tenant_id": tenant_id,
|
|
}
|
|
return jwt.encode(payload, X_SERVICE_AUTH_JWT_SECRET, algorithm="HS256"), "service"
|
|
|
|
|
|
async def get_ls_user_id_from_email(email: str) -> dict[str, str | None]:
|
|
"""Get the LangSmith user ID and tenant ID from a user's email."""
|
|
if not LANGSMITH_API_KEY:
|
|
logger.warning("LangSmith API key not configured; cannot resolve LS user for %s", email)
|
|
return {"ls_user_id": None, "tenant_id": None}
|
|
|
|
url = f"{LANGSMITH_API_URL}/api/v1/workspaces/current/members/active"
|
|
|
|
async with httpx.AsyncClient(timeout=DEFAULT_HTTP_TIMEOUT) as client:
|
|
try:
|
|
response = await client.get(
|
|
url,
|
|
headers={"X-API-Key": LANGSMITH_API_KEY},
|
|
params={"emails": [email]},
|
|
)
|
|
response.raise_for_status()
|
|
members = response.json()
|
|
|
|
if members and len(members) > 0:
|
|
member = members[0]
|
|
return {
|
|
"ls_user_id": member.get("ls_user_id"),
|
|
"tenant_id": member.get("tenant_id"),
|
|
}
|
|
except Exception as e:
|
|
logger.exception("Error getting LangSmith user info for email: %s", e)
|
|
return {"ls_user_id": None, "tenant_id": None}
|
|
|
|
|
|
def _extract_expires_at(response_data: dict[str, Any]) -> str | None:
|
|
"""Pull an expiry from a LangSmith auth response in any of its known shapes."""
|
|
expires_at = response_data.get("expires_at") or response_data.get("expiresAt")
|
|
if isinstance(expires_at, str) and expires_at:
|
|
return expires_at
|
|
if isinstance(expires_at, int | float):
|
|
return datetime.fromtimestamp(float(expires_at), tz=UTC).isoformat()
|
|
expires_in = response_data.get("expires_in") or response_data.get("expiresIn")
|
|
if isinstance(expires_in, int | float) and expires_in > 0:
|
|
return (datetime.now(UTC) + timedelta(seconds=int(expires_in))).isoformat()
|
|
return None
|
|
|
|
|
|
async def get_github_token_for_user(ls_user_id: str, tenant_id: str) -> dict[str, Any]:
|
|
"""Get GitHub OAuth token for a user via LangSmith agent auth."""
|
|
if not GITHUB_OAUTH_PROVIDER_ID:
|
|
logger.error("GitHub auth failed: GITHUB_OAUTH_PROVIDER_ID is not configured")
|
|
return {"error": "GITHUB_OAUTH_PROVIDER_ID not configured"}
|
|
|
|
try:
|
|
headers = {
|
|
"X-Tenant-Id": tenant_id,
|
|
"X-User-Id": ls_user_id,
|
|
}
|
|
secret_key, secret_type = get_secret_key_for_user(ls_user_id, tenant_id)
|
|
if secret_type == "api_key":
|
|
headers["X-API-Key"] = secret_key
|
|
else:
|
|
headers["X-Service-Key"] = secret_key
|
|
|
|
payload = {
|
|
"provider": GITHUB_OAUTH_PROVIDER_ID,
|
|
"scopes": ["repo"],
|
|
"user_id": ls_user_id,
|
|
"ls_user_id": ls_user_id,
|
|
}
|
|
|
|
async with httpx.AsyncClient(timeout=DEFAULT_HTTP_TIMEOUT) as client:
|
|
response = await client.post(
|
|
f"{LANGSMITH_HOST_API_URL}/v2/auth/authenticate",
|
|
json=payload,
|
|
headers=headers,
|
|
)
|
|
response.raise_for_status()
|
|
response_data = response.json()
|
|
|
|
token = response_data.get("token")
|
|
auth_url = response_data.get("url")
|
|
|
|
if token:
|
|
result: dict[str, Any] = {"token": token}
|
|
expires_at = _extract_expires_at(response_data)
|
|
if expires_at:
|
|
result["expires_at"] = expires_at
|
|
return result
|
|
if auth_url:
|
|
return {"auth_url": auth_url}
|
|
# Log the full upstream body server-side only; the returned error becomes a
|
|
# user-facing Slack/Linear comment, so never echo the raw response body.
|
|
logger.error(
|
|
"GitHub auth returned an unexpected result (no token/url): %s", response_data
|
|
)
|
|
return {"error": "GitHub auth returned an unexpected result"}
|
|
|
|
except httpx.HTTPStatusError as e:
|
|
# Log the full upstream body server-side only; the returned error becomes a
|
|
# user-facing Slack/Linear comment, so never echo the raw response text.
|
|
logger.error("GitHub auth API HTTP error: %s - %s", e.response.status_code, e.response.text)
|
|
return {"error": f"GitHub auth failed (status {e.response.status_code})"}
|
|
except Exception as e: # noqa: BLE001
|
|
logger.error("GitHub auth API call failed: %s: %s", type(e).__name__, str(e))
|
|
return {"error": str(e)}
|
|
|
|
|
|
async def resolve_github_token_from_email(email: str) -> dict[str, Any]:
|
|
"""Resolve a GitHub token for a user identified by email.
|
|
|
|
Chains get_ls_user_id_from_email -> get_github_token_for_user.
|
|
|
|
Returns:
|
|
Dict with one of:
|
|
- {"token": str} on success
|
|
- {"auth_url": str} if user needs to authenticate via OAuth
|
|
- {"error": str} on failure; error="no_ls_user" if email not in LangSmith
|
|
"""
|
|
user_info = await get_ls_user_id_from_email(email)
|
|
ls_user_id = user_info.get("ls_user_id")
|
|
tenant_id = user_info.get("tenant_id")
|
|
|
|
if not ls_user_id or not tenant_id:
|
|
logger.warning(
|
|
"No LangSmith user found for email %s (ls_user_id=%s, tenant_id=%s)",
|
|
email,
|
|
ls_user_id,
|
|
tenant_id,
|
|
)
|
|
return {"error": "no_ls_user", "email": email}
|
|
|
|
auth_result = await get_github_token_for_user(ls_user_id, tenant_id)
|
|
return auth_result
|
|
|
|
|
|
async def leave_failure_comment(
|
|
source: str,
|
|
message: str,
|
|
) -> None:
|
|
"""Leave an auth failure comment for the appropriate source."""
|
|
config = get_config()
|
|
configurable = config.get("configurable", {})
|
|
|
|
if source == "linear":
|
|
linear_issue = configurable.get("linear_issue", {})
|
|
issue_id = linear_issue.get("id") if isinstance(linear_issue, dict) else None
|
|
if issue_id:
|
|
logger.info(
|
|
"Posting auth failure comment to Linear issue %s (source=%s)",
|
|
issue_id,
|
|
source,
|
|
)
|
|
await comment_on_linear_issue(issue_id, message)
|
|
return
|
|
if source == "slack":
|
|
slack_thread = configurable.get("slack_thread", {})
|
|
channel_id = slack_thread.get("channel_id") if isinstance(slack_thread, dict) else None
|
|
thread_ts = slack_thread.get("thread_ts") if isinstance(slack_thread, dict) else None
|
|
if channel_id and thread_ts:
|
|
# The auth-failure ``message`` can carry a per-user GitHub auth URL,
|
|
# which must not be posted in a shared thread (anyone could complete
|
|
# it and bind the wrong account). Post a generic, token-free notice and
|
|
# let the user finish sign-in from their own authenticated dashboard.
|
|
from ..dashboard.oauth import build_settings_url
|
|
|
|
settings_url = build_settings_url()
|
|
link = (
|
|
f"<{settings_url}|your Open SWE settings>"
|
|
if settings_url
|
|
else "your Open SWE settings"
|
|
)
|
|
logger.info(
|
|
"Posting generic auth-failure notice to Slack channel %s thread %s",
|
|
channel_id,
|
|
thread_ts,
|
|
)
|
|
await post_slack_thread_reply(
|
|
channel_id,
|
|
thread_ts,
|
|
"⚠️ I couldn't resolve your GitHub account for this run. Sign in with GitHub and "
|
|
f"connect your Slack account in {link}, then tag me again.",
|
|
)
|
|
return
|
|
if source in ("github", "github_push"):
|
|
logger.warning(
|
|
"Auth failure for GitHub-triggered run (no token to post comment): %s", message
|
|
)
|
|
return
|
|
raise ValueError(f"Unknown source: {source}")
|
|
|
|
|
|
def _current_repo() -> Any:
|
|
"""Best-effort read of the run's repo (owner/name) for cache binding."""
|
|
try:
|
|
configurable = get_config().get("configurable", {})
|
|
except Exception:
|
|
return None
|
|
return configurable.get("repo") if isinstance(configurable, dict) else None
|
|
|
|
|
|
def _cache_resolved_github_token(
|
|
thread_id: str, token: str, expires_at: str | None = None
|
|
) -> tuple[str, str | None]:
|
|
cache_github_token_for_thread(thread_id, token, expires_at=expires_at, repo=_current_repo())
|
|
return token, expires_at
|
|
|
|
|
|
async def resolve_token_from_email(
|
|
email: str | None,
|
|
source: str,
|
|
) -> tuple[str, str | None]:
|
|
"""Resolve and cache a GitHub token based on user email."""
|
|
config = get_config()
|
|
configurable = config.get("configurable", {})
|
|
thread_id = configurable.get("thread_id")
|
|
if not thread_id:
|
|
raise ValueError("GitHub auth failed: missing thread_id")
|
|
if not email:
|
|
message = (
|
|
"❌ **GitHub Auth Error**\n\n"
|
|
"Failed to authenticate with GitHub: missing_user_email\n\n"
|
|
"Please try again or contact support."
|
|
)
|
|
await leave_failure_comment(source, message)
|
|
raise ValueError("GitHub auth failed: missing user_email")
|
|
|
|
user_info = await get_ls_user_id_from_email(email)
|
|
ls_user_id = user_info.get("ls_user_id")
|
|
tenant_id = user_info.get("tenant_id")
|
|
if not ls_user_id or not tenant_id:
|
|
account_label = _source_account_label(source)
|
|
message = (
|
|
"🔐 **GitHub Authentication Required**\n\n"
|
|
f"Could not find a LangSmith account for **{email}**.\n\n"
|
|
"Please ensure this email is invited to the main LangSmith organization. "
|
|
f"If your {account_label} account uses a different email than your LangSmith account, "
|
|
"you may need to update one of them to match.\n\n"
|
|
"Once your email is added to LangSmith, "
|
|
f"{_retry_instruction(source)}"
|
|
)
|
|
await leave_failure_comment(source, message)
|
|
raise ValueError(f"No ls_user_id found from email {email}")
|
|
|
|
auth_result = await get_github_token_for_user(ls_user_id, tenant_id)
|
|
auth_url = auth_result.get("auth_url")
|
|
if auth_url:
|
|
work_item_label = _work_item_label(source)
|
|
auth_link_text = _auth_link_text(source, auth_url)
|
|
message = (
|
|
"🔐 **GitHub Authentication Required**\n\n"
|
|
f"To allow the Open SWE agent to work on this {work_item_label}, "
|
|
"please authenticate with GitHub by clicking the link below:\n\n"
|
|
f"{auth_link_text}\n\n"
|
|
f"{_retry_instruction(source)}"
|
|
)
|
|
await leave_failure_comment(source, message)
|
|
raise ValueError("User not authenticated.")
|
|
|
|
token = auth_result.get("token")
|
|
if not token:
|
|
error = auth_result.get("error", "unknown")
|
|
message = (
|
|
"❌ **GitHub Auth Error**\n\n"
|
|
f"Failed to authenticate with GitHub: {error}\n\n"
|
|
"Please try again or contact support."
|
|
)
|
|
await leave_failure_comment(source, message)
|
|
raise ValueError(f"No token found: {error}")
|
|
|
|
expires_at = auth_result.get("expires_at") if isinstance(auth_result, dict) else None
|
|
return _cache_resolved_github_token(
|
|
thread_id, token, expires_at=expires_at if isinstance(expires_at, str) else None
|
|
)
|
|
|
|
|
|
async def _resolve_dashboard_user_token(
|
|
thread_id: str, github_login: str
|
|
) -> tuple[str, str | None] | None:
|
|
"""Resolve a per-user GitHub token from the dashboard OAuth store."""
|
|
login = github_login.strip()
|
|
if not login:
|
|
raise ValueError("missing github_login")
|
|
|
|
from ..dashboard.profiles import OAUTH_TOKENS_NAMESPACE, get_valid_access_token
|
|
from ..dashboard.profiles import _get_value as get_oauth_record
|
|
|
|
token = await get_valid_access_token(login)
|
|
if not token:
|
|
return None
|
|
record = await get_oauth_record(OAUTH_TOKENS_NAMESPACE, login)
|
|
expires_at = record.get("token_expires_at") if isinstance(record, dict) else None
|
|
return _cache_resolved_github_token(
|
|
thread_id, token, expires_at=expires_at if isinstance(expires_at, str) else None
|
|
)
|
|
|
|
|
|
async def _resolve_bot_installation_token(thread_id: str) -> tuple[str, str | None]:
|
|
"""Get a GitHub App installation token and cache it for the thread.
|
|
|
|
AUTHZ-003 (accepted): in bot-token-only mode every run shares one GitHub App
|
|
installation token, so its blast radius is the whole installation rather than
|
|
a single user. This is a documented, accepted prod posture for this
|
|
single-tenant deployment, not a defect.
|
|
"""
|
|
bot_token, expires_at = await get_github_app_installation_token_with_expiry()
|
|
if not bot_token:
|
|
raise RuntimeError(
|
|
"Bot-token-only mode is active (LANGSMITH_API_KEY_PROD set without "
|
|
"X_SERVICE_AUTH_JWT_SECRET) but the GitHub App is not configured. "
|
|
"Set GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY, and GITHUB_APP_INSTALLATION_ID."
|
|
)
|
|
logger.info(
|
|
"Using GitHub App installation token for thread %s (bot-token-only mode)", thread_id
|
|
)
|
|
return _cache_resolved_github_token(thread_id, bot_token, expires_at=expires_at)
|
|
|
|
|
|
async def resolve_github_token(config: RunnableConfig, thread_id: str) -> tuple[str, str | None]:
|
|
"""Resolve a GitHub token from the run config based on the source.
|
|
|
|
Routes to the correct auth method depending on whether the run was
|
|
triggered from GitHub (login-based) or Linear/Slack (email-based).
|
|
|
|
In bot-token-only mode (LANGSMITH_API_KEY_PROD set without
|
|
X_SERVICE_AUTH_JWT_SECRET), the GitHub App installation token is used
|
|
for all operations instead of per-user OAuth tokens.
|
|
|
|
Raises:
|
|
RuntimeError: If source is missing or token resolution fails.
|
|
"""
|
|
configurable = config["configurable"]
|
|
source = configurable.get("source")
|
|
if not source:
|
|
logger.error("Missing source for thread %s; cannot route auth failure responses", thread_id)
|
|
raise RuntimeError(f"GitHub auth failed for thread {thread_id}: missing source")
|
|
|
|
github_login = configurable.get("github_login")
|
|
|
|
# DEFAULT: Slack/dashboard/schedule runs use the GitHub App installation token,
|
|
# so all git/gh operations + the PR come in as the app `seahaven-openswe[bot]`
|
|
# (deterministic; matches GitHub-issue runs; eliminates the self-review 422).
|
|
# OPT-IN: a profile with `author_prs_as_user: true` restores the per-user OAuth
|
|
# token so the run is attributed to the triggering user.
|
|
if (
|
|
source in ("slack", "dashboard", "schedule")
|
|
and isinstance(github_login, str)
|
|
and github_login.strip()
|
|
):
|
|
from ..dashboard.agent_overrides import load_profile, profile_author_prs_as_user
|
|
|
|
if profile_author_prs_as_user(await load_profile(github_login.strip())):
|
|
try:
|
|
user_token = await _resolve_dashboard_user_token(thread_id, github_login)
|
|
except ValueError as exc:
|
|
logger.error("GitHub auth failed for thread %s: %s", thread_id, str(exc))
|
|
raise RuntimeError(str(exc)) from exc
|
|
if user_token is not None:
|
|
return user_token
|
|
# Opt-in set but no valid user token: in bot-token-only mode fall back
|
|
# to the bot; otherwise block and require auth.
|
|
if not is_bot_token_only_mode():
|
|
raise GitHubUserAuthRequired(source, github_login)
|
|
return await _resolve_bot_installation_token(thread_id)
|
|
|
|
if is_bot_token_only_mode():
|
|
return await _resolve_bot_installation_token(thread_id)
|
|
|
|
try:
|
|
if source == "github":
|
|
cached_token, cached_expires_at = await get_github_token_from_thread(
|
|
thread_id, expected_repo=configurable.get("repo")
|
|
)
|
|
if cached_token:
|
|
return cached_token, cached_expires_at
|
|
from ..dashboard.user_mappings import email_for_login
|
|
|
|
email = await email_for_login(github_login)
|
|
if not email:
|
|
raise ValueError(f"No email mapping found for GitHub user '{github_login}'")
|
|
return await resolve_token_from_email(email, source)
|
|
return await resolve_token_from_email(configurable.get("user_email"), source)
|
|
except ValueError as exc:
|
|
logger.error("GitHub auth failed for thread %s: %s", thread_id, str(exc))
|
|
raise RuntimeError(str(exc)) from exc
|