Skip to content

Arc

Arc is the Python client for Arc, the AI assistant built into the CX Agent Studio console. It drives an assistant session on an app the way the console does, over the public v1beta REST API: streamed turns (StreamChatAiAssistant), confirmation-card answers, clarification option panels, client-managed long-running operations (evaluation runs are polled and the session is resumed automatically), session CRUD and session artifacts.

Each turn returns a TurnStreamEvents aggregate that you can render as markdown or inspect field by field. Confirmation cards are answered by a ConfirmationPolicy (manual, click, mixed, scripted) or explicitly with send_confirmation_response. The cxas arc CLI (reference) is a thin wrapper around this class.

Quick Example

from cxas_scrapi.core.arc import Arc
from cxas_scrapi.utils.arc_confirmation_policy import make_policy

with Arc(app_name="projects/my-project/locations/us/apps/my-app") as arc:
    session_id = "arc-sdk-demo"

    # Ask a question; cards stay pending with the default manual policy.
    events = arc.chat(
        session_id, "What does this app do? Summarize its agents and tools."
    )
    print(events.format_markdown())

    # Build something, clicking through confirmation cards while declining destructive tools.
    events = arc.chat(
        session_id,
        "Add a guardrail that blocks requests for medical advice.",
        confirmation_policy=make_policy("click", deny_tools=("*delete*",)),
        timeout_seconds=1800,
    )
    print(events.text)
    for action in events.confirmation_actions:
        print(action.tool, action.action, "typed" if action.typed else "clicked")

    # Anything still waiting for a human decision?
    for card in events.pending_confirmation_requests:
        print(card.confirmation_id, card.tool, card.context)
        # e.g. arc.send_confirmation_response(session_id, card.confirmation_id, confirmed=True)

    # Artifacts recorded on the session (gcsUri pointers), e.g. an exported bundle.
    for artifact in arc.session_artifacts(session_id):
        print(artifact.get("displayName"), artifact.get("gcsUri"))

Errors surface as ArcApiError (HTTP status and decoded message), ArcStreamTimeout (idle stream or turn deadline; .partial holds what streamed so far), or ArcStreamInterrupted (connection lost after exhausting re-attach attempts; .partial holds what streamed so far).

Reference

arc

Client for the CX Agent Studio AI assistant (Arc).

Arc is the conversational builder assistant embedded in the CX Agent Studio console. This module drives it the way the console does, over the public v1beta REST API:

  • SessionService.StreamChatAiAssistant (server streaming) for turns, confirmation-card answers and client-managed LRO resumption;
  • SessionService.CancelAssistantTurn / GenerateOnboardingSuggestions;
  • AssistantService session CRUD (assistantSessions);
  • google.longrunning.Operations and EvaluationRuns for LRO polling.

Example::

from cxas_scrapi.core.arc import Arc

arc = Arc(app_name="projects/my-proj/locations/us/apps/my-app")
events = arc.chat("arc-cli-demo", "What does this app do?")
print(events.format_markdown())

Arc

Arc(app_name, *, client_profile=CLIENT_PROFILE_CONSOLE, api_endpoint=None, stream_idle_timeout=CONSOLE_STREAM_IDLE_TIMEOUT_SECONDS, max_reattach_attempts=2, rate_limiter=None, http_session=None, progress=None, **kwargs)

Bases: Common

Drives an assistant session on a CX Agent Studio app.

Parameters:

Name Type Description Default
app_name str

Full app resource name (projects/{p}/locations/{l}/apps/{a}).

required
client_profile str

console (default) sends the capabilities the console sends, so gated tools pause on confirmation cards; legacy omits CONFIRMATION_CARDS and the server auto-denies gated tools.

CLIENT_PROFILE_CONSOLE
api_endpoint str | None

API host; defaults to CES_API_ENDPOINT or prod.

None
stream_idle_timeout float

Seconds without any streamed event before the turn is abandoned client-side.

CONSOLE_STREAM_IDLE_TIMEOUT_SECONDS
max_reattach_attempts int

How many times a dropped connection is re-attached (attachOnly + resumeFromSequenceNumber) while the turn is still running server-side.

2
rate_limiter RateLimiter | None

Optional :class:RateLimiter applied before each streaming request.

None
http_session Session | None

Optional requests.Session (tests inject fakes).

None
progress Callable[[str], None] | None

Optional callback for short progress messages.

None
**kwargs Any

Forwarded to :class:Common (credentials, scopes, ...).

{}
Source code in src/cxas_scrapi/core/arc.py
def __init__(
    self,
    app_name: str,
    *,
    client_profile: str = CLIENT_PROFILE_CONSOLE,
    api_endpoint: str | None = None,
    stream_idle_timeout: float = CONSOLE_STREAM_IDLE_TIMEOUT_SECONDS,
    max_reattach_attempts: int = 2,
    rate_limiter: RateLimiter | None = None,
    http_session: requests.Session | None = None,
    progress: Callable[[str], None] | None = None,
    **kwargs: Any,
) -> None:
    kwargs.setdefault("user_agent_extension", "arc")
    super().__init__(app_name=app_name, **kwargs)
    if client_profile not in (
        CLIENT_PROFILE_CONSOLE,
        CLIENT_PROFILE_LEGACY,
    ):
        raise ValueError(
            f"client_profile must be '{CLIENT_PROFILE_CONSOLE}' or "
            f"'{CLIENT_PROFILE_LEGACY}', got {client_profile!r}"
        )
    self.client_profile = client_profile
    self.api_endpoint = normalize_api_endpoint(api_endpoint)
    self._base_url = f"https://{self.api_endpoint}/{API_VERSION}"
    self.stream_idle_timeout = stream_idle_timeout
    self.max_reattach_attempts = max(0, int(max_reattach_attempts))
    self.rate_limiter = rate_limiter
    self._progress_cb = progress
    self._owns_sessions = http_session is None
    self.session = http_session or _retrying_session()
    # Streams must not be retried by the adapter; use a plain session.
    self._stream_session = http_session or requests.Session()
    self.last_stream_events: TurnStreamEvents | None = None
    self._active_turn_events: TurnStreamEvents | None = None
    if self.api_endpoint != PROD_API_ENDPOINT:
        self._progress(
            f"using non-default API endpoint: {self.api_endpoint}"
        )

active_turn_events property

active_turn_events

Events of the turn currently in flight (for partial rendering).

close

close()

Closes HTTP sessions owned by this client.

Source code in src/cxas_scrapi/core/arc.py
def close(self) -> None:
    """Closes HTTP sessions owned by this client."""
    if self._owns_sessions:
        self.session.close()
        if self._stream_session is not self.session:
            self._stream_session.close()

session_name

session_name(session_id)

Returns the full assistantSessions resource name.

Source code in src/cxas_scrapi/core/arc.py
def session_name(self, session_id: str) -> str:
    """Returns the full ``assistantSessions`` resource name."""
    raw = session_id.strip()
    if "assistantSessions/" in raw:
        prefix, _ = raw.split("assistantSessions/", 1)
        prefix = prefix.rstrip("/")
        if prefix:
            own = _APP_PREFIX_RE.match(self.app_name)
            got = _APP_PREFIX_RE.match(prefix)
            if got is None or (
                own is not None and got.groups() != own.groups()
            ):
                raise ValueError(
                    f"Session {session_id!r} does not belong to "
                    f"{self.app_name!r}."
                )
    short = urllib.parse.quote(session_short_id(raw), safe="")
    return f"{self.app_name}/assistantSessions/{short}"

list_sessions

list_sessions(page_size=20, filter_='')

Lists assistant sessions on the app (first page_size only).

Source code in src/cxas_scrapi/core/arc.py
def list_sessions(
    self, page_size: int = 20, filter_: str = ""
) -> list[dict[str, Any]]:
    """Lists assistant sessions on the app (first ``page_size`` only)."""
    params: dict[str, Any] = {"pageSize": page_size}
    if filter_:
        params["filter"] = filter_
    data = self._request(
        "GET", f"{self.app_name}/assistantSessions", params=params
    )
    return list(data.get("assistantSessions", []))

get_session

get_session(session_id)

Gets an assistant session (messages, artifacts, active turn).

Source code in src/cxas_scrapi/core/arc.py
def get_session(self, session_id: str) -> dict[str, Any]:
    """Gets an assistant session (messages, artifacts, active turn)."""
    return self._request("GET", self.session_name(session_id))

create_session

create_session(session_id)

Explicitly creates an assistant session (streams create lazily).

Source code in src/cxas_scrapi/core/arc.py
def create_session(self, session_id: str) -> dict[str, Any]:
    """Explicitly creates an assistant session (streams create lazily)."""
    short = session_short_id(session_id)
    return self._request(
        "POST",
        f"{self.app_name}/assistantSessions",
        params={"assistantSessionId": short},
        data={"assistantSessionId": short},
    )

delete_session

delete_session(session_id)

Deletes an assistant session.

Source code in src/cxas_scrapi/core/arc.py
def delete_session(self, session_id: str) -> None:
    """Deletes an assistant session."""
    self._request("DELETE", self.session_name(session_id))

cancel_turn

cancel_turn(session_id, turn_id='')

Cancels the in-flight turn of a session.

Source code in src/cxas_scrapi/core/arc.py
def cancel_turn(self, session_id: str, turn_id: str = "") -> dict[str, Any]:
    """Cancels the in-flight turn of a session."""
    body: dict[str, Any] = {}
    if turn_id:
        body["turnId"] = turn_id
    return self._request(
        "POST",
        f"{self.session_name(session_id)}:cancelAssistantTurn",
        data=body,
    )

generate_onboarding_suggestions

generate_onboarding_suggestions()

Returns starter suggestions the console shows on an empty session.

Source code in src/cxas_scrapi/core/arc.py
def generate_onboarding_suggestions(self) -> list[dict[str, Any]]:
    """Returns starter suggestions the console shows on an empty session."""
    data = self._request(
        "POST", f"{self.app_name}:generateOnboardingSuggestions", data={}
    )
    return list(data.get("suggestions", []))

session_artifacts

session_artifacts(session_id)

Artifacts (gcsUri pointers) recorded on the session.

Source code in src/cxas_scrapi/core/arc.py
def session_artifacts(self, session_id: str) -> list[dict[str, Any]]:
    """Artifacts (``gcsUri`` pointers) recorded on the session."""
    return list(self.get_session(session_id).get("artifacts", []))

get_operation

get_operation(name)

Gets a long-running operation by resource name.

Source code in src/cxas_scrapi/core/arc.py
def get_operation(self, name: str) -> dict[str, Any]:
    """Gets a long-running operation by resource name."""
    return self._request("GET", name)

get_evaluation_run

get_evaluation_run(name)

Gets an evaluation run by resource name.

Source code in src/cxas_scrapi/core/arc.py
def get_evaluation_run(self, name: str) -> dict[str, Any]:
    """Gets an evaluation run by resource name."""
    return self._request("GET", name)

list_evaluation_runs

list_evaluation_runs(page_size=10)

Lists the most recent evaluation runs on the app.

Source code in src/cxas_scrapi/core/arc.py
def list_evaluation_runs(self, page_size: int = 10) -> list[dict[str, Any]]:
    """Lists the most recent evaluation runs on the app."""
    data = self._request(
        "GET",
        f"{self.app_name}/evaluationRuns",
        params={"pageSize": page_size},
    )
    return list(data.get("evaluationRuns", []))

stream_turn

stream_turn(session_id, message='', *, attached_gcs_uris=(), confirmation_response=None, operation_completed_event=None, resume_from_sequence_number=None, enable_confirmation_cards=None, enable_client_managed_lro=True, timeout_seconds=1800, on_event=None, into=None)

Sends one StreamChatAiAssistant request and consumes the stream.

This is the low-level primitive: no confirmation policy and no LRO resumption. See :meth:chat for the console-equivalent turn loop.

Parameters:

Name Type Description Default
session_id str

Short id or full session name.

required
message str

User text (may be empty for a pure card click).

''
attached_gcs_uris Sequence[str]

gs:// URIs attached to the turn.

()
confirmation_response dict[str, Any] | None

{"confirmationId": ..., "confirmed": bool} or {"confirmationId": ..., "answerText": str}.

None
operation_completed_event dict[str, Any] | None

Client-managed LRO completion event.

None
resume_from_sequence_number int | None

Replay from this sequence number.

None
enable_confirmation_cards bool | None

Override the profile's card setting.

None
enable_client_managed_lro bool

Advertise CLIENT_MANAGED_LRO.

True
timeout_seconds float

Overall deadline for this stream.

1800
on_event Callable[[dict[str, Any]], None] | None

Callback for every raw JSON event.

None
into TurnStreamEvents | None

Merge the sub-stream into this aggregate instead of a new one.

None

Returns:

Type Description
TurnStreamEvents

The events of this stream (into when provided).

Source code in src/cxas_scrapi/core/arc.py
def stream_turn(
    self,
    session_id: str,
    message: str = "",
    *,
    attached_gcs_uris: Sequence[str] = (),
    confirmation_response: dict[str, Any] | None = None,
    operation_completed_event: dict[str, Any] | None = None,
    resume_from_sequence_number: int | None = None,
    enable_confirmation_cards: bool | None = None,
    enable_client_managed_lro: bool = True,
    timeout_seconds: float = 1800,
    on_event: Callable[[dict[str, Any]], None] | None = None,
    into: TurnStreamEvents | None = None,
) -> TurnStreamEvents:
    """Sends one ``StreamChatAiAssistant`` request and consumes the stream.

    This is the low-level primitive: no confirmation policy and no LRO
    resumption. See :meth:`chat` for the console-equivalent turn loop.

    Args:
        session_id: Short id or full session name.
        message: User text (may be empty for a pure card click).
        attached_gcs_uris: ``gs://`` URIs attached to the turn.
        confirmation_response: ``{"confirmationId": ..., "confirmed":
            bool}`` or ``{"confirmationId": ..., "answerText": str}``.
        operation_completed_event: Client-managed LRO completion event.
        resume_from_sequence_number: Replay from this sequence number.
        enable_confirmation_cards: Override the profile's card setting.
        enable_client_managed_lro: Advertise ``CLIENT_MANAGED_LRO``.
        timeout_seconds: Overall deadline for this stream.
        on_event: Callback for every raw JSON event.
        into: Merge the sub-stream into this aggregate instead of a new one.

    Returns:
        The events of this stream (``into`` when provided).
    """
    body: dict[str, Any] = {
        "message": message or "",
        "clientCapabilities": self._capabilities(
            enable_confirmation_cards,
            enable_client_managed_lro=enable_client_managed_lro,
        ),
    }
    if attached_gcs_uris:
        body["attachedGcsUris"] = list(attached_gcs_uris)
    if confirmation_response:
        body["confirmationResponse"] = confirmation_response
    if operation_completed_event:
        body["operationCompletedEvent"] = operation_completed_event
    if resume_from_sequence_number is not None:
        body["resumeFromSequenceNumber"] = str(resume_from_sequence_number)

    if self.rate_limiter is not None:
        self.rate_limiter.wait_and_consume()

    url = (
        f"{self._base_url}/{self.session_name(session_id)}"
        ":streamChatAiAssistant"
    )
    reducer = TurnStreamReducer(on_progress=self._progress)
    target = into if into is not None else TurnStreamEvents()
    deadline = time.monotonic() + timeout_seconds
    count = 0
    request_body = body
    reattached = 0
    handoffs = 0
    merged = False

    def _merge_once() -> None:
        nonlocal merged
        if not merged:
            target.merge(reducer.events)
            merged = True

    try:
        while True:
            seq_before = reducer.events.last_sequence_number
            reducer.events.handoff = None
            try:
                with self._stream_session.post(
                    url,
                    params={"alt": "sse"},
                    headers=self._headers(),
                    json=request_body,
                    stream=True,
                    timeout=(30, self.stream_idle_timeout),
                ) as response:
                    if response.status_code >= 400:
                        raise self._error_from_response(response)
                    for obj in iter_stream_json(response):
                        count += 1
                        reducer.feed(obj)
                        if on_event is not None:
                            on_event(obj)
                        if time.monotonic() > deadline:
                            _merge_once()
                            raise ArcStreamTimeout(
                                f"Turn exceeded {timeout_seconds:.0f}s "
                                f"deadline after {count} events.",
                                target,
                            )
                if reducer.events.turn_completed is not None:
                    break
                seq = reducer.events.last_sequence_number
                if (
                    reducer.events.handoff is not None
                    and handoffs < _MAX_HANDOFF_RECONNECTS
                ):
                    handoffs += 1
                    resume_seq = seq if seq is not None else 0
                    request_body = {
                        "attachOnly": True,
                        "resumeFromSequenceNumber": str(resume_seq),
                        "clientCapabilities": body["clientCapabilities"],
                    }
                    continue
                if seq is not None:
                    if seq_before is not None and seq > seq_before:
                        reattached = 0
                    if reattached < self.max_reattach_attempts:
                        reattached += 1
                        self._progress(
                            "stream closed before turnCompleted after "
                            f"{count} events; re-attaching from sequence "
                            f"{seq} (attempt {reattached})"
                        )
                        time.sleep(min(2 * reattached, 5))
                        request_body = {
                            "attachOnly": True,
                            "resumeFromSequenceNumber": str(seq),
                            "clientCapabilities": (
                                body["clientCapabilities"]
                            ),
                        }
                        continue
                    _merge_once()
                    raise ArcStreamInterrupted(
                        "Stream closed before turnCompleted after "
                        f"{count} events (last sequence {seq}).",
                        target,
                    )
                break
            except (
                requests.exceptions.ReadTimeout,
                requests.exceptions.ConnectionError,
                requests.exceptions.ChunkedEncodingError,
            ) as e:
                if reducer.events.turn_completed is not None:
                    break
                # requests surfaces a read timeout that happens *while
                # iterating* the body as ConnectionError(ReadTimeoutError).
                if _is_read_timeout(e):
                    _merge_once()
                    raise ArcStreamTimeout(
                        f"Stream idle for {self.stream_idle_timeout:.0f}s "
                        f"after {count} events.",
                        target,
                    ) from e
                seq = reducer.events.last_sequence_number
                if (
                    seq_before is not None
                    and seq is not None
                    and seq > seq_before
                ):
                    reattached = 0
                if (
                    seq is not None
                    and reattached < self.max_reattach_attempts
                ):
                    # The turn keeps running server-side; re-attach and
                    # replay from the last sequence number we saw.
                    reattached += 1
                    self._progress(
                        f"stream dropped after {count} events; "
                        f"re-attaching from sequence {seq} "
                        f"(attempt {reattached})"
                    )
                    time.sleep(min(2 * reattached, 5))
                    request_body = {
                        "attachOnly": True,
                        "resumeFromSequenceNumber": str(seq),
                        "clientCapabilities": body["clientCapabilities"],
                    }
                    continue
                _merge_once()
                raise ArcStreamInterrupted(
                    f"Stream interrupted after {count} events: {e}", target
                ) from e
    finally:
        _merge_once()
    return target

chat

chat(session_id, message, *, attached_gcs_uris=(), confirmation_policy=None, max_confirmation_rounds=5, enable_confirmation_cards=None, timeout_seconds=1800, auto_resolve_lro=True, lro_timeout_seconds=1800, lro_poll_interval_seconds=5, max_lro_iterations=10)

Sends a user message and runs the console-equivalent turn loop.

Pending LROs are polled and resumed (auto_resolve_lro) and confirmation cards are answered by confirmation_policy (none or a ManualPolicy leaves them pending for the caller).

Source code in src/cxas_scrapi/core/arc.py
def chat(
    self,
    session_id: str,
    message: str,
    *,
    attached_gcs_uris: Sequence[str] = (),
    confirmation_policy: ConfirmationPolicy | None = None,
    max_confirmation_rounds: int = 5,
    enable_confirmation_cards: bool | None = None,
    timeout_seconds: float = 1800,
    auto_resolve_lro: bool = True,
    lro_timeout_seconds: float = 1800,
    lro_poll_interval_seconds: float = 5,
    max_lro_iterations: int = 10,
) -> TurnStreamEvents:
    """Sends a user message and runs the console-equivalent turn loop.

    Pending LROs are polled and resumed (``auto_resolve_lro``) and
    confirmation cards are answered by ``confirmation_policy`` (none or a
    ``ManualPolicy`` leaves them pending for the caller).
    """
    return self._run_turn(
        session_id,
        message=message,
        attached_gcs_uris=attached_gcs_uris,
        enable_confirmation_cards=enable_confirmation_cards,
        confirmation_policy=confirmation_policy,
        max_confirmation_rounds=max_confirmation_rounds,
        timeout_seconds=timeout_seconds,
        auto_resolve_lro=auto_resolve_lro,
        lro_timeout_seconds=lro_timeout_seconds,
        lro_poll_interval_seconds=lro_poll_interval_seconds,
        max_lro_iterations=max_lro_iterations,
    )

send_confirmation_response

send_confirmation_response(session_id, confirmation_id, *, confirmed=None, answer_text=None, tool='', confirmation_policy=None, max_confirmation_rounds=5, timeout_seconds=1800, auto_resolve_lro=True, lro_timeout_seconds=1800, lro_poll_interval_seconds=5, max_lro_iterations=10)

Answers a confirmation card the way a console click does.

Source code in src/cxas_scrapi/core/arc.py
def send_confirmation_response(
    self,
    session_id: str,
    confirmation_id: str,
    *,
    confirmed: bool | None = None,
    answer_text: str | None = None,
    tool: str = "",
    confirmation_policy: ConfirmationPolicy | None = None,
    max_confirmation_rounds: int = 5,
    timeout_seconds: float = 1800,
    auto_resolve_lro: bool = True,
    lro_timeout_seconds: float = 1800,
    lro_poll_interval_seconds: float = 5,
    max_lro_iterations: int = 10,
) -> TurnStreamEvents:
    """Answers a confirmation card the way a console click does."""
    if (confirmed is None) == (answer_text is None):
        raise ValueError("Pass exactly one of confirmed or answer_text.")
    response: dict[str, Any] = {"confirmationId": confirmation_id}
    if confirmed is not None:
        response["confirmed"] = bool(confirmed)
        action = "CLICK_CONFIRM" if confirmed else "CLICK_DENY"
        text = ""
    else:
        response["answerText"] = answer_text or ""
        action = "CLICK_ANSWER"
        text = answer_text or ""
    explicit = ConfirmationActionRecord(
        confirmation_id=confirmation_id,
        tool=tool,
        action=action,
        text=text,
        typed=False,
        policy="manual",
        round=0,
        reason="explicit call",
    )
    return self._run_turn(
        session_id,
        confirmation_response=response,
        explicit_action=explicit,
        enable_confirmation_cards=True,
        confirmation_policy=confirmation_policy,
        max_confirmation_rounds=max_confirmation_rounds,
        timeout_seconds=timeout_seconds,
        auto_resolve_lro=auto_resolve_lro,
        lro_timeout_seconds=lro_timeout_seconds,
        lro_poll_interval_seconds=lro_poll_interval_seconds,
        max_lro_iterations=max_lro_iterations,
    )

poll_evaluation_run

poll_evaluation_run(run_name, *, timeout_seconds=1800, poll_interval_seconds=5)

Polls an evaluation run until it reaches a terminal state.

Source code in src/cxas_scrapi/core/arc.py
def poll_evaluation_run(
    self,
    run_name: str,
    *,
    timeout_seconds: float = 1800,
    poll_interval_seconds: float = 5,
) -> dict[str, Any]:
    """Polls an evaluation run until it reaches a terminal state."""
    deadline = time.monotonic() + timeout_seconds
    last: dict[str, Any] = {}
    while True:
        last = self.get_evaluation_run(run_name)
        state = str(last.get("state", ""))
        progress = last.get("progress") or {}
        total = int(progress.get("totalCount", 0) or 0)
        failed = int(progress.get("failedCount", 0) or 0)
        errored = int(progress.get("errorCount", 0) or 0)
        cancelled = int(progress.get("cancelledCount", 0) or 0)
        passed = int(progress.get("passedCount", 0) or 0)
        completed = int(progress.get("completedCount", 0) or 0)
        if not passed and completed:
            passed = max(completed - failed - errored - cancelled, 0)
        extra = (f", errored {errored}" if errored else "") + (
            f", cancelled {cancelled}" if cancelled else ""
        )
        self._progress(
            f"evaluation run {state or 'RUNNING'}: {completed}/{total} "
            f"(failed {failed}{extra})"
        )
        if state in _TERMINAL_RUN_STATES:
            pass_rate = round(100.0 * passed / total, 1) if total else 0.0
            result: dict[str, Any] = {
                "status": "SUCCEEDED" if state == "COMPLETED" else state,
                "state": state,
                "evaluation_run": last.get("name", run_name),
                "pass_rate": pass_rate,
                "passed_count": passed,
                "failed_count": failed,
                "total_count": total,
            }
            if errored:
                result["error_count"] = errored
            if cancelled:
                result["cancelled_count"] = cancelled
            run_error = last.get("error")
            if run_error:
                result["error"] = (
                    run_error.get("message", str(run_error))
                    if isinstance(run_error, dict)
                    else str(run_error)
                )
            return result
        now = time.monotonic()
        if now > deadline:
            return {
                "status": "TIMEOUT",
                "state": state,
                "evaluation_run": run_name,
                "error": (
                    f"evaluation run not finished after {timeout_seconds}s"
                ),
            }
        time.sleep(min(poll_interval_seconds, max(deadline - now, 0.0)))

poll_operation

poll_operation(operation_name, *, timeout_seconds=1800, poll_interval_seconds=5)

Polls an operation; delegates to the evaluation run when present.

Source code in src/cxas_scrapi/core/arc.py
def poll_operation(
    self,
    operation_name: str,
    *,
    timeout_seconds: float = 1800,
    poll_interval_seconds: float = 5,
) -> dict[str, Any]:
    """Polls an operation; delegates to the evaluation run when present."""
    deadline = time.monotonic() + timeout_seconds
    while True:
        op = self.get_operation(operation_name)
        if op.get("done") and op.get("error"):
            error = op["error"]
            return {
                "status": "FAILED",
                "error": (
                    error.get("message", str(error))
                    if isinstance(error, dict)
                    else str(error)
                ),
            }
        metadata = op.get("metadata") or {}
        response = op.get("response") or {}
        run_ref = metadata.get("evaluationRun") or response.get(
            "evaluationRun"
        )
        run_name = (
            run_ref.get("name") if isinstance(run_ref, dict) else run_ref
        )
        if run_name:
            remaining = max(deadline - time.monotonic(), 0.0)
            return self.poll_evaluation_run(
                str(run_name),
                timeout_seconds=remaining,
                poll_interval_seconds=poll_interval_seconds,
            )
        if op.get("done"):
            return {"status": "SUCCEEDED", "response": response}
        now = time.monotonic()
        if now > deadline:
            return {
                "status": "TIMEOUT",
                "error": f"operation not done after {timeout_seconds}s",
            }
        self._progress(
            f"operation running: {operation_name.rsplit('/', 1)[-1]}"
        )
        time.sleep(min(poll_interval_seconds, max(deadline - now, 0.0)))

poll_detached_job

poll_detached_job(session_id, job_id, *, timeout_seconds=1800, poll_interval_seconds=5)

Polls the session for a detached assistant job's terminal status.

Source code in src/cxas_scrapi/core/arc.py
def poll_detached_job(
    self,
    session_id: str,
    job_id: str,
    *,
    timeout_seconds: float = 1800,
    poll_interval_seconds: float = 5,
) -> dict[str, Any]:
    """Polls the session for a detached assistant job's terminal status."""
    deadline = time.monotonic() + timeout_seconds
    while True:
        session = self.get_session(session_id)
        for status in _detached_job_statuses(session):
            if status.get("job_id") != job_id:
                continue
            state = str(status.get("status", "")).upper()
            if state in (
                "COMPLETED",
                "SUCCEEDED",
                "FAILED",
                "ERROR",
                "CANCELLED",
            ):
                return {
                    "status": "SUCCEEDED"
                    if state in ("COMPLETED", "SUCCEEDED")
                    else state,
                    "memo_path": status.get("memo_path", ""),
                }
        now = time.monotonic()
        if now > deadline:
            return {
                "status": "TIMEOUT",
                "error": "detached job not finished",
            }
        self._progress(f"detached job running: {job_id}")
        time.sleep(min(poll_interval_seconds, max(deadline - now, 0.0)))

ArcError

Bases: RuntimeError

Base error for Arc client failures.

ArcApiError

ArcApiError(status_code, message, body=None)

Bases: ArcError

An HTTP error returned by the API, with the decoded status if any.

Source code in src/cxas_scrapi/core/arc.py
def __init__(self, status_code: int, message: str, body: Any = None):
    super().__init__(f"HTTP {status_code}: {message}")
    self.status_code = status_code
    self.message = message
    self.body = body

ArcStreamTimeout

ArcStreamTimeout(message, partial)

Bases: ArcError

The stream went idle or the turn exceeded its deadline.

Source code in src/cxas_scrapi/core/arc.py
def __init__(self, message: str, partial: TurnStreamEvents):
    super().__init__(message)
    self.partial = partial

ArcStreamInterrupted

ArcStreamInterrupted(message, partial)

Bases: ArcError

The connection dropped mid-stream and could not be re-attached.

Source code in src/cxas_scrapi/core/arc.py
def __init__(self, message: str, partial: TurnStreamEvents):
    super().__init__(message)
    self.partial = partial

iter_stream_json

iter_stream_json(response)

Yields JSON objects from a streaming REST response.

Handles both ?alt=sse (data: {...} lines) and the default One Platform JSON-array framing ([{...},{...}]).

Source code in src/cxas_scrapi/core/arc.py
def iter_stream_json(response: requests.Response) -> Iterator[dict[str, Any]]:
    """Yields JSON objects from a streaming REST response.

    Handles both ``?alt=sse`` (``data: {...}`` lines) and the default
    One Platform JSON-array framing (``[{...},{...}]``).
    """
    content_type = (
        response.headers.get("content-type")
        or response.headers.get("Content-Type")
        or ""
    ).lower()
    if "text/event-stream" in content_type:
        for raw in response.iter_lines(decode_unicode=False):
            if not raw or not raw.startswith(b"data:"):
                continue
            payload = raw[5:].strip()
            if not payload:
                continue
            yield json.loads(payload.decode("utf-8"))
        return

    decoder = json.JSONDecoder()
    # Chunks may split a multi-byte UTF-8 sequence; decode incrementally.
    utf8 = codecs.getincrementaldecoder("utf-8")()
    buffer = ""
    started = False
    for chunk in response.iter_content(chunk_size=8192, decode_unicode=False):
        if not chunk:
            continue
        buffer += utf8.decode(chunk)
        while True:
            buffer = buffer.lstrip()
            if not started:
                if not buffer:
                    break
                if buffer[0] == "[":
                    buffer = buffer[1:]
                started = True
                continue
            if buffer[:1] in (",", "]"):
                buffer = buffer[1:]
                continue
            if not buffer:
                break
            try:
                obj, end = decoder.raw_decode(buffer)
            except ValueError:
                break  # need more bytes
            buffer = buffer[end:]
            if isinstance(obj, dict):
                yield obj
    rest = buffer.strip().strip("],").strip()
    if rest:
        obj = json.loads(rest)
        if isinstance(obj, dict):
            yield obj

TurnStreamEvents dataclass

TurnStreamEvents(text='', thoughts=list(), statuses=list(), errors=list(), tool_calls=list(), tool_responses=list(), artifacts=list(), option_questions=list(), confirmation_requests=list(), confirmation_actions=list(), contract_metadata=None, initiated_lros=list(), handoff=None, turn_completed=None, last_sequence_number=None)

Aggregates all structured events emitted during an assistant turn.

pending_confirmation_requests property

pending_confirmation_requests

Cards raised in this turn that the client has not answered yet.

pending_option_questions property

pending_option_questions

Standalone option questions not owned by a confirmation card.

merge

merge(other)

Merges events from a subsequent stream (e.g. LRO resumption).

Source code in src/cxas_scrapi/utils/arc_events.py
def merge(self, other: TurnStreamEvents) -> None:
    """Merges events from a subsequent stream (e.g. LRO resumption)."""
    if other.text:
        self.text = (
            f"{self.text}\n\n{other.text}" if self.text else other.text
        )
    self.thoughts.extend(other.thoughts)
    self.statuses.extend(other.statuses)
    self.errors.extend(other.errors)
    self.tool_calls.extend(other.tool_calls)
    self.tool_responses.extend(other.tool_responses)
    for art in other.artifacts:
        existing = next(
            (
                a
                for a in self.artifacts
                if a.artifact_id and a.artifact_id == art.artifact_id
            ),
            None,
        )
        if existing is None:
            self.artifacts.append(dataclasses.replace(art))
            continue
        for field in (
            "display_name",
            "mime_type",
            "content",
            "gcs_uri",
            "state",
        ):
            value = getattr(art, field)
            if value:
                setattr(existing, field, value)
    self.option_questions.extend(other.option_questions)
    self.confirmation_requests.extend(other.confirmation_requests)
    self.confirmation_actions.extend(other.confirmation_actions)
    if other.contract_metadata is not None:
        self.contract_metadata = other.contract_metadata
    for lro in other.initiated_lros:
        if lro not in self.initiated_lros:
            self.initiated_lros.append(lro)
    if other.handoff is not None:
        self.handoff = other.handoff
    if other.turn_completed is not None:
        self.turn_completed = other.turn_completed
    if other.last_sequence_number is not None:
        self.last_sequence_number = other.last_sequence_number

to_dict

to_dict()

Serializes the turn events to a JSON-compatible dictionary.

Source code in src/cxas_scrapi/utils/arc_events.py
def to_dict(self) -> dict[str, Any]:
    """Serializes the turn events to a JSON-compatible dictionary."""
    return dataclasses.asdict(self)

format_markdown

format_markdown(include_thoughts=False, include_tools=True)

Renders the turn as markdown sections, mirroring the console.

Source code in src/cxas_scrapi/utils/arc_events.py
def format_markdown(
    self, include_thoughts: bool = False, include_tools: bool = True
) -> str:
    """Renders the turn as markdown sections, mirroring the console."""
    sections: list[str] = []
    if include_thoughts and self.thoughts:
        body = "\n\n".join(t.strip() for t in self.thoughts if t.strip())
        if body:
            sections.append(f"### [Thoughts]\n{body}")
    if include_tools and (self.tool_calls or self.tool_responses):
        lines = ["### [Tool Activity]"]
        for tc in self.tool_calls:
            name = tc.display_name or tc.tool or tc.id or "tool"
            lines.append(f"- **Call** `{name}`: {_compact_json(tc.args)}")
        for tr in self.tool_responses:
            name = tr.display_name or tr.tool or tr.id or "tool"
            lines.append(
                f"- **Response** `{name}`: {_compact_json(tr.response)}"
            )
        sections.append("\n".join(lines))
    if self.text.strip():
        sections.append(self.text.strip())
    if self.errors:
        lines = ["### [Errors]"]
        for err in self.errors:
            msg = err.message or f"code={err.code}"
            lines.append(f"- `code={err.code}`: {msg}")
        sections.append("\n".join(lines))
    for art in self.artifacts:
        meta = [f"state={art.state or 'UNKNOWN'}"]
        if art.mime_type:
            meta.append(f"mime={art.mime_type}")
        if art.gcs_uri:
            meta.append(f"gcs_uri={art.gcs_uri}")
        title = art.display_name or art.artifact_id or "artifact"
        header = f"### [Artifact] {title} ({', '.join(meta)})"
        sections.append(
            f"{header}\n{art.content.rstrip()}" if art.content else header
        )
    if self.contract_metadata is not None and (
        self.contract_metadata.contract_related
        or self.contract_metadata.contract_finalized
        or self.contract_metadata.contract_draft_complete
    ):
        cm = self.contract_metadata
        sections.append(
            "### [Contract Progress]\n"
            f"- Contract related: {cm.contract_related}\n"
            f"- Draft complete: {cm.contract_draft_complete}\n"
            f"- Finalized: {cm.contract_finalized}"
        )
    if self.confirmation_actions:
        lines = ["### [Confirmation Actions]"]
        for a in self.confirmation_actions:
            how = "typed" if a.typed else "clicked"
            detail = f' "{a.text}"' if a.text else ""
            tool = f" ({a.tool})" if a.tool else ""
            lines.append(
                f"- `{a.confirmation_id}`{tool}: {a.action}{detail} "
                f"[{how}, policy={a.policy or 'manual'}, round={a.round}]"
            )
        sections.append("\n".join(lines))
    pending_cards = self.pending_confirmation_requests
    if pending_cards:
        lines = ["### [Confirmation Requests] ⚠️ awaiting your answer"]
        for cr in pending_cards:
            lines.append(f"- **Card** `{cr.confirmation_id}`")
            if cr.tool:
                lines.append(f"  - Tool: `{cr.tool}`")
            if cr.agent_name:
                lines.append(f"  - Agent: `{cr.agent_name}`")
            if cr.context:
                lines.append(f"  - Context: {cr.context.strip()}")
            if cr.questions:
                for qi, q in enumerate(cr.questions, start=1):
                    lines.append(f"  - Q{qi}: {q.question}")
                    lines.extend(_format_options(q.options, indent="    "))
            labels = []
            if cr.positive_label:
                labels.append(f'confirm="{cr.positive_label}"')
            if cr.negative_label:
                labels.append(f'decline="{cr.negative_label}"')
            if labels:
                lines.append(f"  - Buttons: {', '.join(labels)}")
            if cr.expire_time:
                lines.append(f"  - Expires: {cr.expire_time}")
        sections.append("\n".join(lines))
    pending_options = self.pending_option_questions
    if pending_options:
        lines = ["### [Clarification Options]"]
        for qi, q in enumerate(pending_options, start=1):
            lines.append(f"{qi}. {q.question}")
            lines.extend(_format_options(q.options, indent="   "))
        sections.append("\n".join(lines))
    if self.turn_completed is not None:
        tc = self.turn_completed
        notes: list[str] = []
        if tc.reason and tc.reason != "COMPLETED":
            notes.append(f"> Note: turn ended with reason `{tc.reason}`.")
        if (
            tc.final_sequence_number is not None
            and self.last_sequence_number is not None
            and tc.final_sequence_number > self.last_sequence_number
        ):
            notes.append(
                "> Note: stream missed events up to sequence "
                f"{tc.final_sequence_number} "
                f"(last seen: {self.last_sequence_number})."
            )
        if notes:
            sections.append("\n".join(notes))
    return "\n\n".join(sections)

arc_confirmation_policy

Decides how a programmatic Arc client answers confirmation cards.

The CXAS Console renders every AssistantConfirmationRequest from the CXAS AI assistant as a card. A human can click Confirm/Decline, pick options on a question (ask_user) card, skip the questions, or ignore the card and type in the composer, which the server treats as a reply to the paused tool call. A ConfirmationPolicy reproduces those choices for scripts, the cxas arc CLI and test harnesses, so that programmatic traffic exercises the same server paths as the Console.

Answer text for question cards uses the Console's wire format for submitted option choices.

ConfirmationPolicy

Bases: ABC

Maps pending cards to the UI actions a user would take.

answers_cards property

answers_cards

Whether the client should loop and answer cards with this policy.

decide abstractmethod

decide(cards)

Returns at most one action per card, in the order to send them.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
@abc.abstractmethod
def decide(self, cards: Sequence[CardLike]) -> list[ConfirmationAction]:
    """Returns at most one action per card, in the order to send them."""

describe

describe()

Returns a short description for logs and recorded actions.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def describe(self) -> str:
    """Returns a short description for logs and recorded actions."""
    return self.name

ManualPolicy

Bases: ConfirmationPolicy

Surfaces cards without answering them (the caller decides).

answers_cards property

answers_cards

See base class.

decide

decide(cards)

See base class.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def decide(self, cards: Sequence[CardLike]) -> list[ConfirmationAction]:
    """See base class."""
    del cards
    return []

ClickPolicy

ClickPolicy(answers=None, question_answerer=None, deny_tools=())

Bases: ConfirmationPolicy

Clicks like an attentive user: confirm gates, answer question cards.

Question cards are answered by, in order: an explicit answers entry keyed by confirmation id or tool, the question_answerer callback (e.g. a test harness's deterministic responder), then the first option of every question.

Initializes ClickPolicy with explicit answers and deny globs.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def __init__(
    self,
    answers: Mapping[str, str] | None = None,
    question_answerer: QuestionAnswerer | None = None,
    deny_tools: Sequence[str] = (),
):
    """Initializes ClickPolicy with explicit answers and deny globs."""
    self._answers = dict(answers or {})
    self._question_answerer = question_answerer
    self._deny_tools = tuple(deny_tools)

decide

decide(cards)

See base class.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def decide(self, cards: Sequence[CardLike]) -> list[ConfirmationAction]:
    """See base class."""
    return [self._click(c) for c in cards if c.confirmation_id]

MixedPolicy

MixedPolicy(typed_reply_probability=DEFAULT_TYPED_REPLY_PROBABILITY, seed=None, typed_confirm_text=DEFAULT_TYPED_CONFIRM_TEXT, typed_deny_text=DEFAULT_TYPED_DENY_TEXT, **click_kwargs)

Bases: ClickPolicy

Like click, but types the answer instead with probability p.

In production most users type a reply instead of clicking the card, which exercises a different server path than a click. The draw is seeded and logged so a failing run can be replayed.

Initializes MixedPolicy with a seeded typed-reply probability.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def __init__(
    self,
    typed_reply_probability: float = DEFAULT_TYPED_REPLY_PROBABILITY,
    seed: int | None = None,
    typed_confirm_text: str = DEFAULT_TYPED_CONFIRM_TEXT,
    typed_deny_text: str = DEFAULT_TYPED_DENY_TEXT,
    **click_kwargs: Any,
):
    """Initializes MixedPolicy with a seeded typed-reply probability."""
    super().__init__(**click_kwargs)
    if not 0.0 <= typed_reply_probability <= 1.0:
        raise ValueError(
            "typed_reply_probability must be in [0, 1], got"
            f" {typed_reply_probability}"
        )
    self.typed_reply_probability = typed_reply_probability
    self.seed = seed if seed is not None else time.time_ns() % (2**31)
    self._rng = random.Random(self.seed)
    self._typed_confirm_text = typed_confirm_text
    self._typed_deny_text = typed_deny_text
    logger.info(
        "MixedPolicy typed_reply_probability=%s seed=%s",
        self.typed_reply_probability,
        self.seed,
    )

decide

decide(cards)

See base class.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def decide(self, cards: Sequence[CardLike]) -> list[ConfirmationAction]:
    """See base class."""
    actions = []
    for click in super().decide(cards):
        action = click
        draw = self._rng.random()
        if draw < self.typed_reply_probability:
            action = _typed_variant(
                click,
                self._typed_confirm_text,
                self._typed_deny_text,
                reason=f"mixed draw={draw:.4f} seed={self.seed}",
            )
        actions.append(action)
    return actions

describe

describe()

Returns the probability and seed, so a run can be replayed.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def describe(self) -> str:
    """Returns the probability and seed, so a run can be replayed."""
    return f"mixed(p={self.typed_reply_probability}, seed={self.seed})"

ScriptedPolicy

ScriptedPolicy(rules=(), default='click', typed_reply_probability=0.0, seed=None, typed_confirm_text=DEFAULT_TYPED_CONFIRM_TEXT, typed_deny_text=DEFAULT_TYPED_DENY_TEXT, question_answerer=None, answers=None, deny_tools=())

Bases: ConfirmationPolicy

Answers cards from an ordered rule list, falling back to click.

Script schema (dict or YAML):

default: click            # click | manual
typed_reply_probability: 0.0
seed: 0
typed_confirm_text: "Yes"
rules:
  - {tool: "deploy*", action: type, text: "yes"}
  - {kind: question, action: skip_all}

Initializes ScriptedPolicy with ordered rules and a fallback.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def __init__(
    self,
    rules: Sequence[ScriptRule] = (),
    default: str = "click",
    typed_reply_probability: float = 0.0,
    seed: int | None = None,
    typed_confirm_text: str = DEFAULT_TYPED_CONFIRM_TEXT,
    typed_deny_text: str = DEFAULT_TYPED_DENY_TEXT,
    question_answerer: QuestionAnswerer | None = None,
    answers: Mapping[str, str] | None = None,
    deny_tools: Sequence[str] = (),
):
    """Initializes ScriptedPolicy with ordered rules and a fallback."""
    if default not in ("click", "manual"):
        raise ValueError(f"Unknown scripted default {default!r}")
    self._rules = [dataclasses.replace(r, _seen=0, _used=0) for r in rules]
    self._default = default
    self._typed_confirm_text = typed_confirm_text
    self._fallback = MixedPolicy(
        typed_reply_probability=typed_reply_probability,
        seed=seed if seed is not None else 0,
        typed_confirm_text=typed_confirm_text,
        typed_deny_text=typed_deny_text,
        question_answerer=question_answerer,
        answers=answers,
        deny_tools=deny_tools,
    )
    self._click = ClickPolicy(
        question_answerer=question_answerer,
        answers=answers,
        deny_tools=deny_tools,
    )

reset

reset()

Resets per-rule occurrence and usage counters for a new session.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def reset(self) -> None:
    """Resets per-rule occurrence and usage counters for a new session."""
    for rule in self._rules:
        rule._seen = 0
        rule._used = 0

from_dict classmethod

from_dict(script, question_answerer=None)

Builds a policy from a parsed script (see the class docstring).

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
@classmethod
def from_dict(
    cls,
    script: Mapping[str, Any],
    question_answerer: QuestionAnswerer | None = None,
) -> ScriptedPolicy:
    """Builds a policy from a parsed script (see the class docstring)."""
    known = {
        "rules",
        "default",
        "typed_reply_probability",
        "seed",
        "typed_confirm_text",
        "typed_deny_text",
        "answers",
        "deny_tools",
    }
    unknown = set(script) - known
    if unknown:
        raise ValueError(
            f"Unknown confirmation script keys: {sorted(unknown)}"
        )
    rules = [
        r if isinstance(r, ScriptRule) else ScriptRule(**dict(r))
        for r in script.get("rules") or []
    ]
    return cls(
        rules=rules,
        default=str(script.get("default", "click")),
        typed_reply_probability=float(
            script.get("typed_reply_probability", 0.0)
        ),
        seed=script.get("seed"),
        typed_confirm_text=str(
            script.get("typed_confirm_text", DEFAULT_TYPED_CONFIRM_TEXT)
        ),
        typed_deny_text=str(
            script.get("typed_deny_text", DEFAULT_TYPED_DENY_TEXT)
        ),
        question_answerer=question_answerer,
        answers=script.get("answers"),
        deny_tools=tuple(script.get("deny_tools") or ()),
    )

from_yaml classmethod

from_yaml(yaml_text, question_answerer=None)

Builds a policy from YAML (optionally under confirmation_script:).

The yaml package is imported lazily so the module stays importable without it.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
@classmethod
def from_yaml(
    cls,
    yaml_text: str,
    question_answerer: QuestionAnswerer | None = None,
) -> ScriptedPolicy:
    """Builds a policy from YAML (optionally under `confirmation_script:`).

    The `yaml` package is imported lazily so the module stays importable
    without it.
    """
    import yaml  # noqa: PLC0415 - optional dependency, loaded lazily.

    data = yaml.safe_load(yaml_text) or {}
    if "confirmation_script" in data:
        data = data["confirmation_script"] or {}
    return cls.from_dict(data, question_answerer=question_answerer)

decide

decide(cards)

See base class.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def decide(self, cards: Sequence[CardLike]) -> list[ConfirmationAction]:
    """See base class."""
    actions = []
    for card in cards:
        if not card.confirmation_id:
            continue
        matched = False
        for rule in self._rules:
            if rule.max_uses and rule._used >= rule.max_uses:
                continue
            if not rule.filters_match(card):
                continue
            rule._seen += 1
            if rule.occurrence and rule._seen != rule.occurrence:
                continue
            rule._used += 1
            matched = True
            action = self._from_rule(rule, card)
            if action is not None:
                actions.append(action)
            break
        if not matched and self._default == "click":
            actions.extend(self._fallback.decide([card]))
    return actions

describe

describe()

Returns the rule count, default and fallback policy.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def describe(self) -> str:
    """Returns the rule count, default and fallback policy."""
    return (
        f"scripted(rules={len(self._rules)}, default={self._default},"
        f" fallback={self._fallback.describe()})"
    )

make_policy

make_policy(name, typed_reply_probability=None, seed=None, script=None, question_answerer=None, answers=None, deny_tools=())

Builds a policy from its CLI/config name.

Parameters:

Name Type Description Default
name str | None

Policy name ("manual", "click", "mixed", or "scripted"). None or empty defaults to "manual".

required
typed_reply_probability float | None

Probability of typing instead of clicking for "mixed" or "scripted" policies. None uses DEFAULT_TYPED_REPLY_PROBABILITY for "mixed".

None
seed int | None

Optional RNG seed for "mixed" or "scripted" policies; None picks a time-based seed for "mixed" or 0 for "scripted".

None
script Mapping[str, Any] | None

Script configuration mapping for "scripted" policy; None uses an empty script.

None
question_answerer QuestionAnswerer | None

Optional callback returning an answer for question cards.

None
answers Mapping[str, str] | None

Optional explicit answer overrides keyed by confirmation ID or tool name.

None
deny_tools Sequence[str]

Optional fnmatch globs of gated tools to automatically decline under "click", "mixed", or "scripted" fallback.

()

Returns:

Type Description
ConfirmationPolicy

The configured ConfirmationPolicy instance.

Raises:

Type Description
ValueError

If name is not a recognized policy name or the script/policy parameters are invalid.

Source code in src/cxas_scrapi/utils/arc_confirmation_policy.py
def make_policy(
    name: str | None,
    typed_reply_probability: float | None = None,
    seed: int | None = None,
    script: Mapping[str, Any] | None = None,
    question_answerer: QuestionAnswerer | None = None,
    answers: Mapping[str, str] | None = None,
    deny_tools: Sequence[str] = (),
) -> ConfirmationPolicy:
    """Builds a policy from its CLI/config name.

    Args:
        name: Policy name ("manual", "click", "mixed", or "scripted"). None or
            empty defaults to "manual".
        typed_reply_probability: Probability of typing instead of clicking for
            "mixed" or "scripted" policies. None uses
            DEFAULT_TYPED_REPLY_PROBABILITY for "mixed".
        seed: Optional RNG seed for "mixed" or "scripted" policies; None picks
            a time-based seed for "mixed" or 0 for "scripted".
        script: Script configuration mapping for "scripted" policy; None uses
            an empty script.
        question_answerer: Optional callback returning an answer for question
            cards.
        answers: Optional explicit answer overrides keyed by confirmation ID
            or tool name.
        deny_tools: Optional fnmatch globs of gated tools to automatically
            decline under "click", "mixed", or "scripted" fallback.

    Returns:
        The configured ConfirmationPolicy instance.

    Raises:
        ValueError: If `name` is not a recognized policy name or the
            script/policy parameters are invalid.
    """
    key = (name or "manual").strip().lower()
    if key == "manual":
        return ManualPolicy()
    if key == "click":
        return ClickPolicy(
            question_answerer=question_answerer,
            answers=answers,
            deny_tools=deny_tools,
        )
    if key == "mixed":
        return MixedPolicy(
            typed_reply_probability=(
                DEFAULT_TYPED_REPLY_PROBABILITY
                if typed_reply_probability is None
                else typed_reply_probability
            ),
            seed=seed,
            question_answerer=question_answerer,
            answers=answers,
            deny_tools=deny_tools,
        )
    if key == "scripted":
        merged = dict(script or {})
        if (
            typed_reply_probability is not None
            and "typed_reply_probability" not in merged
        ):
            merged["typed_reply_probability"] = typed_reply_probability
        if seed is not None and "seed" not in merged:
            merged["seed"] = seed
        if answers is not None and "answers" not in merged:
            merged["answers"] = answers
        if deny_tools and "deny_tools" not in merged:
            merged["deny_tools"] = list(deny_tools)
        return ScriptedPolicy.from_dict(
            merged, question_answerer=question_answerer
        )
    raise ValueError(
        f"Unknown confirmation policy {name!r}; expected one of {POLICY_NAMES}"
    )