Skip to content

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.

fix(blocks): accept Conductor prompt IDs as Get Session cursors and expose next_after (#15114)

Abhimanyu Yadav17e9e59d924c
diff --git a/autogpt_platform/backend/backend/blocks/conductor/_api.py b/autogpt_platform/backend/backend/blocks/conductor/_api.py
index b6d1a16314..8730a07110 100644
--- a/autogpt_platform/backend/backend/blocks/conductor/_api.py
+++ b/autogpt_platform/backend/backend/blocks/conductor/_api.py
@@ -77,6 +77,14 @@ class SectionAction(str, Enum):
DELETE = "delete"
+class ConductorAPIError(ValueError):
+ """A non-2xx response from the Conductor API, with its HTTP status."""
+
+ def __init__(self, message: str, status: int):
+ super().__init__(message)
+ self.status = status
+
+
def clean(payload: dict[str, Any]) -> dict[str, Any]:
"""Drop None and empty-string values.
@@ -125,7 +133,7 @@ class ConductorClient:
method, url, json=json_body, params=query or None
)
if not response.ok:
- raise ValueError(_error_message(response))
+ raise ConductorAPIError(_error_message(response), response.status)
try:
body = response.json()
except Exception:
@@ -295,7 +303,9 @@ class ConductorClient:
"""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.
+ `offset`; the API answers 404 for an id that is not a row of this
+ session, which includes the receipt ids returned when a prompt is
+ sent. Pages are clamped to PAGE_SIZE rows server-side.
"""
return await self._call(
"GET",
diff --git a/autogpt_platform/backend/backend/blocks/conductor/_mocks.py b/autogpt_platform/backend/backend/blocks/conductor/_mocks.py
index 2d377476e5..51fb8e2556 100644
--- a/autogpt_platform/backend/backend/blocks/conductor/_mocks.py
+++ b/autogpt_platform/backend/backend/blocks/conductor/_mocks.py
@@ -49,4 +49,5 @@ WAIT_MOCK_REPLY = {
"reply": "All tests pass now.",
"timed_out": False,
"truncated": False,
+ "prompt_row_id": MOCK_PROMPT_MESSAGE["id"],
}
diff --git a/autogpt_platform/backend/backend/blocks/conductor/_transcript.py b/autogpt_platform/backend/backend/blocks/conductor/_transcript.py
index 99d248655c..e3aeb5c727 100644
--- a/autogpt_platform/backend/backend/blocks/conductor/_transcript.py
+++ b/autogpt_platform/backend/backend/blocks/conductor/_transcript.py
@@ -5,17 +5,22 @@ 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.
+receipt ids are different namespaces: only row ids work as `after` cursors
+on the API, so `find_prompt_row` maps a receipt to its row and `read_after`
+accepts either.
"""
import asyncio
+import logging
import time
from collections import deque
+from collections.abc import Awaitable, Callable
from typing import Any
-from ._api import PAGE_SIZE, ConductorClient
+from ._api import PAGE_SIZE, ConductorAPIError, ConductorClient
from ._paging import (
Remaining,
+ Rows,
bounded,
expired,
fetch_after,
@@ -42,6 +47,8 @@ NON_AGENT_TYPES = USER_TYPES | {"system"}
STARTUP_RAW_TYPES = frozenset({"system", "command_lifecycle"})
STARTUP_CODEX_EVENTS = frozenset({"thread.started", "turn.started"})
+logger = logging.getLogger(__name__)
+
async def wait_for_reply(
client: ConductorClient,
@@ -101,9 +108,77 @@ async def wait_for_reply(
"reply": reply_text(messages),
"timed_out": timed_out,
"truncated": turn.truncated,
+ "prompt_row_id": turn.prompt_row_id,
}
+async def find_prompt_row(
+ client: ConductorClient,
+ session_id: str,
+ receipt_id: str,
+ remaining: Remaining = None,
+ search_history: bool = True,
+) -> str:
+ """Row id of the transcript row recording the prompt `receipt_id`.
+
+ Looks through the newest rows the same way the wait loop does, and by
+ default through bounded older pages after that; returns "" when the
+ prompt has no row yet (it is still queued) or is older than the search.
+ With `search_history` off only the newest rows are read, which is enough
+ right after sending.
+ """
+
+ def is_prompt(row: dict[str, Any]) -> bool:
+ return _is_prompt_row(row, receipt_id)
+
+ rows = await _search(
+ client, session_id, is_prompt, remaining, search_history=search_history
+ )
+ return next(
+ (str(row["id"]) for row in rows if is_prompt(row) and row.get("id")), ""
+ )
+
+
+async def prompt_cursor(lookup: Awaitable[str], receipt_id: str) -> str:
+ """The `after` cursor to hand out for a just-sent prompt: its row id when
+ `lookup` finds one, otherwise the receipt itself, which `read_after`
+ resolves later. A failed lookup is logged rather than raised, since the
+ prompt was already sent."""
+ try:
+ return await lookup or receipt_id
+ except Exception as e:
+ logger.warning(
+ "Could not resolve prompt %s to a transcript row: %s", receipt_id, e
+ )
+ return receipt_id
+
+
+async def read_after(
+ client: ConductorClient, session_id: str, cursor: str, count: int
+) -> tuple[Rows, bool, str]:
+ """`fetch_after` for a cursor that is either a row id or a prompt receipt.
+
+ A row id is paged directly. When the API rejects the cursor as not a row
+ of the session (404) it is taken to be the receipt returned when a prompt
+ was sent and resolved to that prompt's row; the row id actually used is
+ returned so callers can continue from it without resolving again.
+ """
+ try:
+ rows, has_more = await fetch_after(client, session_id, cursor, count)
+ return rows, has_more, cursor
+ except ConductorAPIError as e:
+ if e.status != 404:
+ raise
+ row_id = await find_prompt_row(client, session_id, cursor)
+ if not row_id:
+ raise ValueError(
+ f"after={cursor!r} is neither a transcript row ID of session "
+ f"{session_id} nor the ID of a prompt recorded in it ({e})"
+ ) from e
+ rows, has_more = await fetch_after(client, session_id, row_id, count)
+ return rows, has_more, row_id
+
+
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))]
@@ -145,6 +220,7 @@ class _TurnCollector:
def __init__(self, receipt_id: str):
self.receipt_id = receipt_id
self.turn_id = ""
+ self.prompt_row_id = ""
self.resolved = False
self.progressed = False
self.truncated = False
@@ -173,19 +249,7 @@ class _TurnCollector:
"""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)
+ self._consume_all(await _search(client, session_id, self._belongs, remaining))
def _consume_all(self, rows: list[dict[str, Any]]) -> None:
for row in rows:
@@ -197,6 +261,7 @@ class _TurnCollector:
if not self.resolved:
if self._is_prompt(row):
self.turn_id = _turn_of(row)
+ self.prompt_row_id = str(row.get("id") or "")
elif self.receipt_id in _tags(row):
# The prompt row is older than anything read: the turn's
# start is not in `rows`.
@@ -215,10 +280,7 @@ class _TurnCollector:
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
- )
+ return _is_prompt_row(row, self.receipt_id)
def _same_turn(self, row: dict[str, Any]) -> bool:
tags = _tags(row)
@@ -234,6 +296,37 @@ class _TurnCollector:
self.rows.append(row)
+async def _search(
+ client: ConductorClient,
+ session_id: str,
+ belongs: Callable[[dict[str, Any]], bool],
+ remaining: Remaining,
+ search_history: bool = True,
+) -> Rows:
+ """The newest PROMPT_SCAN_MESSAGES rows and, when none of them satisfies
+ `belongs` and `search_history` is on, up to PROMPT_SEARCH_MESSAGES older
+ rows read page by page until one does. Oldest first."""
+ rows, start = await fetch_tail_at(
+ client, session_id, PROMPT_SCAN_MESSAGES, remaining
+ )
+ found = any(belongs(row) for row in rows)
+ budget = PROMPT_SEARCH_MESSAGES if search_history else 0
+ 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(belongs(row) for row in page)
+ rows = page + rows
+ return rows
+
+
+def _is_prompt_row(row: dict[str, Any], receipt_id: str) -> bool:
+ """Whether `row` records the prompt whose receipt is `receipt_id`: live
+ rows carry it as `content.id`, plain rows as the row id itself."""
+ return _content(row).get("id") == receipt_id or row.get("id") == receipt_id
+
+
def _content(row: dict[str, Any]) -> dict[str, Any]:
content = row.get("content")
return content if isinstance(content, dict) else {}
diff --git a/autogpt_platform/backend/backend/blocks/conductor/create_session.py b/autogpt_platform/backend/backend/blocks/conductor/create_session.py
index e0a38dd9cd..8ac01eb408 100644
--- a/autogpt_platform/backend/backend/blocks/conductor/create_session.py
+++ b/autogpt_platform/backend/backend/blocks/conductor/create_session.py
@@ -22,7 +22,7 @@ from ._api import (
)
from ._config import conductor
from ._mocks import WAIT_MOCK_REPLY
-from ._transcript import wait_for_reply
+from ._transcript import find_prompt_row, prompt_cursor, wait_for_reply
CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"
@@ -83,6 +83,12 @@ class ConductorCreateSessionBlock(Block):
initial_message_id: str = SchemaField(
description="ID of the initial prompt message, empty when none was sent"
)
+ next_after: str = SchemaField(
+ description="Transcript row ID of the prompt's row; pass it as "
+ "`after` to Get Session to read the agent's turn. Falls back to "
+ "initial_message_id while the prompt has no row yet, which Get Session "
+ "also accepts"
+ )
session_status: str = SchemaField(
description="idle, working or error once waiting finished"
)
@@ -127,9 +133,11 @@ class ConductorCreateSessionBlock(Block):
("session_id", "sess_1"),
("deep_link", "conductor://s/1"),
("initial_message_id", "msg_1"),
+ ("next_after", "row_1"),
("session_id", "sess_1"),
("deep_link", "conductor://s/1"),
("initial_message_id", "msg_1"),
+ ("next_after", "row_1"),
("session_status", "idle"),
("reply", "All tests pass now."),
("messages", lambda m: len(m) == 1),
@@ -148,6 +156,7 @@ class ConductorCreateSessionBlock(Block):
},
},
"_wait": lambda *args, **kwargs: WAIT_MOCK_REPLY,
+ "_prompt_row": lambda *args, **kwargs: "row_1",
},
)
@@ -156,6 +165,13 @@ class ConductorCreateSessionBlock(Block):
) -> dict[str, Any]:
return await ConductorClient(credentials).create_session(payload)
+ async def _prompt_row(
+ self, credentials: APIKeyCredentials, session_id: str, message_id: str
+ ) -> str:
+ return await find_prompt_row(
+ ConductorClient(credentials), session_id, message_id, search_history=False
+ )
+
async def _wait(
self,
credentials: APIKeyCredentials,
@@ -204,7 +220,12 @@ class ConductorCreateSessionBlock(Block):
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):
+ if not (session_id and message_id):
+ return
+ if not input_data.wait_for_reply:
+ yield "next_after", await prompt_cursor(
+ self._prompt_row(credentials, session_id, message_id), message_id
+ )
return
try:
waited = await self._wait(
@@ -220,6 +241,7 @@ class ConductorCreateSessionBlock(Block):
block_name=self.name,
block_id=self.id,
) from e
+ yield "next_after", str(waited.get("prompt_row_id") or message_id)
yield "session_status", waited["session_status"]
yield "reply", waited["reply"]
yield "messages", waited["messages"]
diff --git a/autogpt_platform/backend/backend/blocks/conductor/create_workspace.py b/autogpt_platform/backend/backend/blocks/conductor/create_workspace.py
index d18e439f04..41f0bfeb46 100644
--- a/autogpt_platform/backend/backend/blocks/conductor/create_workspace.py
+++ b/autogpt_platform/backend/backend/blocks/conductor/create_workspace.py
@@ -21,7 +21,7 @@ from ._api import (
clean,
)
from ._config import conductor
-from ._transcript import wait_for_reply
+from ._transcript import find_prompt_row, prompt_cursor, wait_for_reply
CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"
@@ -103,6 +103,12 @@ class ConductorCreateWorkspaceBlock(Block):
initial_message_id: str = SchemaField(
description="ID of the initial prompt message, empty when none was sent"
)
+ next_after: str = SchemaField(
+ description="Transcript row ID of the prompt's row; pass it as "
+ "`after` to Get Session to read the agent's turn. Falls back to "
+ "initial_message_id while the prompt has no row yet, which Get Session "
+ "also accepts"
+ )
session_status: str = SchemaField(
description="idle, working or error once waiting finished"
)
@@ -148,10 +154,12 @@ class ConductorCreateWorkspaceBlock(Block):
("session_id", "sess_1"),
("deep_link", "conductor://workspace/ws_1"),
("initial_message_id", "msg_1"),
+ ("next_after", "row_1"),
("workspace_id", "ws_1"),
("session_id", "sess_1"),
("deep_link", "conductor://workspace/ws_1"),
("initial_message_id", "msg_1"),
+ ("next_after", "row_1"),
("session_status", "idle"),
("reply", "Done, the fix is on branch fix-login."),
("messages", lambda m: len(m) == 1),
@@ -170,6 +178,7 @@ class ConductorCreateWorkspaceBlock(Block):
"deepLink": "conductor://m/1",
},
},
+ "_prompt_row": lambda *args, **kwargs: "row_1",
"_wait": lambda *args, **kwargs: {
"session_status": "idle",
"error_message": "",
@@ -199,6 +208,7 @@ class ConductorCreateWorkspaceBlock(Block):
"reply": "Done, the fix is on branch fix-login.",
"timed_out": False,
"truncated": False,
+ "prompt_row_id": "row_1",
},
},
)
@@ -208,6 +218,13 @@ class ConductorCreateWorkspaceBlock(Block):
) -> dict[str, Any]:
return await ConductorClient(credentials).create_workspace(payload)
+ async def _prompt_row(
+ self, credentials: APIKeyCredentials, session_id: str, message_id: str
+ ) -> str:
+ return await find_prompt_row(
+ ConductorClient(credentials), session_id, message_id, search_history=False
+ )
+
async def _wait(
self,
credentials: APIKeyCredentials,
@@ -271,7 +288,12 @@ class ConductorCreateWorkspaceBlock(Block):
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):
+ if not (session_id and message_id):
+ return
+ if not input_data.wait_for_reply:
+ yield "next_after", await prompt_cursor(
+ self._prompt_row(credentials, session_id, message_id), message_id
+ )
return
try:
waited = await self._wait(
@@ -287,6 +309,7 @@ class ConductorCreateWorkspaceBlock(Block):
block_name=self.name,
block_id=self.id,
) from e
+ yield "next_after", str(waited.get("prompt_row_id") or message_id)
yield "session_status", waited["session_status"]
yield "reply", waited["reply"]
yield "messages", waited["messages"]
diff --git a/autogpt_platform/backend/backend/blocks/conductor/get_session.py b/autogpt_platform/backend/backend/blocks/conductor/get_session.py
index 441d319da3..d85aca2ee8 100644
--- a/autogpt_platform/backend/backend/blocks/conductor/get_session.py
+++ b/autogpt_platform/backend/backend/blocks/conductor/get_session.py
@@ -16,8 +16,8 @@ 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
+from ._paging import fetch_tail
+from ._transcript import latest_reply, read_after
CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"
@@ -38,13 +38,17 @@ class ConductorGetSessionBlock(Block):
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",
+ description="Read forward from this message (exclusive) instead of "
+ "returning the most recent messages. Accepts a transcript row ID "
+ "(next_after from a previous call or from Send Message / Create "
+ "Session) or the prompt ID those blocks return as message_id / "
+ "initial_message_id, which is resolved to the prompt's row",
default="",
)
message_id: str = SchemaField(
- description="Also fetch this single message by ID", default=""
+ description="Also fetch this single message by its transcript row ID "
+ "(not a prompt ID returned by Send Message)",
+ default="",
)
class Output(BlockSchemaOutput):
@@ -67,8 +71,9 @@ class ConductorGetSessionBlock(Block):
"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"
+ description="Transcript row ID of the last returned message (or the "
+ "row `after` resolved to when nothing followed it); pass it as "
+ "after to read what follows"
)
message: dict = SchemaField(
description="The single message requested by message_id"
@@ -126,12 +131,13 @@ class ConductorGetSessionBlock(Block):
}
if input_data.message_limit > 0:
if input_data.after:
- rows, has_more = await fetch_after(
+ rows, has_more, cursor = await read_after(
client,
input_data.session_id,
input_data.after,
input_data.message_limit,
)
+ result["cursor"] = cursor
else:
rows, has_more = await fetch_tail(
client, input_data.session_id, input_data.message_limit
@@ -165,10 +171,9 @@ class ConductorGetSessionBlock(Block):
yield "messages", messages
yield "latest_reply", latest_reply(messages)
yield "has_more", bool(listing.get("hasMore", False))
+ cursor = str(data.get("cursor") or input_data.after)
yield "next_after", (
- str(messages[-1].get("id") or input_data.after)
- if messages
- else input_data.after
+ str(messages[-1].get("id") or cursor) if messages else cursor
)
if data.get("message"):
yield "message", data["message"]
diff --git a/autogpt_platform/backend/backend/blocks/conductor/send_message.py b/autogpt_platform/backend/backend/blocks/conductor/send_message.py
index 34d44e6e56..a63c2a5ff7 100644
--- a/autogpt_platform/backend/backend/blocks/conductor/send_message.py
+++ b/autogpt_platform/backend/backend/blocks/conductor/send_message.py
@@ -16,7 +16,7 @@ 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
+from ._transcript import find_prompt_row, prompt_cursor, wait_for_reply
CREDENTIALS_DESCRIPTION = "Conductor API key from app.conductor.build/users/api-keys"
@@ -52,6 +52,12 @@ class ConductorSendMessageBlock(Block):
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")
+ next_after: str = SchemaField(
+ description="Transcript row ID of the prompt's row; pass it as "
+ "`after` to Get Session to read the agent's turn. Falls back to "
+ "message_id while the prompt has no row yet, which Get Session "
+ "also accepts"
+ )
session_status: str = SchemaField(
description="idle, working or error once waiting finished"
)
@@ -87,6 +93,7 @@ class ConductorSendMessageBlock(Block):
("message_id", "msg_1"),
("state", "queued"),
("deep_link", "conductor://m/1"),
+ ("next_after", "row_1"),
("session_status", "idle"),
("reply", "All tests pass now."),
("messages", lambda m: len(m) == 1),
@@ -101,6 +108,7 @@ class ConductorSendMessageBlock(Block):
"deepLink": "conductor://m/1",
},
"_wait": lambda *args, **kwargs: WAIT_MOCK_REPLY,
+ "_prompt_row": lambda *args, **kwargs: "row_1",
},
)
@@ -109,6 +117,13 @@ class ConductorSendMessageBlock(Block):
) -> dict[str, Any]:
return await ConductorClient(credentials).send_message(session_id, message)
+ async def _prompt_row(
+ self, credentials: APIKeyCredentials, session_id: str, message_id: str
+ ) -> str:
+ return await find_prompt_row(
+ ConductorClient(credentials), session_id, message_id, search_history=False
+ )
+
async def _wait(
self,
credentials: APIKeyCredentials,
@@ -158,6 +173,10 @@ class ConductorSendMessageBlock(Block):
yield "deep_link", str(sent.get("deepLink") or "")
if not input_data.wait_for_reply:
+ yield "next_after", await prompt_cursor(
+ self._prompt_row(credentials, input_data.session_id, message_id),
+ message_id,
+ )
return
try:
waited = await self._wait(
@@ -173,6 +192,7 @@ class ConductorSendMessageBlock(Block):
block_name=self.name,
block_id=self.id,
) from e
+ yield "next_after", str(waited.get("prompt_row_id") or message_id)
yield "session_status", waited["session_status"]
yield "reply", waited["reply"]
yield "messages", waited["messages"]
diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_conductor.py b/autogpt_platform/backend/backend/blocks/conductor/test_conductor.py
index 197dfb3a9e..d6003230f8 100644
--- a/autogpt_platform/backend/backend/blocks/conductor/test_conductor.py
+++ b/autogpt_platform/backend/backend/blocks/conductor/test_conductor.py
@@ -165,6 +165,7 @@ async def test_send_message_without_waiting_returns_only_the_receipt():
"state": "sent",
"deepLink": "d",
},
+ "_prompt_row": lambda *a, **k: "row-m1",
"_wait": lambda *a, **k: pytest.fail("should not wait"),
},
)
@@ -177,7 +178,12 @@ async def test_send_message_without_waiting_returns_only_the_receipt():
"wait_for_reply": False,
},
)
- assert outputs == {"message_id": "m1", "state": "sent", "deep_link": "d"}
+ assert outputs == {
+ "message_id": "m1",
+ "state": "sent",
+ "deep_link": "d",
+ "next_after": "row-m1",
+ }
@pytest.mark.asyncio
diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_fixtures.py b/autogpt_platform/backend/backend/blocks/conductor/test_fixtures.py
index 92e1c1818f..18de746fff 100644
--- a/autogpt_platform/backend/backend/blocks/conductor/test_fixtures.py
+++ b/autogpt_platform/backend/backend/blocks/conductor/test_fixtures.py
@@ -5,7 +5,8 @@ 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.
+row ``id``, so the API rejects it as an ``after`` cursor; the blocks resolve
+it to the row themselves.
Named ``test_*`` so the block loader skips it; it defines no tests itself.
"""
@@ -19,7 +20,7 @@ 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.blocks.conductor._api import PAGE_SIZE, ConductorAPIError, ConductorClient
from backend.data.execution import ExecutionContext
from backend.sdk import APIKeyCredentials
@@ -211,9 +212,10 @@ class FakeTranscript:
if after:
index = next((i for i, r in enumerate(self.rows) if r["id"] == after), None)
if index is None:
- raise ValueError(
+ raise ConductorAPIError(
"Conductor API error (HTTP 404): Cursor message not found "
- "in this session"
+ "in this session",
+ 404,
)
start = index + 1
else:
diff --git a/autogpt_platform/backend/backend/blocks/conductor/test_session_cursor.py b/autogpt_platform/backend/backend/blocks/conductor/test_session_cursor.py
index d323649114..eb218b5c81 100644
--- a/autogpt_platform/backend/backend/blocks/conductor/test_session_cursor.py
+++ b/autogpt_platform/backend/backend/blocks/conductor/test_session_cursor.py
@@ -1,11 +1,150 @@
+"""Get Session `after` cursors and the `next_after` handed out by the
+prompt-sending blocks (SECRT-2789).
+
+The API's `after` is a transcript row id, while Send Message / Create
+Session / Create Workspace return the prompt's receipt id. The blocks bridge
+the two: senders resolve the prompt's row into `next_after`, and Get Session
+resolves a receipt passed as `after` instead of surfacing the API's 404.
+"""
+
+from typing import Any
+from unittest import mock
+
import pytest
+from backend.blocks.conductor._api import ConductorAPIError
+from backend.blocks.conductor._transcript import find_prompt_row, read_after
+from backend.blocks.conductor.create_session import ConductorCreateSessionBlock
+from backend.blocks.conductor.create_workspace import ConductorCreateWorkspaceBlock
from backend.blocks.conductor.get_session import ConductorGetSessionBlock
+from backend.blocks.conductor.send_message import ConductorSendMessageBlock
from backend.blocks.conductor.test_fixtures import (
+ CLAUDE_LIFECYCLE,
+ OLD_TURN,
+ RECEIPT,
+ TEST_CREDENTIALS,
TEST_CREDENTIALS_INPUT,
+ FakeTranscript,
+ agent_row,
+ claude_turn,
collect,
mock_block,
+ user_row,
+ wait_client,
)
+from backend.util.exceptions import BlockExecutionError
+
+PROMPT_ROW = "row-prompt"
+
+
+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.list_messages = transcript.list_messages
+ return client
+
+
+async def _get_session(transcript: FakeTranscript, **inputs: Any) -> dict:
+ block = ConductorGetSessionBlock()
+ with mock.patch(
+ "backend.blocks.conductor.get_session.ConductorClient",
+ return_value=_session_client(transcript),
+ ):
+ return await collect(
+ block,
+ {"credentials": TEST_CREDENTIALS_INPUT, "session_id": "s1", **inputs},
+ )
+
+
+# --- Get Session: `after` accepts either id ---------------------------------
+
+
+async def test_initial_message_id_works_as_the_after_cursor():
+ """The receipt from Create Session / Send Message, which the API rejects
+ with 404, reads the prompt's turn instead of failing."""
+ turn = claude_turn(RECEIPT, 0, "Done")
+ transcript = FakeTranscript([user_row(PROMPT_ROW, RECEIPT, 0), *turn])
+
+ outputs = await _get_session(transcript, after=RECEIPT, message_limit=20)
+
+ assert [m["id"] for m in outputs["messages"]] == [r["id"] for r in turn]
+ assert outputs["latest_reply"] == "Done"
+ assert outputs["has_more"] is False
+ assert outputs["next_after"] == "r-idle"
+ assert transcript.calls[0] == {"after": RECEIPT, "limit": 20, "offset": None}
+ assert transcript.calls[-1]["after"] == PROMPT_ROW
+
+
+async def test_after_receipt_with_no_reply_yet_returns_the_prompt_row_as_cursor():
+ """Nothing follows a queued prompt: no rows, no error, and `next_after`
+ is the resolved row id so the next poll pages directly."""
+ transcript = FakeTranscript(
+ [user_row("row-0", OLD_TURN, 0), user_row(PROMPT_ROW, RECEIPT, 1)]
+ )
+
+ outputs = await _get_session(transcript, after=RECEIPT)
+
+ assert outputs["messages"] == []
+ assert outputs["has_more"] is False
+ assert outputs["next_after"] == PROMPT_ROW
+
+
+async def test_after_receipt_is_found_beyond_the_newest_rows():
+ """The prompt sits 320 rows back: the same bounded history search as the
+ wait loop locates it."""
+ other = "22222222-0000-4000-8000-000000000000"
+ rows = [
+ user_row(PROMPT_ROW, RECEIPT, 0),
+ *claude_turn(RECEIPT, 0, "Ours"),
+ user_row("row-other", other, 11),
+ *[agent_row(f"life-{i}", other, 12 + i, CLAUDE_LIFECYCLE) for i in range(320)],
+ ]
+ transcript = FakeTranscript(rows)
+
+ outputs = await _get_session(transcript, after=RECEIPT, message_limit=3)
+
+ assert [m["id"] for m in outputs["messages"]] == ["r-sys", "r-life", "r-think"]
+ assert outputs["has_more"] is True
+ assert outputs["next_after"] == "r-think"
+
+
+async def test_a_row_id_cursor_is_paged_without_a_lookup():
+ rows = [user_row(PROMPT_ROW, RECEIPT, 0), *claude_turn(RECEIPT, 0, "Done")]
+ transcript = FakeTranscript(rows)
+
+ outputs = await _get_session(transcript, after=PROMPT_ROW, message_limit=2)
+
+ assert [m["id"] for m in outputs["messages"]] == ["r-sys", "r-life"]
+ assert transcript.calls == [{"after": PROMPT_ROW, "limit": 2, "offset": None}]
+
+
+async def test_an_unknown_cursor_names_both_id_spaces():
+ transcript = FakeTranscript([user_row(PROMPT_ROW, RECEIPT, 0)])
+
+ with pytest.raises(
+ BlockExecutionError, match="neither a transcript row ID.*prompt"
+ ):
+ await _get_session(transcript, after="not-an-id")
+
+
+async def test_non_404_errors_are_not_treated_as_a_receipt():
+ client = wait_client(FakeTranscript([]), [{"status": "idle"}])
+
+ async def boom(*args: Any, **kwargs: Any) -> dict[str, Any]:
+ raise ConductorAPIError("Conductor API error (HTTP 500)", 500)
+
+ client.list_messages = boom
+ with pytest.raises(ConductorAPIError, match="HTTP 500"):
+ await read_after(client, "s1", RECEIPT, 10)
@pytest.mark.asyncio
@@ -28,3 +167,181 @@ async def test_incremental_poll_preserves_cursor_without_a_new_row_id(messages:
assert result["messages"] == messages
assert result["next_after"] == "last-seen-row"
+
+
+# --- find_prompt_row ----------------------------------------------------------
+
+
+async def test_find_prompt_row_maps_a_receipt_to_its_row():
+ rows = [user_row("row-0", OLD_TURN, 0), user_row(PROMPT_ROW, RECEIPT, 1)]
+ client = wait_client(FakeTranscript(rows), [{"status": "idle"}])
+ assert await find_prompt_row(client, "s1", RECEIPT) == PROMPT_ROW
+ assert await find_prompt_row(client, "s1", "unknown") == ""
+
+
+async def test_find_prompt_row_without_history_reads_only_the_newest_rows():
+ rows = [
+ user_row(PROMPT_ROW, RECEIPT, 0),
+ *[
+ agent_row(f"life-{i}", OLD_TURN, 1 + i, CLAUDE_LIFECYCLE)
+ for i in range(320)
+ ],
+ ]
+ transcript = FakeTranscript(rows)
+ client = wait_client(transcript, [{"status": "idle"}])
+
+ assert await find_prompt_row(client, "s1", RECEIPT, search_history=False) == ""
+ # Only the tail is read: the first page, one-row probes for the end and
+ # the newest 300 rows; no older page is fetched.
+ assert all(
+ call["limit"] == 1 or call["offset"] == 0 or call["offset"] >= len(rows) - 300
+ for call in transcript.calls
+ if call["after"] == ""
+ )
+ shallow_calls = len(transcript.calls)
+ assert await find_prompt_row(client, "s1", RECEIPT) == PROMPT_ROW
+ assert len(transcript.calls) > shallow_calls + 1
+
+
+# --- senders hand out `next_after` --------------------------------------------
+
+
+def _sender(block, send_name: str, receipt: dict, prompt_row):
+ mock_block(
+ block,
+ {
+ send_name: lambda *a, **k: receipt,
+ "_prompt_row": prompt_row,
+ "_wait": lambda *a, **k: pytest.fail("should not wait"),
+ },
+ )
+ return block
+
+
+async def test_send_message_without_waiting_hands_out_the_prompt_row():
+ block = _sender(
+ ConductorSendMessageBlock(),
+ "_send",
+ {"messageId": RECEIPT, "state": "sent", "deepLink": "d"},
+ lambda *a, **k: PROMPT_ROW,
+ )
+ outputs = await collect(
+ block,
+ {
+ "credentials": TEST_CREDENTIALS_INPUT,
+ "session_id": "s1",
+ "message": "go",
+ "wait_for_reply": False,
+ },
+ )
+ assert outputs["message_id"] == RECEIPT
+ assert outputs["next_after"] == PROMPT_ROW
+
+
+ "prompt_row",
+ [lambda *a, **k: "", mock.Mock(side_effect=ValueError("HTTP 503"))],
+ ids=["not recorded yet", "lookup failed"],
+)
+async def test_create_session_falls_back_to_the_receipt_as_cursor(prompt_row):
+ """The prompt may still be queued when the block returns, and the session
+ was already created, so a missing or failed lookup is not an error: the
+ receipt is handed out instead and Get Session resolves it later."""
+ block = _sender(
+ ConductorCreateSessionBlock(),
+ "_create",
+ {
+ "id": "sess_1",
+ "deepLink": "conductor://s/1",
+ "initialMessage": {"messageId": RECEIPT, "state": "queued"},
+ },
+ prompt_row,
+ )
+ outputs = await collect(
+ block,
+ {
+ "credentials": TEST_CREDENTIALS_INPUT,
+ "workspace_id": "ws_1",
+ "message": "go",
+ "wait_for_reply": False,
+ },
+ )
+ assert outputs["initial_message_id"] == RECEIPT
+ assert outputs["next_after"] == RECEIPT
+
+
+async def test_create_session_without_a_prompt_has_no_cursor():
+ block = _sender(
+ ConductorCreateSessionBlock(),
+ "_create",
+ {"id": "sess_1", "deepLink": "conductor://s/1"},
+ lambda *a, **k: pytest.fail("nothing to resolve"),
+ )
+ outputs = await collect(
+ block, {"credentials": TEST_CREDENTIALS_INPUT, "workspace_id": "ws_1"}
+ )
+ assert outputs["initial_message_id"] == ""
+ assert "next_after" not in outputs
+
+
+async def test_create_workspace_waiting_reports_the_prompt_row_seen_by_the_wait():
+ block = ConductorCreateWorkspaceBlock()
+ mock_block(
+ block,
+ {
+ "_create": lambda *a, **k: {
+ "workspaceId": "ws_1",
+ "sessionId": "sess_1",
+ "deepLink": "d",
+ "initialMessage": {"messageId": RECEIPT, "state": "queued"},
+ },
+ "_prompt_row": lambda *a, **k: pytest.fail("the wait resolves it"),
+ "_wait": lambda *a, **k: {
+ "session_status": "idle",
+ "error_message": "",
+ "messages": [],
+ "reply": "",
+ "timed_out": False,
+ "truncated": False,
+ "prompt_row_id": PROMPT_ROW,
+ },
+ },
+ )
+ outputs = await collect(
+ block,
+ {
+ "credentials": TEST_CREDENTIALS_INPUT,
+ "project_id": "proj_1",
+ "message": "go",
+ "wait_for_reply": True,
+ },
+ )
+ assert outputs["next_after"] == PROMPT_ROW
+ assert outputs["session_status"] == "idle"
+
+
+async def test_sender_prompt_row_uses_a_shallow_lookup():
+ """Right after sending, the prompt is among the newest rows or not
+ recorded at all, so the senders never page into older history."""
+ rows = [
+ user_row("row-0", OLD_TURN, 0),
+ *[
+ agent_row(f"life-{i}", OLD_TURN, 1 + i, CLAUDE_LIFECYCLE)
+ for i in range(320)
+ ],
+ ]
+ transcript = FakeTranscript(rows)
+ block = ConductorSendMessageBlock()
+ with mock.patch(
+ "backend.blocks.conductor.send_message.ConductorClient",
+ return_value=wait_client(transcript, [{"status": "idle"}]),
+ ):
+ assert await block._prompt_row(TEST_CREDENTIALS, "s1", RECEIPT) == ""
+ assert len(transcript.calls) < 12
diff --git a/docs/integrations/block-integrations/conductor/create_session.md b/docs/integrations/block-integrations/conductor/create_session.md
index 67a0345b3b..13fb474514 100644
--- a/docs/integrations/block-integrations/conductor/create_session.md
+++ b/docs/integrations/block-integrations/conductor/create_session.md
@@ -10,7 +10,7 @@ Start a new agent session (chat) in an existing Conductor workspace, optionally
### 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).
+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 and `next_after` is the prompt's transcript row ID to pass as `after` to Get Session (the receipt itself while the prompt is still queued, which Get Session also accepts); 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
@@ -36,6 +36,7 @@ The block posts to `POST /v0/sessions` with `workspaceId`, `agent` and any non-b
| 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 |
+| next_after | Transcript row ID of the prompt's row; pass it as `after` to Get Session to read the agent's turn. Falls back to initial_message_id while the prompt has no row yet, which Get Session also accepts | 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]] |
diff --git a/docs/integrations/block-integrations/conductor/create_workspace.md b/docs/integrations/block-integrations/conductor/create_workspace.md
index b66b179517..a6a835bfde 100644
--- a/docs/integrations/block-integrations/conductor/create_workspace.md
+++ b/docs/integrations/block-integrations/conductor/create_workspace.md
@@ -10,7 +10,7 @@ Create a Conductor cloud workspace for a project or repository, optionally start
### 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).
+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, together with `next_after`: the prompt's transcript row ID to pass as `after` to Get Session (the receipt itself while the prompt has no row yet, which Get Session also accepts). 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
@@ -42,6 +42,7 @@ The block posts to `POST /v0/workspaces` with exactly one of `project_id` or `re
| 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 |
+| next_after | Transcript row ID of the prompt's row; pass it as `after` to Get Session to read the agent's turn. Falls back to initial_message_id while the prompt has no row yet, which Get Session also accepts | 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]] |
diff --git a/docs/integrations/block-integrations/conductor/get_session.md b/docs/integrations/block-integrations/conductor/get_session.md
index fe0a898239..8e207342db 100644
--- a/docs/integrations/block-integrations/conductor/get_session.md
+++ b/docs/integrations/block-integrations/conductor/get_session.md
@@ -10,7 +10,7 @@ Get a Conductor agent session: its details, whether the agent is idle, working o
### 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).
+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, which is how to poll incrementally (`next_after` is the row ID to pass on the next call). `after` takes a transcript row ID, such as `next_after` from Send Message, Create Session, Create Workspace or a previous Get Session call; the prompt ID those blocks return as `message_id` / `initial_message_id` is a different namespace that the API rejects with 404, so when it is passed the block locates the prompt's row itself (newest 300 rows, then up to 1000 older ones) and pages from there, reporting that row ID through `next_after` when nothing follows it yet. `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
@@ -19,8 +19,8 @@ The block calls `GET /v0/sessions/{id}` and `GET /v0/sessions/{id}/status`, then
|-------|-------------|------|----------|
| 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 |
+| after | Read forward from this message (exclusive) instead of returning the most recent messages. Accepts a transcript row ID (next_after from a previous call or from Send Message / Create Session) or the prompt ID those blocks return as message_id / initial_message_id, which is resolved to the prompt's row | str | No |
+| message_id | Also fetch this single message by its transcript row ID (not a prompt ID returned by Send Message) | str | No |
### Outputs
@@ -33,7 +33,7 @@ The block calls `GET /v0/sessions/{id}` and `GET /v0/sessions/{id}/status`, then
| 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 |
+| next_after | Transcript row ID of the last returned message (or the row `after` resolved to when nothing followed it); 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 |
diff --git a/docs/integrations/block-integrations/conductor/send_message.md b/docs/integrations/block-integrations/conductor/send_message.md
index 0f85a14a33..ef8cb612ae 100644
--- a/docs/integrations/block-integrations/conductor/send_message.md
+++ b/docs/integrations/block-integrations/conductor/send_message.md
@@ -10,7 +10,7 @@ Send a prompt to a Conductor agent session and, by default, wait for the agent t
### 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.
+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 its row ID, and the API only accepts row IDs as `after` cursors; 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`. Either way it returns the prompt row's ID as `next_after`, ready to pass to Get Session's `after` (without `wait_for_reply` it checks the newest rows once; while the prompt is still queued and has no row, `next_after` is the receipt itself, which Get Session also resolves). 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
@@ -31,6 +31,7 @@ The block posts `{message}` to `POST /v0/sessions/{id}/messages` and returns the
| message_id | ID of the sent prompt | str |
| state | queued or sent | str |
| deep_link | Link that opens the message | str |
+| next_after | Transcript row ID of the prompt's row; pass it as `after` to Get Session to read the agent's turn. Falls back to message_id while the prompt has no row yet, which Get Session also accepts | 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]] |