Skip to content

SessionState

🛈 DocStrings

Everything the client knows about one session.

Source code in src/acptui/protocol/state.py
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
@dataclass(eq=False)
class SessionState:
    """Everything the client knows about one session."""

    session_id: str
    cwd: str
    title: str | None = None
    entries: list[Entry] = field(default_factory=list)
    tool_calls: dict[str, ToolCallEntry] = field(default_factory=dict)
    terminals: dict[str, TerminalState] = field(default_factory=dict)
    plans: dict[str, PlanEntry] = field(default_factory=dict)
    commands: list[AvailableCommand] = field(default_factory=list)
    config_options: list[SessionConfigOption] = field(default_factory=list)
    usage: Usage | None = None
    activity: SessionActivity = "idle"
    stop_reason: str | None = None
    last_error: Error | None = None
    last_turn_usage: TurnUsage | None = None
    background: list[BackgroundWork] = field(default_factory=list)
    suggestions: list[PromptSuggestion] = field(default_factory=list)
    cursors: dict[str, CursorState] = field(default_factory=dict)
    subagents: dict[str, SubagentEntry] = field(default_factory=dict)
    updated_at: str | None = None
    parent_id: str | None = None
    """For a subagent session: the session that owns it."""
    replaying: bool = False
    _messages: dict[tuple[MessageRole, str], MessageEntry] = field(default_factory=dict)
    _compactions: dict[str, CompactionEntry] = field(default_factory=dict)

    @property
    def running(self) -> bool:
        """Whether the agent is working on a turn."""
        return self.activity in {"running", "requires_action"}

    # --- Forks --------------------------------------------------------------------

    def anchor_index(self, cursor: CursorState) -> int | None:
        """How many timeline entries come before ``cursor`` (None: it cannot be placed)."""
        anchor = cursor.anchor
        match anchor:
            case CursorToolCallAnchor(tool_call_id=tool_call_id):
                entry: Entry | None = self.tool_calls.get(tool_call_id)
            case CursorCompactionAnchor(compaction_id=compaction_id):
                entry = self._compactions.get(compaction_id)
            case (
                UserMessageCursorAnchor()
                | AgentMessageCursorAnchor()
                | AgentThoughtCursorAnchor()
                | SessionMessageCursorAnchor()
            ):
                role = ANCHOR_ROLES[anchor.type]
                entry = self._messages.get((role, anchor.message_id))
            case _:
                return None
        if entry is None or anchor is None or anchor.position not in {"before", "after"}:
            return None
        index = next((i for i, e in enumerate(self.entries) if e is entry), None)
        if index is None:
            return None
        return index if anchor.position == "before" else index + 1

    def forked(self, session_id: str, cursor: CursorState | None = None) -> SessionState:
        """A fork of this session: its timeline (up to ``cursor``), under ``session_id``.

        What the agent forked is its history; this is what the client shows of it. The
        entries are copies: the source session goes on independently.
        """
        cut = len(self.entries) if cursor is None else self.anchor_index(cursor)
        source = copy.deepcopy(self)
        entries = source.entries[: len(self.entries) if cut is None else cut]
        kept = {id(e) for e in entries}
        return SessionState(  # Untitled: the fork's title is the agent's to give
            session_id,
            self.cwd,
            entries=entries,
            tool_calls={k: v for k, v in source.tool_calls.items() if id(v) in kept},
            terminals=source.terminals,
            plans={k: v for k, v in source.plans.items() if id(v) in kept},
            commands=list(self.commands),
            config_options=list(self.config_options),
            usage=self.usage,
            subagents={k: v for k, v in source.subagents.items() if id(v) in kept},
            _messages={k: v for k, v in source._messages.items() if id(v) in kept},
            _compactions={k: v for k, v in source._compactions.items() if id(v) in kept},
        )

    # --- Local events -------------------------------------------------------------

    def add_local_user_message(self, blocks: Sequence[ContentBlock]) -> list[Change]:
        """Show a prompt the user just sent, before the agent acknowledges it."""
        entry = MessageEntry("user", None, list(blocks))
        self.entries.append(entry)
        return [EntryAdded(entry)]

    def acknowledge_user_message(self, entry: MessageEntry, message_id: str) -> None:
        """Record the ID the agent gave a local user message (``session/prompt`` result)."""
        if entry.message_id is None and ("user", message_id) not in self._messages:
            entry.message_id = message_id
            self._messages["user", message_id] = entry

    def add_notice(self, severity: str, title: str, description: str | None = None) -> list[Change]:
        """Add a client-side notice to the timeline."""
        entry = NoticeEntry(severity, title, description)
        self.entries.append(entry)
        return [EntryAdded(entry)]

    # --- Updates ------------------------------------------------------------------

    def apply(self, update: SessionUpdate) -> list[Change]:  # noqa: PLR0911
        """Apply one ``session/update``; returns what changed."""
        match update:
            case UserMessageChunk() | AgentMessageChunk() | AgentThoughtChunk():
                return self._message_chunk(update)
            case UserMessage() | AgentMessage() | AgentThought():
                return self._message_upsert(update)
            case ToolCallSessionUpdate():
                return self.apply_tool_call(update)
            case ToolCallContentChunk():
                return self._tool_call_chunk(update)
            case TerminalUpdate():
                return self._terminal_update(update)
            case TerminalOutputChunk():
                terminal = self._terminal(update.terminal_id)
                data = _decode(update.data)
                terminal.append(data)
                return [TerminalChanged(terminal, data)]
            case PlanUpdate():
                return self._plan_update(update.plan)
            case PlanRemoved():
                if (plan := self.plans.pop(update.plan_id, None)) is None:
                    return []
                plan.removed = True
                return [EntryChanged(plan)]
            case (
                RunningStateSessionUpdate()
                | IdleStateSessionUpdate()
                | RequiresActionStateSessionUpdate()
                | UnknownStateSessionUpdate()
                | OtherStateSessionUpdate()
            ):
                return self._state_update(update)
            case AvailableCommandsUpdate():
                self.commands = list(update.available_commands)
                return [SessionChanged("commands")]
            case ConfigOptionUpdate():
                self.config_options = list(update.config_options)
                return [SessionChanged("config")]
            case SessionInfoUpdate():
                if is_set(update.updated_at):
                    self.updated_at = update.updated_at
                if not is_set(update.title):
                    return []
                self.title = update.title
                return [SessionChanged("title")]
            case UsageUpdate():
                cost = self.usage.cost if self.usage is not None else None
                if is_set(update.cost):
                    cost = update.cost
                self.usage = Usage(update.used, update.size, cost)
                return [SessionChanged("usage")]
            case Notice():
                description = update.description if is_set(update.description) else None
                return self.add_notice(update.severity, update.title, description)
            case CompactionUpdate():
                return self._compaction_update(update)
            case CompactionSummaryChunk():
                compaction, changes = self._compaction(update.compaction_id)
                compaction.summary.append(update.content)
                return [*changes, EntryChanged(compaction)]
            case ReplayComplete():
                self.replaying = False
                return [SessionChanged("replay")]
            case PromptSuggestionsUpdate():
                self.suggestions = list(update.suggestions)
                return [SessionChanged("suggestions")]
            case CursorUpdate():
                return self._cursor_update(update)
            case SubagentUpdate():
                return self._subagent_update(update)
            case SessionMessage():
                return self._session_message(update)
            case SessionMessageChunk():
                entry, created = self._message_entry("session", update.message_id)
                entry.blocks.append(update.content)
                text = update.content.text if isinstance(update.content, TextContent) else None
                return [EntryAdded(entry) if created else EntryChanged(entry, appended=text)]
            case _:
                # Custom (``_``-prefixed) or future update kinds: nothing to show.
                return []

    def _cursor_update(self, update: CursorUpdate) -> list[Change]:
        cursor = self.cursors.get(update.cursor_id)
        if cursor is None:
            cursor = self.cursors[update.cursor_id] = CursorState(update.cursor_id)
        if is_set(update.anchor) and update.anchor is not None and cursor.anchor is None:
            cursor.anchor = update.anchor  # fixed after the first update
        if is_set(update.capabilities):
            caps = update.capabilities
            cursor.can_fork = caps is not None and is_set(caps.fork) and caps.fork is not None
        return [SessionChanged("cursors")]

    def _subagent_update(self, update: SubagentUpdate) -> list[Change]:
        entry = self.subagents.get(update.session_id)
        created = entry is None
        if entry is None:
            entry = self.subagents[update.session_id] = SubagentEntry(update.session_id)
            self.entries.append(entry)
        if is_set(update.title):
            entry.title = update.title
        if is_set(update.description):
            entry.description = update.description
        if is_set(update.cwd):
            entry.cwd = update.cwd
        if is_set(update.additional_directories):
            entry.additional_directories = list(update.additional_directories or ())
        if is_set(update.capabilities):
            caps = update.capabilities
            entry.can_cancel = caps is not None and is_set(caps.cancel) and caps.cancel is not None
        if is_set(update.state):
            entry.activity = update.state.state if update.state is not None else "unknown"
        return [EntryAdded(entry) if created else EntryChanged(entry)]

    def _session_message(self, update: SessionMessage) -> list[Change]:
        entry, created = self._message_entry("session", update.message_id)
        if is_set(update.sender_session_id):
            entry.sender_session_id = update.sender_session_id
        if is_set(update.recipient_session_id):
            entry.recipient_session_id = update.recipient_session_id
        if is_set(update.content):
            entry.blocks = list(update.content or ())
        return [EntryAdded(entry) if created else EntryChanged(entry)]

    def set_config_options(self, options: Sequence[SessionConfigOption]) -> list[Change]:
        """Replace the config options (e.g. from a ``session/set_config_option`` result)."""
        self.config_options = list(options)
        return [SessionChanged("config")]

    def set_commands(self, commands: Sequence[AvailableCommand]) -> list[Change]:
        """Replace the available commands (e.g. from a ``session/new`` result)."""
        self.commands = list(commands)
        return [SessionChanged("commands")]

    def _message_entry(self, role: MessageRole, message_id: str) -> tuple[MessageEntry, bool]:
        """The message with this ID, creating it if needed; also whether it is new.

        A user message the agent reports first (before ``session/prompt`` returned)
        adopts the oldest local user message still waiting for its ID.
        """
        if (entry := self._messages.get((role, message_id))) is not None:
            return entry, False
        if role == "user" and not self.replaying:
            pending = next(
                (
                    e
                    for e in self.entries
                    if isinstance(e, MessageEntry) and e.role == "user" and e.message_id is None
                ),
                None,
            )
            if pending is not None:
                pending.message_id = message_id
                pending.blocks.clear()
                self._messages[role, message_id] = pending
                return pending, False
        entry = MessageEntry(role, message_id)
        self._messages[role, message_id] = entry
        self.entries.append(entry)
        return entry, True

    def _message_chunk(
        self, update: UserMessageChunk | AgentMessageChunk | AgentThoughtChunk
    ) -> list[Change]:
        role: MessageRole = (
            "user"
            if isinstance(update, UserMessageChunk)
            else "agent"
            if isinstance(update, AgentMessageChunk)
            else "thought"
        )
        entry, created = self._message_entry(role, update.message_id)
        replaced = not created and role == "user" and not entry.blocks
        entry.blocks.append(update.content)
        if created:
            return [EntryAdded(entry)]
        if replaced or not isinstance(update.content, TextContent):
            return [EntryChanged(entry)]
        return [EntryChanged(entry, appended=update.content.text)]

    def _message_upsert(self, update: UserMessage | AgentMessage | AgentThought) -> list[Change]:
        role: MessageRole = (
            "user"
            if isinstance(update, UserMessage)
            else "agent"
            if isinstance(update, AgentMessage)
            else "thought"
        )
        entry, created = self._message_entry(role, update.message_id)
        if is_set(update.content):
            entry.blocks = list(update.content or ())
        return [EntryAdded(entry) if created else EntryChanged(entry)]

    def apply_tool_call(self, update: ToolCallUpdate) -> list[Change]:
        """Apply a tool call upsert (also used for tool calls in permission requests)."""
        entry = self.tool_calls.get(update.tool_call_id)
        if entry is None:
            entry = ToolCallEntry(update.tool_call_id)
            entry.apply(update)
            self.tool_calls[update.tool_call_id] = entry
            self.entries.append(entry)
            return [EntryAdded(entry)]
        entry.apply(update)
        return [EntryChanged(entry)]

    def _tool_call_chunk(self, update: ToolCallContentChunk) -> list[Change]:
        entry = self.tool_calls.get(update.tool_call_id)
        if entry is None:
            entry = ToolCallEntry(update.tool_call_id, content=[update.content])
            self.tool_calls[update.tool_call_id] = entry
            self.entries.append(entry)
            return [EntryAdded(entry)]
        entry.content.append(update.content)
        return [EntryChanged(entry)]

    def _terminal(self, terminal_id: str) -> TerminalState:
        if (terminal := self.terminals.get(terminal_id)) is None:
            terminal = self.terminals[terminal_id] = TerminalState(terminal_id)
        return terminal

    def _terminal_update(self, update: TerminalUpdate) -> list[Change]:
        terminal = self._terminal(update.terminal_id)
        if is_set(update.command):
            terminal.command = update.command
        if is_set(update.cwd):
            terminal.cwd = update.cwd
        if is_set(update.output):
            terminal.output = bytearray()
            if update.output is not None:
                terminal.append(_decode(update.output.data))
        if is_set(update.exit_status):
            terminal.exit_status = update.exit_status
        if is_set(update.size):
            terminal.size = update.size
        if is_set(update.capabilities):
            caps = update.capabilities
            terminal.can_cancel = (
                caps is not None and is_set(caps.cancel) and caps.cancel is not None
            )
        return [TerminalChanged(terminal)]

    def _plan_update(self, content: PlanItems | PlanMarkdown | object) -> list[Change]:
        if not isinstance(content, PlanItems | PlanMarkdown):
            return []
        plan = self.plans.get(content.plan_id)
        if plan is None:
            plan = self.plans[content.plan_id] = PlanEntry(content.plan_id, content)
            self.entries.append(plan)
            return [EntryAdded(plan)]
        plan.content = content
        return [EntryChanged(plan)]

    def _state_update(
        self,
        update: RunningStateSessionUpdate
        | IdleStateSessionUpdate
        | RequiresActionStateSessionUpdate
        | UnknownStateSessionUpdate
        | OtherStateSessionUpdate,
    ) -> list[Change]:
        changes: list[Change] = []
        if is_set(update.background):
            self.background = list(update.background or ())
        match update:
            case RunningStateSessionUpdate():
                self.activity = "running"
                self.stop_reason = None
                self.last_error = None
            case RequiresActionStateSessionUpdate():
                self.activity = "requires_action"
            case UnknownStateSessionUpdate() | OtherStateSessionUpdate():
                self.activity = "unknown"
            case IdleStateSessionUpdate():
                self.activity = "idle"
                stop = update.stop_reason if is_set(update.stop_reason) else None
                self.stop_reason = stop
                error = update.error if is_set(update.error) else None
                self.last_error = error
                if is_set(update.usage) and update.usage is not None:
                    self.last_turn_usage = update.usage
                if stop == "error" or error is not None:
                    detail = error.message if error is not None else None
                    changes += self.add_notice("error", "The turn failed", detail)
                elif stop == "cancelled":
                    changes += self.add_notice("warning", "Cancelled")
                elif stop == "refusal":
                    changes += self.add_notice("warning", "The agent refused to continue")
                elif stop in {"max_tokens", "max_turn_requests"}:
                    changes += self.add_notice("warning", f"Turn stopped: {stop.replace('_', ' ')}")
        return [SessionChanged("activity"), *changes]

    def _compaction(self, compaction_id: str) -> tuple[CompactionEntry, list[Change]]:
        if (entry := self._compactions.get(compaction_id)) is not None:
            return entry, []
        entry = self._compactions[compaction_id] = CompactionEntry(compaction_id, "in_progress")
        self.entries.append(entry)
        return entry, [EntryAdded(entry)]

    def _compaction_update(self, update: CompactionUpdate) -> list[Change]:
        entry, changes = self._compaction(update.compaction_id)
        if is_set(update.status):
            entry.status = update.status if update.status is not None else "in_progress"
        if is_set(update.summary):
            entry.summary = list(update.summary or ())
        if is_set(update.error):
            entry.error = update.error
        return changes or [EntryChanged(entry)]

parent_id class-attribute instance-attribute

parent_id: str | None = None

For a subagent session: the session that owns it.

running property

running: bool

Whether the agent is working on a turn.

acknowledge_user_message

acknowledge_user_message(entry: MessageEntry, message_id: str) -> None

Record the ID the agent gave a local user message (session/prompt result).

Source code in src/acptui/protocol/state.py
def acknowledge_user_message(self, entry: MessageEntry, message_id: str) -> None:
    """Record the ID the agent gave a local user message (``session/prompt`` result)."""
    if entry.message_id is None and ("user", message_id) not in self._messages:
        entry.message_id = message_id
        self._messages["user", message_id] = entry

add_local_user_message

add_local_user_message(blocks: Sequence[ContentBlock]) -> list[Change]

Show a prompt the user just sent, before the agent acknowledges it.

Source code in src/acptui/protocol/state.py
def add_local_user_message(self, blocks: Sequence[ContentBlock]) -> list[Change]:
    """Show a prompt the user just sent, before the agent acknowledges it."""
    entry = MessageEntry("user", None, list(blocks))
    self.entries.append(entry)
    return [EntryAdded(entry)]

add_notice

add_notice(severity: str, title: str, description: str | None = None) -> list[Change]

Add a client-side notice to the timeline.

Source code in src/acptui/protocol/state.py
def add_notice(self, severity: str, title: str, description: str | None = None) -> list[Change]:
    """Add a client-side notice to the timeline."""
    entry = NoticeEntry(severity, title, description)
    self.entries.append(entry)
    return [EntryAdded(entry)]

anchor_index

anchor_index(cursor: CursorState) -> int | None

How many timeline entries come before cursor (None: it cannot be placed).

Source code in src/acptui/protocol/state.py
def anchor_index(self, cursor: CursorState) -> int | None:
    """How many timeline entries come before ``cursor`` (None: it cannot be placed)."""
    anchor = cursor.anchor
    match anchor:
        case CursorToolCallAnchor(tool_call_id=tool_call_id):
            entry: Entry | None = self.tool_calls.get(tool_call_id)
        case CursorCompactionAnchor(compaction_id=compaction_id):
            entry = self._compactions.get(compaction_id)
        case (
            UserMessageCursorAnchor()
            | AgentMessageCursorAnchor()
            | AgentThoughtCursorAnchor()
            | SessionMessageCursorAnchor()
        ):
            role = ANCHOR_ROLES[anchor.type]
            entry = self._messages.get((role, anchor.message_id))
        case _:
            return None
    if entry is None or anchor is None or anchor.position not in {"before", "after"}:
        return None
    index = next((i for i, e in enumerate(self.entries) if e is entry), None)
    if index is None:
        return None
    return index if anchor.position == "before" else index + 1

apply

apply(update: SessionUpdate) -> list[Change]

Apply one session/update; returns what changed.

Source code in src/acptui/protocol/state.py
def apply(self, update: SessionUpdate) -> list[Change]:  # noqa: PLR0911
    """Apply one ``session/update``; returns what changed."""
    match update:
        case UserMessageChunk() | AgentMessageChunk() | AgentThoughtChunk():
            return self._message_chunk(update)
        case UserMessage() | AgentMessage() | AgentThought():
            return self._message_upsert(update)
        case ToolCallSessionUpdate():
            return self.apply_tool_call(update)
        case ToolCallContentChunk():
            return self._tool_call_chunk(update)
        case TerminalUpdate():
            return self._terminal_update(update)
        case TerminalOutputChunk():
            terminal = self._terminal(update.terminal_id)
            data = _decode(update.data)
            terminal.append(data)
            return [TerminalChanged(terminal, data)]
        case PlanUpdate():
            return self._plan_update(update.plan)
        case PlanRemoved():
            if (plan := self.plans.pop(update.plan_id, None)) is None:
                return []
            plan.removed = True
            return [EntryChanged(plan)]
        case (
            RunningStateSessionUpdate()
            | IdleStateSessionUpdate()
            | RequiresActionStateSessionUpdate()
            | UnknownStateSessionUpdate()
            | OtherStateSessionUpdate()
        ):
            return self._state_update(update)
        case AvailableCommandsUpdate():
            self.commands = list(update.available_commands)
            return [SessionChanged("commands")]
        case ConfigOptionUpdate():
            self.config_options = list(update.config_options)
            return [SessionChanged("config")]
        case SessionInfoUpdate():
            if is_set(update.updated_at):
                self.updated_at = update.updated_at
            if not is_set(update.title):
                return []
            self.title = update.title
            return [SessionChanged("title")]
        case UsageUpdate():
            cost = self.usage.cost if self.usage is not None else None
            if is_set(update.cost):
                cost = update.cost
            self.usage = Usage(update.used, update.size, cost)
            return [SessionChanged("usage")]
        case Notice():
            description = update.description if is_set(update.description) else None
            return self.add_notice(update.severity, update.title, description)
        case CompactionUpdate():
            return self._compaction_update(update)
        case CompactionSummaryChunk():
            compaction, changes = self._compaction(update.compaction_id)
            compaction.summary.append(update.content)
            return [*changes, EntryChanged(compaction)]
        case ReplayComplete():
            self.replaying = False
            return [SessionChanged("replay")]
        case PromptSuggestionsUpdate():
            self.suggestions = list(update.suggestions)
            return [SessionChanged("suggestions")]
        case CursorUpdate():
            return self._cursor_update(update)
        case SubagentUpdate():
            return self._subagent_update(update)
        case SessionMessage():
            return self._session_message(update)
        case SessionMessageChunk():
            entry, created = self._message_entry("session", update.message_id)
            entry.blocks.append(update.content)
            text = update.content.text if isinstance(update.content, TextContent) else None
            return [EntryAdded(entry) if created else EntryChanged(entry, appended=text)]
        case _:
            # Custom (``_``-prefixed) or future update kinds: nothing to show.
            return []

apply_tool_call

apply_tool_call(update: ToolCallUpdate) -> list[Change]

Apply a tool call upsert (also used for tool calls in permission requests).

Source code in src/acptui/protocol/state.py
def apply_tool_call(self, update: ToolCallUpdate) -> list[Change]:
    """Apply a tool call upsert (also used for tool calls in permission requests)."""
    entry = self.tool_calls.get(update.tool_call_id)
    if entry is None:
        entry = ToolCallEntry(update.tool_call_id)
        entry.apply(update)
        self.tool_calls[update.tool_call_id] = entry
        self.entries.append(entry)
        return [EntryAdded(entry)]
    entry.apply(update)
    return [EntryChanged(entry)]

forked

forked(session_id: str, cursor: CursorState | None = None) -> SessionState

A fork of this session: its timeline (up to cursor), under session_id.

What the agent forked is its history; this is what the client shows of it. The entries are copies: the source session goes on independently.

Source code in src/acptui/protocol/state.py
def forked(self, session_id: str, cursor: CursorState | None = None) -> SessionState:
    """A fork of this session: its timeline (up to ``cursor``), under ``session_id``.

    What the agent forked is its history; this is what the client shows of it. The
    entries are copies: the source session goes on independently.
    """
    cut = len(self.entries) if cursor is None else self.anchor_index(cursor)
    source = copy.deepcopy(self)
    entries = source.entries[: len(self.entries) if cut is None else cut]
    kept = {id(e) for e in entries}
    return SessionState(  # Untitled: the fork's title is the agent's to give
        session_id,
        self.cwd,
        entries=entries,
        tool_calls={k: v for k, v in source.tool_calls.items() if id(v) in kept},
        terminals=source.terminals,
        plans={k: v for k, v in source.plans.items() if id(v) in kept},
        commands=list(self.commands),
        config_options=list(self.config_options),
        usage=self.usage,
        subagents={k: v for k, v in source.subagents.items() if id(v) in kept},
        _messages={k: v for k, v in source._messages.items() if id(v) in kept},
        _compactions={k: v for k, v in source._compactions.items() if id(v) in kept},
    )

set_commands

set_commands(commands: Sequence[AvailableCommand]) -> list[Change]

Replace the available commands (e.g. from a session/new result).

Source code in src/acptui/protocol/state.py
def set_commands(self, commands: Sequence[AvailableCommand]) -> list[Change]:
    """Replace the available commands (e.g. from a ``session/new`` result)."""
    self.commands = list(commands)
    return [SessionChanged("commands")]

set_config_options

set_config_options(options: Sequence[SessionConfigOption]) -> list[Change]

Replace the config options (e.g. from a session/set_config_option result).

Source code in src/acptui/protocol/state.py
def set_config_options(self, options: Sequence[SessionConfigOption]) -> list[Change]:
    """Replace the config options (e.g. from a ``session/set_config_option`` result)."""
    self.config_options = list(options)
    return [SessionChanged("config")]

:fa-brands-github: Show source on GitHub