AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(blocks): add Conductor integration blocks (#14950)
Abhimanyu Yadav5c9fec7760f3
diff --git a/autogpt_platform/backend/backend/blocks/conductor/__init__.py b/autogpt_platform/backend/backend/blocks/conductor/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/blocks/conductor/_api.py b/autogpt_platform/backend/backend/blocks/conductor/_api.pynew file mode 100644index 0000000000..b6d1a16314--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/_api.py@@ -0,0 +1,344 @@+from enum import Enum+from typing import Any++from backend.sdk import APIKeyCredentials, Requests++CONDUCTOR_API_URL = "https://api.conductor.build"+API_V0 = f"{CONDUCTOR_API_URL}/v0"++# A block-level wall-clock cap for the send-and-wait blocks. The executor+# wraps `run` in `wait_for(execution_timeout_seconds)`, so the block's own+# `timeout_seconds` input is bounded below this.+MAX_WAIT_SECONDS = 2 * 60 * 60++# The API serves at most this many rows per list request (larger `limit`+# values are clamped server-side) and defaults to a much smaller page, so+# every listing that wants more than a handful of rows must page explicitly.+PAGE_SIZE = 100++# Throttled/5xx read responses are retried, but only a few times with short+# back-off: the wait loops enforce their own wall-clock deadline and an+# open-ended retry would silently outlive it.+RETRY_MAX_ATTEMPTS = 4+RETRY_MAX_WAIT_SECONDS = 10.0+++class ConductorAgent(str, Enum):+ CLAUDE = "claude"+ CODEX = "codex"+ CURSOR = "cursor"+ ACP = "acp"+++class ConductorEffort(str, Enum):+ DEFAULT = ""+ NONE = "none"+ LOW = "low"+ MEDIUM = "medium"+ HIGH = "high"+ XHIGH = "xhigh"+ MAX = "max"+ ULTRA = "ultra"+++class WorkspaceState(str, Enum):+ INITIALIZING = "initializing"+ READY = "ready"+ SLEEPING = "sleeping"+ ARCHIVED = "archived"+ DELETED = "deleted"+ UPDATING = "updating"+ UNSTARTED = "unstarted"+++class WorkspaceAction(str, Enum):+ RENAME = "rename"+ ARCHIVE = "archive"+ UNARCHIVE = "unarchive"+ SLEEP = "sleep"+ SHARE_PREVIEW = "share_preview"+ STOP_PREVIEW = "stop_preview"+ MOVE_TO_SECTION = "move_to_section"+++class SessionAction(str, Enum):+ RENAME = "rename"+ CANCEL = "cancel"+ ARCHIVE = "archive"+++class RoutineAction(str, Enum):+ CREATE = "create"+ ROTATE_WEBHOOK_URL = "rotate_webhook_url"+++class SectionAction(str, Enum):+ CREATE = "create"+ DELETE = "delete"+++def clean(payload: dict[str, Any]) -> dict[str, Any]:+ """Drop None and empty-string values.++ The API declares `additionalProperties: false` and `minLength: 1` on most+ string fields, so an unset optional must be omitted rather than sent blank.+ Enum members are unwrapped to their value.+ """+ cleaned: dict[str, Any] = {}+ for key, value in payload.items():+ if isinstance(value, Enum):+ value = value.value+ if value is None or value == "":+ continue+ cleaned[key] = value+ return cleaned+++class ConductorClient:+ """Thin async client for api.conductor.build.++ Every route lives under /v0 except `GET /me`, which is served at the API+ root. Errors carry a `userMessage` field which is surfaced verbatim.+ """++ def __init__(self, credentials: APIKeyCredentials):+ self.requests = _requests(credentials, RETRY_MAX_ATTEMPTS)+ self.mutation_requests = _requests(credentials, 1)++ async def _call(+ self,+ method: str,+ url: str,+ *,+ json_body: dict[str, Any] | None = None,+ params: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ # aiohttp wants repeated keys as a list of pairs, not a list value.+ query: list[tuple[str, Any]] = []+ for key, value in (params or {}).items():+ if value is None or value == "" or value == []:+ continue+ values = value if isinstance(value, list) else [value]+ query.extend((key, _query_value(v)) for v in values)+ requests = self.requests if method == "GET" else self.mutation_requests+ response = await requests.request(+ method, url, json=json_body, params=query or None+ )+ if not response.ok:+ raise ValueError(_error_message(response))+ try:+ body = response.json()+ except Exception:+ return {}+ return body if isinstance(body, dict) else {"data": body}++ # --- account -----------------------------------------------------------++ async def get_me(self) -> dict[str, Any]:+ return await self._call("GET", f"{CONDUCTOR_API_URL}/me")++ async def list_projects(+ self, limit: int | None = None, offset: int | None = None+ ) -> dict[str, Any]:+ return await self._call(+ "GET", f"{API_V0}/projects", params={"limit": limit, "offset": offset}+ )++ async def get_project(self, project_id: str) -> dict[str, Any]:+ return await self._call("GET", f"{API_V0}/projects/{project_id}")++ async def list_sections(+ self, limit: int | None = None, offset: int | None = None+ ) -> dict[str, Any]:+ return await self._call(+ "GET", f"{API_V0}/sections", params={"limit": limit, "offset": offset}+ )++ async def create_section(self, name: str, emoji: str) -> dict[str, Any]:+ return await self._call(+ "POST",+ f"{API_V0}/sections",+ json_body=clean({"name": name, "emoji": emoji}),+ )++ async def delete_section(self, section_id: str) -> dict[str, Any]:+ return await self._call("DELETE", f"{API_V0}/sections/{section_id}")++ async def list_routines(+ self, limit: int | None = None, offset: int | None = None+ ) -> dict[str, Any]:+ return await self._call(+ "GET", f"{API_V0}/routines", params={"limit": limit, "offset": offset}+ )++ async def create_routine(self, payload: dict[str, Any]) -> dict[str, Any]:+ return await self._call("POST", f"{API_V0}/routines", json_body=payload)++ async def rotate_routine_secret(self, routine_id: str) -> dict[str, Any]:+ return await self._call(+ "POST", f"{API_V0}/routines/{routine_id}/rotate-secret", json_body={}+ )++ # --- workspaces --------------------------------------------------------++ async def list_workspaces(+ self, params: dict[str, Any], project_id: str = ""+ ) -> dict[str, Any]:+ url = (+ f"{API_V0}/projects/{project_id}/workspaces"+ if project_id+ else f"{API_V0}/workspaces"+ )+ return await self._call("GET", url, params=params)++ async def create_workspace(self, payload: dict[str, Any]) -> dict[str, Any]:+ return await self._call("POST", f"{API_V0}/workspaces", json_body=payload)++ async def get_workspace(self, workspace_id: str) -> dict[str, Any]:+ return await self._call("GET", f"{API_V0}/workspaces/{workspace_id}")++ async def workspace_status(self, workspace_id: str) -> dict[str, Any]:+ return await self._call("GET", f"{API_V0}/workspaces/{workspace_id}/status")++ async def workspace_sessions(+ self,+ workspace_id: str,+ include_archived: bool,+ limit: int | None = None,+ offset: int | None = None,+ ) -> dict[str, Any]:+ return await self._call(+ "GET",+ f"{API_V0}/workspaces/{workspace_id}/sessions",+ params={+ "includeArchived": include_archived,+ "limit": limit,+ "offset": offset,+ },+ )++ async def rename_workspace(self, workspace_id: str, name: str) -> dict[str, Any]:+ return await self._call(+ "POST",+ f"{API_V0}/workspaces/{workspace_id}/rename",+ json_body={"name": name},+ )++ async def workspace_lifecycle(self, workspace_id: str, verb: str) -> dict[str, Any]:+ """verb is one of archive, unarchive, sleep."""+ return await self._call(+ "POST", f"{API_V0}/workspaces/{workspace_id}/{verb}", json_body={}+ )++ async def get_preview(self, workspace_id: str) -> dict[str, Any]:+ return await self._call("GET", f"{API_V0}/workspaces/{workspace_id}/preview")++ async def share_preview(self, workspace_id: str, port: int) -> dict[str, Any]:+ return await self._call(+ "PUT",+ f"{API_V0}/workspaces/{workspace_id}/preview",+ json_body={"port": port},+ )++ async def stop_preview(self, workspace_id: str) -> dict[str, Any]:+ return await self._call("DELETE", f"{API_V0}/workspaces/{workspace_id}/preview")++ async def set_workspace_section(+ self, workspace_id: str, section_id: str | None+ ) -> dict[str, Any]:+ return await self._call(+ "PUT",+ f"{API_V0}/workspaces/{workspace_id}/section",+ json_body={"sectionId": section_id},+ )++ # --- sessions ----------------------------------------------------------++ async def create_session(self, payload: dict[str, Any]) -> dict[str, Any]:+ return await self._call("POST", f"{API_V0}/sessions", json_body=payload)++ async def get_session(self, session_id: str) -> dict[str, Any]:+ return await self._call("GET", f"{API_V0}/sessions/{session_id}")++ async def session_status(self, session_id: str) -> dict[str, Any]:+ return await self._call("GET", f"{API_V0}/sessions/{session_id}/status")++ async def rename_session(self, session_id: str, name: str) -> dict[str, Any]:+ return await self._call(+ "POST", f"{API_V0}/sessions/{session_id}/rename", json_body={"name": name}+ )++ async def cancel_session(self, session_id: str) -> dict[str, Any]:+ return await self._call(+ "POST", f"{API_V0}/sessions/{session_id}/cancel", json_body={}+ )++ async def archive_session(self, session_id: str) -> dict[str, Any]:+ return await self._call(+ "POST", f"{API_V0}/sessions/{session_id}/archive", json_body={}+ )++ async def send_message(self, session_id: str, message: str) -> dict[str, Any]:+ return await self._call(+ "POST",+ f"{API_V0}/sessions/{session_id}/messages",+ json_body={"message": message},+ )++ async def list_messages(+ self,+ session_id: str,+ after: str = "",+ limit: int | None = None,+ offset: int | None = None,+ ) -> dict[str, Any]:+ """One page of a session's transcript, oldest first.++ `after` is an exclusive row-id cursor and cannot be combined with+ `offset`. Pages are clamped to PAGE_SIZE rows server-side.+ """+ return await self._call(+ "GET",+ f"{API_V0}/sessions/{session_id}/messages",+ params={"after": after, "limit": limit, "offset": offset},+ )++ async def get_message(self, message_id: str) -> dict[str, Any]:+ return await self._call("GET", f"{API_V0}/messages/{message_id}")+++def _requests(credentials: APIKeyCredentials, attempts: int) -> Requests:+ return Requests(+ trusted_origins=[CONDUCTOR_API_URL],+ raise_for_status=False,+ extra_headers={+ "Authorization": f"Bearer {credentials.api_key.get_secret_value()}"+ },+ retry_max_attempts=attempts,+ retry_max_wait=RETRY_MAX_WAIT_SECONDS,+ )+++def _query_value(value: Any) -> Any:+ if isinstance(value, bool):+ return "true" if value else "false"+ if isinstance(value, Enum):+ return value.value+ return value+++def _error_message(response: Any) -> str:+ detail = ""+ try:+ body = response.json()+ if isinstance(body, dict):+ detail = str(body.get("userMessage") or body.get("message") or "")+ except Exception:+ pass+ if not detail:+ try:+ detail = response.text()[:300]+ except Exception:+ detail = ""+ prefix = f"Conductor API error (HTTP {response.status})"+ return f"{prefix}: {detail}" if detail else prefixdiff --git a/autogpt_platform/backend/backend/blocks/conductor/_config.py b/autogpt_platform/backend/backend/blocks/conductor/_config.pynew file mode 100644index 0000000000..2730b9a1c8--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/_config.py@@ -0,0 +1,13 @@+from backend.sdk import ProviderBuilder++# Conductor bills per seat, not per API call, so the provider registers no+# base_cost and its blocks report no provider_cost.+conductor = (+ ProviderBuilder("conductor")+ .with_description(+ "Cloud coding-agent workspaces: create workspaces, prompt agents, "+ "read transcripts and manage preview URLs, sections and routines"+ )+ .with_supported_auth_types("api_key")+ .build()+)diff --git a/autogpt_platform/backend/backend/blocks/conductor/_mocks.py b/autogpt_platform/backend/backend/blocks/conductor/_mocks.pynew file mode 100644index 0000000000..2d377476e5--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/_mocks.py@@ -0,0 +1,52 @@+"""Shared, sanitized fixtures for the Conductor blocks' inline test_mock data.++Shapes mirror the live API: a `userMessage` row whose `content.id` is the+send receipt, and an `agent` row carrying a Claude Code `assistant` event in+`content.rawPayload` tagged with the turn it belongs to.+"""++MOCK_RECEIPT_ID = "msg_1"++MOCK_PROMPT_MESSAGE = {+ "id": "row_1",+ "sessionId": "sess_1",+ "sessionIndex": 1,+ "type": "userMessage",+ "content": {+ "type": "userMessage",+ "id": MOCK_RECEIPT_ID,+ "turnId": MOCK_RECEIPT_ID,+ "message": "Run the tests",+ "state": "sent",+ },+ "receivedAt": "2026-09-26T00:00:00Z",+}++MOCK_REPLY_MESSAGE = {+ "id": "row_2",+ "sessionId": "sess_1",+ "sessionIndex": 2,+ "type": "agent",+ "content": {+ "type": "agent",+ "rawPayload": {+ "type": "assistant",+ "message": {+ "role": "assistant",+ "content": [{"type": "text", "text": "All tests pass now."}],+ },+ },+ "userMessageId": MOCK_RECEIPT_ID,+ "turnId": MOCK_RECEIPT_ID,+ },+ "receivedAt": "2026-09-26T00:00:01Z",+}++WAIT_MOCK_REPLY = {+ "session_status": "idle",+ "error_message": "",+ "messages": [MOCK_REPLY_MESSAGE],+ "reply": "All tests pass now.",+ "timed_out": False,+ "truncated": False,+}diff --git a/autogpt_platform/backend/backend/blocks/conductor/_paging.py b/autogpt_platform/backend/backend/blocks/conductor/_paging.pynew file mode 100644index 0000000000..9475761ee2--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/_paging.py@@ -0,0 +1,189 @@+"""Bounded paging over a Conductor session transcript.++`GET /sessions/{id}/messages` serves ascending rows in pages of at most+PAGE_SIZE, paged either from the start with `offset` or forward from a row id+with `after` (the two cannot be combined) and never from the end. These+helpers read a bounded slice either way, and every request can be capped by+the caller's remaining wall-clock budget.+"""++import asyncio+from collections.abc import Callable, Coroutine+from typing import Any++from ._api import PAGE_SIZE, ConductorClient++Rows = list[dict[str, Any]]+# Returns the seconds left before the caller's deadline; None means unbounded.+Remaining = Callable[[], float] | None++# Upper bound on the exponential search for the transcript end (2**40 rows).+MAX_PROBES = 40+++async def fetch_after(+ client: ConductorClient,+ session_id: str,+ after: str,+ count: int,+ remaining: Remaining = None,+) -> tuple[Rows, bool]:+ """Up to `count` rows after the `after` cursor, oldest first.++ Also reports whether more rows follow the returned slice (either because+ the server has more or because `count`/the deadline stopped the read).+ """+ rows: Rows = []+ cursor = after+ while True:+ page = await bounded(+ client.list_messages(+ session_id, after=cursor, limit=min(PAGE_SIZE, count - len(rows))+ ),+ remaining,+ )+ data = list(page.get("data") or [])+ rows.extend(data)+ has_more = bool(page.get("hasMore")) and bool(data)+ cursor = str(data[-1].get("id") or "") if data else ""+ if not has_more or not cursor or len(rows) >= count or expired(remaining):+ return rows, has_more+++async def fetch_tail(+ client: ConductorClient,+ session_id: str,+ count: int,+ remaining: Remaining = None,+) -> tuple[Rows, bool]:+ """The newest `count` rows, oldest first, and whether older rows exist."""+ rows, start = await fetch_tail_at(client, session_id, count, remaining)+ return rows, start > 0+++async def fetch_tail_at(+ client: ConductorClient,+ session_id: str,+ count: int,+ remaining: Remaining = None,+) -> tuple[Rows, int]:+ """The newest `count` rows, oldest first, and the offset of the first one.++ A transcript that fits in one page costs one request. Otherwise the end is+ located with `limit=1` probes (exponential then binary search, stopping+ once the bracket is no wider than `count`) and the slice is read from+ just before it.+ """+ first = await bounded(+ client.list_messages(session_id, offset=0, limit=min(count, PAGE_SIZE)),+ remaining,+ )+ rows = list(first.get("data") or [])+ if not first.get("hasMore"):+ return rows, 0+ low, high = await _bracket_end(client, session_id, len(rows), count, remaining)+ start = max(0, low + 1 - count)+ rows = await _fetch_from(client, session_id, start, high - start, remaining)+ return rows[-count:], start + max(0, len(rows) - count)+++async def fetch_before(+ client: ConductorClient,+ session_id: str,+ end: int,+ count: int,+ remaining: Remaining = None,+) -> tuple[Rows, int]:+ """Up to `count` rows ending just before offset `end`, oldest first, and+ the offset of the first one. Transcripts are append-only, so offsets of+ older rows are stable."""+ start = max(0, end - count)+ rows = await _fetch_from(client, session_id, start, end - start, remaining)+ return rows, start+++async def bounded(+ coro: Coroutine[Any, Any, dict[str, Any]], remaining: Remaining+) -> dict[str, Any]:+ """Await one request, capped by the remaining budget when there is one.++ Once the budget is spent no request is started: the coroutine is closed+ and TimeoutError is raised, so a wait never outlives its deadline by+ a chain of late requests.+ """+ if remaining is None:+ return await coro+ timeout = remaining()+ if timeout <= 0:+ coro.close()+ raise TimeoutError("deadline passed before the request was started")+ return await asyncio.wait_for(coro, timeout=timeout)+++def expired(remaining: Remaining) -> bool:+ return remaining is not None and remaining() <= 0+++async def _bracket_end(+ client: ConductorClient,+ session_id: str,+ low: int,+ width: int,+ remaining: Remaining,+) -> tuple[int, int]:+ """Find (low, high) with row `low` existing and row `high` not, such that+ high - low <= width. `low` must be a row index known to exist."""+ high = 0+ probe = max(2 * low, 1)+ for _ in range(MAX_PROBES):+ exists, more = await _probe(client, session_id, probe, remaining)+ if exists and not more:+ return probe, probe + 1+ if not exists:+ high = probe+ break+ low, probe = probe, probe * 2+ if high == 0:+ raise ValueError("transcript is too long to locate its end")+ while high - low > width:+ mid = (low + high) // 2+ exists, more = await _probe(client, session_id, mid, remaining)+ if exists and not more:+ return mid, mid + 1+ if exists:+ low = mid+ else:+ high = mid+ return low, high+++async def _probe(+ client: ConductorClient, session_id: str, offset: int, remaining: Remaining+) -> tuple[bool, bool]:+ """Whether a row exists at `offset` and whether any row follows it."""+ page = await bounded(+ client.list_messages(session_id, offset=offset, limit=1), remaining+ )+ return bool(page.get("data")), bool(page.get("hasMore"))+++async def _fetch_from(+ client: ConductorClient,+ session_id: str,+ offset: int,+ count: int,+ remaining: Remaining,+) -> Rows:+ """Up to `count` rows starting at `offset`: one offset page, then cursors."""+ first = await bounded(+ client.list_messages(session_id, offset=offset, limit=min(PAGE_SIZE, count)),+ remaining,+ )+ rows = list(first.get("data") or [])+ cursor = str(rows[-1].get("id") or "") if rows else ""+ if not first.get("hasMore") or not cursor or len(rows) >= count:+ return rows+ more, _ = await fetch_after(+ client, session_id, cursor, count - len(rows), remaining+ )+ return rows + morediff --git a/autogpt_platform/backend/backend/blocks/conductor/_transcript.py b/autogpt_platform/backend/backend/blocks/conductor/_transcript.pynew file mode 100644index 0000000000..99d248655c--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/_transcript.py@@ -0,0 +1,321 @@+"""Parse Conductor transcript rows and wait for an agent's reply.++Transcript rows are `{id, sessionIndex, type, content, receivedAt}`. Live+sessions use two row types: `userMessage`, whose `content.id` is the receipt+id returned when the prompt was sent, and `agent`, whose `content.rawPayload`+is the harness's own event (Claude Code stream-json or Codex app-server+events) tagged with the `turnId`/`userMessageId` it belongs to. Row ids and+receipt ids are different namespaces: only row ids work as `after` cursors.+"""++import asyncio+import time+from collections import deque+from typing import Any++from ._api import PAGE_SIZE, ConductorClient+from ._paging import (+ Remaining,+ bounded,+ expired,+ fetch_after,+ fetch_before,+ fetch_tail_at,+)++# Rows kept for one reply. A longer turn keeps its newest rows (the answer is+# at the end) and reports `truncated`.+MAX_TURN_MESSAGES = 1000+# How far back the first poll looks for the prompt row. A just-sent prompt is+# among the newest rows; if it is not there yet it has not been recorded.+PROMPT_SCAN_MESSAGES = 300+# When neither the prompt row nor a row of its turn is among the newest+# PROMPT_SCAN_MESSAGES, this many older rows are read before giving up on the+# history and waiting for the turn to arrive.+PROMPT_SEARCH_MESSAGES = MAX_TURN_MESSAGES++USER_TYPES = frozenset({"usermessage", "user", "human", "prompt"})+NON_AGENT_TYPES = USER_TYPES | {"system"}+# Harness events that only mark a turn as launched. Claude Code's `system`+# (init) and Conductor's `command_lifecycle` rows, and Codex's thread/turn+# started events, say nothing about whether the agent produced anything.+STARTUP_RAW_TYPES = frozenset({"system", "command_lifecycle"})+STARTUP_CODEX_EVENTS = frozenset({"thread.started", "turn.started"})+++async def wait_for_reply(+ client: ConductorClient,+ session_id: str,+ prompt_message_id: str,+ timeout_seconds: float,+ poll_interval_seconds: float,+) -> dict[str, Any]:+ """Wait until the agent has answered the prompt, then return its turn.++ Each poll reads the transcript rows that arrived since the previous poll+ and then the session status, so the status is never older than the rows+ it is judged against. The wait ends when the session reports `error`, or+ `idle` after the prompt's turn has progressed past its startup events+ (an idle session whose prompt is still queued, or that has only launched+ the agent, is not a finished one); the transcript is then read once more+ for rows written just before the status changed. Sleeps and requests+ never outlive `timeout_seconds`: nothing is started once it has elapsed,+ and a reply that completes after it is reported as timed out.+ """+ deadline = time.monotonic() + timeout_seconds++ def remaining() -> float:+ return deadline - time.monotonic()++ turn = _TurnCollector(prompt_message_id)+ status: dict[str, Any] = {}+ timed_out = False+ while True:+ await asyncio.sleep(min(poll_interval_seconds, max(0.0, remaining())))+ if expired(remaining):+ timed_out = True+ break+ try:+ await turn.refresh(client, session_id, remaining)+ status = await bounded(client.session_status(session_id), remaining)+ except TimeoutError:+ timed_out = True+ break+ if expired(remaining):+ timed_out = True+ break+ state = str(status.get("status") or "")+ if state == "error" or (state == "idle" and turn.progressed):+ try:+ await turn.refresh(client, session_id, remaining)+ except TimeoutError:+ timed_out = True+ break+ messages = list(turn.rows)+ return {+ "session_status": str(status.get("status") or ""),+ "error_message": str(+ status.get("errorMessage") or status.get("lastError") or ""+ ),+ "messages": messages,+ "reply": reply_text(messages),+ "timed_out": timed_out,+ "truncated": turn.truncated,+ }+++def reply_text(messages: list[dict[str, Any]]) -> str:+ """All visible agent text of a transcript slice, oldest first."""+ texts = [text for message in messages if (text := message_text(message))]+ return "\n\n".join(texts) if texts else _result_text(messages)+++def latest_reply(messages: list[dict[str, Any]]) -> str:+ """Text of the newest text-bearing agent message in the slice."""+ for message in reversed(messages):+ if text := message_text(message):+ return text+ return _result_text(messages)+++def message_text(message: dict[str, Any]) -> str:+ """Visible assistant text of one row; empty for prompts, tool calls and+ results, reasoning and lifecycle events, or shapes we do not recognise."""+ if not is_agent_message(message):+ return ""+ raw = _raw_payload(message)+ if raw is not None:+ return _raw_text(raw)+ return _plain_text(message.get("content"))+++def is_agent_message(message: dict[str, Any]) -> bool:+ return str(message.get("type") or "").lower() not in NON_AGENT_TYPES+++class _TurnCollector:+ """Accumulates the rows of one prompt's turn across polls.++ The turn is resolved by its prompt row (`content.id` or row id equal to+ the receipt) or, when that row is older than the rows read, by agent rows+ tagged with the receipt as their `turnId`/`userMessageId`; in the latter+ case the omitted history is reported through `truncated`.+ """++ def __init__(self, receipt_id: str):+ self.receipt_id = receipt_id+ self.turn_id = ""+ self.resolved = False+ self.progressed = False+ self.truncated = False+ self.cursor = ""+ self.rows: deque[dict[str, Any]] = deque(maxlen=MAX_TURN_MESSAGES)++ async def refresh(+ self, client: ConductorClient, session_id: str, remaining: Remaining+ ) -> None:+ """Consume every row that arrived since the last refresh, one page at+ a time so rows already read survive a request that hits the deadline."""+ if not self.cursor:+ await self._locate(client, session_id, remaining)+ return+ while True:+ rows, has_more = await fetch_after(+ client, session_id, self.cursor, PAGE_SIZE, remaining+ )+ self._consume_all(rows)+ if not has_more or expired(remaining):+ return++ async def _locate(+ self, client: ConductorClient, session_id: str, remaining: Remaining+ ) -> None:+ """First read: the newest rows, then bounded older pages until one+ belongs to the turn. Rows are consumed oldest first only once the+ search stops, so unresolved history is never skipped past."""+ rows, start = await fetch_tail_at(+ client, session_id, PROMPT_SCAN_MESSAGES, remaining+ )+ found = any(self._belongs(row) for row in rows)+ budget = PROMPT_SEARCH_MESSAGES+ while not found and start > 0 and budget > 0 and not expired(remaining):+ page, start = await fetch_before(+ client, session_id, start, min(PAGE_SIZE, budget), remaining+ )+ budget -= max(len(page), 1)+ found = any(self._belongs(row) for row in page)+ rows = page + rows+ self._consume_all(rows)++ def _consume_all(self, rows: list[dict[str, Any]]) -> None:+ for row in rows:+ self._consume(row)+ if rows:+ self.cursor = str(rows[-1].get("id") or self.cursor)++ def _consume(self, row: dict[str, Any]) -> None:+ if not self.resolved:+ if self._is_prompt(row):+ self.turn_id = _turn_of(row)+ elif self.receipt_id in _tags(row):+ # The prompt row is older than anything read: the turn's+ # start is not in `rows`.+ self.turn_id = self.receipt_id+ self.truncated = True+ else:+ return+ self.resolved = True+ elif not self._same_turn(row):+ return+ if is_agent_message(row) and not _is_startup(row):+ self.progressed = True+ self._keep(row)++ def _belongs(self, row: dict[str, Any]) -> bool:+ return self._is_prompt(row) or self.receipt_id in _tags(row)++ def _is_prompt(self, row: dict[str, Any]) -> bool:+ return (+ _content(row).get("id") == self.receipt_id+ or row.get("id") == self.receipt_id+ )++ def _same_turn(self, row: dict[str, Any]) -> bool:+ tags = _tags(row)+ return (+ (not tags and not self.turn_id)+ or self.turn_id in tags+ or self.receipt_id in tags+ )++ def _keep(self, row: dict[str, Any]) -> None:+ if len(self.rows) == self.rows.maxlen:+ self.truncated = True+ self.rows.append(row)+++def _content(row: dict[str, Any]) -> dict[str, Any]:+ content = row.get("content")+ return content if isinstance(content, dict) else {}+++def _turn_of(row: dict[str, Any]) -> str:+ content = _content(row)+ return str(content.get("turnId") or content.get("userMessageId") or "")+++def _tags(row: dict[str, Any]) -> frozenset[str]:+ """The turn identifiers a row carries (`turnId`, `userMessageId`)."""+ content = _content(row)+ return frozenset(+ str(tag) for tag in (content.get("turnId"), content.get("userMessageId")) if tag+ )+++def _is_startup(row: dict[str, Any]) -> bool:+ raw = _raw_payload(row)+ if raw is None:+ return False+ if raw.get("type") in STARTUP_RAW_TYPES:+ return True+ event = raw.get("event")+ return isinstance(event, dict) and event.get("type") in STARTUP_CODEX_EVENTS+++def _raw_payload(message: dict[str, Any]) -> dict[str, Any] | None:+ raw = _content(message).get("rawPayload")+ return raw if isinstance(raw, dict) else None+++def _raw_text(raw: dict[str, Any]) -> str:+ """Assistant text of a Claude `assistant` event or a completed Codex+ `agentMessage` item. Every other event carries no visible text."""+ if raw.get("type") == "assistant":+ message = raw.get("message")+ return _text_parts(message.get("content")) if isinstance(message, dict) else ""+ event = raw.get("event")+ if not isinstance(event, dict) or event.get("type") != "item.completed":+ return ""+ item = event.get("item")+ if isinstance(item, dict) and item.get("type") == "agentMessage":+ return str(item.get("text") or "")+ return ""+++def _text_parts(content: Any) -> str:+ if isinstance(content, str):+ return content+ if not isinstance(content, list):+ return ""+ texts = [+ str(part["text"])+ for part in content+ if isinstance(part, dict) and part.get("type") == "text" and part.get("text")+ ]+ return "\n".join(texts)+++def _plain_text(content: Any) -> str:+ """Text of the simple shapes: a string, `{text}` or a list of text parts."""+ if isinstance(content, str):+ return content+ if isinstance(content, dict):+ text = content.get("text")+ return text if isinstance(text, str) else ""+ if isinstance(content, list):+ parts = [_plain_text(part) for part in content]+ return "\n".join(part for part in parts if part)+ return ""+++def _result_text(messages: list[dict[str, Any]]) -> str:+ """Claude's final `result` event repeats the answer; use it only when no+ assistant text was seen (for example a turn that ended without one)."""+ for message in reversed(messages):+ raw = _raw_payload(message)+ if raw is None or raw.get("type") != "result" or raw.get("is_error"):+ continue+ result = raw.get("result")+ if isinstance(result, str) and result:+ return result+ return ""diff --git a/autogpt_platform/backend/backend/blocks/conductor/account.py b/autogpt_platform/backend/backend/blocks/conductor/account.pynew file mode 100644index 0000000000..908c8b5dff--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/account.py@@ -0,0 +1,127 @@+import asyncio+from collections.abc import Awaitable, Callable+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError++from ._api import PAGE_SIZE, ConductorClient+from ._config import conductor+++async def paginate(+ fetch: Callable[[int, int], Awaitable[dict[str, Any]]], limit: int+) -> list[dict[str, Any]]:+ """Walk a `{data, offset, hasMore}` listing until `limit` items or the end."""+ items: list[dict[str, Any]] = []+ offset = 0+ while len(items) < limit:+ page = await fetch(min(PAGE_SIZE, limit - len(items)), offset)+ data = page.get("data") or []+ items.extend(data)+ if not page.get("hasMore") or not data:+ break+ offset += len(data)+ return items[:limit]+++class ConductorGetAccountBlock(Block):+ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description="Conductor API key from app.conductor.build/users/api-keys"+ )+ limit: int = SchemaField(+ description="Maximum number of projects, sections and routines to list",+ default=100,+ ge=1,+ le=1000,+ )++ class Output(BlockSchemaOutput):+ user: dict = SchemaField(+ description="The authenticated identity: userId, name, email, organizationId"+ )+ projects: list[dict] = SchemaField(+ description="Repositories you can create workspaces in: id, name, gitRemote"+ )+ sections: list[dict] = SchemaField(+ description="Your cloud sections: id, name, emoji, workspaceIds"+ )+ routines: list[dict] = SchemaField(+ description="Your routines: id, name, prompt, repoUrl, agent, model, "+ "enabled, runCount, triggers (webhook URLs are not included)"+ )++ def __init__(self):+ super().__init__(+ id="f0f522e1-99eb-4bf3-b394-202494a35189",+ description="Get an overview of your Conductor account in one call: who "+ "you are, the projects (repositories) you can open workspaces in, your "+ "sections and your routines. Use this first to find project IDs.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.READ,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": conductor.get_test_credentials().model_dump(),+ },+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("user", {"userId": "user_1", "authMethod": "api-key"}),+ ("projects", [{"id": "proj_1", "name": "autogpt", "gitRemote": "x"}]),+ ("sections", []),+ ("routines", []),+ ],+ test_mock={+ "_fetch": lambda *args, **kwargs: {+ "user": {"userId": "user_1", "authMethod": "api-key"},+ "projects": [{"id": "proj_1", "name": "autogpt", "gitRemote": "x"}],+ "sections": [],+ "routines": [],+ }+ },+ )++ async def _fetch(+ self, credentials: APIKeyCredentials, limit: int+ ) -> dict[str, Any]:+ client = ConductorClient(credentials)+ user, projects, sections, routines = await asyncio.gather(+ client.get_me(),+ paginate(client.list_projects, limit),+ paginate(client.list_sections, limit),+ paginate(client.list_routines, limit),+ )+ return {+ "user": user,+ "projects": projects,+ "sections": sections,+ "routines": routines,+ }++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ try:+ data = await self._fetch(credentials, input_data.limit)+ except Exception as e:+ raise BlockExecutionError(+ message=f"Get account failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ yield "user", data["user"]+ yield "projects", data["projects"]+ yield "sections", data["sections"]+ yield "routines", data["routines"]diff --git a/autogpt_platform/backend/backend/blocks/conductor/create_session.py b/autogpt_platform/backend/backend/blocks/conductor/create_session.pynew file mode 100644index 0000000000..e0a38dd9cd--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/create_session.py@@ -0,0 +1,228 @@+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError++from ._api import (+ MAX_WAIT_SECONDS,+ ConductorAgent,+ ConductorClient,+ ConductorEffort,+ clean,+)+from ._config import conductor+from ._mocks import WAIT_MOCK_REPLY+from ._transcript import wait_for_reply++CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"+++class ConductorCreateSessionBlock(Block):+ execution_timeout_seconds: int | None = MAX_WAIT_SECONDS + 300++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description=CREDENTIALS_DESCRIPTION+ )+ workspace_id: str = SchemaField(description="Workspace to add the session to")+ message: str = SchemaField(+ description="Initial prompt for the agent; leave empty for an idle "+ "session",+ default="",+ advanced=False,+ )+ agent: ConductorAgent = SchemaField(+ description="Agent to run",+ default=ConductorAgent.CLAUDE,+ advanced=False,+ )+ model: str = SchemaField(+ description="Model id such as fable-5-1, opus-5-5-1m, sonnet-5-1m, "+ "gpt-6-astra or auto. Leave empty for Conductor's default.",+ default="",+ advanced=False,+ )+ effort: ConductorEffort = SchemaField(+ description="Reasoning effort; leave empty for the default",+ default=ConductorEffort.DEFAULT,+ )+ fast_mode: bool = SchemaField(description="Enable fast mode", default=False)+ name: str = SchemaField(description="Session name", default="")+ wait_for_reply: bool = SchemaField(+ description="After sending the initial prompt, wait until the agent is "+ "idle and return its reply",+ default=False,+ advanced=False,+ )+ timeout_seconds: int = SchemaField(+ description="How long to wait for the reply",+ default=900,+ ge=1,+ le=MAX_WAIT_SECONDS,+ )+ poll_interval_seconds: int = SchemaField(+ description="Seconds between status checks while waiting",+ default=10,+ ge=1,+ le=300,+ )++ class Output(BlockSchemaOutput):+ session_id: str = SchemaField(description="ID of the new session")+ deep_link: str = SchemaField(description="Link that opens the session")+ initial_message_id: str = SchemaField(+ description="ID of the initial prompt message, empty when none was sent"+ )+ session_status: str = SchemaField(+ description="idle, working or error once waiting finished"+ )+ reply: str = SchemaField(description="Text the agent produced in response")+ messages: list[dict] = SchemaField(+ description="Raw transcript messages after the prompt"+ )+ timed_out: bool = SchemaField(+ description="True when the wait ended before the agent went idle"+ )+ truncated: bool = SchemaField(+ description="True when the turn produced more messages than are "+ "kept; messages holds the newest ones and reply may be incomplete"+ )+ error_message: str = SchemaField(description="Session error, if any")++ def __init__(self):+ super().__init__(+ id="3d4b2ccb-d654-4b5d-9750-e67f393f53f0",+ description="Start a new agent session (chat) in an existing Conductor "+ "workspace, optionally with a first prompt, and optionally wait for "+ "the agent's reply.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.EXTERNAL,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input=[+ {+ "credentials": conductor.get_test_credentials().model_dump(),+ "workspace_id": "ws_1",+ "message": "Run the tests",+ },+ {+ "credentials": conductor.get_test_credentials().model_dump(),+ "workspace_id": "ws_1",+ "message": "Run the tests",+ "wait_for_reply": True,+ },+ ],+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("session_id", "sess_1"),+ ("deep_link", "conductor://s/1"),+ ("initial_message_id", "msg_1"),+ ("session_id", "sess_1"),+ ("deep_link", "conductor://s/1"),+ ("initial_message_id", "msg_1"),+ ("session_status", "idle"),+ ("reply", "All tests pass now."),+ ("messages", lambda m: len(m) == 1),+ ("timed_out", False),+ ("truncated", False),+ ("error_message", ""),+ ],+ test_mock={+ "_create": lambda *args, **kwargs: {+ "id": "sess_1",+ "deepLink": "conductor://s/1",+ "initialMessage": {+ "messageId": "msg_1",+ "state": "queued",+ "deepLink": "conductor://m/1",+ },+ },+ "_wait": lambda *args, **kwargs: WAIT_MOCK_REPLY,+ },+ )++ async def _create(+ self, credentials: APIKeyCredentials, payload: dict[str, Any]+ ) -> dict[str, Any]:+ return await ConductorClient(credentials).create_session(payload)++ async def _wait(+ self,+ credentials: APIKeyCredentials,+ session_id: str,+ after_message_id: str,+ timeout_seconds: int,+ poll_interval_seconds: int,+ ) -> dict[str, Any]:+ return await wait_for_reply(+ ConductorClient(credentials),+ session_id,+ after_message_id,+ timeout_seconds,+ poll_interval_seconds,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ payload = clean(+ {+ "workspaceId": input_data.workspace_id,+ "agent": input_data.agent,+ "model": input_data.model,+ "effort": input_data.effort,+ "name": input_data.name,+ "message": input_data.message,+ }+ )+ if input_data.fast_mode:+ payload["fastMode"] = True++ try:+ created = await self._create(credentials, payload)+ except Exception as e:+ raise BlockExecutionError(+ message=f"Create session failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ session_id = str(created.get("id") or "")+ initial = created.get("initialMessage") or {}+ message_id = str(initial.get("messageId") or "")+ yield "session_id", session_id+ yield "deep_link", str(created.get("deepLink") or "")+ yield "initial_message_id", message_id++ if not (input_data.wait_for_reply and session_id and message_id):+ return+ try:+ waited = await self._wait(+ credentials,+ session_id,+ message_id,+ input_data.timeout_seconds,+ input_data.poll_interval_seconds,+ )+ except Exception as e:+ raise BlockExecutionError(+ message=f"Waiting for the agent failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e+ yield "session_status", waited["session_status"]+ yield "reply", waited["reply"]+ yield "messages", waited["messages"]+ yield "timed_out", waited["timed_out"]+ yield "truncated", bool(waited.get("truncated", False))+ yield "error_message", waited["error_message"]diff --git a/autogpt_platform/backend/backend/blocks/conductor/create_workspace.py b/autogpt_platform/backend/backend/blocks/conductor/create_workspace.pynew file mode 100644index 0000000000..d18e439f04--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/create_workspace.py@@ -0,0 +1,295 @@+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError, BlockInputError++from ._api import (+ MAX_WAIT_SECONDS,+ ConductorAgent,+ ConductorClient,+ ConductorEffort,+ clean,+)+from ._config import conductor+from ._transcript import wait_for_reply++CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"+++class ConductorCreateWorkspaceBlock(Block):+ execution_timeout_seconds: int | None = MAX_WAIT_SECONDS + 300++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description=CREDENTIALS_DESCRIPTION+ )+ project_id: str = SchemaField(+ description="Project (repository) to open the workspace in. Find IDs "+ "with Get Account. Use this or repository_url, not both.",+ default="",+ advanced=False,+ )+ repository_url: str = SchemaField(+ description="Git repository URL to open instead of a project ID",+ default="",+ )+ message: str = SchemaField(+ description="Initial prompt for the agent. Leave empty to create an "+ "idle workspace.",+ default="",+ advanced=False,+ )+ branch: str = SchemaField(description="Branch to start from", default="")+ name: str = SchemaField(description="Workspace name", default="")+ session_name: str = SchemaField(+ description="Name of the initial agent session", default=""+ )+ agent: ConductorAgent = SchemaField(+ description="Agent for the initial session",+ default=ConductorAgent.CLAUDE,+ advanced=False,+ )+ model: str = SchemaField(+ description="Model id such as fable-5-1, opus-5-5-1m, sonnet-5-1m, "+ "gpt-6-astra or auto. Leave empty for Conductor's default.",+ default="",+ advanced=False,+ )+ effort: ConductorEffort = SchemaField(+ description="Reasoning effort; leave empty for the default",+ default=ConductorEffort.DEFAULT,+ )+ fast_mode: bool = SchemaField(description="Enable fast mode", default=False)+ env: dict[str, str] = SchemaField(+ description="Environment variables for the workspace",+ default_factory=dict,+ )+ restricted_access: bool = SchemaField(+ description="Restrict the workspace to its creator", default=False+ )+ wait_for_reply: bool = SchemaField(+ description="After sending the initial prompt, wait until the agent is "+ "idle and return its reply",+ default=False,+ advanced=False,+ )+ timeout_seconds: int = SchemaField(+ description="How long to wait for the reply",+ default=900,+ ge=1,+ le=MAX_WAIT_SECONDS,+ )+ poll_interval_seconds: int = SchemaField(+ description="Seconds between status checks while waiting",+ default=10,+ ge=1,+ le=300,+ )++ class Output(BlockSchemaOutput):+ workspace_id: str = SchemaField(description="ID of the new workspace")+ session_id: str = SchemaField(description="ID of the initial session")+ deep_link: str = SchemaField(description="Link that opens the workspace")+ initial_message_id: str = SchemaField(+ description="ID of the initial prompt message, empty when none was sent"+ )+ session_status: str = SchemaField(+ description="idle, working or error once waiting finished"+ )+ reply: str = SchemaField(description="Text the agent produced in response")+ messages: list[dict] = SchemaField(+ description="Raw transcript messages after the prompt"+ )+ timed_out: bool = SchemaField(+ description="True when the wait ended before the agent went idle"+ )+ truncated: bool = SchemaField(+ description="True when the turn produced more messages than are "+ "kept; messages holds the newest ones and reply may be incomplete"+ )+ error_message: str = SchemaField(description="Session error, if any")++ def __init__(self):+ super().__init__(+ id="d419c562-873c-4a67-b83f-9bcf11254f3f",+ description="Create a Conductor cloud workspace for a project or "+ "repository, optionally start its agent with a prompt and wait for "+ "the reply.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.EXTERNAL,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input=[+ {+ "credentials": conductor.get_test_credentials().model_dump(),+ "project_id": "proj_1",+ "message": "Fix the login bug",+ },+ {+ "credentials": conductor.get_test_credentials().model_dump(),+ "project_id": "proj_1",+ "message": "Fix the login bug",+ "wait_for_reply": True,+ },+ ],+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("workspace_id", "ws_1"),+ ("session_id", "sess_1"),+ ("deep_link", "conductor://workspace/ws_1"),+ ("initial_message_id", "msg_1"),+ ("workspace_id", "ws_1"),+ ("session_id", "sess_1"),+ ("deep_link", "conductor://workspace/ws_1"),+ ("initial_message_id", "msg_1"),+ ("session_status", "idle"),+ ("reply", "Done, the fix is on branch fix-login."),+ ("messages", lambda m: len(m) == 1),+ ("timed_out", False),+ ("truncated", False),+ ("error_message", ""),+ ],+ test_mock={+ "_create": lambda *args, **kwargs: {+ "workspaceId": "ws_1",+ "sessionId": "sess_1",+ "deepLink": "conductor://workspace/ws_1",+ "initialMessage": {+ "messageId": "msg_1",+ "state": "queued",+ "deepLink": "conductor://m/1",+ },+ },+ "_wait": lambda *args, **kwargs: {+ "session_status": "idle",+ "error_message": "",+ "messages": [+ {+ "id": "row_2",+ "type": "agent",+ "content": {+ "type": "agent",+ "rawPayload": {+ "type": "assistant",+ "message": {+ "role": "assistant",+ "content": [+ {+ "type": "text",+ "text": "Done, the fix is on "+ "branch fix-login.",+ }+ ],+ },+ },+ "turnId": "msg_1",+ },+ }+ ],+ "reply": "Done, the fix is on branch fix-login.",+ "timed_out": False,+ "truncated": False,+ },+ },+ )++ async def _create(+ self, credentials: APIKeyCredentials, payload: dict[str, Any]+ ) -> dict[str, Any]:+ return await ConductorClient(credentials).create_workspace(payload)++ async def _wait(+ self,+ credentials: APIKeyCredentials,+ session_id: str,+ after_message_id: str,+ timeout_seconds: int,+ poll_interval_seconds: int,+ ) -> dict[str, Any]:+ return await wait_for_reply(+ ConductorClient(credentials),+ session_id,+ after_message_id,+ timeout_seconds,+ poll_interval_seconds,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ if bool(input_data.project_id) == bool(input_data.repository_url):+ raise BlockInputError(+ message="Provide exactly one of project_id or repository_url",+ block_name=self.name,+ block_id=self.id,+ )++ payload = clean(+ {+ "projectId": input_data.project_id,+ "repositoryUrl": input_data.repository_url,+ "branch": input_data.branch,+ "name": input_data.name,+ "sessionName": input_data.session_name,+ "agent": input_data.agent,+ "model": input_data.model,+ "effort": input_data.effort,+ "message": input_data.message,+ }+ )+ if input_data.fast_mode:+ payload["fastMode"] = True+ if input_data.env:+ payload["env"] = dict(input_data.env)+ if input_data.restricted_access:+ payload["access"] = {"restricted": True}++ try:+ created = await self._create(credentials, payload)+ except Exception as e:+ raise BlockExecutionError(+ message=f"Create workspace failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ session_id = str(created.get("sessionId") or "")+ initial = created.get("initialMessage") or {}+ message_id = str(initial.get("messageId") or "")+ yield "workspace_id", str(created.get("workspaceId") or "")+ yield "session_id", session_id+ yield "deep_link", str(created.get("deepLink") or "")+ yield "initial_message_id", message_id++ if not (input_data.wait_for_reply and session_id and message_id):+ return+ try:+ waited = await self._wait(+ credentials,+ session_id,+ message_id,+ input_data.timeout_seconds,+ input_data.poll_interval_seconds,+ )+ except Exception as e:+ raise BlockExecutionError(+ message=f"Waiting for the agent failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e+ yield "session_status", waited["session_status"]+ yield "reply", waited["reply"]+ yield "messages", waited["messages"]+ yield "timed_out", waited["timed_out"]+ yield "truncated", bool(waited.get("truncated", False))+ yield "error_message", waited["error_message"]diff --git a/autogpt_platform/backend/backend/blocks/conductor/get_session.py b/autogpt_platform/backend/backend/blocks/conductor/get_session.pynew file mode 100644index 0000000000..441d319da3--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/get_session.py@@ -0,0 +1,175 @@+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError++from ._api import ConductorClient+from ._config import conductor+from ._mocks import MOCK_PROMPT_MESSAGE, MOCK_REPLY_MESSAGE+from ._paging import fetch_after, fetch_tail+from ._transcript import latest_reply++CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"+++class ConductorGetSessionBlock(Block):+ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description=CREDENTIALS_DESCRIPTION+ )+ session_id: str = SchemaField(description="Session ID")+ message_limit: int = SchemaField(+ description="How many transcript messages to return: the most recent "+ "ones, or the ones following `after` when it is set; 0 skips the "+ "transcript",+ default=20,+ ge=0,+ le=500,+ advanced=False,+ )+ after: str = SchemaField(+ description="Read forward from this transcript message ID (exclusive) "+ "instead of returning the most recent messages; use next_after from "+ "a previous call to poll incrementally",+ default="",+ )+ message_id: str = SchemaField(+ description="Also fetch this single message by ID", default=""+ )++ class Output(BlockSchemaOutput):+ session: dict = SchemaField(+ description="Session: id, name, model, resolvedModel, effort, "+ "fastMode, deepLink, archivedAt"+ )+ status: str = SchemaField(description="idle, working or error")+ error_message: str = SchemaField(description="Last session error, if any")+ messages: list[dict] = SchemaField(+ description="Transcript messages, oldest first: id, sessionIndex, "+ "type, content, receivedAt"+ )+ latest_reply: str = SchemaField(+ description="Text of the newest agent message with visible text in "+ "the returned transcript slice"+ )+ has_more: bool = SchemaField(+ description="True when the transcript has messages beyond the returned "+ "slice: older ones by default, newer ones when after is set"+ )+ next_after: str = SchemaField(+ description="ID of the last returned message; pass it as after to read "+ "what follows"+ )+ message: dict = SchemaField(+ description="The single message requested by message_id"+ )+ deep_link: str = SchemaField(description="Link that opens the session")++ def __init__(self):+ super().__init__(+ id="fabe3db0-fb32-4b05-8e68-b169477b02ec",+ description="Get a Conductor agent session: its details, whether the "+ "agent is idle, working or errored, and recent transcript messages.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.READ,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": conductor.get_test_credentials().model_dump(),+ "session_id": "sess_1",+ },+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("session", lambda s: s["id"] == "sess_1"),+ ("status", "idle"),+ ("error_message", ""),+ ("messages", lambda m: len(m) == 2),+ ("latest_reply", "All tests pass now."),+ ("has_more", False),+ ("next_after", "row_2"),+ ("deep_link", "conductor://s/1"),+ ],+ test_mock={+ "_fetch": lambda *args, **kwargs: {+ "session": {"id": "sess_1", "deepLink": "conductor://s/1"},+ "status": {+ "workspaceId": "ws_1",+ "sessionId": "sess_1",+ "status": "idle",+ "updatedAt": "2026-09-26T00:00:00Z",+ },+ "messages": {+ "data": [MOCK_PROMPT_MESSAGE, MOCK_REPLY_MESSAGE],+ "hasMore": False,+ },+ }+ },+ )++ async def _fetch(+ self, credentials: APIKeyCredentials, input_data: Input+ ) -> dict[str, Any]:+ client = ConductorClient(credentials)+ result: dict[str, Any] = {+ "session": await client.get_session(input_data.session_id),+ "status": await client.session_status(input_data.session_id),+ }+ if input_data.message_limit > 0:+ if input_data.after:+ rows, has_more = await fetch_after(+ client,+ input_data.session_id,+ input_data.after,+ input_data.message_limit,+ )+ else:+ rows, has_more = await fetch_tail(+ client, input_data.session_id, input_data.message_limit+ )+ result["messages"] = {"data": rows, "hasMore": has_more}+ if input_data.message_id:+ result["message"] = await client.get_message(input_data.message_id)+ return result++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ try:+ data = await self._fetch(credentials, input_data)+ except Exception as e:+ raise BlockExecutionError(+ message=f"Get session failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ session = data.get("session") or {}+ status = data.get("status") or {}+ listing = data.get("messages") or {}+ messages = list(listing.get("data") or [])+ yield "session", session+ yield "status", str(status.get("status") or "")+ yield "error_message", str(+ status.get("errorMessage") or status.get("lastError") or ""+ )+ yield "messages", messages+ yield "latest_reply", latest_reply(messages)+ yield "has_more", bool(listing.get("hasMore", False))+ yield "next_after", (+ str(messages[-1].get("id") or input_data.after)+ if messages+ else input_data.after+ )+ if data.get("message"):+ yield "message", data["message"]+ yield "deep_link", str(session.get("deepLink") or "")diff --git a/autogpt_platform/backend/backend/blocks/conductor/get_workspace.py b/autogpt_platform/backend/backend/blocks/conductor/get_workspace.pynew file mode 100644index 0000000000..0f8c9f8cda--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/get_workspace.py@@ -0,0 +1,205 @@+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError++from ._api import PAGE_SIZE, ConductorClient+from ._config import conductor++CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"+++class ConductorGetWorkspaceBlock(Block):+ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description=CREDENTIALS_DESCRIPTION+ )+ workspace_id: str = SchemaField(description="Workspace ID")+ include_archived_sessions: bool = SchemaField(+ description="Include archived sessions in the session list",+ default=False,+ )+ session_limit: int = SchemaField(+ description="Maximum number of sessions to return",+ default=50,+ ge=1,+ le=500,+ )+ session_offset: int = SchemaField(+ description="Number of sessions to skip; use next_session_offset to "+ "read the following page",+ default=0,+ ge=0,+ )++ class Output(BlockSchemaOutput):+ workspace: dict = SchemaField(+ description="Workspace: id, projectId, name, state, repoUrl, deepLink, "+ "creatorName, lastActivityAt"+ )+ status: str = SchemaField(+ description="initializing, ready, sleeping, archived, deleted, "+ "updating or unstarted"+ )+ lifecycle_step: str = SchemaField(+ description="Setup step while initializing: building_snapshot, "+ "preparing, setting_up or updating"+ )+ error_message: str = SchemaField(description="Workspace error, if any")+ preview_url: str = SchemaField(+ description="Public preview URL when a port is shared, else empty"+ )+ preview_port: int = SchemaField(+ description="Port being shared at the preview URL, 0 when none"+ )+ sessions: list[dict] = SchemaField(+ description="Agent sessions in the workspace: id, name, model, "+ "effort, deepLink"+ )+ sessions_has_more: bool = SchemaField(+ description="True when the workspace has more sessions than returned"+ )+ next_session_offset: int = SchemaField(+ description="session_offset to request the next page of sessions"+ )+ deep_link: str = SchemaField(description="Link that opens the workspace")++ def __init__(self):+ super().__init__(+ id="c62c7983-e5c5-4468-b551-c98068610e24",+ description="Get everything about one Conductor workspace: details, "+ "current status, shared preview URL and its agent sessions.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.READ,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": conductor.get_test_credentials().model_dump(),+ "workspace_id": "ws_1",+ },+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("workspace", lambda w: w["id"] == "ws_1"),+ ("status", "ready"),+ ("lifecycle_step", ""),+ ("error_message", ""),+ ("preview_url", "https://ws-1.preview.conductor.build"),+ ("preview_port", 3000),+ ("sessions", lambda s: len(s) == 1),+ ("sessions_has_more", False),+ ("next_session_offset", 1),+ ("deep_link", "conductor://workspace/ws_1"),+ ],+ test_mock={+ "_fetch": lambda *args, **kwargs: {+ "workspace": {+ "id": "ws_1",+ "name": "fix-login",+ "state": "ready",+ "repoUrl": "https://github.com/x/y",+ "createdAt": "2026-09-26T00:00:00Z",+ "deepLink": "conductor://workspace/ws_1",+ },+ "status": {+ "workspaceId": "ws_1",+ "status": "ready",+ "updatedAt": "2026-09-26T00:00:00Z",+ },+ "preview": {+ "preview": {+ "port": 3000,+ "url": "https://ws-1.preview.conductor.build",+ }+ },+ "sessions": {+ "data": [{"id": "sess_1", "deepLink": "conductor://s/1"}],+ "offset": 0,+ "hasMore": False,+ },+ }+ },+ )++ async def _fetch(+ self, credentials: APIKeyCredentials, input_data: Input+ ) -> dict[str, Any]:+ client = ConductorClient(credentials)+ workspace_id = input_data.workspace_id+ result: dict[str, Any] = {+ "workspace": await client.get_workspace(workspace_id),+ "status": await client.workspace_status(workspace_id),+ }+ # Preview and session listings are best-effort: a workspace that is+ # still initializing may not serve them yet.+ try:+ result["preview"] = await client.get_preview(workspace_id)+ except ValueError:+ result["preview"] = {}+ try:+ result["sessions"] = await _list_sessions(client, input_data)+ except ValueError:+ result["sessions"] = {}+ return result++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ try:+ data = await self._fetch(credentials, input_data)+ except Exception as e:+ raise BlockExecutionError(+ message=f"Get workspace failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ workspace = data.get("workspace") or {}+ status = data.get("status") or {}+ preview = (data.get("preview") or {}).get("preview") or {}+ yield "workspace", workspace+ yield "status", str(status.get("status") or workspace.get("state") or "")+ yield "lifecycle_step", str(+ status.get("lifecycleStep") or workspace.get("lifecycleStep") or ""+ )+ yield "error_message", str(status.get("errorMessage") or "")+ yield "preview_url", str(preview.get("url") or "")+ yield "preview_port", int(preview.get("port") or 0)+ sessions = list((data.get("sessions") or {}).get("data") or [])+ yield "sessions", sessions+ yield "sessions_has_more", bool(+ (data.get("sessions") or {}).get("hasMore", False)+ )+ yield "next_session_offset", input_data.session_offset + len(sessions)+ yield "deep_link", str(workspace.get("deepLink") or "")+++async def _list_sessions(+ client: ConductorClient, input_data: ConductorGetWorkspaceBlock.Input+) -> dict[str, Any]:+ """Page the session listing (PAGE_SIZE rows per request) up to the+ requested limit and report whether more sessions follow."""+ sessions: list[dict[str, Any]] = []+ offset = input_data.session_offset+ has_more = True+ while has_more and len(sessions) < input_data.session_limit:+ page = await client.workspace_sessions(+ input_data.workspace_id,+ input_data.include_archived_sessions,+ limit=min(PAGE_SIZE, input_data.session_limit - len(sessions)),+ offset=offset,+ )+ data = list(page.get("data") or [])+ sessions.extend(data)+ offset += len(data)+ has_more = bool(page.get("hasMore")) and bool(data)+ return {"data": sessions, "hasMore": has_more}diff --git a/autogpt_platform/backend/backend/blocks/conductor/list_workspaces.py b/autogpt_platform/backend/backend/blocks/conductor/list_workspaces.pynew file mode 100644index 0000000000..0bc747279b--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/list_workspaces.py@@ -0,0 +1,200 @@+from datetime import UTC, datetime+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError, BlockInputError++from ._api import ConductorClient, WorkspaceState+from ._config import conductor++CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"+++class ConductorListWorkspacesBlock(Block):+ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description=CREDENTIALS_DESCRIPTION+ )+ project_id: str = SchemaField(+ description="Only workspaces of this project (repository). Leave empty "+ "for all projects.",+ default="",+ advanced=False,+ )+ state: list[WorkspaceState] = SchemaField(+ description="Only workspaces in these states, e.g. ready, sleeping",+ default_factory=list,+ advanced=False,+ )+ name: str = SchemaField(+ description="Filter by workspace name", default="", advanced=False+ )+ repo: str = SchemaField(description="Filter by repository URL", default="")+ creator: str = SchemaField(description="Filter by creator user ID", default="")+ since: str = SchemaField(+ description="Only workspaces whose last activity is on or after this "+ "ISO-8601 date or timestamp",+ default="",+ )+ include_archived: bool = SchemaField(+ description="Include archived workspaces", default=False+ )+ limit: int = SchemaField(+ description="Maximum number of workspaces", default=50, ge=1, le=500+ )+ offset: int = SchemaField(description="Pagination offset", default=0, ge=0)++ class Output(BlockSchemaOutput):+ workspaces: list[dict] = SchemaField(+ description="Workspaces: id, projectId, name, state, repoUrl, deepLink, "+ "creatorName, lastActivityAt"+ )+ workspace: dict = SchemaField(description="Each workspace, one at a time")+ has_more: bool = SchemaField(description="Whether more pages exist")+ next_offset: int = SchemaField(+ description="Offset to request the next page; with project_id a page "+ "can be filtered down to nothing while has_more is still true"+ )++ def __init__(self):+ super().__init__(+ id="2410943a-0e63-47d9-a205-9f0dc8fc9b9b",+ description="List Conductor workspaces, optionally filtered by project, "+ "state, name, repository, creator or activity date. When filtering "+ "within a project, a page can be empty while has_more is true; "+ "continue with next_offset until has_more is false.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.READ,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": conductor.get_test_credentials().model_dump(),+ "state": ["ready"],+ },+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("workspaces", lambda ws: len(ws) == 1 and ws[0]["id"] == "ws_1"),+ ("workspace", lambda w: w["id"] == "ws_1"),+ ("has_more", False),+ ("next_offset", 1),+ ],+ test_mock={+ "_fetch": lambda *args, **kwargs: {+ "data": [+ {+ "id": "ws_1",+ "name": "fix-login",+ "state": "ready",+ "repoUrl": "https://github.com/x/y",+ "createdAt": "2026-09-26T00:00:00Z",+ "deepLink": "conductor://workspace/ws_1",+ }+ ],+ "offset": 0,+ "hasMore": False,+ }+ },+ )++ async def _fetch(+ self, credentials: APIKeyCredentials, input_data: Input+ ) -> dict[str, Any]:+ client = ConductorClient(credentials)+ if input_data.project_id:+ # The per-project route accepts no filters; see run().+ params: dict[str, Any] = {+ "limit": input_data.limit,+ "offset": input_data.offset,+ }+ else:+ params = {+ "limit": input_data.limit,+ "offset": input_data.offset,+ "includeArchived": input_data.include_archived,+ "state": [s.value for s in input_data.state],+ "name": input_data.name,+ "repo": input_data.repo,+ "creator": input_data.creator,+ "since": input_data.since,+ }+ return await client.list_workspaces(params, input_data.project_id)++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ since = _parse_timestamp(input_data.since)+ if input_data.since and since is None:+ raise BlockInputError(+ message="since must be an ISO-8601 date or timestamp",+ block_name=self.name,+ block_id=self.id,+ )+ try:+ listing = await self._fetch(credentials, input_data)+ except Exception as e:+ raise BlockExecutionError(+ message=f"List workspaces failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ workspaces = list(listing.get("data") or [])+ if input_data.project_id:+ # The per-project route only paginates, so every filter the+ # cross-project route would apply is applied to the page here.+ workspaces = [w for w in workspaces if _matches(w, input_data, since)]++ yield "workspaces", workspaces+ for workspace in workspaces:+ yield "workspace", workspace+ yield "has_more", bool(listing.get("hasMore", False))+ yield "next_offset", input_data.offset + len(listing.get("data") or [])+++def _matches(+ workspace: dict[str, Any],+ input_data: ConductorListWorkspacesBlock.Input,+ since: datetime | None,+) -> bool:+ """Mirror the cross-project route's filters: exact state and creator,+ case-insensitive name and repository substrings, activity since a date,+ and archived workspaces hidden unless asked for explicitly."""+ state = str(workspace.get("state") or "")+ wanted = {s.value for s in input_data.state}+ if wanted and state not in wanted:+ return False+ if not wanted and not input_data.include_archived and state == "archived":+ return False+ if input_data.creator and workspace.get("creatorId") != input_data.creator:+ return False+ name = str(workspace.get("name") or "").lower()+ if input_data.name and input_data.name.lower() not in name:+ return False+ repo = str(workspace.get("repoUrl") or "").lower()+ if input_data.repo and input_data.repo.lower() not in repo:+ return False+ if since is None:+ return True+ last_activity = _parse_timestamp(str(workspace.get("lastActivityAt") or ""))+ return last_activity is not None and last_activity >= since+++def _parse_timestamp(value: str) -> datetime | None:+ """Parse an ISO-8601 date or timestamp; naive values are taken as UTC."""+ if not value:+ return None+ try:+ parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))+ except ValueError:+ return None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)diff --git a/autogpt_platform/backend/backend/blocks/conductor/manage_session.py b/autogpt_platform/backend/backend/blocks/conductor/manage_session.pynew file mode 100644index 0000000000..c009393405--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/manage_session.py@@ -0,0 +1,116 @@+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError, BlockInputError++from ._api import ConductorClient, SessionAction+from ._config import conductor++CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"+++class ConductorManageSessionBlock(Block):+ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description=CREDENTIALS_DESCRIPTION+ )+ session_id: str = SchemaField(description="Session ID")+ action: SessionAction = SchemaField(+ description="rename, cancel (stop the current turn and drop queued "+ "prompts) or archive",+ default=SessionAction.CANCEL,+ advanced=False,+ )+ name: str = SchemaField(+ description="New session name (rename)", default="", advanced=False+ )++ class Output(BlockSchemaOutput):+ session_id: str = SchemaField(description="Session ID")+ workspace_id: str = SchemaField(+ description="Workspace the session belongs to, when reported"+ )+ status: str = SchemaField(+ description="Session status after the action, when reported"+ )+ canceled_queued_messages: int = SchemaField(+ description="Queued prompts dropped by cancel or archive"+ )+ result: dict = SchemaField(description="Raw API response")++ def __init__(self):+ super().__init__(+ id="3923754c-2198-4925-a1eb-06757eb7c4d0",+ description="Rename, cancel or archive a Conductor agent session. "+ "Cancel stops the running turn and drops queued prompts.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.EXTERNAL,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": conductor.get_test_credentials().model_dump(),+ "session_id": "sess_1",+ "action": SessionAction.CANCEL.value,+ },+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("session_id", "sess_1"),+ ("workspace_id", "ws_1"),+ ("status", "idle"),+ ("canceled_queued_messages", 2),+ ("result", lambda r: r["canceledQueuedMessages"] == 2),+ ],+ test_mock={+ "_perform": lambda *args, **kwargs: {+ "workspaceId": "ws_1",+ "sessionId": "sess_1",+ "status": "idle",+ "canceledQueuedMessages": 2,+ }+ },+ )++ async def _perform(+ self, credentials: APIKeyCredentials, input_data: Input+ ) -> dict[str, Any]:+ client = ConductorClient(credentials)+ if input_data.action == SessionAction.RENAME:+ return await client.rename_session(input_data.session_id, input_data.name)+ if input_data.action == SessionAction.CANCEL:+ return await client.cancel_session(input_data.session_id)+ return await client.archive_session(input_data.session_id)++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ if input_data.action == SessionAction.RENAME and not input_data.name.strip():+ raise BlockInputError(+ message="name is required to rename a session",+ block_name=self.name,+ block_id=self.id,+ )++ try:+ result = await self._perform(credentials, input_data)+ except Exception as e:+ raise BlockExecutionError(+ message=f"Session {input_data.action.value} failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ yield "session_id", str(result.get("sessionId") or input_data.session_id)+ yield "workspace_id", str(result.get("workspaceId") or "")+ yield "status", str(result.get("status") or "")+ yield "canceled_queued_messages", int(result.get("canceledQueuedMessages") or 0)+ yield "result", resultdiff --git a/autogpt_platform/backend/backend/blocks/conductor/manage_workspace.py b/autogpt_platform/backend/backend/blocks/conductor/manage_workspace.pynew file mode 100644index 0000000000..8e3fe82514--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/manage_workspace.py@@ -0,0 +1,152 @@+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError, BlockInputError++from ._api import ConductorClient, WorkspaceAction+from ._config import conductor++CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"+++class ConductorManageWorkspaceBlock(Block):+ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description=CREDENTIALS_DESCRIPTION+ )+ workspace_id: str = SchemaField(description="Workspace ID")+ action: WorkspaceAction = SchemaField(+ description="rename, archive, unarchive, sleep, share_preview (expose "+ "a port at a public preview URL), stop_preview, or move_to_section",+ default=WorkspaceAction.RENAME,+ advanced=False,+ )+ name: str = SchemaField(+ description="New workspace name (rename)", default="", advanced=False+ )+ port: int = SchemaField(+ description="Port inside the workspace to share (share_preview)",+ default=3000,+ ge=1,+ le=65535,+ advanced=False,+ )+ section_id: str = SchemaField(+ description="Target section ID (move_to_section); empty clears the "+ "section",+ default="",+ advanced=False,+ )++ class Output(BlockSchemaOutput):+ workspace_id: str = SchemaField(description="Workspace ID")+ status: str = SchemaField(+ description="Workspace state after the action, when reported"+ )+ preview_url: str = SchemaField(+ description="Preview URL after a share_preview action, else empty"+ )+ result: dict = SchemaField(description="Raw API response")++ def __init__(self):+ super().__init__(+ id="96582ded-a249-4998-8454-eabc8ffc28fc",+ description="Change a Conductor workspace: rename it, archive, "+ "unarchive or sleep it, share or stop sharing a port at its public "+ "preview URL, or move it into a section.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.EXTERNAL,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input=[+ {+ "credentials": conductor.get_test_credentials().model_dump(),+ "workspace_id": "ws_1",+ "action": WorkspaceAction.SHARE_PREVIEW.value,+ "port": 3000,+ },+ {+ "credentials": conductor.get_test_credentials().model_dump(),+ "workspace_id": "ws_1",+ "action": WorkspaceAction.ARCHIVE.value,+ },+ ],+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("workspace_id", "ws_1"),+ ("status", ""),+ ("preview_url", "https://ws-1.preview.conductor.build"),+ ("result", lambda r: r["preview"]["port"] == 3000),+ ("workspace_id", "ws_1"),+ ("status", "archived"),+ ("preview_url", ""),+ ("result", {"workspaceId": "ws_1", "status": "archived"}),+ ],+ test_mock={+ "_perform": lambda credentials, input_data: (+ {+ "preview": {+ "port": 3000,+ "url": "https://ws-1.preview.conductor.build",+ }+ }+ if input_data.action == WorkspaceAction.SHARE_PREVIEW+ else {"workspaceId": "ws_1", "status": "archived"}+ )+ },+ )++ async def _perform(+ self, credentials: APIKeyCredentials, input_data: Input+ ) -> dict[str, Any]:+ client = ConductorClient(credentials)+ ws = input_data.workspace_id+ action = input_data.action+ if action == WorkspaceAction.RENAME:+ return await client.rename_workspace(ws, input_data.name)+ if action in (+ WorkspaceAction.ARCHIVE,+ WorkspaceAction.UNARCHIVE,+ WorkspaceAction.SLEEP,+ ):+ return await client.workspace_lifecycle(ws, action.value)+ if action == WorkspaceAction.SHARE_PREVIEW:+ return await client.share_preview(ws, input_data.port)+ if action == WorkspaceAction.STOP_PREVIEW:+ return await client.stop_preview(ws)+ return await client.set_workspace_section(ws, input_data.section_id or None)++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ if input_data.action == WorkspaceAction.RENAME and not input_data.name.strip():+ raise BlockInputError(+ message="name is required to rename a workspace",+ block_name=self.name,+ block_id=self.id,+ )++ try:+ result = await self._perform(credentials, input_data)+ except Exception as e:+ raise BlockExecutionError(+ message=f"Workspace {input_data.action.value} failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ preview = result.get("preview") or {}+ yield "workspace_id", input_data.workspace_id+ yield "status", str(result.get("status") or result.get("state") or "")+ yield "preview_url", str(preview.get("url") or "")+ yield "result", resultdiff --git a/autogpt_platform/backend/backend/blocks/conductor/routines.py b/autogpt_platform/backend/backend/blocks/conductor/routines.pynew file mode 100644index 0000000000..1fea10cfe4--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/routines.py@@ -0,0 +1,187 @@+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError, BlockInputError++from ._api import ConductorAgent, ConductorClient, ConductorEffort, RoutineAction, clean+from ._config import conductor+++def webhook_url(routine: dict[str, Any]) -> str:+ for trigger in routine.get("triggers") or []:+ if trigger.get("webhookUrl"):+ return str(trigger["webhookUrl"])+ return ""+++class ConductorManageRoutineBlock(Block):+ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description="Conductor API key from app.conductor.build/users/api-keys"+ )+ action: RoutineAction = SchemaField(+ description="create a webhook-triggered routine, or rotate_webhook_url to "+ "replace an existing routine's webhook URL",+ default=RoutineAction.CREATE,+ advanced=False,+ )+ routine_id: str = SchemaField(+ description="Routine ID (rotate_webhook_url)", default="", advanced=False+ )+ name: str = SchemaField(+ description="Routine name (create)", default="", advanced=False+ )+ prompt: str = SchemaField(+ description="Prompt the agent runs each time the webhook fires (create)",+ default="",+ advanced=False,+ )+ project_id: str = SchemaField(+ description="Project (repository) the routine runs in (create). "+ "Find IDs with Get Account.",+ default="",+ advanced=False,+ )+ agent: ConductorAgent = SchemaField(+ description="Agent that runs the routine",+ default=ConductorAgent.CLAUDE,+ )+ model: str = SchemaField(+ description="Model id such as fable-5-1, opus-5-5-1m, sonnet-5-1m, "+ "gpt-6-astra or auto. Leave empty for Conductor's default.",+ default="",+ )+ effort: ConductorEffort = SchemaField(+ description="Reasoning effort; leave empty for the default",+ default=ConductorEffort.DEFAULT,+ )+ enabled: bool = SchemaField(+ description="Whether the routine is enabled on creation", default=True+ )++ class Output(BlockSchemaOutput):+ routine_id: str = SchemaField(description="ID of the routine")+ webhook_url: str = SchemaField(+ description="Webhook URL that triggers the routine. POST to it to run "+ "the routine; this is the only time the URL is shown."+ )+ routine: dict = SchemaField(description="Full routine object")++ def __init__(self):+ super().__init__(+ id="017de31f-f2ce-429d-8d71-a2447d76b544",+ description="Create a Conductor routine (a saved prompt that runs a fresh "+ "agent in a project whenever its webhook URL is called) or rotate a "+ "routine's webhook secret. Returns the webhook URL.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.EXTERNAL,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input=[+ {+ "credentials": conductor.get_test_credentials().model_dump(),+ "action": RoutineAction.CREATE.value,+ "name": "Nightly triage",+ "prompt": "Triage new issues",+ "project_id": "proj_1",+ },+ {+ "credentials": conductor.get_test_credentials().model_dump(),+ "action": RoutineAction.ROTATE_WEBHOOK_URL.value,+ "routine_id": "rt_1",+ },+ ],+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("routine_id", "rt_1"),+ ("webhook_url", "https://api.conductor.build/hooks/abc"),+ ("routine", lambda r: r["id"] == "rt_1"),+ ("routine_id", "rt_1"),+ ("webhook_url", "https://api.conductor.build/hooks/abc"),+ ("routine", lambda r: r["id"] == "rt_1"),+ ],+ test_mock={+ "_perform": lambda *args, **kwargs: {+ "id": "rt_1",+ "name": "Nightly triage",+ "prompt": "Triage new issues",+ "repoUrl": "https://github.com/x/y",+ "agent": "claude",+ "enabled": True,+ "triggers": [+ {+ "id": "tr_1",+ "type": "webhook",+ "enabled": True,+ "webhookUrl": "https://api.conductor.build/hooks/abc",+ }+ ],+ }+ },+ )++ async def _perform(+ self, credentials: APIKeyCredentials, input_data: Input+ ) -> dict[str, Any]:+ client = ConductorClient(credentials)+ if input_data.action == RoutineAction.ROTATE_WEBHOOK_URL:+ return await client.rotate_routine_secret(input_data.routine_id)+ payload = clean(+ {+ "name": input_data.name,+ "prompt": input_data.prompt,+ "projectId": input_data.project_id,+ "agent": input_data.agent,+ "model": input_data.model,+ "effort": input_data.effort,+ }+ )+ payload["enabled"] = input_data.enabled+ payload["triggers"] = [{"type": "webhook"}]+ return await client.create_routine(payload)++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ if input_data.action == RoutineAction.CREATE:+ required = {+ "name": input_data.name,+ "prompt": input_data.prompt,+ "project_id": input_data.project_id,+ }+ missing = [key for key, value in required.items() if not value.strip()]+ if missing:+ raise BlockInputError(+ message=f"{', '.join(missing)} required to create a routine",+ block_name=self.name,+ block_id=self.id,+ )+ elif not input_data.routine_id:+ raise BlockInputError(+ message="routine_id is required to rotate a routine secret",+ block_name=self.name,+ block_id=self.id,+ )++ try:+ routine = await self._perform(credentials, input_data)+ except Exception as e:+ raise BlockExecutionError(+ message=f"Routine {input_data.action.value} failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ yield "routine_id", str(routine.get("id") or input_data.routine_id)+ yield "webhook_url", webhook_url(routine)+ yield "routine", routinediff --git a/autogpt_platform/backend/backend/blocks/conductor/sections.py b/autogpt_platform/backend/backend/blocks/conductor/sections.pynew file mode 100644index 0000000000..93917ccc43--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/sections.py@@ -0,0 +1,138 @@+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError, BlockInputError++from ._api import ConductorClient, SectionAction+from ._config import conductor+++class ConductorManageSectionBlock(Block):+ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description="Conductor API key from app.conductor.build/users/api-keys"+ )+ action: SectionAction = SchemaField(+ description="create a personal section, or delete one",+ default=SectionAction.CREATE,+ advanced=False,+ )+ name: str = SchemaField(+ description="Section name (create)", default="", advanced=False+ )+ emoji: str = SchemaField(+ description="Optional emoji shown next to the section name (create)",+ default="",+ )+ section_id: str = SchemaField(+ description="Section ID (delete)", default="", advanced=False+ )++ class Output(BlockSchemaOutput):+ section_id: str = SchemaField(+ description="ID of the created or deleted section"+ )+ section: dict = SchemaField(+ description="The section: id, name, emoji, workspaceIds"+ )+ removed_workspace_ids: list[str] = SchemaField(+ description="Workspaces that were in the section (delete only)"+ )++ def __init__(self):+ super().__init__(+ id="7f5d1f15-feec-45fa-95e5-a37f748cb678",+ description="Create or delete a Conductor cloud section. Sections group "+ "workspaces in the sidebar; move workspaces with Manage Workspace.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.EXTERNAL,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input=[+ {+ "credentials": conductor.get_test_credentials().model_dump(),+ "action": SectionAction.CREATE.value,+ "name": "Bugs",+ "emoji": "🐛",+ },+ {+ "credentials": conductor.get_test_credentials().model_dump(),+ "action": SectionAction.DELETE.value,+ "section_id": "sec_1",+ },+ ],+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("section_id", "sec_1"),+ ("section", {"id": "sec_1", "name": "Bugs", "workspaceIds": []}),+ ("removed_workspace_ids", []),+ ("section_id", "sec_1"),+ ("section", {"id": "sec_1", "name": "Bugs", "workspaceIds": ["ws_1"]}),+ ("removed_workspace_ids", ["ws_1"]),+ ],+ test_mock={+ "_perform": lambda credentials, input_data: {+ "section": {+ "id": "sec_1",+ "name": "Bugs",+ "workspaceIds": (+ []+ if input_data.action == SectionAction.CREATE+ else ["ws_1"]+ ),+ }+ }+ },+ )++ async def _perform(+ self, credentials: APIKeyCredentials, input_data: Input+ ) -> dict[str, Any]:+ client = ConductorClient(credentials)+ if input_data.action == SectionAction.CREATE:+ return await client.create_section(input_data.name, input_data.emoji)+ return await client.delete_section(input_data.section_id)++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ if input_data.action == SectionAction.CREATE and not input_data.name.strip():+ raise BlockInputError(+ message="name is required to create a section",+ block_name=self.name,+ block_id=self.id,+ )+ if input_data.action == SectionAction.DELETE and not input_data.section_id:+ raise BlockInputError(+ message="section_id is required to delete a section",+ block_name=self.name,+ block_id=self.id,+ )++ try:+ result = await self._perform(credentials, input_data)+ except Exception as e:+ raise BlockExecutionError(+ message=f"Section {input_data.action.value} failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ section = result.get("section") or {}+ yield "section_id", str(section.get("id") or input_data.section_id)+ yield "section", section+ yield "removed_workspace_ids", (+ list(section.get("workspaceIds") or [])+ if input_data.action == SectionAction.DELETE+ else []+ )diff --git a/autogpt_platform/backend/backend/blocks/conductor/send_message.py b/autogpt_platform/backend/backend/blocks/conductor/send_message.pynew file mode 100644index 0000000000..34d44e6e56--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/send_message.py@@ -0,0 +1,181 @@+from typing import Any++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockEffect,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)+from backend.util.exceptions import BlockExecutionError, BlockInputError++from ._api import MAX_WAIT_SECONDS, ConductorClient+from ._config import conductor+from ._mocks import WAIT_MOCK_REPLY+from ._transcript import wait_for_reply++CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"+++class ConductorSendMessageBlock(Block):+ execution_timeout_seconds: int | None = MAX_WAIT_SECONDS + 300++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = conductor.credentials_field(+ description=CREDENTIALS_DESCRIPTION+ )+ session_id: str = SchemaField(description="Session to send the prompt to")+ message: str = SchemaField(description="Prompt for the agent")+ wait_for_reply: bool = SchemaField(+ description="Wait until the agent is idle and return its reply",+ default=True,+ advanced=False,+ )+ timeout_seconds: int = SchemaField(+ description="How long to wait for the reply",+ default=900,+ ge=1,+ le=MAX_WAIT_SECONDS,+ )+ poll_interval_seconds: int = SchemaField(+ description="Seconds between status checks while waiting",+ default=10,+ ge=1,+ le=300,+ )++ class Output(BlockSchemaOutput):+ message_id: str = SchemaField(description="ID of the sent prompt")+ state: str = SchemaField(description="queued or sent")+ deep_link: str = SchemaField(description="Link that opens the message")+ session_status: str = SchemaField(+ description="idle, working or error once waiting finished"+ )+ reply: str = SchemaField(description="Text the agent produced in response")+ messages: list[dict] = SchemaField(+ description="Raw transcript messages after the prompt"+ )+ timed_out: bool = SchemaField(+ description="True when the wait ended before the agent went idle"+ )+ truncated: bool = SchemaField(+ description="True when the turn produced more messages than are "+ "kept; messages holds the newest ones and reply may be incomplete"+ )+ error_message: str = SchemaField(description="Session error, if any")++ def __init__(self):+ super().__init__(+ id="4f22dbe5-2855-498a-ab82-6857441ea4b1",+ description="Send a prompt to a Conductor agent session and, by "+ "default, wait for the agent to finish and return its reply.",+ categories={BlockCategory.DEVELOPER_TOOLS},+ effect=BlockEffect.EXTERNAL,+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": conductor.get_test_credentials().model_dump(),+ "session_id": "sess_1",+ "message": "Run the tests",+ },+ test_credentials=conductor.get_test_credentials(),+ test_output=[+ ("message_id", "msg_1"),+ ("state", "queued"),+ ("deep_link", "conductor://m/1"),+ ("session_status", "idle"),+ ("reply", "All tests pass now."),+ ("messages", lambda m: len(m) == 1),+ ("timed_out", False),+ ("truncated", False),+ ("error_message", ""),+ ],+ test_mock={+ "_send": lambda *args, **kwargs: {+ "messageId": "msg_1",+ "state": "queued",+ "deepLink": "conductor://m/1",+ },+ "_wait": lambda *args, **kwargs: WAIT_MOCK_REPLY,+ },+ )++ async def _send(+ self, credentials: APIKeyCredentials, session_id: str, message: str+ ) -> dict[str, Any]:+ return await ConductorClient(credentials).send_message(session_id, message)++ async def _wait(+ self,+ credentials: APIKeyCredentials,+ session_id: str,+ after_message_id: str,+ timeout_seconds: int,+ poll_interval_seconds: int,+ ) -> dict[str, Any]:+ return await wait_for_reply(+ ConductorClient(credentials),+ session_id,+ after_message_id,+ timeout_seconds,+ poll_interval_seconds,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ if not input_data.message.strip():+ raise BlockInputError(+ message="message must not be empty",+ block_name=self.name,+ block_id=self.id,+ )++ try:+ sent = await self._send(+ credentials, input_data.session_id, input_data.message+ )+ except Exception as e:+ raise BlockExecutionError(+ message=f"Send message failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e++ message_id = str(sent.get("messageId") or "")+ if not message_id:+ raise BlockExecutionError(+ message="Conductor returned no messageId for the sent prompt",+ block_name=self.name,+ block_id=self.id,+ )+ yield "message_id", message_id+ yield "state", str(sent.get("state") or "")+ yield "deep_link", str(sent.get("deepLink") or "")++ if not input_data.wait_for_reply:+ return+ try:+ waited = await self._wait(+ credentials,+ input_data.session_id,+ message_id,+ input_data.timeout_seconds,+ input_data.poll_interval_seconds,+ )+ except Exception as e:+ raise BlockExecutionError(+ message=f"Waiting for the agent failed: {e}",+ block_name=self.name,+ block_id=self.id,+ ) from e+ yield "session_status", waited["session_status"]+ yield "reply", waited["reply"]+ yield "messages", waited["messages"]+ yield "timed_out", waited["timed_out"]+ yield "truncated", bool(waited.get("truncated", False))+ yield "error_message", waited["error_message"]diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_account_reads.py b/autogpt_platform/backend/backend/blocks/conductor/test_account_reads.pynew file mode 100644index 0000000000..5b1210543f--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_account_reads.py@@ -0,0 +1,39 @@+import asyncio+from functools import partial+from unittest.mock import AsyncMock, Mock, patch++import pytest++from backend.blocks.conductor.account import ConductorGetAccountBlock+from backend.blocks.conductor.test_fixtures import TEST_CREDENTIALS+++async def test_account_reads_start_concurrently():+ started: set[str] = set()+ all_started = asyncio.Event()++ async def read(name: str, *args):+ started.add(name)+ if len(started) == 4:+ all_started.set()+ await all_started.wait()+ return {"userId": "u1"} if name == "user" else {"data": [{"id": name}]}++ client = Mock(+ get_me=AsyncMock(side_effect=partial(read, "user")),+ list_projects=AsyncMock(side_effect=partial(read, "projects")),+ list_sections=AsyncMock(side_effect=partial(read, "sections")),+ list_routines=AsyncMock(side_effect=partial(read, "routines")),+ )+ with patch("backend.blocks.conductor.account.ConductorClient", return_value=client):+ result = await asyncio.wait_for(+ ConductorGetAccountBlock()._fetch(TEST_CREDENTIALS, 100), timeout=1+ )++ assert result == {+ "user": {"userId": "u1"},+ "projects": [{"id": "projects"}],+ "sections": [{"id": "sections"}],+ "routines": [{"id": "routines"}],+ }diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_action_requests.py b/autogpt_platform/backend/backend/blocks/conductor/test_action_requests.pynew file mode 100644index 0000000000..fb6fc15dd4--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_action_requests.py@@ -0,0 +1,40 @@+from collections.abc import Awaitable, Callable++import pytest++from backend.blocks.conductor._api import API_V0, ConductorClient+from backend.blocks.conductor.test_fixtures import FakeResponse, client_with+++ "operation,args,path",+ [+ (+ ConductorClient.workspace_lifecycle,+ ("ws_1", "sleep"),+ "workspaces/ws_1/sleep",+ ),+ (+ ConductorClient.workspace_lifecycle,+ ("ws_1", "archive"),+ "workspaces/ws_1/archive",+ ),+ (+ ConductorClient.workspace_lifecycle,+ ("ws_1", "unarchive"),+ "workspaces/ws_1/unarchive",+ ),+ (ConductorClient.cancel_session, ("s1",), "sessions/s1/cancel"),+ (ConductorClient.archive_session, ("s1",), "sessions/s1/archive"),+ (ConductorClient.rotate_routine_secret, ("r1",), "routines/r1/rotate-secret"),+ ],+)+async def test_action_posts_send_json_body(+ operation: Callable[..., Awaitable[dict]], args: tuple[str, ...], path: str+):+ client, request = client_with(FakeResponse(200, {"status": "ok"}))++ await operation(client, *args)++ request.assert_awaited_once_with("POST", f"{API_V0}/{path}", json={}, params=None)diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_conductor.py b/autogpt_platform/backend/backend/blocks/conductor/test_conductor.pynew file mode 100644index 0000000000..197dfb3a9e--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_conductor.py@@ -0,0 +1,249 @@+"""Unit tests for the Conductor client and the action blocks.++Complements the ``test_mock`` harness in each block (exercised by+``test_available_blocks``) with direct coverage of the client's URL, paging+and error handling, and the blocks' input validation and output wiring.+Transcript parsing and the wait loop live in ``test_transcript.py``; the+read/list blocks in ``test_listing_blocks.py``.+"""++from typing import Any++import pytest++from backend.blocks.conductor._api import (+ API_V0,+ CONDUCTOR_API_URL,+ ConductorClient,+ clean,+)+from backend.blocks.conductor.create_workspace import ConductorCreateWorkspaceBlock+from backend.blocks.conductor.manage_workspace import ConductorManageWorkspaceBlock+from backend.blocks.conductor.send_message import ConductorSendMessageBlock+from backend.blocks.conductor.test_fixtures import (+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ FakeResponse,+ client_with,+ collect,+ mock_block,+)+from backend.util.exceptions import BlockExecutionError, BlockInputError++# --- client ------------------------------------------------------------------+++async def test_get_me_is_served_from_the_api_root():+ client, request = client_with(FakeResponse(200, {"userId": "u1"}))+ assert await client.get_me() == {"userId": "u1"}+ assert request.call_args.args == ("GET", f"{CONDUCTOR_API_URL}/me")+++async def test_list_workspaces_sends_repeated_state_params():+ client, request = client_with(FakeResponse(200, {"data": [], "hasMore": False}))+ await client.list_workspaces(+ {"state": ["ready", "sleeping"], "includeArchived": True, "name": ""}+ )+ assert request.call_args.args == ("GET", f"{API_V0}/workspaces")+ assert request.call_args.kwargs["params"] == [+ ("state", "ready"),+ ("state", "sleeping"),+ ("includeArchived", "true"),+ ]+++async def test_workspace_sessions_passes_pagination():+ client, request = client_with(FakeResponse(200, {"data": [], "hasMore": False}))+ await client.workspace_sessions("ws_1", True, limit=25, offset=50)+ assert request.call_args.args == ("GET", f"{API_V0}/workspaces/ws_1/sessions")+ assert request.call_args.kwargs["params"] == [+ ("includeArchived", "true"),+ ("limit", 25),+ ("offset", 50),+ ]+++async def test_api_error_surfaces_user_message():+ client, _ = client_with(+ FakeResponse(401, {"userMessage": "requests require an authenticated user"})+ )+ with pytest.raises(ValueError, match=r"HTTP 401.*authenticated user"):+ await client.get_me()+++async def test_api_error_without_json_body_reports_status():+ client, _ = client_with(FakeResponse(502, ValueError("not json")))+ with pytest.raises(ValueError, match="HTTP 502"):+ await client.get_workspace("ws_1")+++def test_client_retries_are_bounded():+ client = ConductorClient(TEST_CREDENTIALS)+ assert client.requests.retry_max_attempts is not None+ assert client.requests.retry_max_attempts <= 5+ assert client.requests.retry_max_wait <= 30+++def test_clean_drops_blank_values_and_unwraps_enums():+ from backend.blocks.conductor._api import ConductorAgent, ConductorEffort++ assert clean(+ {+ "projectId": "p1",+ "branch": "",+ "model": None,+ "agent": ConductorAgent.CODEX,+ "effort": ConductorEffort.DEFAULT,+ }+ ) == {"projectId": "p1", "agent": "codex"}+++# --- blocks ------------------------------------------------------------------+++async def test_create_workspace_requires_exactly_one_target():+ block = ConductorCreateWorkspaceBlock()+ base = {"credentials": TEST_CREDENTIALS_INPUT, "message": "hi"}+ with pytest.raises(BlockInputError, match="exactly one"):+ await collect(block, base)+ with pytest.raises(BlockInputError, match="exactly one"):+ await collect(+ block,+ {**base, "project_id": "p1", "repository_url": "https://x/y.git"},+ )+++async def test_create_workspace_builds_a_clean_payload():+ block = ConductorCreateWorkspaceBlock()+ seen: dict[str, Any] = {}++ def create(_creds, payload):+ seen.update(payload)+ return {"workspaceId": "ws_1", "sessionId": "s1", "deepLink": "d"}++ mock_block(block, {"_create": create})+ outputs = await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "repository_url": "https://github.com/x/y",+ "branch": "main",+ "agent": "codex",+ "fast_mode": True,+ "env": {"FOO": "bar"},+ "restricted_access": True,+ "wait_for_reply": True,+ },+ )+ assert seen == {+ "repositoryUrl": "https://github.com/x/y",+ "branch": "main",+ "agent": "codex",+ "fastMode": True,+ "env": {"FOO": "bar"},+ "access": {"restricted": True},+ }+ assert outputs["initial_message_id"] == ""+ assert "reply" not in outputs+++async def test_send_message_without_waiting_returns_only_the_receipt():+ block = ConductorSendMessageBlock()+ mock_block(+ block,+ {+ "_send": lambda *a, **k: {+ "messageId": "m1",+ "state": "sent",+ "deepLink": "d",+ },+ "_wait": lambda *a, **k: pytest.fail("should not wait"),+ },+ )+ outputs = await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "session_id": "s1",+ "message": "go",+ "wait_for_reply": False,+ },+ )+ assert outputs == {"message_id": "m1", "state": "sent", "deep_link": "d"}+++async def test_send_message_surfaces_truncation():+ block = ConductorSendMessageBlock()+ mock_block(+ block,+ {+ "_send": lambda *a, **k: {+ "messageId": "m1",+ "state": "sent",+ "deepLink": "d",+ },+ "_wait": lambda *a, **k: {+ "session_status": "idle",+ "error_message": "",+ "messages": [],+ "reply": "partial",+ "timed_out": False,+ "truncated": True,+ },+ },+ )+ outputs = await collect(+ block,+ {"credentials": TEST_CREDENTIALS_INPUT, "session_id": "s1", "message": "go"},+ )+ assert outputs["truncated"] is True+ assert outputs["reply"] == "partial"+++async def test_send_message_wraps_api_failures():+ block = ConductorSendMessageBlock()++ def fail(*args, **kwargs):+ raise ValueError("Conductor API error (HTTP 404): no such session")++ mock_block(block, {"_send": fail})+ with pytest.raises(BlockExecutionError, match="HTTP 404"):+ await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "session_id": "s1",+ "message": "go",+ },+ )+++async def test_manage_workspace_rename_requires_a_name():+ block = ConductorManageWorkspaceBlock()+ with pytest.raises(BlockInputError, match="name is required"):+ await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "workspace_id": "ws_1",+ "action": "rename",+ },+ )+++async def test_manage_workspace_clears_section_with_null():+ client, request = client_with(FakeResponse(200, {"ok": True}))+ await client.set_workspace_section("ws_1", None)+ assert request.call_args.kwargs["json"] == {"sectionId": None}diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_fixtures.py b/autogpt_platform/backend/backend/blocks/conductor/test_fixtures.pynew file mode 100644index 0000000000..92e1c1818f--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_fixtures.py@@ -0,0 +1,269 @@+"""Shared fakes and fixtures for the Conductor block tests.++Transcript fixtures mirror the live envelope shapes (sanitized): the API+wraps every row as ``{id, sessionIndex, type, content, receivedAt}`` where+``type`` is ``userMessage`` or ``agent`` and agent rows carry the harness's+raw event in ``content.rawPayload`` plus ``turnId``/``userMessageId``. The+receipt returned by *send message* is the user row's ``content.id``, not its+row ``id``, so it is not a valid ``after`` cursor.++Named ``test_*`` so the block loader skips it; it defines no tests itself.+"""++import contextlib+import inspect+from types import SimpleNamespace+from typing import Any+from unittest import mock++from pydantic import SecretStr++from backend.blocks.conductor import _transcript+from backend.blocks.conductor._api import PAGE_SIZE, ConductorClient+from backend.data.execution import ExecutionContext+from backend.sdk import APIKeyCredentials++TEST_CREDENTIALS = APIKeyCredentials(+ id="01234567-89ab-cdef-0123-456789abcdef",+ provider="conductor",+ api_key=SecretStr("mock-conductor-api-key"),+ title="Mock Conductor API key",+ expires_at=None,+)+TEST_CREDENTIALS_INPUT = {+ "provider": TEST_CREDENTIALS.provider,+ "id": TEST_CREDENTIALS.id,+ "type": TEST_CREDENTIALS.type,+ "title": TEST_CREDENTIALS.title,+}+RECEIPT = "acb3061e-0000-4000-8000-000000000001"+OLD_TURN = "11111111-0000-4000-8000-000000000000"+++class FakeResponse:+ def __init__(self, status: int, body: Any):+ self.status = status+ self.ok = status < 400+ self._body = body++ def json(self) -> Any:+ if isinstance(self._body, Exception):+ raise self._body+ return self._body++ def text(self) -> str:+ return str(self._body)+++def mock_block(block, mocks: dict):+ for name, mock_fn in mocks.items():+ original = getattr(block, name)+ if inspect.iscoroutinefunction(original):++ async def async_mock(*args, _fn=mock_fn, **kwargs):+ return _fn(*args, **kwargs)++ setattr(block, name, async_mock)+ else:+ setattr(block, name, mock_fn)+++async def collect(block, input_data: dict) -> dict:+ outputs = {}+ async for name, value in block.execute(+ input_data,+ credentials=TEST_CREDENTIALS,+ execution_context=ExecutionContext(),+ ):+ outputs[name] = value+ return outputs+++def client_with(response: FakeResponse) -> tuple[ConductorClient, mock.AsyncMock]:+ client = ConductorClient(TEST_CREDENTIALS)+ request = mock.AsyncMock(return_value=response)+ client.requests.request = request+ client.mutation_requests.request = request+ return client, request+++# --- transcript fixtures -----------------------------------------------------+++def user_row(row_id: str, receipt: str, index: int, turn: str = "") -> dict:+ return {+ "id": row_id,+ "sessionId": "s1",+ "sessionIndex": index,+ "type": "userMessage",+ "content": {+ "type": "userMessage",+ "id": receipt,+ "turnId": turn or receipt,+ "message": "Run the tests",+ "state": "sent",+ },+ "receivedAt": "2026-09-26T00:00:00Z",+ }+++def agent_row(row_id: str, turn: str, index: int, raw: dict) -> dict:+ return {+ "id": row_id,+ "sessionId": "s1",+ "sessionIndex": index,+ "type": "agent",+ "content": {+ "type": "agent",+ "rawPayload": raw,+ "userMessageId": turn,+ "turnId": turn,+ },+ "receivedAt": "2026-09-26T00:00:00Z",+ }+++def claude_text(text: str) -> dict:+ return {+ "type": "assistant",+ "message": {"role": "assistant", "content": [{"type": "text", "text": text}]},+ }+++CLAUDE_THINKING = {+ "type": "assistant",+ "message": {+ "role": "assistant",+ "content": [{"type": "thinking", "thinking": "private reasoning"}],+ },+}+CLAUDE_TOOL_USE = {+ "type": "assistant",+ "message": {+ "role": "assistant",+ "content": [{"type": "tool_use", "id": "toolu_1", "name": "Bash", "input": {}}],+ },+}+CLAUDE_TOOL_RESULT = {+ "type": "user",+ "message": {+ "role": "user",+ "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "ok"}],+ },+}+CLAUDE_SYSTEM = {"type": "system", "subtype": "init", "session_id": "x"}+CLAUDE_LIFECYCLE = {"type": "command_lifecycle", "state": "started"}+CLAUDE_TOOL_PROGRESS = {"type": "tool_progress", "tool_name": "Bash"}+++def claude_result(text: str) -> dict:+ return {"type": "result", "subtype": "success", "is_error": False, "result": text}+++def codex_event(kind: str, item: dict | None = None) -> dict:+ event: dict[str, Any] = {"type": kind}+ if item is not None:+ event["item"] = item+ return {"event": event, "thread_id": "thread_1"}+++def claude_turn(receipt: str, start_index: int, answer: str) -> list[dict]:+ """A realistic Claude turn: lifecycle, interim text, a tool call, then the+ answer followed by trailing status/result events."""+ return [+ agent_row("r-sys", receipt, start_index + 1, CLAUDE_SYSTEM),+ agent_row("r-life", receipt, start_index + 2, CLAUDE_LIFECYCLE),+ agent_row("r-think", receipt, start_index + 3, CLAUDE_THINKING),+ agent_row("r-interim", receipt, start_index + 4, claude_text("Reading.")),+ agent_row("r-tool", receipt, start_index + 5, CLAUDE_TOOL_USE),+ agent_row("r-progress", receipt, start_index + 6, CLAUDE_TOOL_PROGRESS),+ agent_row("r-result", receipt, start_index + 7, CLAUDE_TOOL_RESULT),+ agent_row("r-answer", receipt, start_index + 8, claude_text(answer)),+ agent_row("r-final", receipt, start_index + 9, claude_result(answer)),+ agent_row("r-idle", receipt, start_index + 10, CLAUDE_LIFECYCLE),+ ]+++class FakeTranscript:+ """In-memory stand-in for GET /sessions/{id}/messages.++ Reproduces the live semantics: ascending order, a hard page cap, a tiny+ default page, `after` as an exclusive row-id cursor that 404s for+ unknown ids, and `after` + `offset` rejected together.+ """++ def __init__(self, rows: list[dict], default_limit: int = 5):+ self.rows = rows+ self.default_limit = default_limit+ self.calls: list[dict[str, Any]] = []++ async def list_messages(+ self,+ session_id: str,+ after: str = "",+ limit: int | None = None,+ offset: int | None = None,+ ) -> dict[str, Any]:+ self.calls.append({"after": after, "limit": limit, "offset": offset})+ if after and offset is not None:+ raise ValueError("Conductor API error (HTTP 400): after and offset")+ size = min(limit or self.default_limit, PAGE_SIZE)+ if after:+ index = next((i for i, r in enumerate(self.rows) if r["id"] == after), None)+ if index is None:+ raise ValueError(+ "Conductor API error (HTTP 404): Cursor message not found "+ "in this session"+ )+ start = index + 1+ else:+ start = offset or 0+ data = self.rows[start : start + size]+ return {"data": data, "offset": start, "hasMore": start + size < len(self.rows)}+++def wait_client(transcript: FakeTranscript, statuses: list[dict]) -> ConductorClient:+ client = ConductorClient(TEST_CREDENTIALS)+ remaining = list(statuses)++ async def status(session_id: str) -> dict[str, Any]:+ return remaining.pop(0) if len(remaining) > 1 else remaining[0]++ client.session_status = status+ client.list_messages = transcript.list_messages+ return client+++def fake_clock(step: float = 1.0):+ """monotonic() that advances `step` per call and sleep() that jumps it."""+ now = [0.0]++ def monotonic():+ now[0] += step+ return now[0]++ async def sleep(seconds):+ now[0] += seconds++ return monotonic, sleep, now+++def wait_clock(step: float = 1.0, sleeps: list[float] | None = None):+ """Run the wait loop on a fake clock, recording each sleep in `sleeps`.++ Only the loop's own `time` and `asyncio` names are replaced, so asyncio's+ event-loop clock (which `wait_for` timers use) keeps running on real time.+ """+ monotonic, fake_sleep, now = fake_clock(step)++ async def sleep(seconds):+ if sleeps is not None:+ sleeps.append(seconds)+ await fake_sleep(seconds)++ with (+ mock.patch.object(_transcript, "time", SimpleNamespace(monotonic=monotonic)),+ mock.patch.object(_transcript, "asyncio", SimpleNamespace(sleep=sleep)),+ ):+ yield nowdiff --git a/autogpt_platform/backend/backend/blocks/conductor/test_listing_blocks.py b/autogpt_platform/backend/backend/blocks/conductor/test_listing_blocks.pynew file mode 100644index 0000000000..f77751ee59--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_listing_blocks.py@@ -0,0 +1,283 @@+"""Tests for the read/list blocks: transcript tail and cursor paging in Get+Session (R1-05), session pagination in Get Workspace (R1-06) and project+filtering in List Workspaces (R1-07).+"""++from typing import Any+from unittest import mock++import pytest++from backend.blocks.conductor.get_session import ConductorGetSessionBlock+from backend.blocks.conductor.get_workspace import ConductorGetWorkspaceBlock+from backend.blocks.conductor.list_workspaces import ConductorListWorkspacesBlock+from backend.blocks.conductor.test_fixtures import (+ CLAUDE_LIFECYCLE,+ CLAUDE_TOOL_USE,+ RECEIPT,+ TEST_CREDENTIALS_INPUT,+ FakeTranscript,+ agent_row,+ claude_result,+ claude_text,+ claude_turn,+ collect,+ user_row,+)+from backend.util.exceptions import BlockInputError++# --- get session (R1-05) ------------------------------------------------------+++def _session_client(transcript: FakeTranscript):+ client = mock.Mock()+ client.get_session = mock.AsyncMock(+ return_value={"id": "s1", "deepLink": "conductor://s/1"}+ )+ client.session_status = mock.AsyncMock(return_value={"status": "idle"})+ client.get_message = mock.AsyncMock(return_value={"id": "row-1"})+ client.list_messages = transcript.list_messages+ return client+++async def test_get_session_returns_the_recent_tail_by_default():+ rows = [user_row("row-prompt", RECEIPT, 0)]+ rows += [+ agent_row(f"tool-{i}", RECEIPT, i + 1, CLAUDE_TOOL_USE) for i in range(240)+ ]+ rows += [agent_row("row-answer", RECEIPT, 241, claude_text("The answer"))]+ rows += [agent_row("row-trailing", RECEIPT, 242, claude_result("The answer"))]+ rows += [agent_row("row-idle", RECEIPT, 243, CLAUDE_LIFECYCLE)]+ transcript = FakeTranscript(rows)+ block = ConductorGetSessionBlock()+ with mock.patch(+ "backend.blocks.conductor.get_session.ConductorClient",+ return_value=_session_client(transcript),+ ):+ outputs = await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "session_id": "s1",+ "message_limit": 20,+ },+ )+ ids = [m["id"] for m in outputs["messages"]]+ assert len(ids) == 20+ assert ids[-3:] == ["row-answer", "row-trailing", "row-idle"]+ assert outputs["latest_reply"] == "The answer"+ assert outputs["has_more"] is True+ assert outputs["next_after"] == "row-idle"+ assert len(transcript.calls) < 30+ assert all(c["limit"] is not None for c in transcript.calls)+++async def test_get_session_short_transcript_needs_a_single_request():+ rows = [user_row("row-prompt", RECEIPT, 0), *claude_turn(RECEIPT, 0, "Done")]+ transcript = FakeTranscript(rows)+ block = ConductorGetSessionBlock()+ with mock.patch(+ "backend.blocks.conductor.get_session.ConductorClient",+ return_value=_session_client(transcript),+ ):+ outputs = await collect(+ block, {"credentials": TEST_CREDENTIALS_INPUT, "session_id": "s1"}+ )+ assert [m["id"] for m in outputs["messages"]] == [r["id"] for r in rows]+ assert outputs["latest_reply"] == "Done"+ assert outputs["has_more"] is False+ assert len(transcript.calls) == 1+++async def test_get_session_after_reads_forward_from_the_cursor():+ rows = [user_row("row-prompt", RECEIPT, 0), *claude_turn(RECEIPT, 0, "Done")]+ transcript = FakeTranscript(rows)+ block = ConductorGetSessionBlock()+ with mock.patch(+ "backend.blocks.conductor.get_session.ConductorClient",+ return_value=_session_client(transcript),+ ):+ outputs = await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "session_id": "s1",+ "after": "r-tool",+ "message_limit": 2,+ },+ )+ assert [m["id"] for m in outputs["messages"]] == ["r-progress", "r-result"]+ assert outputs["has_more"] is True+ assert outputs["next_after"] == "r-result"+ assert outputs["latest_reply"] == ""+ assert transcript.calls == [{"after": "r-tool", "limit": 2, "offset": None}]+++# --- get workspace (R1-06) ----------------------------------------------------+++async def test_get_workspace_pages_sessions_up_to_the_limit():+ sessions = [{"id": f"sess_{i}", "deepLink": f"conductor://s/{i}"} for i in range(7)]+ calls: list[dict[str, Any]] = []++ async def workspace_sessions(+ workspace_id, include_archived, limit=None, offset=None+ ):+ calls.append(+ {"include_archived": include_archived, "limit": limit, "offset": offset}+ )+ size = min(limit or 5, 3)+ start = offset or 0+ return {+ "data": sessions[start : start + size],+ "offset": start,+ "hasMore": start + size < len(sessions),+ }++ client = mock.Mock()+ client.get_workspace = mock.AsyncMock(return_value={"id": "ws_1", "state": "ready"})+ client.workspace_status = mock.AsyncMock(return_value={"status": "ready"})+ client.get_preview = mock.AsyncMock(return_value={})+ client.workspace_sessions = workspace_sessions+ block = ConductorGetWorkspaceBlock()+ with mock.patch(+ "backend.blocks.conductor.get_workspace.ConductorClient", return_value=client+ ):+ outputs = await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "workspace_id": "ws_1",+ "include_archived_sessions": True,+ "session_limit": 5,+ "session_offset": 1,+ },+ )+ assert [s["id"] for s in outputs["sessions"]] == [f"sess_{i}" for i in range(1, 6)]+ assert outputs["sessions_has_more"] is True+ assert outputs["next_session_offset"] == 6+ assert all(c["include_archived"] is True for c in calls)+ assert [c["offset"] for c in calls] == [1, 4]+++# --- list workspaces (R1-07) --------------------------------------------------+++def _workspace(**overrides) -> dict:+ base = {+ "id": "ws",+ "projectId": "proj_1",+ "name": "fix-login",+ "state": "ready",+ "repoUrl": "https://github.com/acme/app",+ "createdAt": "2026-09-01T00:00:00Z",+ "deepLink": "conductor://workspace/ws",+ "creatorId": "user_a",+ "lastActivityAt": "2026-09-20T00:00:00Z",+ }+ return {**base, **overrides}+++async def test_list_workspaces_applies_every_filter_to_project_listings():+ page = [+ _workspace(id="match"),+ _workspace(id="other-creator", creatorId="user_b"),+ _workspace(id="too-old", lastActivityAt="2026-08-01T00:00:00Z"),+ _workspace(id="other-repo", repoUrl="https://github.com/acme/other"),+ _workspace(id="wrong-state", state="sleeping"),+ _workspace(id="wrong-name", name="add-feature"),+ _workspace(id="archived", state="archived"),+ ]+ client = mock.Mock()+ client.list_workspaces = mock.AsyncMock(+ return_value={"data": page, "offset": 10, "hasMore": True}+ )+ block = ConductorListWorkspacesBlock()+ with mock.patch(+ "backend.blocks.conductor.list_workspaces.ConductorClient", return_value=client+ ):+ outputs = await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "project_id": "proj_1",+ "state": ["ready"],+ "name": "LOGIN",+ "repo": "acme/app",+ "creator": "user_a",+ "since": "2026-09-15",+ "offset": 10,+ "limit": 7,+ },+ )+ assert [w["id"] for w in outputs["workspaces"]] == ["match"]+ assert outputs["workspace"]["id"] == "match"+ assert outputs["has_more"] is True+ assert outputs["next_offset"] == 17+ params = client.list_workspaces.call_args.args[0]+ assert "includeArchived" not in params+ assert params["limit"] == 7 and params["offset"] == 10+ assert client.list_workspaces.call_args.args[1] == "proj_1"+++async def test_list_workspaces_project_listing_hides_archived_unless_asked():+ page = [_workspace(id="live"), _workspace(id="gone", state="archived")]+ client = mock.Mock()+ client.list_workspaces = mock.AsyncMock(+ return_value={"data": page, "offset": 0, "hasMore": False}+ )+ block = ConductorListWorkspacesBlock()+ with mock.patch(+ "backend.blocks.conductor.list_workspaces.ConductorClient", return_value=client+ ):+ hidden = await collect(+ block, {"credentials": TEST_CREDENTIALS_INPUT, "project_id": "proj_1"}+ )+ shown = await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "project_id": "proj_1",+ "include_archived": True,+ },+ )+ explicit = await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "project_id": "proj_1",+ "state": ["archived"],+ },+ )+ assert [w["id"] for w in hidden["workspaces"]] == ["live"]+ assert [w["id"] for w in shown["workspaces"]] == ["live", "gone"]+ assert [w["id"] for w in explicit["workspaces"]] == ["gone"]+++async def test_list_workspaces_rejects_an_invalid_since_before_requesting():+ client = mock.Mock()+ client.list_workspaces = mock.AsyncMock()+ block = ConductorListWorkspacesBlock()+ with (+ mock.patch(+ "backend.blocks.conductor.list_workspaces.ConductorClient",+ return_value=client,+ ),+ pytest.raises(BlockInputError, match="since"),+ ):+ await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "project_id": "proj_1",+ "since": "last tuesday",+ },+ )+ client.list_workspaces.assert_not_called()diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_provider_credentials.py b/autogpt_platform/backend/backend/blocks/conductor/test_provider_credentials.pynew file mode 100644index 0000000000..a41f2d1a0b--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_provider_credentials.py@@ -0,0 +1,24 @@+import runpy+from pathlib import Path++import pytest++from backend.sdk.registry import AutoRegistry+++def test_provider_ignores_server_key_and_accepts_user_api_keys(+ monkeypatch: pytest.MonkeyPatch,+):+ monkeypatch.setenv("CONDUCTOR_API_KEY", "test-server-key-must-not-be-shared")+ monkeypatch.setattr(AutoRegistry, "_providers", {})+ monkeypatch.setattr(AutoRegistry, "_default_credentials", [])+ monkeypatch.setattr(AutoRegistry, "_api_key_mappings", {})++ runpy.run_path(str(Path(__file__).with_name("_config.py")))++ provider = AutoRegistry.get_provider("conductor")+ assert provider is not None+ assert provider.supported_auth_types == {"api_key"}+ assert provider.default_credentials == []+ assert AutoRegistry.get_all_credentials() == []+ assert "conductor" not in AutoRegistry._api_key_mappingsdiff --git a/autogpt_platform/backend/backend/blocks/conductor/test_retry_policy.py b/autogpt_platform/backend/backend/blocks/conductor/test_retry_policy.pynew file mode 100644index 0000000000..ae084ceaf4--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_retry_policy.py@@ -0,0 +1,38 @@+from unittest.mock import AsyncMock, patch++import pytest+from tenacity import wait_none++from backend.blocks.conductor._api import API_V0, RETRY_MAX_ATTEMPTS, ConductorClient+from backend.blocks.conductor.test_fixtures import TEST_CREDENTIALS, FakeResponse+from backend.sdk import Requests++[email protected]("method", ["POST", "PUT", "DELETE"])[email protected]("status", [429, 503])+async def test_mutations_are_attempted_only_once(method: str, status: int):+ request = AsyncMock(return_value=FakeResponse(status, {"message": "try later"}))+ client = ConductorClient(TEST_CREDENTIALS)+ with (+ patch.object(Requests, "_request", request),+ patch("backend.util.request.wait_exponential_jitter", return_value=wait_none()),+ ):+ with pytest.raises(ValueError, match=f"HTTP {status}"):+ await client._call(method, f"{API_V0}/workspaces", json_body={})++ assert request.await_count == 1+++async def test_reads_keep_bounded_retries():+ request = AsyncMock(return_value=FakeResponse(503, {"message": "try later"}))+ client = ConductorClient(TEST_CREDENTIALS)+ with (+ patch.object(Requests, "_request", request),+ patch("backend.util.request.wait_exponential_jitter", return_value=wait_none()),+ ):+ with pytest.raises(ValueError, match="HTTP 503"):+ await client.get_me()++ assert request.await_count == RETRY_MAX_ATTEMPTSdiff --git a/autogpt_platform/backend/backend/blocks/conductor/test_send_message.py b/autogpt_platform/backend/backend/blocks/conductor/test_send_message.pynew file mode 100644index 0000000000..c3a9c27035--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_send_message.py@@ -0,0 +1,42 @@+import pytest++from backend.blocks.conductor.send_message import ConductorSendMessageBlock+from backend.blocks.conductor.test_fixtures import (+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ mock_block,+)+from backend.util.exceptions import BlockExecutionError++[email protected]("wait_for_reply", [True, False])[email protected]("receipt", [{}, {"messageId": None}, {"messageId": ""}])+async def test_missing_receipt_fails_before_emitting_outputs(+ receipt: dict, wait_for_reply: bool+):+ block = ConductorSendMessageBlock()+ mock_block(+ block,+ {+ "_send": lambda *args, **kwargs: receipt,+ "_wait": lambda *args, **kwargs: pytest.fail(+ "must not poll without a receipt"+ ),+ },+ )+ input_data = block.Input.model_validate(+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "session_id": "s1",+ "message": "go",+ "wait_for_reply": wait_for_reply,+ }+ )+ outputs = []++ with pytest.raises(BlockExecutionError, match="messageId"):+ async for output in block.run(input_data, credentials=TEST_CREDENTIALS):+ outputs.append(output)++ assert outputs == []diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_session_cursor.py b/autogpt_platform/backend/backend/blocks/conductor/test_session_cursor.pynew file mode 100644index 0000000000..d323649114--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_session_cursor.py@@ -0,0 +1,30 @@+import pytest++from backend.blocks.conductor.get_session import ConductorGetSessionBlock+from backend.blocks.conductor.test_fixtures import (+ TEST_CREDENTIALS_INPUT,+ collect,+ mock_block,+)++[email protected]("messages", [[], [{"content": "missing row ID"}]])+async def test_incremental_poll_preserves_cursor_without_a_new_row_id(messages: list):+ block = ConductorGetSessionBlock()+ mock_block(+ block,+ {"_fetch": lambda *args, **kwargs: {"messages": {"data": messages}}},+ )++ result = await collect(+ block,+ {+ "credentials": TEST_CREDENTIALS_INPUT,+ "session_id": "s1",+ "after": "last-seen-row",+ },+ )++ assert result["messages"] == messages+ assert result["next_after"] == "last-seen-row"diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_transcript.py b/autogpt_platform/backend/backend/blocks/conductor/test_transcript.pynew file mode 100644index 0000000000..50d5100fb6--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_transcript.py@@ -0,0 +1,611 @@+"""Tests for transcript parsing and the wait-for-reply loop (R1-01..R1-04,+R2-01..R2-03).++Fixtures are sanitized copies of live Claude and Codex envelopes, see+``test_fixtures.py``.+"""++import asyncio+from typing import Any+from unittest import mock++import pytest++from backend.blocks.conductor import _paging, _transcript+from backend.blocks.conductor._api import ConductorClient+from backend.blocks.conductor._transcript import (+ is_agent_message,+ latest_reply,+ message_text,+ reply_text,+ wait_for_reply,+)+from backend.blocks.conductor.test_fixtures import (+ CLAUDE_LIFECYCLE,+ CLAUDE_SYSTEM,+ CLAUDE_TOOL_USE,+ OLD_TURN,+ RECEIPT,+ TEST_CREDENTIALS,+ FakeTranscript,+ agent_row,+ claude_result,+ claude_text,+ claude_turn,+ codex_event,+ user_row,+ wait_client,+ wait_clock,+)++# --- transcript parsing (R1-01) ---------------------------------------------+++def test_user_message_envelope_is_not_an_agent_message():+ row = user_row("row-1", RECEIPT, 1)+ assert is_agent_message(row) is False+ assert message_text(row) == ""+++def test_claude_rows_yield_only_visible_assistant_text():+ rows = claude_turn(RECEIPT, 1, "Done")+ texts = {r["id"]: message_text(r) for r in rows}+ assert texts == {+ "r-sys": "",+ "r-life": "",+ "r-think": "",+ "r-interim": "Reading.",+ "r-tool": "",+ "r-progress": "",+ "r-result": "",+ "r-answer": "Done",+ "r-final": "",+ "r-idle": "",+ }+ assert reply_text(rows) == "Reading.\n\nDone"+ assert latest_reply(rows) == "Done"+++def test_codex_rows_yield_each_agent_message_once():+ rows = [+ user_row("row-1", RECEIPT, 1),+ agent_row("row-2", RECEIPT, 2, codex_event("thread.started")),+ agent_row("row-3", RECEIPT, 3, codex_event("turn.started")),+ agent_row(+ "row-4",+ RECEIPT,+ 4,+ codex_event(+ "item.started", {"type": "userMessage", "id": "i1", "content": []}+ ),+ ),+ agent_row(+ "row-5",+ RECEIPT,+ 5,+ codex_event(+ "item.started", {"type": "agentMessage", "id": "i2", "text": ""}+ ),+ ),+ agent_row(+ "row-6",+ RECEIPT,+ 6,+ codex_event(+ "item.completed", {"type": "agentMessage", "id": "i2", "text": "Hi"}+ ),+ ),+ agent_row(+ "row-7",+ RECEIPT,+ 7,+ codex_event(+ "item.completed",+ {"type": "reasoning", "id": "i3", "summary": ["thinking"]},+ ),+ ),+ agent_row(+ "row-8",+ RECEIPT,+ 8,+ codex_event(+ "item.completed",+ {"type": "commandExecution", "id": "i4", "command": "ls"},+ ),+ ),+ agent_row(+ "row-9",+ RECEIPT,+ 9,+ codex_event(+ "item.completed",+ {"type": "agentMessage", "id": "i5", "text": "All green."},+ ),+ ),+ agent_row("row-10", RECEIPT, 10, codex_event("turn.completed")),+ ]+ assert reply_text(rows) == "Hi\n\nAll green."+ assert latest_reply(rows) == "All green."+++def test_result_text_is_a_fallback_when_no_assistant_text_exists():+ rows = [agent_row("r-final", RECEIPT, 1, claude_result("Only in result"))]+ assert reply_text(rows) == "Only in result"+ assert latest_reply(rows) == "Only in result"+++def test_reply_text_never_serialises_unknown_shapes_as_json():+ messages = [+ {"type": "user", "content": "prompt"},+ {"type": "assistant", "content": {"kind": "tool", "name": "bash"}},+ {"type": "assistant", "content": [{"type": "text", "text": "plain"}]},+ {"type": "assistant", "content": {"text": "dict"}},+ {"type": "assistant", "content": "string"},+ ]+ assert reply_text(messages) == "plain\n\ndict\n\nstring"+ assert latest_reply(messages) == "string"+++# --- waiting (R1-02, R1-03, R1-04) ------------------------------------------+++async def test_wait_for_reply_ignores_idle_before_the_prompt_starts():+ """Idle is not accepted until the prompt row and an agent row of its turn+ exist; the receipt is matched via content.id, never used as a cursor."""+ prior = [+ user_row("row-0", OLD_TURN, 0),+ *[+ agent_row(f"old-{i}", OLD_TURN, i, claude_text("earlier"))+ for i in range(1, 4)+ ],+ ]+ transcript = FakeTranscript(list(prior))+ prompt = user_row("row-prompt", RECEIPT, 4)+ turn = claude_turn(RECEIPT, 4, "Done")+ growth = iter(+ [+ [], # poll 1: idle, prompt not delivered yet+ [prompt], # poll 2: idle, prompt queued, nothing started+ turn[:4], # poll 3: working+ turn[4:], # poll 4: idle with the answer+ ]+ )+ statuses = [+ {"status": "idle"},+ {"status": "idle"},+ {"status": "working"},+ {"status": "idle"},+ ]+ polls = {"n": 0}+ client = ConductorClient(TEST_CREDENTIALS)++ async def status(session_id: str) -> dict[str, Any]:+ transcript.rows.extend(next(growth, []))+ result = statuses[min(polls["n"], len(statuses) - 1)]+ polls["n"] += 1+ return result++ client.session_status = status+ client.list_messages = transcript.list_messages+ with wait_clock() as _:+ result = await wait_for_reply(client, "s1", RECEIPT, 600, 10)++ assert polls["n"] == 4+ assert result["timed_out"] is False+ assert result["session_status"] == "idle"+ assert result["reply"] == "Reading.\n\nDone"+ assert [m["id"] for m in result["messages"]] == [+ "row-prompt",+ *[r["id"] for r in turn],+ ]+ assert result["truncated"] is False+ assert all(call["after"] != RECEIPT for call in transcript.calls)+++async def test_wait_for_reply_accepts_a_fast_turn_finished_between_polls():+ rows = [user_row("row-prompt", RECEIPT, 1), *claude_turn(RECEIPT, 1, "Quick")]+ client = wait_client(FakeTranscript(rows), [{"status": "idle"}])+ with wait_clock() as _:+ result = await wait_for_reply(client, "s1", RECEIPT, 600, 10)+ assert result["timed_out"] is False+ assert result["reply"] == "Reading.\n\nQuick"+++async def test_wait_for_reply_only_returns_rows_of_the_prompts_turn():+ """A prompt queued behind earlier work: rows after the prompt row that+ belong to the previous turn are not part of the reply."""+ rows = [+ user_row("row-0", OLD_TURN, 0),+ agent_row("old-1", OLD_TURN, 1, claude_text("earlier")),+ user_row("row-prompt", RECEIPT, 2),+ agent_row("old-2", OLD_TURN, 3, claude_text("still the old turn")),+ agent_row("old-3", OLD_TURN, 4, claude_result("still the old turn")),+ *claude_turn(RECEIPT, 4, "Ours"),+ ]+ client = wait_client(FakeTranscript(rows), [{"status": "idle"}])+ with wait_clock() as _:+ result = await wait_for_reply(client, "s1", RECEIPT, 600, 10)+ assert result["reply"] == "Reading.\n\nOurs"+ assert "old-2" not in [m["id"] for m in result["messages"]]+++async def test_wait_for_reply_pages_through_the_whole_turn():+ """The answer sits on the third page of a 250-row turn: cursors advance,+ rows are ordered and unique, and no row is fetched by receipt id."""+ filler = [+ agent_row(f"tool-{i}", RECEIPT, i + 1, CLAUDE_TOOL_USE) for i in range(240)+ ]+ rows = [user_row("row-prompt", RECEIPT, 0), *filler]+ rows += [agent_row("row-answer", RECEIPT, 250, claude_text("Found it"))]+ rows += [agent_row("row-trailing", RECEIPT, 251, CLAUDE_LIFECYCLE)]+ transcript = FakeTranscript(rows)+ client = wait_client(transcript, [{"status": "idle"}])+ with wait_clock() as _:+ result = await wait_for_reply(client, "s1", RECEIPT, 600, 10)+ ids = [m["id"] for m in result["messages"]]+ assert ids[0] == "row-prompt"+ assert ids[-2:] == ["row-answer", "row-trailing"]+ assert len(ids) == len(set(ids)) == len(rows)+ assert result["reply"] == "Found it"+ assert result["truncated"] is False+ afters = [c["after"] for c in transcript.calls if c["after"]]+ assert afters, "expected cursor-based paging"+ assert afters == sorted(+ afters, key=lambda a: rows.index(next(r for r in rows if r["id"] == a))+ )+++async def test_wait_for_reply_marks_truncation_when_the_turn_exceeds_the_cap():+ rows = [+ user_row("row-prompt", RECEIPT, 0),+ *[agent_row(f"tool-{i}", RECEIPT, i + 1, CLAUDE_TOOL_USE) for i in range(10)],+ ]+ rows.append(agent_row("row-answer", RECEIPT, 11, claude_text("Late answer")))+ client = wait_client(FakeTranscript(rows), [{"status": "idle"}])+ with mock.patch.object(_transcript, "MAX_TURN_MESSAGES", 4), wait_clock():+ result = await wait_for_reply(client, "s1", RECEIPT, 600, 10)+ assert result["truncated"] is True+ assert len(result["messages"]) == 4+ assert result["messages"][-1]["id"] == "row-answer"+ assert result["reply"] == "Late answer"+++async def test_wait_for_reply_times_out_before_the_prompt_is_delivered():+ client = wait_client(FakeTranscript([]), [{"status": "idle"}])+ with wait_clock() as now:+ result = await wait_for_reply(client, "s1", RECEIPT, 30, 10)+ assert result["timed_out"] is True+ assert result["reply"] == ""+ assert result["messages"] == []+ assert result["session_status"] == "idle"+ assert now[0] < 60+++async def test_wait_for_reply_caps_the_sleep_by_the_remaining_deadline():+ client = wait_client(FakeTranscript([]), [{"status": "working"}])+ sleeps: list[float] = []+ with wait_clock(step=0.0, sleeps=sleeps):+ result = await wait_for_reply(client, "s1", RECEIPT, 1, 300)+ assert result["timed_out"] is True+ assert sleeps and max(sleeps) <= 1+++async def test_wait_for_reply_bounds_a_hanging_status_request():+ client = ConductorClient(TEST_CREDENTIALS)+ never = asyncio.Event()++ async def hang(session_id: str) -> dict[str, Any]:+ await never.wait()+ return {}++ client.session_status = hang+ client.list_messages = FakeTranscript([]).list_messages+ result = await asyncio.wait_for(+ wait_for_reply(client, "s1", RECEIPT, 0.2, 0.05), timeout=5+ )+ assert result["timed_out"] is True+ assert result["reply"] == ""+++async def test_wait_for_reply_returns_on_session_error():+ rows = [+ user_row("row-prompt", RECEIPT, 1),+ agent_row("row-2", RECEIPT, 2, claude_text("Hi")),+ ]+ client = wait_client(+ FakeTranscript(rows), [{"status": "error", "lastError": "boom"}]+ )+ with wait_clock() as _:+ result = await wait_for_reply(client, "s1", RECEIPT, 10, 1)+ assert result["reply"] == "Hi"+ assert result["session_status"] == "error"+ assert result["error_message"] == "boom"+ assert result["timed_out"] is False+++async def test_wait_for_reply_supports_plain_rows_keyed_by_row_id():+ rows = [+ {"id": "m1", "type": "user", "content": "go"},+ {"id": "m2", "type": "assistant", "content": [{"text": "Hi"}]},+ {"id": "m3", "type": "user", "content": "ignored"},+ {"id": "m4", "type": "assistant", "content": {"text": "Done"}},+ ]+ client = wait_client(FakeTranscript(rows), [{"status": "idle"}])+ with wait_clock() as _:+ result = await wait_for_reply(client, "s1", "m1", 10, 1)+ assert result["reply"] == "Hi\n\nDone"+ assert [m["id"] for m in result["messages"]] == ["m1", "m2", "m3", "m4"]+++# --- round 2: prompt outside the first tail (R2-01) --------------------------+++def lifecycle_rows(turn: str, start: int, count: int) -> list[dict]:+ return [+ agent_row(f"life-{start + i}", turn, start + i, CLAUDE_LIFECYCLE)+ for i in range(count)+ ]+++async def run_wait(client, timeout: float, poll: float):+ with wait_clock():+ return await wait_for_reply(client, "s1", RECEIPT, timeout, poll)+++async def test_wait_for_reply_correlates_a_turn_whose_prompt_is_outside_the_tail():+ """A 307-row turn already complete at the first poll: the prompt row is+ older than the newest 300 rows, but the tail is tagged with its turn, so+ the answer is returned and the omitted rows are reported as truncation."""+ rows = [+ user_row("row-prompt", RECEIPT, 0),+ *lifecycle_rows(RECEIPT, 1, 305),+ agent_row("row-answer", RECEIPT, 306, claude_text("Completed")),+ ]+ transcript = FakeTranscript(rows)+ client = wait_client(transcript, [{"status": "idle"}])+ result = await run_wait(client, 30, 10)+ assert result["reply"] == "Completed"+ assert result["timed_out"] is False+ assert result["truncated"] is True+ ids = [m["id"] for m in result["messages"]]+ assert ids[-1] == "row-answer" and "row-prompt" not in ids+++async def test_wait_for_reply_searches_older_pages_for_a_finished_turn():+ """Our turn finished, then another prompt produced 320 rows before the+ first poll: nothing in the tail is ours, so older pages are read until+ the prompt row is found and the whole turn is returned untruncated."""+ other = "22222222-0000-4000-8000-000000000000"+ rows = [+ user_row("row-0", OLD_TURN, 0),+ agent_row("old-1", OLD_TURN, 1, claude_text("earlier")),+ user_row("row-prompt", RECEIPT, 2),+ agent_row("row-answer", RECEIPT, 3, claude_text("Ours")),+ agent_row("row-final", RECEIPT, 4, claude_result("Ours")),+ user_row("row-other", other, 5),+ *lifecycle_rows(other, 6, 320),+ ]+ transcript = FakeTranscript(rows)+ client = wait_client(transcript, [{"status": "idle"}])+ result = await run_wait(client, 60, 10)+ assert result["reply"] == "Ours"+ assert result["timed_out"] is False+ assert result["truncated"] is False+ assert [m["id"] for m in result["messages"]] == [+ "row-prompt",+ "row-answer",+ "row-final",+ ]+++async def test_wait_for_reply_bounds_the_search_for_an_unrecorded_prompt():+ """A long session whose newest 1500 rows are older turns and whose prompt+ has not been recorded yet: the backward search stops at its bound, then+ the prompt and its turn are picked up as they arrive."""+ rows = [user_row("row-0", OLD_TURN, 0), *lifecycle_rows(OLD_TURN, 1, 1500)]+ transcript = FakeTranscript(rows)+ later = [user_row("row-prompt", RECEIPT, 1501), *claude_turn(RECEIPT, 1501, "Late")]+ statuses = iter([{"status": "idle"}, {"status": "working"}, {"status": "idle"}])+ client = ConductorClient(TEST_CREDENTIALS)++ async def status(session_id: str) -> dict[str, Any]:+ state = next(statuses, {"status": "idle"})+ if state["status"] == "working":+ transcript.rows.extend(later)+ return state++ client.session_status = status+ client.list_messages = transcript.list_messages+ result = await run_wait(client, 600, 10)+ assert result["reply"] == "Reading.\n\nLate"+ assert result["timed_out"] is False+ assert result["truncated"] is False+ offsets = [c for c in transcript.calls if c["offset"] is not None]+ assert len(offsets) <= 30, "backward search must be bounded"+++# --- round 2: a real deadline (R2-02) ----------------------------------------+++async def test_wait_for_reply_makes_no_requests_once_the_deadline_passed():+ rows = [user_row("row-prompt", RECEIPT, 1), *claude_turn(RECEIPT, 1, "Done")]+ transcript = FakeTranscript(rows)+ client = wait_client(transcript, [{"status": "idle"}])+ status_calls = {"n": 0}+ inner = client.session_status++ async def counting_status(session_id: str) -> dict[str, Any]:+ status_calls["n"] += 1+ return await inner(session_id)++ client.session_status = counting_status+ result = await run_wait(client, 1, 10)+ assert result["timed_out"] is True+ assert result["reply"] == ""+ assert transcript.calls == []+ assert status_calls["n"] == 0+++async def test_bounded_refuses_to_start_a_request_after_the_deadline():+ ran = {"started": False}++ async def request() -> dict[str, Any]:+ ran["started"] = True+ return {}++ with pytest.raises(TimeoutError):+ await _paging.bounded(request(), lambda: 0.0)+ assert ran["started"] is False+++async def test_tail_probes_stop_at_the_deadline_without_a_grace_period():+ rows = [user_row("row-0", OLD_TURN, 0), *lifecycle_rows(OLD_TURN, 1, 5000)]+ transcript = FakeTranscript(rows)+ client = wait_client(transcript, [{"status": "working"}])+ budget = iter([5.0, 5.0, 0.0])++ def remaining() -> float:+ return next(budget, 0.0)++ with pytest.raises(TimeoutError):+ await _paging.fetch_tail(client, "s1", 300, remaining)+ assert len(transcript.calls) == 2+++async def test_wait_for_reply_keeps_collected_rows_when_a_page_request_times_out():+ rows = [+ user_row("row-prompt", RECEIPT, 1),+ agent_row("row-interim", RECEIPT, 2, claude_text("Reading.")),+ ]+ transcript = FakeTranscript(rows)+ never = asyncio.Event()+ calls = {"n": 0}++ async def list_messages(+ session_id: str,+ after: str = "",+ limit: int | None = None,+ offset: int | None = None,+ ) -> dict[str, Any]:+ calls["n"] += 1+ if calls["n"] > 1:+ await never.wait()+ return await transcript.list_messages(session_id, after, limit, offset)++ client = wait_client(transcript, [{"status": "working"}])+ client.list_messages = list_messages+ result = await asyncio.wait_for(+ wait_for_reply(client, "s1", RECEIPT, 0.3, 0.05), timeout=5+ )+ assert result["timed_out"] is True+ assert result["reply"] == "Reading."+ assert [m["id"] for m in result["messages"]] == ["row-prompt", "row-interim"]+++# --- round 2: startup events are not completion (R2-03) ----------------------+++class LaggingSession:+ """Status and transcript advance one tick per API call, so the status the+ loop sees can be older than the rows it has already read."""++ def __init__(self, statuses: list[str], rows_at: dict[int, list[dict]]):+ self.tick = 0+ self.statuses = statuses+ self.rows_at = rows_at+ self.transcript = FakeTranscript([])++ def _advance(self) -> int:+ tick, self.tick = self.tick, self.tick + 1+ for at, rows in self.rows_at.items():+ if at == tick:+ self.transcript.rows.extend(rows)+ return tick++ async def status(self, session_id: str) -> dict[str, Any]:+ tick = self._advance()+ return {"status": self.statuses[min(tick, len(self.statuses) - 1)]}++ async def list_messages(+ self,+ session_id: str,+ after: str = "",+ limit: int | None = None,+ offset: int | None = None,+ ) -> dict[str, Any]:+ self._advance()+ return await self.transcript.list_messages(session_id, after, limit, offset)++ def client(self) -> ConductorClient:+ client = ConductorClient(TEST_CREDENTIALS)+ client.session_status = self.status+ client.list_messages = self.list_messages+ return client+++async def test_wait_for_reply_keeps_polling_past_a_startup_only_turn():+ """The session is idle while the prompt is queued; the agent starts+ (system/init only) during the same poll, works, then answers."""+ turn = claude_turn(RECEIPT, 1, "Answer")+ session = LaggingSession(+ statuses=["idle", "idle", "working", "working", "working", "idle"],+ rows_at={0: [user_row("row-prompt", RECEIPT, 1), turn[0]], 3: turn[1:]},+ )+ result = await run_wait(session.client(), 600, 10)+ assert result["timed_out"] is False+ assert result["reply"] == "Reading.\n\nAnswer"+ assert result["messages"][-1]["id"] == "r-idle"+++async def test_wait_for_reply_does_not_complete_on_startup_events_alone():+ rows = [+ user_row("row-prompt", RECEIPT, 1),+ agent_row("r-sys", RECEIPT, 2, CLAUDE_SYSTEM),+ agent_row("r-life", RECEIPT, 3, CLAUDE_LIFECYCLE),+ agent_row("r-codex", RECEIPT, 4, codex_event("turn.started")),+ ]+ client = wait_client(FakeTranscript(rows), [{"status": "idle"}])+ result = await run_wait(client, 30, 10)+ assert result["timed_out"] is True+ assert result["reply"] == ""+ assert result["session_status"] == "idle"+ assert [m["id"] for m in result["messages"]] == [+ "row-prompt",+ "r-sys",+ "r-life",+ "r-codex",+ ]+++async def test_wait_for_reply_reads_rows_written_just_before_idle():+ """Rows that land between the transcript read and the status read of the+ same poll belong to the reply."""+ turn = claude_turn(RECEIPT, 1, "Final")+ session = LaggingSession(+ statuses=["working", "idle"],+ rows_at={0: [user_row("row-prompt", RECEIPT, 1), *turn[:4]], 1: turn[4:]},+ )+ result = await run_wait(session.client(), 600, 10)+ assert result["timed_out"] is False+ assert result["reply"] == "Reading.\n\nFinal"+ assert result["messages"][-1]["id"] == "r-idle"diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_turn_isolation.py b/autogpt_platform/backend/backend/blocks/conductor/test_turn_isolation.pynew file mode 100644index 0000000000..ade3192cb6--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_turn_isolation.py@@ -0,0 +1,41 @@+import pytest++from backend.blocks.conductor._transcript import wait_for_reply+from backend.blocks.conductor.test_fixtures import (+ RECEIPT,+ FakeTranscript,+ agent_row,+ claude_text,+ user_row,+ wait_client,+ wait_clock,+)+++async def test_untagged_agent_row_cannot_complete_a_tagged_turn():+ untagged = agent_row("unrelated", "", 2, claude_text("Wrong turn"))+ rows = [user_row("prompt", RECEIPT, 1), untagged]+ client = wait_client(FakeTranscript(rows), [{"status": "idle"}])+ with wait_clock():+ result = await wait_for_reply(client, "s1", RECEIPT, 60, 1)++ assert result["timed_out"] is True+ assert result["reply"] == ""+ assert [row["id"] for row in result["messages"]] == ["prompt"]+++async def test_tagged_reply_excludes_untagged_rows():+ rows = [+ user_row("prompt", RECEIPT, 1),+ agent_row("unrelated", "", 2, claude_text("Wrong turn")),+ agent_row("answer", RECEIPT, 3, claude_text("Correct answer")),+ ]+ client = wait_client(FakeTranscript(rows), [{"status": "idle"}])+ with wait_clock():+ result = await wait_for_reply(client, "s1", RECEIPT, 60, 1)++ assert result["timed_out"] is False+ assert result["reply"] == "Correct answer"+ assert [row["id"] for row in result["messages"]] == ["prompt", "answer"]diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_workspace_availability.py b/autogpt_platform/backend/backend/blocks/conductor/test_workspace_availability.pynew file mode 100644index 0000000000..4c8e69747a--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/conductor/test_workspace_availability.py@@ -0,0 +1,40 @@+from unittest.mock import AsyncMock, Mock, patch++import pytest++from backend.blocks.conductor.get_workspace import ConductorGetWorkspaceBlock+from backend.blocks.conductor.test_fixtures import TEST_CREDENTIALS_INPUT, collect+++ "preview_fails,sessions_fail", [(True, False), (False, True), (True, True)]+)+async def test_initializing_workspace_keeps_details_when_optional_reads_fail(+ preview_fails: bool, sessions_fail: bool+):+ workspace = {"id": "ws1", "state": "initializing"}+ client = Mock(+ get_workspace=AsyncMock(return_value=workspace),+ workspace_status=AsyncMock(return_value={"status": "initializing"}),+ get_preview=AsyncMock(+ return_value={"preview": {"url": "https://preview.example"}},+ side_effect=ValueError("not ready") if preview_fails else None,+ ),+ workspace_sessions=AsyncMock(+ return_value={"data": [{"id": "s1"}], "hasMore": False},+ side_effect=ValueError("not ready") if sessions_fail else None,+ ),+ )+ with patch(+ "backend.blocks.conductor.get_workspace.ConductorClient", return_value=client+ ):+ result = await collect(+ ConductorGetWorkspaceBlock(),+ {"credentials": TEST_CREDENTIALS_INPUT, "workspace_id": "ws1"},+ )++ assert result["workspace"] == workspace+ assert result["status"] == "initializing"+ assert result["preview_url"] == ("" if preview_fails else "https://preview.example")+ assert result["sessions"] == ([] if sessions_fail else [{"id": "s1"}])diff --git a/autogpt_platform/frontend/public/integrations/README.md b/autogpt_platform/frontend/public/integrations/README.mdindex 299a2c579e..9585bbcae6 100644--- a/autogpt_platform/frontend/public/integrations/README.md+++ b/autogpt_platform/frontend/public/integrations/README.md@@ -9,6 +9,7 @@ The generic `database.png` and `generic_webhook.png` icons are rendered from `Da| `allquiet.png` | [All Quiet favicon](https://dtwty4t4iqzp9.cloudfront.net/img/favicon-v4/favicon-96x96.png), linked from [allquiet.app](https://allquiet.app) || `ayrshare.png` | [Ayrshare favicon](https://www.ayrshare.com/favicon-196x196.png) || `compass.png` | [Fieldy app icon](https://www.fieldy.ai/apple-touch-icon.png); the former Compass Wearable domain redirects to Fieldy |+| `conductor.png` | [Conductor site icon](https://www.conductor.build/icon.png), linked from [conductor.build](https://www.conductor.build); resized to 256x256 || `dataforb2b.png` | [DataForB2B favicon](https://dataforb2b.ai/asset/favicon-192x192.png) || `elevenlabs.png` | [ElevenLabs app icon](https://elevenlabs.io/apple-icon.png) || `openseo.png` | [OpenSEO app icon](https://github.com/every-app/open-seo/blob/0ffff93101043aad7600a3b6a499a0cd2887ef49/public/apple-touch-icon.png), served at [openseo.so](https://openseo.so) |diff --git a/autogpt_platform/frontend/public/integrations/conductor.png b/autogpt_platform/frontend/public/integrations/conductor.pngnew file mode 100644index 0000000000..7e3387f7bbBinary files /dev/null and b/autogpt_platform/frontend/public/integrations/conductor.png differdiff --git a/docs/integrations/README.md b/docs/integrations/README.mdindex 23e17bd7e2..45787cde18 100644--- a/docs/integrations/README.md+++ b/docs/integrations/README.md@@ -538,6 +538,17 @@ Below is a comprehensive list of all available blocks, categorized by their prim| [AllQuiet List Incidents](block-integrations/allquiet/incident_search.md#allquiet-list-incidents) | Searches All Quiet incidents by status, severity, team or text || [AllQuiet List Teams](block-integrations/allquiet/teams.md#allquiet-list-teams) | Lists All Quiet teams and their IDs || [AllQuiet Update Incident](block-integrations/allquiet/incidents.md#allquiet-update-incident) | Investigates, resolves, escalates or comments on an All Quiet incident |+| [Conductor Create Session](block-integrations/conductor/create_session.md#conductor-create-session) | Start a new agent session (chat) in an existing Conductor workspace, optionally with a first prompt, and optionally wait for the agent's reply |+| [Conductor Create Workspace](block-integrations/conductor/create_workspace.md#conductor-create-workspace) | Create a Conductor cloud workspace for a project or repository, optionally start its agent with a prompt and wait for the reply |+| [Conductor Get Account](block-integrations/conductor/account.md#conductor-get-account) | Get an overview of your Conductor account in one call: who you are, the projects (repositories) you can open workspaces in, your sections and your routines |+| [Conductor Get Session](block-integrations/conductor/get_session.md#conductor-get-session) | Get a Conductor agent session: its details, whether the agent is idle, working or errored, and recent transcript messages |+| [Conductor Get Workspace](block-integrations/conductor/get_workspace.md#conductor-get-workspace) | Get everything about one Conductor workspace: details, current status, shared preview URL and its agent sessions |+| [Conductor List Workspaces](block-integrations/conductor/list_workspaces.md#conductor-list-workspaces) | List Conductor workspaces, optionally filtered by project, state, name, repository, creator or activity date |+| [Conductor Manage Routine](block-integrations/conductor/routines.md#conductor-manage-routine) | Create a Conductor routine (a saved prompt that runs a fresh agent in a project whenever its webhook URL is called) or rotate a routine's webhook secret |+| [Conductor Manage Section](block-integrations/conductor/sections.md#conductor-manage-section) | Create or delete a Conductor cloud section |+| [Conductor Manage Session](block-integrations/conductor/manage_session.md#conductor-manage-session) | Rename, cancel or archive a Conductor agent session |+| [Conductor Manage Workspace](block-integrations/conductor/manage_workspace.md#conductor-manage-workspace) | Change a Conductor workspace: rename it, archive, unarchive or sleep it, share or stop sharing a port at its public preview URL, or move it into a section |+| [Conductor Send Message](block-integrations/conductor/send_message.md#conductor-send-message) | Send a prompt to a Conductor agent session and, by default, wait for the agent to finish and return its reply || [Exa Code Context](block-integrations/exa/code_context.md#exa-code-context) | Search billions of GitHub repos, docs, and Stack Overflow for relevant code examples || [Execute Code](block-integrations/misc.md#execute-code) | Executes code in a sandbox environment with internet access || [Execute Code Step](block-integrations/misc.md#execute-code-step) | Execute code in a previously instantiated sandbox |diff --git a/docs/integrations/SUMMARY.md b/docs/integrations/SUMMARY.mdindex 21be134710..2b8a48c4ce 100644--- a/docs/integrations/SUMMARY.md+++ b/docs/integrations/SUMMARY.md@@ -48,6 +48,17 @@* [Bannerbear Text Overlay](block-integrations/bannerbear/text_overlay.md)* [Basic](block-integrations/basic.md)* [Compass Triggers](block-integrations/compass/triggers.md)+* [Conductor Account](block-integrations/conductor/account.md)+* [Conductor Create Session](block-integrations/conductor/create_session.md)+* [Conductor Create Workspace](block-integrations/conductor/create_workspace.md)+* [Conductor Get Session](block-integrations/conductor/get_session.md)+* [Conductor Get Workspace](block-integrations/conductor/get_workspace.md)+* [Conductor List Workspaces](block-integrations/conductor/list_workspaces.md)+* [Conductor Manage Session](block-integrations/conductor/manage_session.md)+* [Conductor Manage Workspace](block-integrations/conductor/manage_workspace.md)+* [Conductor Routines](block-integrations/conductor/routines.md)+* [Conductor Sections](block-integrations/conductor/sections.md)+* [Conductor Send Message](block-integrations/conductor/send_message.md)* [Data](block-integrations/data.md)* [DataForB2B Enrich](block-integrations/dataforb2b/enrich.md)* [DataForB2B Reasoning](block-integrations/dataforb2b/reasoning.md)diff --git a/docs/integrations/block-integrations/conductor/account.md b/docs/integrations/block-integrations/conductor/account.mdnew file mode 100644index 0000000000..e16aa21bba--- /dev/null+++ b/docs/integrations/block-integrations/conductor/account.md@@ -0,0 +1,39 @@+# Conductor Account+<!-- MANUAL: file_description -->+One-call overview of a Conductor account: identity, projects (repositories), sections and routines. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor Get Account++### What it is+Get an overview of your Conductor account in one call: who you are, the projects (repositories) you can open workspaces in, your sections and your routines. Use this first to find project IDs.++### How it works+<!-- MANUAL: how_it_works -->+The block calls `GET /me` for the caller's identity, then pages through `GET /v0/projects`, `GET /v0/sections` and `GET /v0/routines` (each `{data, offset, hasMore}` listing) until `limit` items or the end. Routine listings never include webhook URLs; use Manage Routine to create a routine or rotate its secret and receive the URL. Any HTTP or API error (`userMessage` from Conductor) is raised as a block error.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| limit | Maximum number of projects, sections and routines to list | int | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| user | The authenticated identity: userId, name, email, organizationId | Dict[str, Any] |+| projects | Repositories you can create workspaces in: id, name, gitRemote | List[Dict[str, Any]] |+| sections | Your cloud sections: id, name, emoji, workspaceIds | List[Dict[str, Any]] |+| routines | Your routines: id, name, prompt, repoUrl, agent, model, enabled, runCount, triggers (webhook URLs are not included) | List[Dict[str, Any]] |++### Possible use case+<!-- MANUAL: use_case -->+**Orient an agent**: Run this first so AutoPilot or a graph can look up the `projects[].id` it needs before creating a workspace.++**Inventory**: List sections and routines to decide where new workspaces should be filed and which automations already exist.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/conductor/create_session.md b/docs/integrations/block-integrations/conductor/create_session.mdnew file mode 100644index 0000000000..67a0345b3b--- /dev/null+++ b/docs/integrations/block-integrations/conductor/create_session.md@@ -0,0 +1,53 @@+# Conductor Create Session+<!-- MANUAL: file_description -->+Starts a new agent session (chat) in an existing Conductor workspace, optionally with a first prompt, and optionally waits for the reply. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor Create Session++### What it is+Start a new agent session (chat) in an existing Conductor workspace, optionally with a first prompt, and optionally wait for the agent's reply.++### How it works+<!-- MANUAL: how_it_works -->+The block posts to `POST /v0/sessions` with `workspaceId`, `agent` and any non-blank `model`, `effort`, `name` or `message`. When `message` is given the returned `initial_message_id` identifies the prompt; with `wait_for_reply` the block waits the same way as Send Message: it reads the transcript and then the session status on every poll (a wall-clock bound of `timeout_seconds`, reported through `timed_out`), correlates the rows with the prompt's turn, treats the session as done only once it is idle after the turn progressed past its startup events, and returns the rows in `messages` with their visible agent text joined into `reply` (`truncated` is set when the turn exceeded the 1000 rows kept or its start was older than the rows read).+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| workspace_id | Workspace to add the session to | str | Yes |+| message | Initial prompt for the agent; leave empty for an idle session | str | No |+| agent | Agent to run | "claude" \| "codex" \| "cursor" \| "acp" | No |+| model | Model id such as fable-5-1, opus-5-5-1m, sonnet-5-1m, gpt-6-astra or auto. Leave empty for Conductor's default. | str | No |+| effort | Reasoning effort; leave empty for the default | "" \| "none" \| "low" \| "medium" \| "high" \| "xhigh" \| "max" \| "ultra" | No |+| fast_mode | Enable fast mode | bool | No |+| name | Session name | str | No |+| wait_for_reply | After sending the initial prompt, wait until the agent is idle and return its reply | bool | No |+| timeout_seconds | How long to wait for the reply | int | No |+| poll_interval_seconds | Seconds between status checks while waiting | int | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| session_id | ID of the new session | str |+| deep_link | Link that opens the session | str |+| initial_message_id | ID of the initial prompt message, empty when none was sent | str |+| session_status | idle, working or error once waiting finished | str |+| reply | Text the agent produced in response | str |+| messages | Raw transcript messages after the prompt | List[Dict[str, Any]] |+| timed_out | True when the wait ended before the agent went idle | bool |+| truncated | True when the turn produced more messages than are kept; messages holds the newest ones and reply may be incomplete | bool |+| error_message | Session error, if any | str |++### Possible use case+<!-- MANUAL: use_case -->+**Second opinion**: Open a Codex session in a workspace where Claude already worked and ask it to review the diff.++**Split work**: Start one session per sub-task in the same workspace so they share the checkout.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/conductor/create_workspace.md b/docs/integrations/block-integrations/conductor/create_workspace.mdnew file mode 100644index 0000000000..b66b179517--- /dev/null+++ b/docs/integrations/block-integrations/conductor/create_workspace.md@@ -0,0 +1,59 @@+# Conductor Create Workspace+<!-- MANUAL: file_description -->+Creates a Conductor cloud workspace for a project or repository, optionally starts its agent with a prompt and waits for the reply. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor Create Workspace++### What it is+Create a Conductor cloud workspace for a project or repository, optionally start its agent with a prompt and wait for the reply.++### How it works+<!-- MANUAL: how_it_works -->+The block posts to `POST /v0/workspaces` with exactly one of `project_id` or `repository_url` (both or neither is an input error). Blank optional fields are omitted so Conductor applies its defaults; `model` is passed through as-is, so use an id Conductor accepts (for example `fable-5-1`, `opus-5-5-1m`, `sonnet-5-1m`, `gpt-6-astra` or `auto`). When `message` is set the agent starts on it immediately and `initial_message_id` is returned. With `wait_for_reply` the block then waits the same way as Send Message: it reads the transcript and then `GET /v0/sessions/{id}/status` every `poll_interval_seconds` (a wall-clock bound of `timeout_seconds`, reported through `timed_out`), correlates the transcript rows with the prompt's turn (a freshly initializing workspace reports idle until the agent actually starts, and startup events alone are not treated as done), and returns those rows with their visible agent text joined into `reply` (`truncated` is set when the turn exceeded the 1000 rows kept or its start was older than the rows read).+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| project_id | Project (repository) to open the workspace in. Find IDs with Get Account. Use this or repository_url, not both. | str | No |+| repository_url | Git repository URL to open instead of a project ID | str | No |+| message | Initial prompt for the agent. Leave empty to create an idle workspace. | str | No |+| branch | Branch to start from | str | No |+| name | Workspace name | str | No |+| session_name | Name of the initial agent session | str | No |+| agent | Agent for the initial session | "claude" \| "codex" \| "cursor" \| "acp" | No |+| model | Model id such as fable-5-1, opus-5-5-1m, sonnet-5-1m, gpt-6-astra or auto. Leave empty for Conductor's default. | str | No |+| effort | Reasoning effort; leave empty for the default | "" \| "none" \| "low" \| "medium" \| "high" \| "xhigh" \| "max" \| "ultra" | No |+| fast_mode | Enable fast mode | bool | No |+| env | Environment variables for the workspace | Dict[str, str] | No |+| restricted_access | Restrict the workspace to its creator | bool | No |+| wait_for_reply | After sending the initial prompt, wait until the agent is idle and return its reply | bool | No |+| timeout_seconds | How long to wait for the reply | int | No |+| poll_interval_seconds | Seconds between status checks while waiting | int | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| workspace_id | ID of the new workspace | str |+| session_id | ID of the initial session | str |+| deep_link | Link that opens the workspace | str |+| initial_message_id | ID of the initial prompt message, empty when none was sent | str |+| session_status | idle, working or error once waiting finished | str |+| reply | Text the agent produced in response | str |+| messages | Raw transcript messages after the prompt | List[Dict[str, Any]] |+| timed_out | True when the wait ended before the agent went idle | bool |+| truncated | True when the turn produced more messages than are kept; messages holds the newest ones and reply may be incomplete | bool |+| error_message | Session error, if any | str |++### Possible use case+<!-- MANUAL: use_case -->+**Ticket to branch**: Take an issue description from a trigger, create a workspace on the repo with that prompt, and wait for the agent's summary of the change.++**Parallel exploration**: Fan one task out to several workspaces with different `model` or `agent` values and compare the replies.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/conductor/get_session.md b/docs/integrations/block-integrations/conductor/get_session.mdnew file mode 100644index 0000000000..fe0a898239--- /dev/null+++ b/docs/integrations/block-integrations/conductor/get_session.md@@ -0,0 +1,47 @@+# Conductor Get Session+<!-- MANUAL: file_description -->+Reads a Conductor agent session: details, whether the agent is idle, working or errored, and recent transcript messages. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor Get Session++### What it is+Get a Conductor agent session: its details, whether the agent is idle, working or errored, and recent transcript messages.++### How it works+<!-- MANUAL: how_it_works -->+The block calls `GET /v0/sessions/{id}` and `GET /v0/sessions/{id}/status`, then reads the transcript through `GET /v0/sessions/{id}/messages`. The API only pages from the start in ascending order (100 rows per request at most), so by default the block locates the end of the transcript with cheap one-row probes and returns the newest `message_limit` messages; with `after` it instead reads the next `message_limit` messages following that message ID, which is how to poll incrementally (`next_after` is the ID to pass on the next call). `has_more` reports whether older (default) or newer (`after`) messages exist beyond the slice; set `message_limit` to 0 to skip the transcript. `latest_reply` is the newest message with visible agent text, so trailing tool, lifecycle or status events do not hide the answer. Live rows are `userMessage` prompts and `agent` events wrapping the harness's raw payload; only Claude `assistant` text parts and completed Codex `agentMessage` items count as visible text. Pass `message_id` to also fetch one message via `GET /v0/messages/{id}` (a transcript row ID, not a send receipt).+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| session_id | Session ID | str | Yes |+| message_limit | How many transcript messages to return: the most recent ones, or the ones following `after` when it is set; 0 skips the transcript | int | No |+| after | Read forward from this transcript message ID (exclusive) instead of returning the most recent messages; use next_after from a previous call to poll incrementally | str | No |+| message_id | Also fetch this single message by ID | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| session | Session: id, name, model, resolvedModel, effort, fastMode, deepLink, archivedAt | Dict[str, Any] |+| status | idle, working or error | str |+| error_message | Last session error, if any | str |+| messages | Transcript messages, oldest first: id, sessionIndex, type, content, receivedAt | List[Dict[str, Any]] |+| latest_reply | Text of the newest agent message with visible text in the returned transcript slice | str |+| has_more | True when the transcript has messages beyond the returned slice: older ones by default, newer ones when after is set | bool |+| next_after | ID of the last returned message; pass it as after to read what follows | str |+| message | The single message requested by message_id | Dict[str, Any] |+| deep_link | Link that opens the session | str |++### Possible use case+<!-- MANUAL: use_case -->+**Poll a long task**: Check `status` on a schedule and read `latest_reply` once it turns `idle`.++**Incremental transcript**: Keep the last message id and pass it as `after` to fetch only what is new.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/conductor/get_workspace.md b/docs/integrations/block-integrations/conductor/get_workspace.mdnew file mode 100644index 0000000000..2f4a6f6cbf--- /dev/null+++ b/docs/integrations/block-integrations/conductor/get_workspace.md@@ -0,0 +1,50 @@+# Conductor Get Workspace+<!-- MANUAL: file_description -->+Everything about one Conductor workspace: details, status, shared preview URL and its agent sessions. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor Get Workspace++### What it is+Get everything about one Conductor workspace: details, current status, shared preview URL and its agent sessions.++### How it works+<!-- MANUAL: how_it_works -->+The block calls `GET /v0/workspaces/{id}` and `GET /v0/workspaces/{id}/status`, then best-effort `GET /v0/workspaces/{id}/preview` and `GET /v0/workspaces/{id}/sessions` (a workspace that is still initializing may not serve those yet, in which case `preview_url` is empty and `sessions` is empty). The session listing is paged in requests of up to 100 rows until `session_limit` sessions have been collected starting at `session_offset`; `sessions_has_more` and `next_session_offset` let a graph read the following page. `status` is one of initializing, ready, sleeping, archived, deleted, updating or unstarted; `lifecycle_step` and `error_message` explain an initializing or failed workspace.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| workspace_id | Workspace ID | str | Yes |+| include_archived_sessions | Include archived sessions in the session list | bool | No |+| session_limit | Maximum number of sessions to return | int | No |+| session_offset | Number of sessions to skip; use next_session_offset to read the following page | int | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| workspace | Workspace: id, projectId, name, state, repoUrl, deepLink, creatorName, lastActivityAt | Dict[str, Any] |+| status | initializing, ready, sleeping, archived, deleted, updating or unstarted | str |+| lifecycle_step | Setup step while initializing: building_snapshot, preparing, setting_up or updating | str |+| error_message | Workspace error, if any | str |+| preview_url | Public preview URL when a port is shared, else empty | str |+| preview_port | Port being shared at the preview URL, 0 when none | int |+| sessions | Agent sessions in the workspace: id, name, model, effort, deepLink | List[Dict[str, Any]] |+| sessions_has_more | True when the workspace has more sessions than returned | bool |+| next_session_offset | session_offset to request the next page of sessions | int |+| deep_link | Link that opens the workspace | str |++### Possible use case+<!-- MANUAL: use_case -->+**Wait for readiness**: Poll this block after Create Workspace until `status` is `ready` before opening a second session.++**Grab the preview link**: Read `preview_url` after Manage Workspace shared a port, and post it to Slack for review.++**Pick a session**: Use `sessions[].id` to choose which chat to send a follow-up prompt to.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/conductor/list_workspaces.md b/docs/integrations/block-integrations/conductor/list_workspaces.mdnew file mode 100644index 0000000000..fe758e6da3--- /dev/null+++ b/docs/integrations/block-integrations/conductor/list_workspaces.md@@ -0,0 +1,47 @@+# Conductor List Workspaces+<!-- MANUAL: file_description -->+Lists Conductor workspaces with optional project, state, name, repository, creator and activity filters. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor List Workspaces++### What it is+List Conductor workspaces, optionally filtered by project, state, name, repository, creator or activity date. When filtering within a project, a page can be empty while has_more is true; continue with next_offset until has_more is false.++### How it works+<!-- MANUAL: how_it_works -->+Without `project_id` the block calls `GET /v0/workspaces` and passes every filter as query parameters (`state` may repeat). With `project_id` it calls `GET /v0/projects/{id}/workspaces`, which only paginates, so the block applies the same filters itself to each returned page: exact `state` and `creator`, case-insensitive `name` and `repo` substrings, `since` against `lastActivityAt`, and archived workspaces hidden unless `include_archived` is set or `archived` is among the requested states. A filtered page can therefore be empty while `has_more` is still true; keep paging with `next_offset`, which always advances by the raw page size. `since` must be an ISO-8601 date or timestamp and is validated before any request. Each workspace is also emitted one at a time on `workspace` for fan-out.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| project_id | Only workspaces of this project (repository). Leave empty for all projects. | str | No |+| state | Only workspaces in these states, e.g. ready, sleeping | List["initializing" \| "ready" \| "sleeping" \| "archived" \| "deleted" \| "updating" \| "unstarted"] | No |+| name | Filter by workspace name | str | No |+| repo | Filter by repository URL | str | No |+| creator | Filter by creator user ID | str | No |+| since | Only workspaces whose last activity is on or after this ISO-8601 date or timestamp | str | No |+| include_archived | Include archived workspaces | bool | No |+| limit | Maximum number of workspaces | int | No |+| offset | Pagination offset | int | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| workspaces | Workspaces: id, projectId, name, state, repoUrl, deepLink, creatorName, lastActivityAt | List[Dict[str, Any]] |+| workspace | Each workspace, one at a time | Dict[str, Any] |+| has_more | Whether more pages exist | bool |+| next_offset | Offset to request the next page; with project_id a page can be filtered down to nothing while has_more is still true | int |++### Possible use case+<!-- MANUAL: use_case -->+**Find work in progress**: Filter `state` to `ready` to see which workspaces have a live sandbox before sending prompts.++**Clean-up sweep**: List sleeping workspaces older than a `since` date and feed each `workspace` into Manage Workspace to archive it.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/conductor/manage_session.md b/docs/integrations/block-integrations/conductor/manage_session.mdnew file mode 100644index 0000000000..ef8ce805fa--- /dev/null+++ b/docs/integrations/block-integrations/conductor/manage_session.md@@ -0,0 +1,42 @@+# Conductor Manage Session+<!-- MANUAL: file_description -->+Renames, cancels or archives a Conductor agent session. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor Manage Session++### What it is+Rename, cancel or archive a Conductor agent session. Cancel stops the running turn and drops queued prompts.++### How it works+<!-- MANUAL: how_it_works -->+One `action` per run: `rename` posts `{name}` to `/rename`; `cancel` posts `{}` to `/cancel`, stopping the current turn and dropping queued prompts; `archive` posts `{}` to `/archive`. Cancel and archive report `canceled_queued_messages`. The `status` output is Conductor's immediate response: cancellation can still report `working` while the agent stops. Use Get Session to confirm that it reaches `idle`.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| session_id | Session ID | str | Yes |+| action | rename, cancel (stop the current turn and drop queued prompts) or archive | "rename" \| "cancel" \| "archive" | No |+| name | New session name (rename) | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| session_id | Session ID | str |+| workspace_id | Workspace the session belongs to, when reported | str |+| status | Session status after the action, when reported | str |+| canceled_queued_messages | Queued prompts dropped by cancel or archive | int |+| result | Raw API response | Dict[str, Any] |++### Possible use case+<!-- MANUAL: use_case -->+**Stop a runaway agent**: Cancel a session whose `status` has been `working` past a deadline.++**Housekeeping**: Archive finished sessions so Get Workspace lists only active chats.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/conductor/manage_workspace.md b/docs/integrations/block-integrations/conductor/manage_workspace.mdnew file mode 100644index 0000000000..ccb82da113--- /dev/null+++ b/docs/integrations/block-integrations/conductor/manage_workspace.md@@ -0,0 +1,45 @@+# Conductor Manage Workspace+<!-- MANUAL: file_description -->+Renames, archives, unarchives or sleeps a Conductor workspace, shares or stops its public preview URL, or moves it into a section. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor Manage Workspace++### What it is+Change a Conductor workspace: rename it, archive, unarchive or sleep it, share or stop sharing a port at its public preview URL, or move it into a section.++### How it works+<!-- MANUAL: how_it_works -->+One `action` per run. `rename` posts `{name}` to `/rename`; `archive`, `unarchive` and `sleep` post to the matching lifecycle route and return the new `status`; `share_preview` puts `{port}` to `/preview` and returns the public `preview_url`; `stop_preview` deletes it; `move_to_section` puts `{sectionId}` to `/section`, with an empty `section_id` clearing the section. `result` always carries the raw response.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| workspace_id | Workspace ID | str | Yes |+| action | rename, archive, unarchive, sleep, share_preview (expose a port at a public preview URL), stop_preview, or move_to_section | "rename" \| "archive" \| "unarchive" \| "sleep" \| "share_preview" \| "stop_preview" \| "move_to_section" | No |+| name | New workspace name (rename) | str | No |+| port | Port inside the workspace to share (share_preview) | int | No |+| section_id | Target section ID (move_to_section); empty clears the section | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| workspace_id | Workspace ID | str |+| status | Workspace state after the action, when reported | str |+| preview_url | Preview URL after a share_preview action, else empty | str |+| result | Raw API response | Dict[str, Any] |++### Possible use case+<!-- MANUAL: use_case -->+**Share a running app**: After an agent starts a dev server, share port 3000 and hand the `preview_url` to a reviewer.++**Tidy up**: Archive workspaces whose pull request merged, or sleep idle ones to free resources.++**File by project**: Move new workspaces into a per-customer section created with Manage Section.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/conductor/routines.md b/docs/integrations/block-integrations/conductor/routines.mdnew file mode 100644index 0000000000..a46a77b996--- /dev/null+++ b/docs/integrations/block-integrations/conductor/routines.md@@ -0,0 +1,46 @@+# Conductor Routines+<!-- MANUAL: file_description -->+Creates a Conductor routine (a saved prompt that runs a fresh agent whenever its webhook is called) or rotates a routine's webhook secret. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor Manage Routine++### What it is+Create a Conductor routine (a saved prompt that runs a fresh agent in a project whenever its webhook URL is called) or rotate a routine's webhook secret. Returns the webhook URL.++### How it works+<!-- MANUAL: how_it_works -->+`create` posts `name`, `prompt`, `projectId`, `agent`, optional `model`/`effort`, `enabled` and a single webhook trigger to `POST /v0/routines`; `rotate_webhook_url` posts to `POST /v0/routines/{id}/rotate-secret`. Both responses include the trigger's `webhookUrl`, which the block surfaces as `webhook_url`; the plain routine listing in Get Account never includes it, so store the URL when you receive it. Rotating invalidates the previous URL.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| action | create a webhook-triggered routine, or rotate_webhook_url to replace an existing routine's webhook URL | "create" \| "rotate_webhook_url" | No |+| routine_id | Routine ID (rotate_webhook_url) | str | No |+| name | Routine name (create) | str | No |+| prompt | Prompt the agent runs each time the webhook fires (create) | str | No |+| project_id | Project (repository) the routine runs in (create). Find IDs with Get Account. | str | No |+| agent | Agent that runs the routine | "claude" \| "codex" \| "cursor" \| "acp" | No |+| model | Model id such as fable-5-1, opus-5-5-1m, sonnet-5-1m, gpt-6-astra or auto. Leave empty for Conductor's default. | str | No |+| effort | Reasoning effort; leave empty for the default | "" \| "none" \| "low" \| "medium" \| "high" \| "xhigh" \| "max" \| "ultra" | No |+| enabled | Whether the routine is enabled on creation | bool | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| routine_id | ID of the routine | str |+| webhook_url | Webhook URL that triggers the routine. POST to it to run the routine; this is the only time the URL is shown. | str |+| routine | Full routine object | Dict[str, Any] |++### Possible use case+<!-- MANUAL: use_case -->+**Wire up automation**: Create a routine such as "triage new issues" and send its `webhook_url` to another system that calls it on events.++**Credential hygiene**: Rotate a leaked webhook secret and update the caller with the new URL.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/conductor/sections.md b/docs/integrations/block-integrations/conductor/sections.mdnew file mode 100644index 0000000000..d5c76590e0--- /dev/null+++ b/docs/integrations/block-integrations/conductor/sections.md@@ -0,0 +1,41 @@+# Conductor Sections+<!-- MANUAL: file_description -->+Creates or deletes a Conductor cloud section, the sidebar groups that organise workspaces. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor Manage Section++### What it is+Create or delete a Conductor cloud section. Sections group workspaces in the sidebar; move workspaces with Manage Workspace.++### How it works+<!-- MANUAL: how_it_works -->+`create` posts `{name, emoji}` to `POST /v0/sections` and returns the new section; `delete` calls `DELETE /v0/sections/{id}` and returns the section together with the workspace ids that were in it (`removed_workspace_ids`), which are left unfiled rather than deleted. Move workspaces between sections with Manage Workspace's `move_to_section` action.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| action | create a personal section, or delete one | "create" \| "delete" | No |+| name | Section name (create) | str | No |+| emoji | Optional emoji shown next to the section name (create) | str | No |+| section_id | Section ID (delete) | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| section_id | ID of the created or deleted section | str |+| section | The section: id, name, emoji, workspaceIds | Dict[str, Any] |+| removed_workspace_ids | Workspaces that were in the section (delete only) | List[str] |++### Possible use case+<!-- MANUAL: use_case -->+**Per-customer folders**: Create a section per client and move their workspaces into it.++**Retire a project**: Delete its section and archive the returned workspace ids.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/conductor/send_message.md b/docs/integrations/block-integrations/conductor/send_message.mdnew file mode 100644index 0000000000..0f85a14a33--- /dev/null+++ b/docs/integrations/block-integrations/conductor/send_message.md@@ -0,0 +1,48 @@+# Conductor Send Message+<!-- MANUAL: file_description -->+Sends a prompt to a Conductor agent session and, by default, waits for the agent to finish and returns its reply. Requires your own Conductor API key, created at [app.conductor.build/users/api-keys](https://app.conductor.build/users/api-keys) and added through AutoGPT’s credentials UI. Select that credential for each Conductor block; no server-wide default key is used.+<!-- END MANUAL -->++## Conductor Send Message++### What it is+Send a prompt to a Conductor agent session and, by default, wait for the agent to finish and return its reply.++### How it works+<!-- MANUAL: how_it_works -->+The block posts `{message}` to `POST /v0/sessions/{id}/messages` and returns the receipt (`message_id`, `state` queued or sent, `deep_link`). With `wait_for_reply` (the default) it then polls every `poll_interval_seconds`: each poll reads the transcript rows that arrived since the previous one and then `GET /v0/sessions/{id}/status`, so the status is never older than the rows it is judged against. The receipt ID is the prompt's `content.id` in the transcript (not a row ID, so it cannot be used as a cursor); the block looks for that row among the newest 300 rows, then in up to 1000 older rows, and otherwise resolves the turn from agent rows tagged with the receipt as their `turnId`, reporting the omitted history through `truncated`. It finishes when the session reports `error`, or `idle` after the turn has progressed past its startup events (Claude `system`/`command_lifecycle`, Codex `thread.started`/`turn.started`), reading the transcript once more for rows written just before the status changed; a session that is idle because the prompt is still queued, or has only launched the agent, is not treated as finished. `reply` joins the visible agent text of the turn (Claude `assistant` text, completed Codex `agentMessage` items); `messages` has the raw rows of the turn, newest kept when a turn exceeds 1000 rows (`truncated` is set). `timeout_seconds` is a wall-clock bound: sleeps and requests are capped by it, nothing is requested once it has elapsed, and when it elapses `timed_out` is set and whatever arrived so far is returned. The block's own execution cap is two hours, so `timeout_seconds` is limited to that.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| session_id | Session to send the prompt to | str | Yes |+| message | Prompt for the agent | str | Yes |+| wait_for_reply | Wait until the agent is idle and return its reply | bool | No |+| timeout_seconds | How long to wait for the reply | int | No |+| poll_interval_seconds | Seconds between status checks while waiting | int | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| message_id | ID of the sent prompt | str |+| state | queued or sent | str |+| deep_link | Link that opens the message | str |+| session_status | idle, working or error once waiting finished | str |+| reply | Text the agent produced in response | str |+| messages | Raw transcript messages after the prompt | List[Dict[str, Any]] |+| timed_out | True when the wait ended before the agent went idle | bool |+| truncated | True when the turn produced more messages than are kept; messages holds the newest ones and reply may be incomplete | bool |+| error_message | Session error, if any | str |++### Possible use case+<!-- MANUAL: use_case -->+**Conversational driver**: Let AutoPilot steer a coding agent turn by turn: send a prompt, read `reply`, decide the next instruction.++**Fire and forget**: Turn `wait_for_reply` off to queue several prompts and check back later with Get Session.+<!-- END MANUAL -->++---