open-swe/agent/tools/schedule_thread_wakeup.py
Johannes du Plessis 209132d355
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>
2026-06-26 13:48:38 -07:00

142 lines
4.8 KiB
Python

"""Tool that schedules a one-shot re-trigger of the current agent thread."""
from __future__ import annotations
import logging
from datetime import UTC, datetime, timedelta
from typing import Any
from langgraph.config import get_config
from langgraph_sdk import get_client
from ..utils.thread_ops import langgraph_url
logger = logging.getLogger(__name__)
_AGENT_ASSISTANT_ID = "agent"
_MIN_DELAY_SECONDS = 60
_MAX_DELAY_SECONDS = 86_400
_END_TIME_PADDING_SECONDS = 90
_DEFAULT_WAKEUP_PROMPT = (
"This is an automated re-trigger of this thread. The agent scheduled this "
"wakeup to poll for updates. Check the current state of whatever you were "
"waiting on and continue from there."
)
def _ceil_to_next_minute(value: datetime) -> datetime:
"""Round a datetime up to the next whole minute."""
rounded = value.replace(second=0, microsecond=0)
if rounded == value:
return rounded
return rounded + timedelta(minutes=1)
def _build_one_shot_cron(fire_time: datetime) -> str:
"""Build a 5-field cron expression that fires at ``fire_time`` (UTC)."""
return " ".join(
[
str(fire_time.minute),
str(fire_time.hour),
str(fire_time.day),
str(fire_time.month),
"*",
]
)
async def _create_wakeup_cron(
*,
thread_id: str,
fire_time: datetime,
prompt: str,
configurable: dict[str, Any],
) -> dict[str, Any]:
client = get_client(url=langgraph_url())
schedule = _build_one_shot_cron(fire_time)
end_time = fire_time + timedelta(seconds=_END_TIME_PADDING_SECONDS)
run_config: dict[str, Any] = {"configurable": configurable}
cron = await client.crons.create_for_thread(
thread_id,
_AGENT_ASSISTANT_ID,
schedule=schedule,
input={"messages": [{"role": "user", "content": prompt}]},
config=run_config,
end_time=end_time,
timezone="UTC",
metadata={
"kind": "thread_wakeup",
"thread_id": thread_id,
},
)
cron_id = cron.get("cron_id") if isinstance(cron, dict) else getattr(cron, "cron_id", None)
return {
"success": True,
"cron_id": cron_id,
"scheduled_for": fire_time.isoformat(),
"thread_id": thread_id,
}
async def schedule_thread_wakeup(delay_minutes: int, prompt: str | None = None) -> dict[str, Any]:
"""Schedule a one-shot re-trigger of the current thread after a delay.
Use this when you need to poll or check back on something later — e.g.
waiting for CI to finish, a deploy to complete, or an external process
to settle. The current thread will be re-invoked with the given prompt
(or a default wakeup message) after the specified delay.
Args:
delay_minutes: How many minutes from now to wait before re-triggering.
Minimum 1 minute, maximum 1440 (24 hours).
prompt: Optional message to send to the thread when it wakes up.
If omitted, a default polling prompt is used.
Returns a dict with ``success``, ``cron_id``, ``scheduled_for`` (ISO UTC),
and ``thread_id``.
"""
if not isinstance(delay_minutes, int) or delay_minutes < 1:
return {"success": False, "error": "delay_minutes must be a positive integer (>= 1)"}
delay_seconds = delay_minutes * 60
if delay_seconds < _MIN_DELAY_SECONDS:
return {"success": False, "error": "delay must be at least 1 minute"}
if delay_seconds > _MAX_DELAY_SECONDS:
return {"success": False, "error": "delay must be at most 1440 minutes (24 hours)"}
config = get_config()
configurable = config.get("configurable", {}) if isinstance(config, dict) else {}
thread_id = configurable.get("thread_id")
if not isinstance(thread_id, str) or not thread_id:
return {"success": False, "error": "No thread_id in current run config"}
fire_time = _ceil_to_next_minute(datetime.now(UTC) + timedelta(seconds=delay_seconds))
wakeup_prompt = (
prompt.strip() if isinstance(prompt, str) and prompt.strip() else _DEFAULT_WAKEUP_PROMPT
)
passthrough_keys = (
"repo",
"source",
"slack_thread",
"linear_issue",
"github_login",
"user_email",
"schedule_id",
)
wakeup_configurable: dict[str, Any] = {"thread_id": thread_id}
for key in passthrough_keys:
value = configurable.get(key)
if value is not None:
wakeup_configurable[key] = value
try:
return await _create_wakeup_cron(
thread_id=thread_id,
fire_time=fire_time,
prompt=wakeup_prompt,
configurable=wakeup_configurable,
)
except Exception as exc:
logger.exception("Failed to schedule thread wakeup for %s", thread_id)
return {"success": False, "error": str(exc)}