Skip to content

DemoAgent

Base classes

Name Children Inherits
Agent
aclientp.v2.agent
Base class of a v2 agent. Override the methods the agent supports.

⋔ Inheritance diagram

graph TD
  107846717185184["demo.DemoAgent"]
  107846717111712["agent.Agent"]
  137699722799616["builtins.object"]
  107846717111712 --> 107846717185184
  137699722799616 --> 107846717111712

🛈 DocStrings

Bases: Agent

The scripted agent.

Source code in src/acptui/demo.py
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
class DemoAgent(Agent):
    """The scripted agent."""

    def __init__(self, conn: AgentSideConnection) -> None:
        self.conn = conn
        self.sessions: dict[str, DemoSession] = {}
        self.client_skills = False
        self.logged_in = False
        self.providers: dict[str, ProviderInfo] = {
            "main": ProviderInfo(
                provider_id="main",
                supported=["anthropic", "openai"],
                required=True,
                current=ProviderCurrentConfig(
                    api_type="anthropic", base_url="https://api.example.com"
                ),
            ),
            "backup": ProviderInfo(provider_id="backup", supported=["openai"], required=False),
        }

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

    async def initialize(self, params: InitializeRequest) -> InitializeResponse:
        caps = params.capabilities if is_set(params.capabilities) else None
        session_caps = caps.session if caps is not None and is_set(caps.session) else None
        commands = (
            session_caps.commands
            if session_caps is not None and is_set(session_caps.commands)
            else None
        )
        self.client_skills = (
            commands is not None and is_set(commands.skill) and commands.skill is not None
        )
        prompt = PromptCapabilities(
            image=PromptImageCapabilities(),
            audio=PromptAudioCapabilities(),
            embedded_context=PromptEmbeddedContextCapabilities(),
            skill=PromptSkillCapabilities(),
        )
        session = SessionCapabilities(
            prompt=prompt,
            mcp=McpCapabilities(stdio=McpStdioCapabilities(), http=McpHttpCapabilities()),
            delete=SessionDeleteCapabilities(),
            additional_directories=SessionAdditionalDirectoriesCapabilities(),
            system_prompt=SessionSystemPromptCapabilities(
                mode=SessionSystemPromptModeCapabilities(
                    override=SessionSystemPromptOverrideCapabilities()
                )
            ),
            fork=SessionForkCapabilities(),
            archive=SessionArchiveCapabilities(),
            status=SessionStatusCapabilities(),
            options=SessionOptionsCapabilities(),
            title=SessionTitleCapabilities(),
        )
        return InitializeResponse(
            protocol_version=2,
            info=AGENT_INFO,
            capabilities=AgentCapabilities(
                session=session,
                auth=AgentAuthCapabilities(status=AuthStatusCapabilities()),
                providers=ProvidersCapabilities(),
            ),
            auth_methods=[
                AuthMethodAgent(
                    method_id="demo-login", name="Demo login", description="Pretend to log in"
                ),
                AuthMethodTerminal(
                    method_id="demo-terminal", name="Demo terminal login", args=["--login"]
                ),
            ],
        )

    def _authenticated(self) -> bool:
        if self.logged_in or os.environ.get("ACPTUI_DEMO_REQUIRE_AUTH") != "1":
            return True
        marker = os.environ.get("ACPTUI_DEMO_AUTH_FILE")
        return marker is not None and Path(marker).is_file()

    def _commands(self) -> list[AvailableCommand]:
        skills: list[AvailableCommand] = [
            Skill(name="review", description="Review the code (a skill)")
        ]
        return COMMANDS + skills if self.client_skills else list(COMMANDS)

    def _setup(
        self,
        session: DemoSession,
        params: NewSessionRequest | ResumeSessionRequest | ForkSessionRequest,
    ) -> None:
        if not Path(params.cwd).is_dir():
            raise RequestError.invalid_params({"details": f"not a directory: {params.cwd}"})
        session.cwd = params.cwd
        if is_set(params.additional_directories):
            session.additional_directories = list(params.additional_directories)
        if is_set(params.mcp_servers):
            session.mcp_servers = [
                server.model_dump(by_alias=True) for server in params.mcp_servers
            ]
        if is_set(params.system_prompt) and params.system_prompt is not None:
            text = "".join(
                b.text for b in params.system_prompt.content if isinstance(b, TextContent)
            )
            session.system_prompt = f"{params.system_prompt.mode}: {text}"
        if is_set(params.config_options):
            for option in params.config_options:
                session.apply_initial(option)

    async def new_session(self, params: NewSessionRequest) -> NewSessionResponse:
        if not self._authenticated():
            raise RequestError.auth_required({"details": "log in first"})
        session = DemoSession(str(uuid.uuid4()), params.cwd)
        self._setup(session, params)
        self.sessions[session.session_id] = session
        return NewSessionResponse(
            session_id=session.session_id,
            config_options=session.config_options(),
            available_commands=self._commands(),
        )

    async def list_sessions(self, params: ListSessionsRequest) -> ListSessionsResponse:
        cwd = params.cwd if is_set(params.cwd) else None
        archived = params.archived if is_set(params.archived) and params.archived else "exclude"
        infos = [
            SessionInfo(
                session_id=s.session_id,
                cwd=s.cwd,
                title=s.title,
                updated_at=s.updated_at,
                archived=s.archived,
            )
            for s in self.sessions.values()
            if s.history
            and s.parent_id is None
            and (cwd is None or s.cwd == cwd)
            and (archived == "include" or (archived == "only") == s.archived)
        ]
        return ListSessionsResponse(sessions=infos)

    async def resume_session(self, params: ResumeSessionRequest) -> ResumeSessionResponse:
        session = self._session(params.session_id)
        self._setup(session, params)
        if is_set(params.replay_from) and params.replay_from is not None:
            for update in session.history:
                await self._send(session, update, record=False)
            await self._send(session, ReplayComplete(), record=False)
        await self._send(session, IdleStateSessionUpdate(), record=False)
        return ResumeSessionResponse(
            config_options=session.config_options(), available_commands=self._commands()
        )

    async def fork_session(self, params: ForkSessionRequest) -> ForkSessionResponse:
        source = self._session(params.session_id)
        fork = DemoSession(
            str(uuid.uuid4()), params.cwd, title=f"{source.title or 'session'} (fork)"
        )
        self._setup(fork, params)
        cursor_id = params.cursor_id if is_set(params.cursor_id) else None
        if cursor_id is not None and cursor_id not in source.cursors:
            raise RequestError.invalid_params({"details": f"unknown cursor {cursor_id}"})
        cut = source.cursors[cursor_id] if cursor_id is not None else len(source.history)
        fork.history = list(source.history[:cut])
        self.sessions[fork.session_id] = fork
        return ForkSessionResponse(
            session_id=fork.session_id,
            config_options=fork.config_options(),
            available_commands=self._commands(),
        )

    async def close_session(self, params: CloseSessionRequest) -> CloseSessionResponse:
        session = self.sessions.get(params.session_id)
        if session is not None and session.turn is not None:
            session.turn.cancel()
        return CloseSessionResponse()

    async def delete_session(self, params: DeleteSessionRequest) -> DeleteSessionResponse:
        self._session(params.session_id)
        del self.sessions[params.session_id]
        return DeleteSessionResponse()

    async def archive_session(self, params: ArchiveSessionRequest) -> ArchiveSessionResponse:
        self._session(params.session_id).archived = True
        return ArchiveSessionResponse()

    async def unarchive_session(self, params: UnarchiveSessionRequest) -> UnarchiveSessionResponse:
        self._session(params.session_id).archived = False
        return UnarchiveSessionResponse()

    async def session_status(self, params: SessionStatusRequest) -> SessionStatusResponse:
        session = self._session(params.session_id)
        running = session.turn is not None and not session.turn.done()
        state: StateUpdate = RunningStateUpdate() if running else IdleStateUpdate()
        return SessionStatusResponse(status="open", state=state)

    async def session_options(self, params: SessionOptionsRequest) -> SessionOptionsResponse:
        session_id = params.session_id if is_set(params.session_id) else None
        session = self.sessions.get(session_id) if session_id else None
        options = (session or DemoSession("preview", params.cwd)).config_options()
        return SessionOptionsResponse(config_options=options, available_commands=self._commands())

    async def set_session_title(self, params: SetSessionTitleRequest) -> SetSessionTitleResponse:
        session = self._session(params.session_id)
        session.title = params.title.strip()[:80] or session.title
        return SetSessionTitleResponse(title=session.title or "")

    async def set_session_config_option(
        self, params: SetSessionConfigOptionRequest
    ) -> SetSessionConfigOptionResponse:
        session = self._session(params.session_id)
        match params:
            case SetConfigOptionIdRequest(config_id="mode", value=value) if value in {
                "ask",
                "auto",
            }:
                session.mode = value
            case SetConfigOptionIdRequest(config_id="model", value=value) if value in MODELS:
                session.model = value
            case SetConfigOptionBooleanRequest(config_id="thinking", value=value):
                session.thinking = value
            case _:
                raise RequestError.invalid_params({"details": "unknown option or value"})
        return SetSessionConfigOptionResponse(config_options=session.config_options())

    async def cancel(self, params: CancelSessionNotification) -> None:
        session = self.sessions.get(params.session_id)
        if session is not None and session.turn is not None:
            session.turn.cancel()

    async def cancel_terminal(self, params: CancelTerminalRequest) -> CancelTerminalResponse:
        await self.cancel(CancelSessionNotification(session_id=params.session_id))
        return CancelTerminalResponse()

    async def cancel_tool_call(self, params: CancelToolCallRequest) -> CancelToolCallResponse:
        session = self._session(params.session_id)
        session.cancelled_tools.add(params.tool_call_id)
        return CancelToolCallResponse()

    # --- Authentication and providers -----------------------------------------------

    async def login(self, params: LoginAuthRequest) -> LoginAuthResponse:
        if params.method_id != "demo-login":
            raise RequestError.invalid_params({"details": f"unknown method {params.method_id}"})
        self.logged_in = True
        await self._auth_changed()
        return LoginAuthResponse()

    async def logout(self, params: LogoutAuthRequest) -> LogoutAuthResponse:
        self.logged_in = False
        await self._auth_changed()
        return LogoutAuthResponse()

    def _auth_state(self) -> tuple[str, list[AuthAccount]]:
        if self.logged_in:
            return "authenticated", [
                AuthAccount(label="Demo account", active=True, email="demo@example.com")
            ]
        if self._authenticated():
            return "not_required", []
        return "unauthenticated", []

    async def auth_status(self, params: AuthStatusRequest) -> AuthStatusResponse:
        state, accounts = self._auth_state()
        return AuthStatusResponse(state=state, accounts=accounts)

    async def _auth_changed(self) -> None:
        state, accounts = self._auth_state()
        await self.conn.auth_status_update(
            AuthStatusUpdateNotification(state=state, accounts=accounts)
        )

    async def list_providers(self, params: ListProvidersRequest) -> ListProvidersResponse:
        return ListProvidersResponse(providers=list(self.providers.values()))

    async def set_provider(self, params: SetProviderRequest) -> SetProviderResponse:
        provider = self.providers.get(params.provider_id)
        if provider is None or params.api_type not in provider.supported:
            raise RequestError.invalid_params({"details": "unknown provider or api type"})
        provider.current = ProviderCurrentConfig(api_type=params.api_type, base_url=params.base_url)
        return SetProviderResponse()

    async def disable_provider(self, params: DisableProviderRequest) -> DisableProviderResponse:
        provider = self.providers.get(params.provider_id)
        if provider is None or provider.required:
            raise RequestError.invalid_params({"details": "unknown or required provider"})
        provider.current = None
        return DisableProviderResponse()

    # --- Prompts --------------------------------------------------------------------

    async def prompt(self, params: PromptRequest) -> PromptResponse:
        session = self._session(params.session_id)
        if session.turn is not None and not session.turn.done():
            raise RequestError.invalid_request({"details": "a turn is already running"})
        message_id = f"user-{uuid.uuid4()}"
        await self._send(session, UserMessage(message_id=message_id, content=list(params.prompt)))
        text = "".join(b.text for b in params.prompt if isinstance(b, TextContent)).strip()
        skill = next((b.name for b in params.prompt if isinstance(b, SkillReference)), None)
        if session.title is None:
            session.title = text[:60] or "Demo session"
            await self._send(session, SessionInfoUpdate(title=session.title))
        await self._send(session, RunningStateSessionUpdate())
        script = f"/skill {skill}" if skill else text
        session.turn = asyncio.create_task(self._turn(session, script, params.prompt))
        return PromptResponse(message_id=message_id)

    async def _turn(self, session: DemoSession, text: str, prompt: Sequence[ContentBlock]) -> None:
        try:
            command, _, rest = text.partition(" ")
            background: list[BackgroundWork] = []
            match command:
                case "/echo":
                    await self._stream(session, rest or "(nothing to echo)")
                case "/skill":
                    await self._stream(session, f"Running skill **{rest}**.")
                case "/slow":
                    await self._stream(
                        session, "counting slowly: " + " ".join(map(str, range(1, 400))), 0.05
                    )
                case "/fail":
                    error = Error(code=-32603, message="Demo failure: the model is unavailable")
                    await self._send(
                        session, IdleStateSessionUpdate(stop_reason="error", error=error)
                    )
                    return
                case "/crash":
                    sys.stderr.write("demo agent: simulated crash (exit code 3)\n")
                    sys.stderr.flush()
                    await anyio.sleep(0.05)
                    os._exit(3)
                case "/media":
                    await scripts.media(self, session)
                case "/subagent":
                    await scripts.subagent(self, session)
                case "/elicit":
                    await scripts.elicit_form(self, session)
                case "/url":
                    await scripts.elicit_url(self, session)
                case "/compact":
                    await scripts.compact(self, session)
                case "/suggest":
                    await scripts.suggest(self, session)
                case "/plans":
                    await scripts.plans(self, session)
                case "/notice":
                    await scripts.notices(self, session)
                case "/background":
                    background = await scripts.background(self, session)
                case "/ext":
                    await scripts.extension(self, session)
                case "/command":
                    await scripts.command_permission(self, session)
                case "/setup":
                    await self._stream(session, session.describe_setup())
                case "/cancel-tool":
                    await scripts.cancellable_tool(self, session)
                case _:
                    await self._tour(session, len(prompt) - 1)
            await self._send(
                session,
                UsageUpdate(used=12_345, size=200_000, cost=Cost(amount=0.01, currency="USD")),
            )
            await self._mark_cursor(session)
            usage = Usage(total_tokens=1500, input_tokens=1200, output_tokens=300)
            await self._send(
                session,
                IdleStateSessionUpdate(stop_reason="end_turn", usage=usage, background=background),
            )
        except asyncio.CancelledError:
            await self._send(session, IdleStateSessionUpdate(stop_reason="cancelled"))

    async def _mark_cursor(self, session: DemoSession) -> None:
        """Offer a fork point after the last agent message of the turn."""
        last = next(
            (
                u
                for u in reversed(session.history)
                if isinstance(u, AgentMessageChunk | AgentMessage)
            ),
            None,
        )
        if last is None:
            return
        cursor_id = f"cursor-{len(session.cursors) + 1}"
        session.cursors[cursor_id] = len(session.history)
        await self._send(
            session,
            CursorUpdate(
                cursor_id=cursor_id,
                anchor=AgentMessageCursorAnchor(message_id=last.message_id, position="after"),
                capabilities=CursorCapabilities(fork=CursorForkCapabilities()),
            ),
        )

    async def _tour(self, session: DemoSession, attachments: int) -> None:
        cwd = Path(session.cwd)
        target = next(
            (cwd / name for name in ("README.md", "pyproject.toml") if (cwd / name).is_file()),
            cwd / "example.py",
        )
        if session.thinking:
            await self._stream(
                session,
                "The user wants a tour. I'll read a file, run a command, and propose an edit.",
                kind="thought",
            )
        if attachments:
            await self._send(
                session,
                Notice(severity="info", title=f"Received {attachments} attached resource(s)"),
            )
        plan = ["Read the project", "Inspect the directory", "Propose an edit"]
        await self._plan(session, plan, done=0)

        # 1. A read tool call
        read_id = "read-1"
        await self._send(
            session,
            ToolCallSessionUpdate(
                tool_call_id=read_id,
                name="read_file",
                title=f"Read {target.name}",
                kind="read",
                status="in_progress",
                locations=[ToolCallLocation(path=str(target), line=1)],
            ),
        )
        await anyio.sleep(_delay() * 5)
        try:
            head = "".join(target.read_text(encoding="utf-8").splitlines(keepends=True)[:5])
        except (OSError, UnicodeDecodeError):
            head = "(file not readable)"
        await self._send(
            session,
            ToolCallSessionUpdate(
                tool_call_id=read_id,
                status="completed",
                content=[Content(content=TextContent(text=head))],
            ),
        )
        await self._plan(session, plan, done=1)

        # 2. A command in an agent-owned terminal
        term_id = "term-1"
        await self._send(
            session,
            ToolCallSessionUpdate(
                tool_call_id="exec-1",
                name="shell",
                title="ls -la",
                kind="execute",
                status="in_progress",
                content=[Terminal(terminal_id=term_id)],
            ),
        )
        await self._send(
            session,
            TerminalUpdate(
                terminal_id=term_id,
                command="ls -la",
                cwd=session.cwd,
                capabilities=TerminalCapabilities(cancel=TerminalCancelCapabilities()),
            ),
        )
        for line in TERMINAL_LINES:
            await anyio.sleep(_delay() * 3)
            await self._send(session, TerminalOutputChunk.from_bytes(term_id, line.encode()))
        await self._send(
            session,
            TerminalUpdate(
                terminal_id=term_id, exit_status=TerminalExitStatus(exit_code=0), capabilities=None
            ),
        )
        await self._send(session, ToolCallSessionUpdate(tool_call_id="exec-1", status="completed"))
        await self._plan(session, plan, done=2)

        # 3. An edit behind a permission request
        edit = _edit_call(ToolCallUpdate, target)
        await self._send(session, _edit_call(ToolCallSessionUpdate, target))
        allowed = session.mode == "auto" or await self._ask(session, edit)
        status = "completed" if allowed else "failed"
        await self._send(session, ToolCallSessionUpdate(tool_call_id="edit-1", status=status))
        await self._plan(session, plan, done=3)
        await self._stream(session, ANSWER.format(file=target.name))

    async def _ask(self, session: DemoSession, tool_call: ToolCallUpdate) -> bool:
        response = await self.conn.request_permission(
            RequestPermissionRequest(
                session_id=session.session_id,
                title="Allow the demo agent to edit this file?",
                description="Nothing is written: the demo agent only pretends.",
                subject=ToolCallPermissionSubject(tool_call=tool_call),
                options=[
                    PermissionOption(option_id="allow", name="Allow", kind="allow_once"),
                    PermissionOption(
                        option_id="allow-always", name="Always allow", kind="allow_always"
                    ),
                    PermissionOption(option_id="reject", name="Reject", kind="reject_once"),
                ],
            )
        )
        outcome = response.outcome
        if isinstance(outcome, SelectedPermissionOutcome) and outcome.option_id == "allow-always":
            session.mode = "auto"
            await self._send(session, ConfigOptionUpdate(config_options=session.config_options()))
        return isinstance(outcome, SelectedPermissionOutcome) and outcome.option_id.startswith(
            "allow"
        )

    async def _plan(self, session: DemoSession, steps: list[str], done: int) -> None:
        entries = [
            PlanEntry(
                content=step,
                priority="high" if index == 0 else "medium",
                status="completed"
                if index < done
                else "in_progress"
                if index == done
                else "pending",
            )
            for index, step in enumerate(steps)
        ]
        await self._send(session, PlanUpdate(plan=PlanItems(plan_id="plan-1", entries=entries)))

    async def _stream(
        self, session: DemoSession, text: str, delay: float | None = None, kind: str = "message"
    ) -> None:
        message_id = f"{kind}-{uuid.uuid4()}"
        words = text.split(" ")
        for index, word in enumerate(words):
            chunk = TextContent(text=word if index == len(words) - 1 else word + " ")
            update: SessionUpdate = (
                AgentThoughtChunk(message_id=message_id, content=chunk)
                if kind == "thought"
                else AgentMessageChunk(message_id=message_id, content=chunk)
            )
            await self._send(session, update)
            await anyio.sleep(_delay() if delay is None else delay)

    async def _send(
        self, session: DemoSession, update: SessionUpdate, *, record: bool = True
    ) -> None:
        if record and not isinstance(update, RunningStateSessionUpdate | IdleStateSessionUpdate):
            session.history.append(update)
            session.updated_at = datetime.now(UTC).isoformat()
        notification = UpdateSessionNotification(session_id=session.session_id, update=update)
        await self.conn.session_update(notification)

    def _session(self, session_id: str) -> DemoSession:
        if (session := self.sessions.get(session_id)) is None:
            raise RequestError.session_not_found(session_id)
        return session

:fa-brands-github: Show source on GitHub