Skip to content

AgentConnection

🛈 DocStrings

A connection to one agent (local subprocess or remote) speaking ACP v2.

Source code in src/acptui/protocol/connection.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
class AgentConnection:
    """A connection to one agent (local subprocess or remote) speaking ACP v2."""

    def __init__(self, spec: AgentSpec, events: AgentEvents, cwd: Path) -> None:
        self.spec = spec
        self.cwd = cwd
        self._events = events
        self._conn: ClientSideConnection | None = None
        self._process: Process | None = None
        self.init: InitializeResponse | None = None
        """The agent's ``initialize`` response, once connected."""

    # --- Lifecycle -------------------------------------------------------------------

    @asynccontextmanager
    async def open(self) -> AsyncGenerator[Self]:
        """Start (or connect to) the agent and initialize the connection.

        Raises:
            UnsupportedProtocolError: The agent does not speak v2.
            AgentError: The agent could not be started or did not initialize.
        """
        async with AsyncExitStack() as stack:
            writer, reader = await self._open_transport(stack)
            conn = ClientSideConnection(
                _ClientHandler(self._events), writer, reader, observers=[self._observe]
            )
            stack.push_async_callback(conn.close)
            self._conn = conn
            self.init = await self._initialize(conn)
            try:
                yield self
            finally:
                self._conn = None

    async def _open_transport(
        self, stack: AsyncExitStack
    ) -> tuple[ByteSendStream, ByteReceiveStream]:
        spec = self.spec
        if spec.url is not None:
            try:
                reader, writer = await stack.enter_async_context(
                    connect_remote_transport(spec.url, headers=spec.resolved_headers())
                )
            except (OSError, ValueError) as exc:
                msg = f"Could not connect to {spec.url}: {exc}"
                raise AgentError(msg) from exc
            return writer, reader
        program, *args = spec.command
        env = {**os.environ, **spec.resolved_env()}
        try:
            reader, writer, process = await stack.enter_async_context(
                spawn_stdio_transport(
                    program, *args, env=env, cwd=self.cwd, on_stderr=self._events.stderr_line
                )
            )
        except OSError as exc:
            hint = f"\nInstall it with: {spec.install}" if spec.install else ""
            msg = f"Could not start {spec.name} ({spec.target}): {exc}{hint}"
            raise AgentError(msg) from exc
        self._process = process
        return writer, reader

    async def _initialize(self, conn: ClientSideConnection) -> InitializeResponse:
        capabilities = CLIENT_CAPABILITIES
        request = InitializeRequest(protocol_version=2, info=CLIENT_INFO, capabilities=capabilities)
        try:
            with anyio.fail_after(INITIALIZE_TIMEOUT):
                return await conn.initialize(request)
        except ProtocolVersionError as exc:
            name = _agent_name(exc.result, self.spec.name)
            raise UnsupportedProtocolError(name, exc.received) from exc
        except TimeoutError as exc:
            msg = (
                f"{self.spec.name} did not answer `initialize` within {INITIALIZE_TIMEOUT:.0f} s.\n"
                "It may not speak ACP on stdio, or it waits for a login (see the log: ctrl+l)."
            )
            raise AgentError(msg) from exc
        except InvalidResponseError as exc:
            # Claims v2, but the response does not have the v2 shape (e.g. an agent
            # echoing the requested version with a v1 response).
            msg = (
                f"{self.spec.name} answered `initialize` with an invalid ACP v2 response "
                f"({len(exc.errors)} errors). It probably only speaks ACP v1."
            )
            raise AgentError(msg) from exc
        except RequestError as exc:
            if exc.code == -32022:  # noqa: PLR2004
                raise UnsupportedProtocolError(self.spec.name, exc.data) from exc
            msg = (
                f"{self.spec.name} rejected `initialize`: {exc} ({exc.code}).\n"
                "It may only speak ACP v1."
            )
            raise AgentError(msg) from exc
        except ConnectionError as exc:
            msg = f"{self.spec.name} exited during startup{self._exit_suffix()}."
            raise AgentError(msg) from exc

    def _exit_suffix(self) -> str:
        code = self.exit_code
        return f" with exit code {code}" if code is not None else ""

    def _observe(self, event: StreamEvent) -> None:
        self._events.traffic(event.direction, json.dumps(event.message, ensure_ascii=False))

    @property
    def connection(self) -> ClientSideConnection:
        """The live JSON-RPC connection.

        Raises:
            AgentError: Not connected.
        """
        if self._conn is None:
            msg = "not connected to an agent"
            raise AgentError(msg)
        return self._conn

    @property
    def connected(self) -> bool:
        """Whether the connection is open."""
        return self._conn is not None and not self._conn.connection.closed

    @property
    def exit_code(self) -> int | None:
        """Exit code of a local agent that has exited."""
        return self._process.returncode if self._process is not None else None

    async def wait_closed(self) -> None:
        """Wait until the agent disconnects (or exits)."""
        await self.connection.wait_closed()
        if self._process is not None:
            # Give the exit code a moment to arrive after stdout closed.
            with anyio.move_on_after(2):
                await self._process.wait()

    # --- Capabilities ----------------------------------------------------------------

    @property
    def agent_name(self) -> str:
        """Display name of the agent."""
        if self.init is None:
            return self.spec.name
        info = self.init.info
        return info.title if is_set(info.title) and info.title else info.name

    @property
    def agent_version(self) -> str:
        """Version the agent reports."""
        return self.init.info.version if self.init is not None else ""

    @property
    def capabilities(self) -> AgentCapabilities:
        """The agent's capabilities (empty before initialization)."""
        if self.init is not None and is_set(self.init.capabilities):
            return self.init.capabilities
        return AgentCapabilities()

    @property
    def auth_methods(self) -> Sequence[AuthMethod]:
        """Authentication methods the agent offers."""
        if self.init is not None and is_set(self.init.auth_methods):
            return self.init.auth_methods
        return ()

    def supports(self, path: str) -> bool:
        """Whether the agent has a capability, by its dotted wire path (``session.fork``)."""
        return self.init is not None and supports(self.init.capabilities, path)

    @property
    def supports_images(self) -> bool:
        """Whether prompts may contain images."""
        return self.supports("session.prompt.image")

    @property
    def supports_audio(self) -> bool:
        """Whether prompts may contain audio."""
        return self.supports("session.prompt.audio")

    @property
    def supports_embedded_context(self) -> bool:
        """Whether prompts may embed resource contents."""
        return self.supports("session.prompt.embeddedContext")

    @property
    def supports_skills(self) -> bool:
        """Whether prompts may contain ``skill`` blocks."""
        return self.supports("session.prompt.skill")

    @property
    def supports_additional_directories(self) -> bool:
        """``additionalDirectories`` on session setup."""
        return self.supports("session.additionalDirectories")

    @property
    def supports_system_prompt(self) -> bool:
        """``systemPrompt`` on session setup."""
        return self.supports("session.systemPrompt")

    @property
    def supports_system_prompt_override(self) -> bool:
        """The ``override`` system prompt mode."""
        return self.supports("session.systemPrompt.mode.override")

    @property
    def supports_delete(self) -> bool:
        """``session/delete``."""
        return self.supports("session.delete")

    @property
    def supports_fork(self) -> bool:
        """``session/fork``."""
        return self.supports("session.fork")

    @property
    def supports_archive(self) -> bool:
        """``session/archive`` and ``session/unarchive``."""
        return self.supports("session.archive")

    @property
    def supports_status(self) -> bool:
        """``session/status``."""
        return self.supports("session.status")

    @property
    def supports_options(self) -> bool:
        """``session/options``."""
        return self.supports("session.options")

    @property
    def supports_title(self) -> bool:
        """``session/set_title``."""
        return self.supports("session.title")

    @property
    def supports_auth_status(self) -> bool:
        """``auth/status`` (and ``auth/status_update``)."""
        return self.supports("auth.status")

    @property
    def supports_providers(self) -> bool:
        """``providers/list``, ``providers/set`` and ``providers/disable``."""
        return self.supports("providers")

    @property
    def supports_login(self) -> bool:
        """``auth/login`` and ``auth/logout`` (any auth methods advertised)."""
        return bool(self.auth_methods)

    def mcp_transports(self) -> set[str]:
        """MCP transports the agent accepts on session setup."""
        return {name for name in ("stdio", "http", "acp") if self.supports(f"session.mcp.{name}")}

    # --- Calls -----------------------------------------------------------------------

    def _setup_fields(self, setup: SessionSetup) -> _SetupFields:
        directories = (
            list(setup.additional_directories)
            if setup.additional_directories and self.supports_additional_directories
            else None
        )
        transports = self.mcp_transports()
        servers = [server for server in setup.mcp_servers if _mcp_transport(server) in transports]
        system_prompt = None
        if setup.system_prompt and self.supports_system_prompt:
            mode = setup.system_prompt_mode
            if mode == "override" and not self.supports_system_prompt_override:
                mode = "append"
            system_prompt = SystemPrompt(mode=mode, content=[TextContent(text=setup.system_prompt)])
        return _SetupFields(directories, servers, system_prompt, list(setup.config_options))

    async def new_session(self, setup: SessionSetup | None = None) -> NewSessionResponse:
        """Create a session in the working directory."""
        fields = self._setup_fields(setup or SessionSetup())
        request = NewSessionRequest(cwd=str(self.cwd), mcp_servers=fields.mcp_servers)
        _apply_setup(request, fields)
        return await self.connection.new_session(request)

    async def resume_session(
        self, session_id: str, *, replay: bool = True, setup: SessionSetup | None = None
    ) -> ResumeSessionResponse:
        """Resume a session, replaying its history."""
        fields = self._setup_fields(setup or SessionSetup())
        request = ResumeSessionRequest(
            session_id=session_id,
            cwd=str(self.cwd),
            replay_from=ReplayFromStart() if replay else None,
            mcp_servers=fields.mcp_servers,
        )
        _apply_setup(request, fields)
        return await self.connection.resume_session(request)

    async def fork_session(
        self, session_id: str, cursor_id: str | None = None, setup: SessionSetup | None = None
    ) -> ForkSessionResponse:
        """Fork a session (at a cursor, or whole)."""
        fields = self._setup_fields(setup or SessionSetup())
        request = ForkSessionRequest(
            session_id=session_id,
            cwd=str(self.cwd),
            cursor_id=cursor_id,
            mcp_servers=fields.mcp_servers,
        )
        _apply_setup(request, fields)
        return await self.connection.fork_session(request)

    async def list_sessions(
        self, cursor: str | None = None, *, archived: str | None = None
    ) -> ListSessionsResponse:
        """List sessions of the working directory (``archived``: exclude, include, only)."""
        request = ListSessionsRequest(cwd=str(self.cwd), cursor=cursor)
        if archived is not None:
            request.archived = archived
        return await self.connection.list_sessions(request)

    async def close_session(self, session_id: str) -> None:
        """Close a session (errors are ignored: the session is left anyway)."""
        with suppress(RequestError):
            await self.connection.close_session(CloseSessionRequest(session_id=session_id))

    async def delete_session(self, session_id: str) -> None:
        """Delete a session from the agent's list."""
        await self.connection.delete_session(DeleteSessionRequest(session_id=session_id))

    async def archive_session(self, session_id: str, *, archived: bool = True) -> None:
        """Archive (or unarchive) a session."""
        if archived:
            await self.connection.archive_session(ArchiveSessionRequest(session_id=session_id))
        else:
            await self.connection.unarchive_session(UnarchiveSessionRequest(session_id=session_id))

    async def session_status(self, session_id: str) -> SessionStatusResponse:
        """Whether the agent has the session open or saved, and its state."""
        return await self.connection.session_status(SessionStatusRequest(session_id=session_id))

    async def session_options(self, session_id: str | None = None) -> SessionOptionsResponse:
        """Config options and commands a session would start with."""
        request = SessionOptionsRequest(cwd=str(self.cwd), session_id=session_id)
        return await self.connection.session_options(request)

    async def set_title(self, session_id: str, title: str) -> str:
        """Rename a session; returns the title the agent stored."""
        request = SetSessionTitleRequest(session_id=session_id, title=title)
        return (await self.connection.set_session_title(request)).title

    async def prompt(self, session_id: str, blocks: Sequence[ContentBlock]) -> PromptResponse:
        """Send a user message; returns once the agent inserted it.

        Each call gets a fresh idempotency key, so a retried request is not inserted twice.
        """
        request = PromptRequest(
            session_id=session_id, prompt=blocks, idempotency_key=str(uuid.uuid4())
        )
        return await self.connection.prompt(request)

    async def cancel(self, session_id: str) -> None:
        """Cancel the session's foreground work."""
        await self.connection.cancel(CancelSessionNotification(session_id=session_id))

    async def cancel_tool_call(self, session_id: str, tool_call_id: str) -> None:
        """Cancel one tool call."""
        request = CancelToolCallRequest(session_id=session_id, tool_call_id=tool_call_id)
        await self.connection.cancel_tool_call(request)

    async def cancel_terminal(self, session_id: str, terminal_id: str) -> None:
        """Cancel one terminal."""
        request = CancelTerminalRequest(session_id=session_id, terminal_id=terminal_id)
        await self.connection.cancel_terminal(request)

    async def set_config_option(
        self, session_id: str, config_id: str, value: str | bool
    ) -> SetSessionConfigOptionResponse:
        """Set a select (``str`` value) or boolean config option."""
        if isinstance(value, bool):
            request: SetConfigOptionIdRequest | SetConfigOptionBooleanRequest = (
                SetConfigOptionBooleanRequest(
                    session_id=session_id, config_id=config_id, value=value
                )
            )
        else:
            request = SetConfigOptionIdRequest(
                session_id=session_id, config_id=config_id, value=value
            )
        return await self.connection.set_session_config_option(request)

    async def login(self, method_id: str) -> None:
        """Log in with an ``agent`` auth method."""
        await self.connection.login(LoginAuthRequest(method_id=method_id))

    async def logout(self) -> None:
        """Log out."""
        await self.connection.logout(LogoutAuthRequest())

    async def auth_status(self) -> AuthStatusResponse:
        """The agent's authentication state and accounts."""
        return await self.connection.auth_status(AuthStatusRequest())

    async def list_providers(self) -> ListProvidersResponse:
        """The agent's configurable LLM providers."""
        return await self.connection.list_providers(ListProvidersRequest())

    async def set_provider(
        self,
        provider_id: str,
        api_type: str,
        base_url: str,
        headers: Mapping[str, str] | None = None,
    ) -> None:
        """Configure an LLM provider."""
        request = SetProviderRequest(provider_id=provider_id, api_type=api_type, base_url=base_url)
        if headers:
            request.headers = dict(headers)
        await self.connection.set_provider(request)

    async def disable_provider(self, provider_id: str) -> None:
        """Disable an LLM provider."""
        await self.connection.disable_provider(DisableProviderRequest(provider_id=provider_id))

agent_name property

agent_name: str

Display name of the agent.

agent_version property

agent_version: str

Version the agent reports.

auth_methods property

auth_methods: Sequence[AuthMethod]

Authentication methods the agent offers.

capabilities property

capabilities: AgentCapabilities

The agent's capabilities (empty before initialization).

connected property

connected: bool

Whether the connection is open.

connection property

connection: ClientSideConnection

The live JSON-RPC connection.

Raises:

Type Description
AgentError

Not connected.

exit_code property

exit_code: int | None

Exit code of a local agent that has exited.

init instance-attribute

init: InitializeResponse | None = None

The agent's initialize response, once connected.

supports_additional_directories property

supports_additional_directories: bool

additionalDirectories on session setup.

supports_archive property

supports_archive: bool

session/archive and session/unarchive.

supports_audio property

supports_audio: bool

Whether prompts may contain audio.

supports_auth_status property

supports_auth_status: bool

auth/status (and auth/status_update).

supports_delete property

supports_delete: bool

session/delete.

supports_embedded_context property

supports_embedded_context: bool

Whether prompts may embed resource contents.

supports_fork property

supports_fork: bool

session/fork.

supports_images property

supports_images: bool

Whether prompts may contain images.

supports_login property

supports_login: bool

auth/login and auth/logout (any auth methods advertised).

supports_options property

supports_options: bool

session/options.

supports_providers property

supports_providers: bool

providers/list, providers/set and providers/disable.

supports_skills property

supports_skills: bool

Whether prompts may contain skill blocks.

supports_status property

supports_status: bool

session/status.

supports_system_prompt property

supports_system_prompt: bool

systemPrompt on session setup.

supports_system_prompt_override property

supports_system_prompt_override: bool

The override system prompt mode.

supports_title property

supports_title: bool

session/set_title.

archive_session async

archive_session(session_id: str, *, archived: bool = True) -> None

Archive (or unarchive) a session.

Source code in src/acptui/protocol/connection.py
async def archive_session(self, session_id: str, *, archived: bool = True) -> None:
    """Archive (or unarchive) a session."""
    if archived:
        await self.connection.archive_session(ArchiveSessionRequest(session_id=session_id))
    else:
        await self.connection.unarchive_session(UnarchiveSessionRequest(session_id=session_id))

auth_status async

auth_status() -> AuthStatusResponse

The agent's authentication state and accounts.

Source code in src/acptui/protocol/connection.py
async def auth_status(self) -> AuthStatusResponse:
    """The agent's authentication state and accounts."""
    return await self.connection.auth_status(AuthStatusRequest())

cancel async

cancel(session_id: str) -> None

Cancel the session's foreground work.

Source code in src/acptui/protocol/connection.py
async def cancel(self, session_id: str) -> None:
    """Cancel the session's foreground work."""
    await self.connection.cancel(CancelSessionNotification(session_id=session_id))

cancel_terminal async

cancel_terminal(session_id: str, terminal_id: str) -> None

Cancel one terminal.

Source code in src/acptui/protocol/connection.py
async def cancel_terminal(self, session_id: str, terminal_id: str) -> None:
    """Cancel one terminal."""
    request = CancelTerminalRequest(session_id=session_id, terminal_id=terminal_id)
    await self.connection.cancel_terminal(request)

cancel_tool_call async

cancel_tool_call(session_id: str, tool_call_id: str) -> None

Cancel one tool call.

Source code in src/acptui/protocol/connection.py
async def cancel_tool_call(self, session_id: str, tool_call_id: str) -> None:
    """Cancel one tool call."""
    request = CancelToolCallRequest(session_id=session_id, tool_call_id=tool_call_id)
    await self.connection.cancel_tool_call(request)

close_session async

close_session(session_id: str) -> None

Close a session (errors are ignored: the session is left anyway).

Source code in src/acptui/protocol/connection.py
async def close_session(self, session_id: str) -> None:
    """Close a session (errors are ignored: the session is left anyway)."""
    with suppress(RequestError):
        await self.connection.close_session(CloseSessionRequest(session_id=session_id))

delete_session async

delete_session(session_id: str) -> None

Delete a session from the agent's list.

Source code in src/acptui/protocol/connection.py
async def delete_session(self, session_id: str) -> None:
    """Delete a session from the agent's list."""
    await self.connection.delete_session(DeleteSessionRequest(session_id=session_id))

disable_provider async

disable_provider(provider_id: str) -> None

Disable an LLM provider.

Source code in src/acptui/protocol/connection.py
async def disable_provider(self, provider_id: str) -> None:
    """Disable an LLM provider."""
    await self.connection.disable_provider(DisableProviderRequest(provider_id=provider_id))

fork_session async

fork_session(
    session_id: str, cursor_id: str | None = None, setup: SessionSetup | None = None
) -> ForkSessionResponse

Fork a session (at a cursor, or whole).

Source code in src/acptui/protocol/connection.py
async def fork_session(
    self, session_id: str, cursor_id: str | None = None, setup: SessionSetup | None = None
) -> ForkSessionResponse:
    """Fork a session (at a cursor, or whole)."""
    fields = self._setup_fields(setup or SessionSetup())
    request = ForkSessionRequest(
        session_id=session_id,
        cwd=str(self.cwd),
        cursor_id=cursor_id,
        mcp_servers=fields.mcp_servers,
    )
    _apply_setup(request, fields)
    return await self.connection.fork_session(request)

list_providers async

list_providers() -> ListProvidersResponse

The agent's configurable LLM providers.

Source code in src/acptui/protocol/connection.py
async def list_providers(self) -> ListProvidersResponse:
    """The agent's configurable LLM providers."""
    return await self.connection.list_providers(ListProvidersRequest())

list_sessions async

list_sessions(cursor: str | None = None, *, archived: str | None = None) -> ListSessionsResponse

List sessions of the working directory (archived: exclude, include, only).

Source code in src/acptui/protocol/connection.py
async def list_sessions(
    self, cursor: str | None = None, *, archived: str | None = None
) -> ListSessionsResponse:
    """List sessions of the working directory (``archived``: exclude, include, only)."""
    request = ListSessionsRequest(cwd=str(self.cwd), cursor=cursor)
    if archived is not None:
        request.archived = archived
    return await self.connection.list_sessions(request)

login async

login(method_id: str) -> None

Log in with an agent auth method.

Source code in src/acptui/protocol/connection.py
async def login(self, method_id: str) -> None:
    """Log in with an ``agent`` auth method."""
    await self.connection.login(LoginAuthRequest(method_id=method_id))

logout async

logout() -> None

Log out.

Source code in src/acptui/protocol/connection.py
async def logout(self) -> None:
    """Log out."""
    await self.connection.logout(LogoutAuthRequest())

mcp_transports

mcp_transports() -> set[str]

MCP transports the agent accepts on session setup.

Source code in src/acptui/protocol/connection.py
def mcp_transports(self) -> set[str]:
    """MCP transports the agent accepts on session setup."""
    return {name for name in ("stdio", "http", "acp") if self.supports(f"session.mcp.{name}")}

new_session async

new_session(setup: SessionSetup | None = None) -> NewSessionResponse

Create a session in the working directory.

Source code in src/acptui/protocol/connection.py
async def new_session(self, setup: SessionSetup | None = None) -> NewSessionResponse:
    """Create a session in the working directory."""
    fields = self._setup_fields(setup or SessionSetup())
    request = NewSessionRequest(cwd=str(self.cwd), mcp_servers=fields.mcp_servers)
    _apply_setup(request, fields)
    return await self.connection.new_session(request)

open async

open() -> AsyncGenerator[Self]

Start (or connect to) the agent and initialize the connection.

Raises:

Type Description
UnsupportedProtocolError

The agent does not speak v2.

AgentError

The agent could not be started or did not initialize.

Source code in src/acptui/protocol/connection.py
@asynccontextmanager
async def open(self) -> AsyncGenerator[Self]:
    """Start (or connect to) the agent and initialize the connection.

    Raises:
        UnsupportedProtocolError: The agent does not speak v2.
        AgentError: The agent could not be started or did not initialize.
    """
    async with AsyncExitStack() as stack:
        writer, reader = await self._open_transport(stack)
        conn = ClientSideConnection(
            _ClientHandler(self._events), writer, reader, observers=[self._observe]
        )
        stack.push_async_callback(conn.close)
        self._conn = conn
        self.init = await self._initialize(conn)
        try:
            yield self
        finally:
            self._conn = None

prompt async

prompt(session_id: str, blocks: Sequence[ContentBlock]) -> PromptResponse

Send a user message; returns once the agent inserted it.

Each call gets a fresh idempotency key, so a retried request is not inserted twice.

Source code in src/acptui/protocol/connection.py
async def prompt(self, session_id: str, blocks: Sequence[ContentBlock]) -> PromptResponse:
    """Send a user message; returns once the agent inserted it.

    Each call gets a fresh idempotency key, so a retried request is not inserted twice.
    """
    request = PromptRequest(
        session_id=session_id, prompt=blocks, idempotency_key=str(uuid.uuid4())
    )
    return await self.connection.prompt(request)

resume_session async

resume_session(
    session_id: str, *, replay: bool = True, setup: SessionSetup | None = None
) -> ResumeSessionResponse

Resume a session, replaying its history.

Source code in src/acptui/protocol/connection.py
async def resume_session(
    self, session_id: str, *, replay: bool = True, setup: SessionSetup | None = None
) -> ResumeSessionResponse:
    """Resume a session, replaying its history."""
    fields = self._setup_fields(setup or SessionSetup())
    request = ResumeSessionRequest(
        session_id=session_id,
        cwd=str(self.cwd),
        replay_from=ReplayFromStart() if replay else None,
        mcp_servers=fields.mcp_servers,
    )
    _apply_setup(request, fields)
    return await self.connection.resume_session(request)

session_options async

session_options(session_id: str | None = None) -> SessionOptionsResponse

Config options and commands a session would start with.

Source code in src/acptui/protocol/connection.py
async def session_options(self, session_id: str | None = None) -> SessionOptionsResponse:
    """Config options and commands a session would start with."""
    request = SessionOptionsRequest(cwd=str(self.cwd), session_id=session_id)
    return await self.connection.session_options(request)

session_status async

session_status(session_id: str) -> SessionStatusResponse

Whether the agent has the session open or saved, and its state.

Source code in src/acptui/protocol/connection.py
async def session_status(self, session_id: str) -> SessionStatusResponse:
    """Whether the agent has the session open or saved, and its state."""
    return await self.connection.session_status(SessionStatusRequest(session_id=session_id))

set_config_option async

set_config_option(
    session_id: str, config_id: str, value: str | bool
) -> SetSessionConfigOptionResponse

Set a select (str value) or boolean config option.

Source code in src/acptui/protocol/connection.py
async def set_config_option(
    self, session_id: str, config_id: str, value: str | bool
) -> SetSessionConfigOptionResponse:
    """Set a select (``str`` value) or boolean config option."""
    if isinstance(value, bool):
        request: SetConfigOptionIdRequest | SetConfigOptionBooleanRequest = (
            SetConfigOptionBooleanRequest(
                session_id=session_id, config_id=config_id, value=value
            )
        )
    else:
        request = SetConfigOptionIdRequest(
            session_id=session_id, config_id=config_id, value=value
        )
    return await self.connection.set_session_config_option(request)

set_provider async

set_provider(
    provider_id: str, api_type: str, base_url: str, headers: Mapping[str, str] | None = None
) -> None

Configure an LLM provider.

Source code in src/acptui/protocol/connection.py
async def set_provider(
    self,
    provider_id: str,
    api_type: str,
    base_url: str,
    headers: Mapping[str, str] | None = None,
) -> None:
    """Configure an LLM provider."""
    request = SetProviderRequest(provider_id=provider_id, api_type=api_type, base_url=base_url)
    if headers:
        request.headers = dict(headers)
    await self.connection.set_provider(request)

set_title async

set_title(session_id: str, title: str) -> str

Rename a session; returns the title the agent stored.

Source code in src/acptui/protocol/connection.py
async def set_title(self, session_id: str, title: str) -> str:
    """Rename a session; returns the title the agent stored."""
    request = SetSessionTitleRequest(session_id=session_id, title=title)
    return (await self.connection.set_session_title(request)).title

supports

supports(path: str) -> bool

Whether the agent has a capability, by its dotted wire path (session.fork).

Source code in src/acptui/protocol/connection.py
def supports(self, path: str) -> bool:
    """Whether the agent has a capability, by its dotted wire path (``session.fork``)."""
    return self.init is not None and supports(self.init.capabilities, path)

wait_closed async

wait_closed() -> None

Wait until the agent disconnects (or exits).

Source code in src/acptui/protocol/connection.py
async def wait_closed(self) -> None:
    """Wait until the agent disconnects (or exits)."""
    await self.connection.wait_closed()
    if self._process is not None:
        # Give the exit code a moment to arrive after stdout closed.
        with anyio.move_on_after(2):
            await self._process.wait()

:fa-brands-github: Show source on GitHub