Skip to content

ACP

octomate.tentacles.acp.channel

The inbound ACP channel and its connection ownership.

AcpChannelTentacle dataclass

Bases: Tentacle[None, None]

Expose the ACP API and track attached public sessions.

The Octomate host mounts the router at connect time. Each broker dispatches kicks and reads the nerve for its WebSocket connection, so this API channel uses the base tentacle lifecycle rather than the IM channel's ink and siphon.

Source code in octomate/tentacles/acp/channel.py
@dataclass
class AcpChannelTentacle(Tentacle[None, None]):
    """Expose the ACP API and track attached public sessions.

    The Octomate host mounts the router at connect time. Each broker dispatches
    kicks and reads the nerve for its WebSocket connection, so this API channel
    uses the base tentacle lifecycle rather than the IM channel's ink and siphon.
    """

    type: ClassVar[str] = "acp"

    clients: dict[UUID7, AcpBroker] = field(
        default_factory=dict, init=False
    )  # Public threads attached to a connection.

    def routers(self) -> tuple[APIRouter, ...]:
        # The router's authentication dependency imports this class.
        from octomate.tentacles.acp.routes import build_acp_router

        return (build_acp_router(self),)

type class-attribute

type: str = 'acp'

clients class-attribute instance-attribute

clients: dict[UUID7, AcpBroker] = field(
    default_factory=dict, init=False
)

routers

routers() -> tuple[APIRouter, ...]
Source code in octomate/tentacles/acp/channel.py
def routers(self) -> tuple[APIRouter, ...]:
    # The router's authentication dependency imports this class.
    from octomate.tentacles.acp.routes import build_acp_router

    return (build_acp_router(self),)

octomate.tentacles.acp.base

Run outbound ACP providers through the agent interface.

logger module-attribute

logger = logging.getLogger(__name__)

AcpAgentTentacle

Bases: AgentTentacle[str, None]

Execute turns through an installed ACP harness.

Outbound runs use the thread and conversation supplied by the reflex, with the provider session ID stored on that conversation. Each turn holds its managed workspace, provider connection, and MCP credentials until the provider has stopped.

Startup discovers models and their reasoning levels from an unprompted session, selecting each model to read its current thought_level choices. Real sessions validate the chosen model and effort again before submitting their prompt.

Source code in octomate/tentacles/acp/base.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
class AcpAgentTentacle(AgentTentacle[str, None]):
    """Execute turns through an installed ACP harness.

    Outbound runs use the thread and conversation supplied by the reflex, with
    the provider session ID stored on that conversation. Each turn holds its
    managed workspace, provider connection, and MCP credentials until the
    provider has stopped.

    Startup discovers models and their reasoning levels from an unprompted session,
    selecting each model to read its current thought_level choices. Real sessions
    validate the chosen model and effort again before submitting their prompt.
    """

    type: ClassVar[str] = "acp"
    in_process: ClassVar[bool] = True
    config: AcpAgentConfig
    ink: AcpInk
    provider_permission_mode: str | None = None

    def __init__(
        self,
        id: str,
        octomate: Octomate,
        *,
        config: AcpAgentConfig,
        auth: AuthManager | None,
        habitats: HabitatManager,
    ) -> None:
        super().__init__(
            id=id,
            octomate=octomate,
            nerves=octomate.nerves,
            commands=octomate.commands,
            projects=octomate.projects,
            threads=octomate.threads,
            files=octomate.files,
            auth=auth,
            habitats=habitats,
        )
        self.ink = AcpInk()
        self.config = config
        self.gateway = config.gateway
        self.pendings = {}
        self.conversations = octomate.conversations
        self.workspaces = octomate.workspaces
        self.models = {}

    async def __aenter__(self) -> Self:
        """Discover a harness catalog without prompting or creating Octomate history."""
        if self.habitats.config.type == HabitatType.workspace:
            logger.warning(
                "ACP agent %s uses a workspace habitat: only filesystem and terminal "
                "operations delegated to the client are confined. The provider and "
                "its direct tools remain on the host. ACP cannot verify delegation; "
                "confirm provider support or choose a native or hosted habitat.",
                self.id,
            )

        async def handle(
            method: str, params: JsonValue | None, notification: bool
        ) -> JsonValue | None:
            if notification:
                return None
            raise acp.RequestError.method_not_found(method)

        with TemporaryDirectory(prefix="octomate-acp-") as cwd:
            async with NativeAcpClient.connect(
                self.config.provider,
                handle,
                schema.InitializeRequest(
                    protocol_version=acp.PROTOCOL_VERSION,
                    client_capabilities=schema.ClientCapabilities(),
                ),
            ) as client:
                session = await client.new_session(
                    schema.NewSessionRequest(cwd=cwd, mcp_servers=[])
                )
                self.permission_modes = session.permission_modes
                self.provider_permission_mode = session.permission_mode
                if self.config.permission_mode is not None:
                    self.check_permission_mode(self.config.permission_mode)
                self.models = (
                    {option.value: option.value for option in session.models}
                    if session.model_option is not None
                    else {"default": "default"}
                )
                self.default_model = (
                    session.model_option.current_value
                    if session.model_option is not None
                    else None
                )
                abilities = {
                    option.value: option.description or option.name
                    for option in session.models
                }
                self.model_meta = {}
                for model in self.models:
                    await session.select_model(client.connection, model)
                    self.model_meta[model] = ModelMeta(
                        abilities.get(model, self.description), efforts=session.efforts
                    )
                capabilities = client.initialization.agent_capabilities
                if (
                    capabilities is not None
                    and capabilities.session_capabilities is not None
                    and capabilities.session_capabilities.close is not None
                ):
                    # Stop background session updates before closing the transport.
                    await request_model(
                        client.connection,
                        acp.AGENT_METHODS["session_close"],
                        schema.CloseSessionRequest(session_id=session.session_id),
                        schema.CloseSessionResponse,
                    )
        return await super().__aenter__()

    @property
    def default_permission_mode(self) -> str | None:
        return self.config.permission_mode or self.provider_permission_mode

    async def run(
        self,
        user_prompt: str | Sequence[UserContent] | None = None,
        *,
        conversation_address: ChannelAddress,
        invocation: Invocation,
        source_thread_address: ChannelAddress | None = None,
        source_thread_message_ids: Sequence[UUID7] | None = None,
        run_name: str | None = None,
        output_type: OutputSpec[RunOutputDataT] | None = None,
        deferred_tool_results: DeferredToolResults | None = None,
        deferred_suspender: DeferredSuspender | None = None,
        model: Model | KnownModelName | str | None = None,
        effort: str | None = None,
        interactive: bool = True,
        instructions: AgentInstructions[None] = None,
        deps: None = None,
        model_settings: AgentModelSettings[None] | None = None,
        usage_limits: UsageLimits | None = None,
        metadata: AgentMetadata[None] | None = None,
        output_retries: int | None = None,
        infer_name: bool = True,
        toolsets: Sequence[AbstractToolset[None]] | None = None,
        builtin_tools: Sequence[AgentNativeTool[None]] | None = None,
        event_stream_handler: EventStreamHandler[None] | None = None,
        capabilities: Sequence[AgentCapability[None]] | None = None,
        spec: AgentSpecInput | None = None,
    ) -> AgentRunResult[str | RunOutputDataT]:
        """Collect the same agent stream used by the reflex."""
        if event_stream_handler is not None:
            raise ValueError("Use run_stream_events to observe outbound ACP events")
        result: AgentRunResult[str | RunOutputDataT] | None = None
        async with self.run_stream_events(
            user_prompt,
            conversation_address=conversation_address,
            invocation=invocation,
            source_thread_address=source_thread_address,
            source_thread_message_ids=source_thread_message_ids,
            run_name=run_name,
            output_type=output_type,
            deferred_tool_results=deferred_tool_results,
            deferred_suspender=deferred_suspender,
            model=model,
            effort=effort,
            interactive=interactive,
            instructions=instructions,
            deps=deps,
            model_settings=model_settings,
            usage_limits=usage_limits,
            metadata=metadata,
            output_retries=output_retries,
            infer_name=infer_name,
            toolsets=toolsets,
            builtin_tools=builtin_tools,
            capabilities=capabilities,
            spec=spec,
        ) as events:
            async for event in events:
                if isinstance(event, AgentRunResultEvent):
                    result = event.result
        if result is None:
            raise RuntimeError("The ACP stream ended without a result")
        return result

    def run_stream_events(
        self,
        user_prompt: str | Sequence[UserContent] | None = None,
        *,
        conversation_address: ChannelAddress,
        invocation: Invocation,
        source_thread_address: ChannelAddress | None = None,
        source_thread_message_ids: Sequence[UUID7] | None = None,
        run_name: str | None = None,
        output_type: OutputSpec[RunOutputDataT] | None = None,
        deferred_tool_results: DeferredToolResults | None = None,
        deferred_suspender: DeferredSuspender | None = None,
        model: Model | KnownModelName | str | None = None,
        effort: str | None = None,
        interactive: bool = True,
        instructions: AgentInstructions[None] = None,
        deps: None = None,
        model_settings: AgentModelSettings[None] | None = None,
        usage_limits: UsageLimits | None = None,
        metadata: AgentMetadata[None] | None = None,
        output_retries: int | None = None,
        infer_name: bool = True,
        toolsets: Sequence[AbstractToolset[None]] | None = None,
        builtin_tools: Sequence[AgentNativeTool[None]] | None = None,
        capabilities: Sequence[AgentCapability[None]] | None = None,
        spec: AgentSpecInput | None = None,
    ) -> ReactEventStream[str | RunOutputDataT]:
        """Run the supplied prompt in this agent's conversation and workspace."""
        if (
            any(
                value is not None
                for value in (
                    output_type,
                    deferred_tool_results,
                    instructions,
                    model_settings,
                    usage_limits,
                    metadata,
                    output_retries,
                    toolsets,
                    builtin_tools,
                    spec,
                )
            )
            or capabilities
        ):
            raise ValueError(
                "Outbound ACP accepts text prompts, model and effort selection"
            )
        if model is not None and not isinstance(model, str):
            raise ValueError("Outbound ACP requires a model identifier")
        return ReactEventStream(
            self.stream(
                user_prompt,
                conversation_address,
                invocation,
                source_thread_address,
                source_thread_message_ids,
                run_name,
                deferred_suspender if interactive else None,
                self.resolve_model(model),
                effort,
            )
        )

    async def stream(
        self,
        user_prompt: str | Sequence[UserContent] | None,
        address: ChannelAddress,
        invocation: Invocation,
        source_address: ChannelAddress | None,
        source_message_ids: Sequence[UUID7] | None,
        run_name: str | None,
        suspender: DeferredSuspender | None,
        model: str | None,
        effort: str | None,
    ) -> AsyncGenerator[ReactStreamEvent[str]]:
        provider = self.config.provider
        conversation = invocation.conversation
        self.check_conversation(conversation, thread_id=invocation.thread_id)
        if isinstance(user_prompt, str):
            text = user_prompt
        else:
            parts: list[str] = []
            for part in user_prompt or []:
                if not isinstance(part, str | TextContent):
                    raise ValueError("Outbound ACP currently accepts only text")
                parts.append(part.content if isinstance(part, TextContent) else part)
            text = "\n".join(parts)
        if not text.strip():
            raise ValueError("ACP requires a non-empty text prompt")
        effort = await self.resolve_effort(conversation, model=model, effort=effort)
        sender = await self.octomate.users.profile(
            address.channel_tentacle_id, address.user_id
        )
        if sender is None or invocation.owner_id is None:
            raise ValueError("Outbound ACP requires a registered user")
        updates: asyncio.Queue[
            StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
        ] = asyncio.Queue()
        session_id: str | None = None
        env = invocation.environment
        if isinstance(invocation.habitat, HostedHabitat):
            config = invocation.workspace.volumes.get("config")
            if config is None:
                raise ValueError("Managed ACP requires a configuration volume")
            env["HOME"] = str(invocation.habitat.path(config))

        async def handle(
            method: str, params: JsonValue | None, notification: bool
        ) -> JsonValue | None:
            if notification:
                return None
            if method == "session/request_permission":
                request = schema.RequestPermissionRequest.model_validate(params)
            elif method == "elicitation/create":
                if suspender is None:
                    raise acp.RequestError.invalid_params(
                        {"reason": "Form elicitation was not negotiated"}
                    )
                request = schema.CreateFormSessionElicitationRequest.model_validate(
                    params
                )
                if request.requested_schema.type != "object":
                    raise acp.RequestError.invalid_params(
                        {"reason": "ACP forms require an object schema"}
                    )
            else:
                if client_workspace is not None:
                    return await client_workspace.handle(method, params)
                raise acp.RequestError.method_not_found(method)
            if request.session_id != session_id:
                raise acp.RequestError.invalid_params({"reason": "Unknown session"})
            response = (
                await self.permission(request, suspender, updates)
                if isinstance(request, schema.RequestPermissionRequest)
                else await self.elicit(request, suspender, updates)
            )
            return json_value_adapter.validate_python(
                response.model_dump(mode="json", by_alias=True, exclude_none=True)
            )

        async with (
            workspace(invocation.habitat, str(invocation.cwd)) as client_workspace,
            AsyncExitStack() as credentials,
            NativeAcpClient.connect(
                provider,
                handle,
                schema.InitializeRequest(
                    protocol_version=acp.PROTOCOL_VERSION,
                    client_capabilities=schema.ClientCapabilities(
                        fs=schema.FileSystemCapabilities(
                            read_text_file=True, write_text_file=True
                        )
                        if client_workspace is not None
                        else None,
                        terminal=client_workspace is not None,
                        elicitation=schema.ElicitationCapabilities(
                            form=schema.ElicitationFormCapabilities()
                        )
                        if suspender is not None
                        else None,
                    ),
                ),
                habitat=invocation.habitat,
                cwd=str(invocation.cwd),
                env=env,
            ) as client,
        ):
            if client_workspace is not None:
                client_workspace.session_id = conversation.external_id
            mcp_servers = await credentials.enter_async_context(
                self.mcp_servers(
                    client,
                    invocation.owner_id,
                    conversation.id,
                    habitat=invocation.habitat,
                )
            )
            if conversation.external_id is None:
                native = await client.new_session(
                    schema.NewSessionRequest(
                        cwd=str(invocation.cwd), mcp_servers=[*mcp_servers]
                    )
                )
                session_id = native.session_id
                await self.conversations.set_external_id(conversation, session_id)
            else:
                capabilities = client.initialization.agent_capabilities
                session_id = conversation.external_id
                response: schema.LoadSessionResponse | schema.ResumeSessionResponse
                if capabilities is not None and capabilities.load_session:
                    response = await request_model(
                        client.connection,
                        acp.AGENT_METHODS["session_load"],
                        schema.LoadSessionRequest(
                            session_id=session_id,
                            cwd=str(invocation.cwd),
                            mcp_servers=[*mcp_servers],
                        ),
                        schema.LoadSessionResponse,
                    )
                elif (
                    capabilities is not None
                    and capabilities.session_capabilities is not None
                    and capabilities.session_capabilities.resume is not None
                ):
                    response = await request_model(
                        client.connection,
                        acp.AGENT_METHODS["session_resume"],
                        schema.ResumeSessionRequest(
                            session_id=session_id,
                            cwd=str(invocation.cwd),
                            mcp_servers=[*mcp_servers],
                        ),
                        schema.ResumeSessionResponse,
                    )
                else:
                    raise ValueError("The ACP provider cannot reopen this conversation")
                native = NativeAcpSession(
                    provider, str(invocation.cwd), session_id, response
                )
            if client_workspace is not None:
                client_workspace.session_id = session_id
            selected_model = await native.select_model(client.connection, model)
            await native.select_effort(client.connection, effort)
            await native.select_mode(
                client.connection,
                conversation.permission_mode or self.config.permission_mode,
            )
            request = schema.PromptRequest(
                session_id=session_id, prompt=[acp.text_block(text)]
            )
            async with (
                self.driving(session_id),
                aclosing(
                    self.invoke(
                        client,
                        invocation,
                        request,
                        address,
                        sender,
                        source_address,
                        source_message_ids,
                        run_name,
                        updates,
                        selected_model,
                    )
                ) as events,
            ):
                async for event in events:
                    yield event

    async def permission(
        self,
        request: schema.RequestPermissionRequest,
        suspender: DeferredSuspender | None,
        updates: asyncio.Queue[
            StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
        ],
    ) -> schema.RequestPermissionResponse:
        """Route provider approvals through the existing live deferred-action flow."""
        if suspender is None:
            return schema.RequestPermissionResponse(
                outcome=schema.DeniedOutcome(outcome="cancelled")
            )
        # A boolean card cannot express a provider's remembered scope or distinguish
        # several options of the same kind. Present its exact options in that case.
        simple = len({option.kind for option in request.options}) == len(
            request.options
        ) and all(
            option.kind in {"allow_once", "reject_once"} for option in request.options
        )
        names = [option.name for option in request.options]
        labels = {
            option.name
            if names.count(option.name) == 1
            else f"{option.name} ({option.option_id})": option
            for option in request.options
        }
        call = ToolCallPart(
            tool_name=request.tool_call.title or "ACP tool",
            tool_call_id=request.tool_call.tool_call_id,
            args=request.tool_call.model_dump_json(by_alias=True, exclude_none=True)
            if simple
            else {
                "questions": [
                    {
                        "question": f"Permission: {request.tool_call.title or 'ACP tool'}",
                        "choices": list(labels)[:MAX_QUESTION_CHOICES],
                        "hint": request.tool_call.model_dump_json(
                            by_alias=True, exclude_none=True
                        )
                        + "\nOptions: "
                        + "; ".join(labels),
                    }
                ]
            },
        )
        batch = await self.await_human(
            DeferredToolRequests(approvals=[call])
            if simple
            else DeferredToolRequests(calls=[call]),
            suspender,
            updates,
        )
        option: schema.PermissionOption | None = None
        if batch is not None and simple:
            action = batch.approvals[0]
            # ACP's allow_always has provider-defined scope, not allow_session scope.
            if not action.metadata.get("allow_session"):
                kind = "allow_once" if action.result else "reject_once"
                option = next(
                    (option for option in request.options if option.kind == kind), None
                )
        elif batch is not None:
            answer = batch.questions[0].result
            option = labels.get(answer) if isinstance(answer, str) else None
        if option is None:
            return schema.RequestPermissionResponse(
                outcome=schema.DeniedOutcome(outcome="cancelled")
            )
        return schema.RequestPermissionResponse(
            outcome=schema.AllowedOutcome(
                outcome="selected", option_id=option.option_id
            )
        )

    async def elicit(
        self,
        request: schema.CreateFormSessionElicitationRequest,
        suspender: DeferredSuspender | None,
        updates: asyncio.Queue[
            StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
        ],
    ) -> schema.CreateElicitationResponse:
        """Answer a negotiated form on its live ACP request, preserving field types."""
        if suspender is None:
            return schema.CancelElicitationResponse(action="cancel")
        form = AcpForm(request, self.id)
        batch = await self.await_human(
            DeferredToolRequests(
                calls=[
                    ToolCallPart(
                        tool_name="acp_elicitation",
                        tool_call_id=request.tool_call_id or str(uuid7()),
                        args={"questions": form.questions()},
                    )
                ]
            ),
            suspender,
            updates,
            form=form,
        )
        if batch is None:
            return schema.CancelElicitationResponse(action="cancel")
        decision = form.decision(batch)
        if decision in {"Decline", "Cancel"}:
            await self.octomate.deferred_actions.mark_batch(
                batch.id, "completed", completed=True
            )
            return (
                schema.DeclineElicitationResponse(action="decline")
                if decision == "Decline"
                else schema.CancelElicitationResponse(action="cancel")
            )
        if decision != "Submit":
            await self.octomate.deferred_actions.mark_batch(batch.id, "failed")
            raise ValueError("Select Submit, Decline, or Cancel for the ACP form")
        try:
            content = form.content(batch)
        except ValueError:
            await self.octomate.deferred_actions.mark_batch(batch.id, "failed")
            raise
        return schema.AcceptElicitationResponse(action="accept", content=content)

    async def await_human(
        self,
        requests: DeferredToolRequests,
        suspender: DeferredSuspender,
        updates: asyncio.Queue[
            StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
        ],
        *,
        form: AcpForm | None = None,
    ) -> DeferredActionBatch | None:
        """Collect partial card replies without ending the provider's live request.

        Timeout or transport cancellation expires the batch so a late reply cannot
        be delivered to another request. Forms keep draft answers editable until
        an explicit submission passes validation.
        """
        batch_id = uuid7()
        future: asyncio.Future[DeferredActionBatchResponse] = (
            asyncio.get_running_loop().create_future()
        )
        self.pendings[batch_id] = future
        try:
            updates.put_nowait(await suspender.pause(requests, batch_id=batch_id))
            batch: DeferredActionBatch | None = None
            complete = False
            async with asyncio.timeout(self.config.approval_timeout):
                while not complete:
                    response = await future
                    future = asyncio.get_running_loop().create_future()
                    self.pendings[batch_id] = future
                    batch = await self.octomate.deferred_actions.resolve_batch(
                        response, finalize=form is None
                    )
                    complete = await self.review_response(
                        batch, response, form, updates
                    )
            return batch
        except (TimeoutError, asyncio.CancelledError) as error:
            cancelled = await drain_task(
                asyncio.create_task(
                    self.octomate.deferred_actions.mark_batch(batch_id, "expired")
                )
            )
            if cancelled or isinstance(error, asyncio.CancelledError):
                raise asyncio.CancelledError from error
            return None
        finally:
            self.pendings.pop(batch_id, None)
            future.cancel()

    async def review_response(
        self,
        batch: DeferredActionBatch,
        response: DeferredActionBatchResponse,
        form: AcpForm | None,
        updates: asyncio.Queue[
            StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
        ],
    ) -> bool:
        """Settle permission replies; keep form drafts open until a valid submission."""
        if form is None:
            updates.put_nowait(ActionBatchAnsweredEvent.of(response))
            return batch.completed
        decision = form.decision(batch)
        if decision in {"Decline", "Cancel"}:
            return True
        if decision != "Submit":
            await self.octomate.deferred_actions.publish_update(batch)
            return False
        try:
            form.content(batch)
        except AcpFormValidationError as error:
            control = max(batch.questions, key=lambda action: action.position)
            await self.octomate.deferred_actions.review_questions(
                batch.id, errors=error.errors, reset=control.id
            )
            return False
        await self.octomate.deferred_actions.submit_questions(batch.id)
        return True

    @asynccontextmanager
    async def mcp_servers(
        self,
        client: NativeAcpClient,
        user_id: UUID7,
        conversation_id: UUID7,
        *,
        habitat: Habitat,
    ) -> AsyncGenerator[list[schema.HttpMcpServer]]:
        """Supply remote Octomate MCP with the caller's shared runtime API key."""
        if not self.gateway:
            yield []
            return
        capabilities = client.initialization.agent_capabilities
        if (
            capabilities is None
            or capabilities.mcp_capabilities is None
            or not capabilities.mcp_capabilities.http
        ):
            raise ValueError("The ACP provider must support HTTP MCP servers")
        auth = self.octomate.auth
        if auth is None or user_id is None:
            raise ValueError(
                "ACP MCP access requires a registered user and authentication"
            )
        issued = await auth.runtime_api_key(user_id, agent_id=self.id, scopes=["mcp"])
        if issued.bearer is None:
            raise RuntimeError("Issued runtime API key has no bearer")
        yield [
            schema.HttpMcpServer(
                name=OCTOMATE_SERVER_NAME,
                type="http",
                url=f"{habitat.core_url}{OCTOMATE_MCP_PATH}",
                headers=[
                    schema.HttpHeader(
                        name="Authorization",
                        value=f"Bearer {issued.bearer.get_secret_value()}",
                    ),
                    schema.HttpHeader(
                        name=CONVERSATION_HEADER, value=str(conversation_id)
                    ),
                ],
            )
        ]

    async def invoke(
        self,
        client: NativeAcpClient,
        invocation: Invocation,
        request: schema.PromptRequest,
        address: ChannelAddress,
        sender: UserProfile,
        source_address: ChannelAddress | None,
        source_message_ids: Sequence[UUID7] | None,
        run_name: str | None,
        updates: asyncio.Queue[
            StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
        ],
        model: str | None,
    ) -> AsyncGenerator[ReactStreamEvent[str]]:
        conversation = invocation.conversation
        interruption = invocation.interruption
        interruption.check()
        sent = asyncio.Event()
        history = AcpHistory(request)
        run_id = str(uuid7())

        def observe(event: StreamEvent) -> None:
            if (
                event.direction == StreamDirection.OUTGOING
                and event.message.get("method") == "session/prompt"
            ):
                sent.set()
            params = event.message.get("params")
            if (
                event.direction == StreamDirection.INCOMING
                and event.message.get("method") == "session/update"
                and isinstance(params, dict)
                and params.get("sessionId") == request.session_id
            ):
                updates.put_nowait(event)

        client.connection.add_observer(observe)
        prompt = asyncio.create_task(
            request_model(
                client.connection,
                acp.AGENT_METHODS["session_prompt"],
                request,
                schema.PromptResponse,
            )
        )
        prompt.add_done_callback(lambda task: updates.put_nowait(None))

        async def interrupt() -> None:
            await sent.wait()
            await notify_model(
                client.connection,
                acp.AGENT_METHODS["session_cancel"],
                schema.CancelNotification(session_id=request.session_id),
            )

        failed = False
        handling = interruption.handling(interrupt)
        await handling.__aenter__()
        try:
            while (event := await updates.get()) is not None:
                if isinstance(event, ActionBatchEvent | ActionBatchAnsweredEvent):
                    yield event
                    continue
                for wire in history.feed(
                    schema.SessionNotification.model_validate(event.message["params"])
                ):
                    yield wire
            for wire in history.end_part():
                yield wire
            response = await asyncio.shield(prompt)
            assert history.request.metadata is not None
            history.request.metadata["stop_reason"] = response.stop_reason
            if response.usage is not None:
                assert history.response.metadata is not None
                # ACP agents disagree on whether these totals cover a turn or a session.
                history.response.metadata["usage"] = json_value_adapter.validate_json(
                    response.usage.model_dump_json(by_alias=True, exclude_none=True)
                )
        except (asyncio.CancelledError, GeneratorExit):
            failed = True
            assert history.request.metadata is not None
            history.request.metadata["stop_reason"] = "cancelled"
            with CancelScope(shield=True):
                await notify_model(
                    client.connection,
                    acp.AGENT_METHODS["session_cancel"],
                    schema.CancelNotification(session_id=request.session_id),
                )
                await prompt
            raise
        except Exception as error:
            failed = True
            assert history.request.metadata is not None
            history.request.metadata["error"] = str(error)
            if not prompt.done():
                await notify_model(
                    client.connection,
                    acp.AGENT_METHODS["session_cancel"],
                    schema.CancelNotification(session_id=request.session_id),
                )
                await prompt
            raise
        finally:
            await handling.__aexit__(None, None, None)
            with CancelScope(shield=True):
                await self.record(
                    invocation,
                    history,
                    run_id,
                    address,
                    sender,
                    source_address,
                    source_message_ids,
                    run_name,
                    updates,
                    model,
                    failed=failed or interruption.requested,
                )
        interruption.check()
        yield AgentRunResultEvent(
            AgentRunResult(
                output=history.answer,
                _state=GraphAgentState(
                    message_history=history.messages,
                    usage=RunUsage(),
                    run_id=run_id,
                    conversation_id=str(conversation.id),
                ),
            )
        )

    async def record(
        self,
        invocation: Invocation,
        history: AcpHistory,
        run_id: str,
        address: ChannelAddress,
        sender: UserProfile,
        source_address: ChannelAddress | None,
        source_message_ids: Sequence[UUID7] | None,
        run_name: str | None,
        updates: asyncio.Queue[
            StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
        ],
        model: str | None,
        *,
        failed: bool,
    ) -> None:
        """Bind existing inbound messages and preserve partial replies on failure."""
        while not updates.empty():
            pending = updates.get_nowait()
            if isinstance(pending, StreamEvent):
                history.feed(
                    schema.SessionNotification.model_validate(pending.message["params"])
                )
        run = await self.conversations.record_agent_run(
            invocation.conversation,
            run_id,
            history.messages,
            name=run_name,
            model_name=model,
            context_window=history.context_window,
            context_used=history.context_used,
            cwd=invocation.workspace.path,
            external_id=history.prompt.session_id,
            parent_run_id=invocation.parent_run_id,
            parent_tool_call_id=invocation.parent_tool_call_id,
        )
        assert run is not None
        if source_message_ids:
            await self.threads.bind_messages(
                list(source_message_ids),
                run.messages[0].id,
                kind="request_source",
                run_id=run.id,
            )
            source_thread = await self.threads.ensure(source_address or address)
            await self.threads.advance_prompt_cursor(
                source_thread, source_message_ids[-1]
            )
        if failed and history.answer:
            reply = await self.threads.record_outbound(
                address,
                agent_tentacle_id=self.id,
                segments=[TextSegment(data={"text": history.answer})],
                sender=sender,
            )
            await self.threads.bind_messages(
                [reply.id],
                run.messages[1].id,
                kind="assistant_reply",
                run_id=run.id,
            )

type class-attribute

type: str = 'acp'

in_process class-attribute

in_process: bool = True

provider_permission_mode class-attribute instance-attribute

provider_permission_mode: str | None = None

ink instance-attribute

ink: AcpInk = AcpInk()

config instance-attribute

config: AcpAgentConfig = config

gateway instance-attribute

gateway = config.gateway

pendings instance-attribute

pendings = {}

conversations instance-attribute

conversations = octomate.conversations

workspaces instance-attribute

workspaces = octomate.workspaces

models instance-attribute

models = {}

default_permission_mode property

default_permission_mode: str | None

run async

run(
    user_prompt: str | Sequence[UserContent] | None = None,
    *,
    conversation_address: ChannelAddress,
    invocation: Invocation,
    source_thread_address: ChannelAddress | None = None,
    source_thread_message_ids: Sequence[UUID7]
    | None = None,
    run_name: str | None = None,
    output_type: OutputSpec[RunOutputDataT] | None = None,
    deferred_tool_results: DeferredToolResults
    | None = None,
    deferred_suspender: DeferredSuspender | None = None,
    model: Model | KnownModelName | str | None = None,
    effort: str | None = None,
    interactive: bool = True,
    instructions: AgentInstructions[None] = None,
    deps: None = None,
    model_settings: AgentModelSettings[None] | None = None,
    usage_limits: UsageLimits | None = None,
    metadata: AgentMetadata[None] | None = None,
    output_retries: int | None = None,
    infer_name: bool = True,
    toolsets: Sequence[AbstractToolset[None]] | None = None,
    builtin_tools: Sequence[AgentNativeTool[None]]
    | None = None,
    event_stream_handler: EventStreamHandler[None]
    | None = None,
    capabilities: Sequence[AgentCapability[None]]
    | None = None,
    spec: AgentSpecInput | None = None,
) -> AgentRunResult[str | RunOutputDataT]

Collect the same agent stream used by the reflex.

Source code in octomate/tentacles/acp/base.py
async def run(
    self,
    user_prompt: str | Sequence[UserContent] | None = None,
    *,
    conversation_address: ChannelAddress,
    invocation: Invocation,
    source_thread_address: ChannelAddress | None = None,
    source_thread_message_ids: Sequence[UUID7] | None = None,
    run_name: str | None = None,
    output_type: OutputSpec[RunOutputDataT] | None = None,
    deferred_tool_results: DeferredToolResults | None = None,
    deferred_suspender: DeferredSuspender | None = None,
    model: Model | KnownModelName | str | None = None,
    effort: str | None = None,
    interactive: bool = True,
    instructions: AgentInstructions[None] = None,
    deps: None = None,
    model_settings: AgentModelSettings[None] | None = None,
    usage_limits: UsageLimits | None = None,
    metadata: AgentMetadata[None] | None = None,
    output_retries: int | None = None,
    infer_name: bool = True,
    toolsets: Sequence[AbstractToolset[None]] | None = None,
    builtin_tools: Sequence[AgentNativeTool[None]] | None = None,
    event_stream_handler: EventStreamHandler[None] | None = None,
    capabilities: Sequence[AgentCapability[None]] | None = None,
    spec: AgentSpecInput | None = None,
) -> AgentRunResult[str | RunOutputDataT]:
    """Collect the same agent stream used by the reflex."""
    if event_stream_handler is not None:
        raise ValueError("Use run_stream_events to observe outbound ACP events")
    result: AgentRunResult[str | RunOutputDataT] | None = None
    async with self.run_stream_events(
        user_prompt,
        conversation_address=conversation_address,
        invocation=invocation,
        source_thread_address=source_thread_address,
        source_thread_message_ids=source_thread_message_ids,
        run_name=run_name,
        output_type=output_type,
        deferred_tool_results=deferred_tool_results,
        deferred_suspender=deferred_suspender,
        model=model,
        effort=effort,
        interactive=interactive,
        instructions=instructions,
        deps=deps,
        model_settings=model_settings,
        usage_limits=usage_limits,
        metadata=metadata,
        output_retries=output_retries,
        infer_name=infer_name,
        toolsets=toolsets,
        builtin_tools=builtin_tools,
        capabilities=capabilities,
        spec=spec,
    ) as events:
        async for event in events:
            if isinstance(event, AgentRunResultEvent):
                result = event.result
    if result is None:
        raise RuntimeError("The ACP stream ended without a result")
    return result

run_stream_events

run_stream_events(
    user_prompt: str | Sequence[UserContent] | None = None,
    *,
    conversation_address: ChannelAddress,
    invocation: Invocation,
    source_thread_address: ChannelAddress | None = None,
    source_thread_message_ids: Sequence[UUID7]
    | None = None,
    run_name: str | None = None,
    output_type: OutputSpec[RunOutputDataT] | None = None,
    deferred_tool_results: DeferredToolResults
    | None = None,
    deferred_suspender: DeferredSuspender | None = None,
    model: Model | KnownModelName | str | None = None,
    effort: str | None = None,
    interactive: bool = True,
    instructions: AgentInstructions[None] = None,
    deps: None = None,
    model_settings: AgentModelSettings[None] | None = None,
    usage_limits: UsageLimits | None = None,
    metadata: AgentMetadata[None] | None = None,
    output_retries: int | None = None,
    infer_name: bool = True,
    toolsets: Sequence[AbstractToolset[None]] | None = None,
    builtin_tools: Sequence[AgentNativeTool[None]]
    | None = None,
    capabilities: Sequence[AgentCapability[None]]
    | None = None,
    spec: AgentSpecInput | None = None,
) -> ReactEventStream[str | RunOutputDataT]

Run the supplied prompt in this agent's conversation and workspace.

Source code in octomate/tentacles/acp/base.py
def run_stream_events(
    self,
    user_prompt: str | Sequence[UserContent] | None = None,
    *,
    conversation_address: ChannelAddress,
    invocation: Invocation,
    source_thread_address: ChannelAddress | None = None,
    source_thread_message_ids: Sequence[UUID7] | None = None,
    run_name: str | None = None,
    output_type: OutputSpec[RunOutputDataT] | None = None,
    deferred_tool_results: DeferredToolResults | None = None,
    deferred_suspender: DeferredSuspender | None = None,
    model: Model | KnownModelName | str | None = None,
    effort: str | None = None,
    interactive: bool = True,
    instructions: AgentInstructions[None] = None,
    deps: None = None,
    model_settings: AgentModelSettings[None] | None = None,
    usage_limits: UsageLimits | None = None,
    metadata: AgentMetadata[None] | None = None,
    output_retries: int | None = None,
    infer_name: bool = True,
    toolsets: Sequence[AbstractToolset[None]] | None = None,
    builtin_tools: Sequence[AgentNativeTool[None]] | None = None,
    capabilities: Sequence[AgentCapability[None]] | None = None,
    spec: AgentSpecInput | None = None,
) -> ReactEventStream[str | RunOutputDataT]:
    """Run the supplied prompt in this agent's conversation and workspace."""
    if (
        any(
            value is not None
            for value in (
                output_type,
                deferred_tool_results,
                instructions,
                model_settings,
                usage_limits,
                metadata,
                output_retries,
                toolsets,
                builtin_tools,
                spec,
            )
        )
        or capabilities
    ):
        raise ValueError(
            "Outbound ACP accepts text prompts, model and effort selection"
        )
    if model is not None and not isinstance(model, str):
        raise ValueError("Outbound ACP requires a model identifier")
    return ReactEventStream(
        self.stream(
            user_prompt,
            conversation_address,
            invocation,
            source_thread_address,
            source_thread_message_ids,
            run_name,
            deferred_suspender if interactive else None,
            self.resolve_model(model),
            effort,
        )
    )

stream async

stream(
    user_prompt: str | Sequence[UserContent] | None,
    address: ChannelAddress,
    invocation: Invocation,
    source_address: ChannelAddress | None,
    source_message_ids: Sequence[UUID7] | None,
    run_name: str | None,
    suspender: DeferredSuspender | None,
    model: str | None,
    effort: str | None,
) -> AsyncGenerator[ReactStreamEvent[str]]
Source code in octomate/tentacles/acp/base.py
async def stream(
    self,
    user_prompt: str | Sequence[UserContent] | None,
    address: ChannelAddress,
    invocation: Invocation,
    source_address: ChannelAddress | None,
    source_message_ids: Sequence[UUID7] | None,
    run_name: str | None,
    suspender: DeferredSuspender | None,
    model: str | None,
    effort: str | None,
) -> AsyncGenerator[ReactStreamEvent[str]]:
    provider = self.config.provider
    conversation = invocation.conversation
    self.check_conversation(conversation, thread_id=invocation.thread_id)
    if isinstance(user_prompt, str):
        text = user_prompt
    else:
        parts: list[str] = []
        for part in user_prompt or []:
            if not isinstance(part, str | TextContent):
                raise ValueError("Outbound ACP currently accepts only text")
            parts.append(part.content if isinstance(part, TextContent) else part)
        text = "\n".join(parts)
    if not text.strip():
        raise ValueError("ACP requires a non-empty text prompt")
    effort = await self.resolve_effort(conversation, model=model, effort=effort)
    sender = await self.octomate.users.profile(
        address.channel_tentacle_id, address.user_id
    )
    if sender is None or invocation.owner_id is None:
        raise ValueError("Outbound ACP requires a registered user")
    updates: asyncio.Queue[
        StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
    ] = asyncio.Queue()
    session_id: str | None = None
    env = invocation.environment
    if isinstance(invocation.habitat, HostedHabitat):
        config = invocation.workspace.volumes.get("config")
        if config is None:
            raise ValueError("Managed ACP requires a configuration volume")
        env["HOME"] = str(invocation.habitat.path(config))

    async def handle(
        method: str, params: JsonValue | None, notification: bool
    ) -> JsonValue | None:
        if notification:
            return None
        if method == "session/request_permission":
            request = schema.RequestPermissionRequest.model_validate(params)
        elif method == "elicitation/create":
            if suspender is None:
                raise acp.RequestError.invalid_params(
                    {"reason": "Form elicitation was not negotiated"}
                )
            request = schema.CreateFormSessionElicitationRequest.model_validate(
                params
            )
            if request.requested_schema.type != "object":
                raise acp.RequestError.invalid_params(
                    {"reason": "ACP forms require an object schema"}
                )
        else:
            if client_workspace is not None:
                return await client_workspace.handle(method, params)
            raise acp.RequestError.method_not_found(method)
        if request.session_id != session_id:
            raise acp.RequestError.invalid_params({"reason": "Unknown session"})
        response = (
            await self.permission(request, suspender, updates)
            if isinstance(request, schema.RequestPermissionRequest)
            else await self.elicit(request, suspender, updates)
        )
        return json_value_adapter.validate_python(
            response.model_dump(mode="json", by_alias=True, exclude_none=True)
        )

    async with (
        workspace(invocation.habitat, str(invocation.cwd)) as client_workspace,
        AsyncExitStack() as credentials,
        NativeAcpClient.connect(
            provider,
            handle,
            schema.InitializeRequest(
                protocol_version=acp.PROTOCOL_VERSION,
                client_capabilities=schema.ClientCapabilities(
                    fs=schema.FileSystemCapabilities(
                        read_text_file=True, write_text_file=True
                    )
                    if client_workspace is not None
                    else None,
                    terminal=client_workspace is not None,
                    elicitation=schema.ElicitationCapabilities(
                        form=schema.ElicitationFormCapabilities()
                    )
                    if suspender is not None
                    else None,
                ),
            ),
            habitat=invocation.habitat,
            cwd=str(invocation.cwd),
            env=env,
        ) as client,
    ):
        if client_workspace is not None:
            client_workspace.session_id = conversation.external_id
        mcp_servers = await credentials.enter_async_context(
            self.mcp_servers(
                client,
                invocation.owner_id,
                conversation.id,
                habitat=invocation.habitat,
            )
        )
        if conversation.external_id is None:
            native = await client.new_session(
                schema.NewSessionRequest(
                    cwd=str(invocation.cwd), mcp_servers=[*mcp_servers]
                )
            )
            session_id = native.session_id
            await self.conversations.set_external_id(conversation, session_id)
        else:
            capabilities = client.initialization.agent_capabilities
            session_id = conversation.external_id
            response: schema.LoadSessionResponse | schema.ResumeSessionResponse
            if capabilities is not None and capabilities.load_session:
                response = await request_model(
                    client.connection,
                    acp.AGENT_METHODS["session_load"],
                    schema.LoadSessionRequest(
                        session_id=session_id,
                        cwd=str(invocation.cwd),
                        mcp_servers=[*mcp_servers],
                    ),
                    schema.LoadSessionResponse,
                )
            elif (
                capabilities is not None
                and capabilities.session_capabilities is not None
                and capabilities.session_capabilities.resume is not None
            ):
                response = await request_model(
                    client.connection,
                    acp.AGENT_METHODS["session_resume"],
                    schema.ResumeSessionRequest(
                        session_id=session_id,
                        cwd=str(invocation.cwd),
                        mcp_servers=[*mcp_servers],
                    ),
                    schema.ResumeSessionResponse,
                )
            else:
                raise ValueError("The ACP provider cannot reopen this conversation")
            native = NativeAcpSession(
                provider, str(invocation.cwd), session_id, response
            )
        if client_workspace is not None:
            client_workspace.session_id = session_id
        selected_model = await native.select_model(client.connection, model)
        await native.select_effort(client.connection, effort)
        await native.select_mode(
            client.connection,
            conversation.permission_mode or self.config.permission_mode,
        )
        request = schema.PromptRequest(
            session_id=session_id, prompt=[acp.text_block(text)]
        )
        async with (
            self.driving(session_id),
            aclosing(
                self.invoke(
                    client,
                    invocation,
                    request,
                    address,
                    sender,
                    source_address,
                    source_message_ids,
                    run_name,
                    updates,
                    selected_model,
                )
            ) as events,
        ):
            async for event in events:
                yield event

permission async

permission(
    request: RequestPermissionRequest,
    suspender: DeferredSuspender | None,
    updates: Queue[
        StreamEvent
        | ActionBatchEvent
        | ActionBatchAnsweredEvent
        | None
    ],
) -> schema.RequestPermissionResponse

Route provider approvals through the existing live deferred-action flow.

Source code in octomate/tentacles/acp/base.py
async def permission(
    self,
    request: schema.RequestPermissionRequest,
    suspender: DeferredSuspender | None,
    updates: asyncio.Queue[
        StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
    ],
) -> schema.RequestPermissionResponse:
    """Route provider approvals through the existing live deferred-action flow."""
    if suspender is None:
        return schema.RequestPermissionResponse(
            outcome=schema.DeniedOutcome(outcome="cancelled")
        )
    # A boolean card cannot express a provider's remembered scope or distinguish
    # several options of the same kind. Present its exact options in that case.
    simple = len({option.kind for option in request.options}) == len(
        request.options
    ) and all(
        option.kind in {"allow_once", "reject_once"} for option in request.options
    )
    names = [option.name for option in request.options]
    labels = {
        option.name
        if names.count(option.name) == 1
        else f"{option.name} ({option.option_id})": option
        for option in request.options
    }
    call = ToolCallPart(
        tool_name=request.tool_call.title or "ACP tool",
        tool_call_id=request.tool_call.tool_call_id,
        args=request.tool_call.model_dump_json(by_alias=True, exclude_none=True)
        if simple
        else {
            "questions": [
                {
                    "question": f"Permission: {request.tool_call.title or 'ACP tool'}",
                    "choices": list(labels)[:MAX_QUESTION_CHOICES],
                    "hint": request.tool_call.model_dump_json(
                        by_alias=True, exclude_none=True
                    )
                    + "\nOptions: "
                    + "; ".join(labels),
                }
            ]
        },
    )
    batch = await self.await_human(
        DeferredToolRequests(approvals=[call])
        if simple
        else DeferredToolRequests(calls=[call]),
        suspender,
        updates,
    )
    option: schema.PermissionOption | None = None
    if batch is not None and simple:
        action = batch.approvals[0]
        # ACP's allow_always has provider-defined scope, not allow_session scope.
        if not action.metadata.get("allow_session"):
            kind = "allow_once" if action.result else "reject_once"
            option = next(
                (option for option in request.options if option.kind == kind), None
            )
    elif batch is not None:
        answer = batch.questions[0].result
        option = labels.get(answer) if isinstance(answer, str) else None
    if option is None:
        return schema.RequestPermissionResponse(
            outcome=schema.DeniedOutcome(outcome="cancelled")
        )
    return schema.RequestPermissionResponse(
        outcome=schema.AllowedOutcome(
            outcome="selected", option_id=option.option_id
        )
    )

elicit async

elicit(
    request: CreateFormSessionElicitationRequest,
    suspender: DeferredSuspender | None,
    updates: Queue[
        StreamEvent
        | ActionBatchEvent
        | ActionBatchAnsweredEvent
        | None
    ],
) -> schema.CreateElicitationResponse

Answer a negotiated form on its live ACP request, preserving field types.

Source code in octomate/tentacles/acp/base.py
async def elicit(
    self,
    request: schema.CreateFormSessionElicitationRequest,
    suspender: DeferredSuspender | None,
    updates: asyncio.Queue[
        StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
    ],
) -> schema.CreateElicitationResponse:
    """Answer a negotiated form on its live ACP request, preserving field types."""
    if suspender is None:
        return schema.CancelElicitationResponse(action="cancel")
    form = AcpForm(request, self.id)
    batch = await self.await_human(
        DeferredToolRequests(
            calls=[
                ToolCallPart(
                    tool_name="acp_elicitation",
                    tool_call_id=request.tool_call_id or str(uuid7()),
                    args={"questions": form.questions()},
                )
            ]
        ),
        suspender,
        updates,
        form=form,
    )
    if batch is None:
        return schema.CancelElicitationResponse(action="cancel")
    decision = form.decision(batch)
    if decision in {"Decline", "Cancel"}:
        await self.octomate.deferred_actions.mark_batch(
            batch.id, "completed", completed=True
        )
        return (
            schema.DeclineElicitationResponse(action="decline")
            if decision == "Decline"
            else schema.CancelElicitationResponse(action="cancel")
        )
    if decision != "Submit":
        await self.octomate.deferred_actions.mark_batch(batch.id, "failed")
        raise ValueError("Select Submit, Decline, or Cancel for the ACP form")
    try:
        content = form.content(batch)
    except ValueError:
        await self.octomate.deferred_actions.mark_batch(batch.id, "failed")
        raise
    return schema.AcceptElicitationResponse(action="accept", content=content)

await_human async

await_human(
    requests: DeferredToolRequests,
    suspender: DeferredSuspender,
    updates: Queue[
        StreamEvent
        | ActionBatchEvent
        | ActionBatchAnsweredEvent
        | None
    ],
    *,
    form: AcpForm | None = None,
) -> DeferredActionBatch | None

Collect partial card replies without ending the provider's live request.

Timeout or transport cancellation expires the batch so a late reply cannot be delivered to another request. Forms keep draft answers editable until an explicit submission passes validation.

Source code in octomate/tentacles/acp/base.py
async def await_human(
    self,
    requests: DeferredToolRequests,
    suspender: DeferredSuspender,
    updates: asyncio.Queue[
        StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
    ],
    *,
    form: AcpForm | None = None,
) -> DeferredActionBatch | None:
    """Collect partial card replies without ending the provider's live request.

    Timeout or transport cancellation expires the batch so a late reply cannot
    be delivered to another request. Forms keep draft answers editable until
    an explicit submission passes validation.
    """
    batch_id = uuid7()
    future: asyncio.Future[DeferredActionBatchResponse] = (
        asyncio.get_running_loop().create_future()
    )
    self.pendings[batch_id] = future
    try:
        updates.put_nowait(await suspender.pause(requests, batch_id=batch_id))
        batch: DeferredActionBatch | None = None
        complete = False
        async with asyncio.timeout(self.config.approval_timeout):
            while not complete:
                response = await future
                future = asyncio.get_running_loop().create_future()
                self.pendings[batch_id] = future
                batch = await self.octomate.deferred_actions.resolve_batch(
                    response, finalize=form is None
                )
                complete = await self.review_response(
                    batch, response, form, updates
                )
        return batch
    except (TimeoutError, asyncio.CancelledError) as error:
        cancelled = await drain_task(
            asyncio.create_task(
                self.octomate.deferred_actions.mark_batch(batch_id, "expired")
            )
        )
        if cancelled or isinstance(error, asyncio.CancelledError):
            raise asyncio.CancelledError from error
        return None
    finally:
        self.pendings.pop(batch_id, None)
        future.cancel()

review_response async

review_response(
    batch: DeferredActionBatch,
    response: DeferredActionBatchResponse,
    form: AcpForm | None,
    updates: Queue[
        StreamEvent
        | ActionBatchEvent
        | ActionBatchAnsweredEvent
        | None
    ],
) -> bool

Settle permission replies; keep form drafts open until a valid submission.

Source code in octomate/tentacles/acp/base.py
async def review_response(
    self,
    batch: DeferredActionBatch,
    response: DeferredActionBatchResponse,
    form: AcpForm | None,
    updates: asyncio.Queue[
        StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
    ],
) -> bool:
    """Settle permission replies; keep form drafts open until a valid submission."""
    if form is None:
        updates.put_nowait(ActionBatchAnsweredEvent.of(response))
        return batch.completed
    decision = form.decision(batch)
    if decision in {"Decline", "Cancel"}:
        return True
    if decision != "Submit":
        await self.octomate.deferred_actions.publish_update(batch)
        return False
    try:
        form.content(batch)
    except AcpFormValidationError as error:
        control = max(batch.questions, key=lambda action: action.position)
        await self.octomate.deferred_actions.review_questions(
            batch.id, errors=error.errors, reset=control.id
        )
        return False
    await self.octomate.deferred_actions.submit_questions(batch.id)
    return True

mcp_servers async

mcp_servers(
    client: NativeAcpClient,
    user_id: UUID7,
    conversation_id: UUID7,
    *,
    habitat: Habitat,
) -> AsyncGenerator[list[schema.HttpMcpServer]]

Supply remote Octomate MCP with the caller's shared runtime API key.

Source code in octomate/tentacles/acp/base.py
@asynccontextmanager
async def mcp_servers(
    self,
    client: NativeAcpClient,
    user_id: UUID7,
    conversation_id: UUID7,
    *,
    habitat: Habitat,
) -> AsyncGenerator[list[schema.HttpMcpServer]]:
    """Supply remote Octomate MCP with the caller's shared runtime API key."""
    if not self.gateway:
        yield []
        return
    capabilities = client.initialization.agent_capabilities
    if (
        capabilities is None
        or capabilities.mcp_capabilities is None
        or not capabilities.mcp_capabilities.http
    ):
        raise ValueError("The ACP provider must support HTTP MCP servers")
    auth = self.octomate.auth
    if auth is None or user_id is None:
        raise ValueError(
            "ACP MCP access requires a registered user and authentication"
        )
    issued = await auth.runtime_api_key(user_id, agent_id=self.id, scopes=["mcp"])
    if issued.bearer is None:
        raise RuntimeError("Issued runtime API key has no bearer")
    yield [
        schema.HttpMcpServer(
            name=OCTOMATE_SERVER_NAME,
            type="http",
            url=f"{habitat.core_url}{OCTOMATE_MCP_PATH}",
            headers=[
                schema.HttpHeader(
                    name="Authorization",
                    value=f"Bearer {issued.bearer.get_secret_value()}",
                ),
                schema.HttpHeader(
                    name=CONVERSATION_HEADER, value=str(conversation_id)
                ),
            ],
        )
    ]

invoke async

invoke(
    client: NativeAcpClient,
    invocation: Invocation,
    request: PromptRequest,
    address: ChannelAddress,
    sender: UserProfile,
    source_address: ChannelAddress | None,
    source_message_ids: Sequence[UUID7] | None,
    run_name: str | None,
    updates: Queue[
        StreamEvent
        | ActionBatchEvent
        | ActionBatchAnsweredEvent
        | None
    ],
    model: str | None,
) -> AsyncGenerator[ReactStreamEvent[str]]
Source code in octomate/tentacles/acp/base.py
async def invoke(
    self,
    client: NativeAcpClient,
    invocation: Invocation,
    request: schema.PromptRequest,
    address: ChannelAddress,
    sender: UserProfile,
    source_address: ChannelAddress | None,
    source_message_ids: Sequence[UUID7] | None,
    run_name: str | None,
    updates: asyncio.Queue[
        StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
    ],
    model: str | None,
) -> AsyncGenerator[ReactStreamEvent[str]]:
    conversation = invocation.conversation
    interruption = invocation.interruption
    interruption.check()
    sent = asyncio.Event()
    history = AcpHistory(request)
    run_id = str(uuid7())

    def observe(event: StreamEvent) -> None:
        if (
            event.direction == StreamDirection.OUTGOING
            and event.message.get("method") == "session/prompt"
        ):
            sent.set()
        params = event.message.get("params")
        if (
            event.direction == StreamDirection.INCOMING
            and event.message.get("method") == "session/update"
            and isinstance(params, dict)
            and params.get("sessionId") == request.session_id
        ):
            updates.put_nowait(event)

    client.connection.add_observer(observe)
    prompt = asyncio.create_task(
        request_model(
            client.connection,
            acp.AGENT_METHODS["session_prompt"],
            request,
            schema.PromptResponse,
        )
    )
    prompt.add_done_callback(lambda task: updates.put_nowait(None))

    async def interrupt() -> None:
        await sent.wait()
        await notify_model(
            client.connection,
            acp.AGENT_METHODS["session_cancel"],
            schema.CancelNotification(session_id=request.session_id),
        )

    failed = False
    handling = interruption.handling(interrupt)
    await handling.__aenter__()
    try:
        while (event := await updates.get()) is not None:
            if isinstance(event, ActionBatchEvent | ActionBatchAnsweredEvent):
                yield event
                continue
            for wire in history.feed(
                schema.SessionNotification.model_validate(event.message["params"])
            ):
                yield wire
        for wire in history.end_part():
            yield wire
        response = await asyncio.shield(prompt)
        assert history.request.metadata is not None
        history.request.metadata["stop_reason"] = response.stop_reason
        if response.usage is not None:
            assert history.response.metadata is not None
            # ACP agents disagree on whether these totals cover a turn or a session.
            history.response.metadata["usage"] = json_value_adapter.validate_json(
                response.usage.model_dump_json(by_alias=True, exclude_none=True)
            )
    except (asyncio.CancelledError, GeneratorExit):
        failed = True
        assert history.request.metadata is not None
        history.request.metadata["stop_reason"] = "cancelled"
        with CancelScope(shield=True):
            await notify_model(
                client.connection,
                acp.AGENT_METHODS["session_cancel"],
                schema.CancelNotification(session_id=request.session_id),
            )
            await prompt
        raise
    except Exception as error:
        failed = True
        assert history.request.metadata is not None
        history.request.metadata["error"] = str(error)
        if not prompt.done():
            await notify_model(
                client.connection,
                acp.AGENT_METHODS["session_cancel"],
                schema.CancelNotification(session_id=request.session_id),
            )
            await prompt
        raise
    finally:
        await handling.__aexit__(None, None, None)
        with CancelScope(shield=True):
            await self.record(
                invocation,
                history,
                run_id,
                address,
                sender,
                source_address,
                source_message_ids,
                run_name,
                updates,
                model,
                failed=failed or interruption.requested,
            )
    interruption.check()
    yield AgentRunResultEvent(
        AgentRunResult(
            output=history.answer,
            _state=GraphAgentState(
                message_history=history.messages,
                usage=RunUsage(),
                run_id=run_id,
                conversation_id=str(conversation.id),
            ),
        )
    )

record async

record(
    invocation: Invocation,
    history: AcpHistory,
    run_id: str,
    address: ChannelAddress,
    sender: UserProfile,
    source_address: ChannelAddress | None,
    source_message_ids: Sequence[UUID7] | None,
    run_name: str | None,
    updates: Queue[
        StreamEvent
        | ActionBatchEvent
        | ActionBatchAnsweredEvent
        | None
    ],
    model: str | None,
    *,
    failed: bool,
) -> None

Bind existing inbound messages and preserve partial replies on failure.

Source code in octomate/tentacles/acp/base.py
async def record(
    self,
    invocation: Invocation,
    history: AcpHistory,
    run_id: str,
    address: ChannelAddress,
    sender: UserProfile,
    source_address: ChannelAddress | None,
    source_message_ids: Sequence[UUID7] | None,
    run_name: str | None,
    updates: asyncio.Queue[
        StreamEvent | ActionBatchEvent | ActionBatchAnsweredEvent | None
    ],
    model: str | None,
    *,
    failed: bool,
) -> None:
    """Bind existing inbound messages and preserve partial replies on failure."""
    while not updates.empty():
        pending = updates.get_nowait()
        if isinstance(pending, StreamEvent):
            history.feed(
                schema.SessionNotification.model_validate(pending.message["params"])
            )
    run = await self.conversations.record_agent_run(
        invocation.conversation,
        run_id,
        history.messages,
        name=run_name,
        model_name=model,
        context_window=history.context_window,
        context_used=history.context_used,
        cwd=invocation.workspace.path,
        external_id=history.prompt.session_id,
        parent_run_id=invocation.parent_run_id,
        parent_tool_call_id=invocation.parent_tool_call_id,
    )
    assert run is not None
    if source_message_ids:
        await self.threads.bind_messages(
            list(source_message_ids),
            run.messages[0].id,
            kind="request_source",
            run_id=run.id,
        )
        source_thread = await self.threads.ensure(source_address or address)
        await self.threads.advance_prompt_cursor(
            source_thread, source_message_ids[-1]
        )
    if failed and history.answer:
        reply = await self.threads.record_outbound(
            address,
            agent_tentacle_id=self.id,
            segments=[TextSegment(data={"text": history.answer})],
            sender=sender,
        )
        await self.threads.bind_messages(
            [reply.id],
            run.messages[1].id,
            kind="assistant_reply",
            run_id=run.id,
        )

octomate.tentacles.acp.ink

ACP runtime session capabilities.

AcpInk

Bases: AgentInk

ACP session forking is not implemented.

Source code in octomate/tentacles/acp/ink.py
class AcpInk(AgentInk):
    """ACP session forking is not implemented."""

    supports_session_fork: ClassVar[bool] = False

supports_session_fork class-attribute

supports_session_fork: bool = False

octomate.tentacles.acp.broker

One ACP agent over Octomate's registered model routes.

Public session IDs are thread UUIDs. Model option values identify a registered agent and catalog model; provider session IDs remain on their conversations. Sessions are private to their creating account, including before their first message. A connection exclusively attaches the sessions it creates or reopens.

The cwd selects a registered project, otherwise the ordinary chat workspace is used. Additional directories, client tools, and session-supplied MCP servers are unsupported. Agents use their existing Octomate tools and linked MCP accounts.

AcpSession dataclass

A public thread's connection and active prompt state.

Source code in octomate/tentacles/acp/broker.py
@dataclass
class AcpSession:
    """A public thread's connection and active prompt state."""

    thread: Thread
    settings_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
    prompt_scope: CancelScope | None = None
    running: bool = False  # A dispatched prompt has not emitted its asleep event.

    @property
    def selection(self) -> AgentRouteKey:
        """Read the selected agent and model from the thread's recorded handoff."""
        agent_id = self.thread.active_agent_tentacle_id
        if agent_id is None:
            raise ValueError("The session has no selected agent")
        return AgentRouteKey(agent_id, self.thread.active_model)

thread instance-attribute

thread: Thread

settings_lock class-attribute instance-attribute

settings_lock: Lock = field(default_factory=asyncio.Lock)

prompt_scope class-attribute instance-attribute

prompt_scope: CancelScope | None = None

running class-attribute instance-attribute

running: bool = False

selection property

selection: AgentRouteKey

Read the selected agent and model from the thread's recorded handoff.

AcpBroker dataclass

Serve one authenticated connection using kicks and a nerve subscription.

Permission requests are answered directly with ACP request_permission. Questions use negotiated form elicitation; without that capability the prompt fails explicitly rather than fabricating answers. Disconnect and cancellation settle the graph before releasing session attachments.

Source code in octomate/tentacles/acp/broker.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
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
@dataclass
class AcpBroker:
    """Serve one authenticated connection using kicks and a nerve subscription.

    Permission requests are answered directly with ACP request_permission.
    Questions use negotiated form elicitation; without that capability the prompt
    fails explicitly rather than fabricating answers. Disconnect and cancellation
    settle the graph before releasing session attachments.
    """

    tentacle: AcpChannelTentacle
    sender: UserProfile
    connection: Connection
    nerves: Nerves
    initialized: bool = False
    capabilities: schema.ClientCapabilities = field(
        default_factory=lambda: schema.ClientCapabilities()
    )
    sessions: dict[str, AcpSession] = field(default_factory=dict)
    disconnected: bool = False
    closed: asyncio.Event = field(default_factory=asyncio.Event)

    @property
    def routes(self) -> dict[str, AgentRouteKey]:
        return {
            f"{agent.id}:{model or ''}": AgentRouteKey(agent.id, model)
            for agent in self.tentacle.octomate.agents.values()
            if agent.models
            for model in [None, *agent.models]
        }

    def session(self, session_id: str) -> AcpSession:
        session = self.sessions.get(session_id)
        if session is None:
            raise ValueError("Session is not attached to this connection")
        return session

    async def config_options(
        self, session: AcpSession
    ) -> list[schema.SessionConfigOptionSelect | schema.SessionConfigOptionBoolean]:
        options: list[
            schema.SessionConfigOptionSelect | schema.SessionConfigOptionBoolean
        ] = [
            schema.SessionConfigOptionSelect(
                id="model",
                name="Model",
                category="model",
                type="select",
                current_value=f"{session.selection.agent_id}:{session.selection.model or ''}",
                options=[
                    schema.SessionConfigSelectOption(
                        value=value,
                        name=f"{route.agent_id} / {route.model or 'Default'}",
                    )
                    for value, route in self.routes.items()
                ],
            )
        ]
        modes = await self.modes(session)
        if modes is not None:
            options.append(
                schema.SessionConfigOptionSelect(
                    id="mode",
                    name="Permissions",
                    category="mode",
                    type="select",
                    current_value=modes.current_mode_id,
                    options=[
                        schema.SessionConfigSelectOption(
                            value=mode.id, name=mode.name, description=mode.description
                        )
                        for mode in modes.available_modes
                    ],
                )
            )
        return options

    async def handle(
        self, method: str, params: JsonValue | None, notification: bool
    ) -> JsonValue | None:
        """Validate protocol payloads once, then dispatch typed session operations."""
        if notification:
            if method == "session/cancel" and self.initialized:
                request = schema.CancelNotification.model_validate(params)
                session = self.sessions.get(request.session_id)
                if session is not None and session.prompt_scope is not None:
                    session.prompt_scope.cancel()
            return None
        try:
            response = await self.request(method, params)
        except (ValueError, PermissionError, StillAwake) as error:
            raise acp.RequestError.invalid_params({"reason": str(error)}) from error
        return json_value_adapter.validate_python(
            response.model_dump(mode="json", by_alias=True, exclude_none=True)
        )

    async def request(
        self, method: str, params: JsonValue | None
    ) -> (
        schema.InitializeResponse
        | schema.NewSessionResponse
        | schema.LoadSessionResponse
        | schema.ResumeSessionResponse
        | schema.ListSessionsResponse
        | schema.PromptResponse
        | schema.SetSessionConfigOptionResponse
        | schema.SetSessionModeResponse
    ):
        if method == "initialize":
            if self.initialized:
                raise acp.RequestError.invalid_request(
                    {"reason": "Already initialized"}
                )
            request = schema.InitializeRequest.model_validate(params)
            self.capabilities = (
                request.client_capabilities or schema.ClientCapabilities()
            )
            self.initialized = True
            return schema.InitializeResponse(
                protocol_version=acp.PROTOCOL_VERSION,
                agent_info=schema.Implementation(name="octomate", version="1"),
                auth_methods=[],
                agent_capabilities=schema.AgentCapabilities(
                    auth=None,
                    load_session=True,
                    session_capabilities=schema.SessionCapabilities(
                        list=schema.SessionListCapabilities(),
                        resume=schema.SessionResumeCapabilities(),
                    ),
                    mcp_capabilities=schema.McpCapabilities(),
                    prompt_capabilities=schema.PromptCapabilities(),
                ),
            )
        if not self.initialized:
            raise acp.RequestError.invalid_request({"reason": "Initialize first"})
        if method == "session/new":
            return await self.new_session(
                schema.NewSessionRequest.model_validate(params)
            )
        if method in {"session/load", "session/resume"}:
            request_type = (
                schema.LoadSessionRequest
                if method == "session/load"
                else schema.ResumeSessionRequest
            )
            return await self.reopen(request_type.model_validate(params))
        if method == "session/list":
            return await self.list_sessions(
                schema.ListSessionsRequest.model_validate(params)
            )
        if method == "session/prompt":
            return await self.prompt(schema.PromptRequest.model_validate(params))
        if method == "session/set_config_option":
            request = schema.SetSessionConfigOptionSelectRequest.model_validate(
                params, strict=True
            )
            session = self.session(request.session_id)
            if request.config_id == "model" and request.value in self.routes:
                await self.select(session, self.routes[request.value])
            elif request.config_id == "mode":
                await self.set_mode(session, request.value)
            else:
                raise ValueError("Unknown configuration option")
            options = await self.config_options(session)
            await self.update(
                request.session_id,
                schema.ConfigOptionUpdate(
                    session_update="config_option_update", config_options=options
                ),
            )
            return schema.SetSessionConfigOptionResponse(config_options=options)
        if method == "session/set_mode":
            request = schema.SetSessionModeRequest.model_validate(params)
            session = self.session(request.session_id)
            await self.set_mode(session, request.mode_id)
            await self.update(
                request.session_id,
                schema.ConfigOptionUpdate(
                    session_update="config_option_update",
                    config_options=await self.config_options(session),
                ),
            )
            return schema.SetSessionModeResponse()
        raise acp.RequestError.method_not_found(method)

    async def update(
        self,
        session_id: str,
        update: AcpUpdate | schema.UserMessageChunk | schema.ConfigOptionUpdate,
    ) -> None:
        payload = schema.SessionNotification(session_id=session_id, update=update)
        await self.connection.send_notification(
            "session/update",
            json_value_adapter.validate_python(
                payload.model_dump(mode="json", by_alias=True, exclude_none=True)
            ),
        )

    async def new_session(
        self, request: schema.NewSessionRequest
    ) -> schema.NewSessionResponse:
        app = self.tentacle.octomate
        if request.mcp_servers:
            raise ValueError("Session-supplied MCP servers are not supported")
        if not self.routes:
            raise ValueError("No agent models are available")
        cwd, additional = await AcpProvider.resolve_workspace(
            request.cwd, request.additional_directories
        )
        if additional:
            raise ValueError("Server sessions use only their managed workspace")
        owner_id = self.sender.user_id
        if owner_id is None:
            raise ValueError("Creating a session requires a registered owner")
        project = await app.projects.resolve(owner_id, Path(cwd))
        selection = next(iter(self.routes.values()))
        thread = await app.threads.ensure(
            ThreadKey(
                channel_tentacle_id=self.tentacle.id,
                chat_type="thread",
                chat_id=str(self.sender.user_id),
                channel_thread_id=uuid7().hex,
            ),
            project=project,
            new=True,
            owner_id=self.sender.user_id,
        )
        await app.workspaces.resolve(thread.id, project, self.sender.user_id)
        session = AcpSession(thread)
        await self.select(session, selection)
        self.sessions[str(thread.id)] = session
        self.tentacle.clients[thread.id] = self
        return schema.NewSessionResponse(
            session_id=str(thread.id),
            config_options=await self.config_options(session),
            modes=await self.modes(session),
        )

    async def select(self, session: AcpSession, selection: AgentRouteKey) -> None:
        async with session.settings_lock:
            app = self.tentacle.octomate
            agent = app.agents[selection.agent_id]
            conversation = await agent.resolve_conversation(
                session.thread.id,
                conversation_address=session.thread.key.address(
                    self.sender.channel_user_id
                ),
            )
            if (
                session.thread.active_agent_tentacle_id,
                session.thread.active_model,
            ) != selection:
                await app.threads.record_handoff(
                    session.thread,
                    to_agent_tentacle_id=selection.agent_id,
                    to_model=selection.model,
                    source_agent_tentacle_id=session.thread.active_agent_tentacle_id,
                    target_conversation_id=conversation.id,
                    reason="The ACP caller selected this model.",
                )

    async def set_mode(self, session: AcpSession, mode: str) -> None:
        async with session.settings_lock:
            agent = self.tentacle.octomate.agents[session.selection.agent_id]
            agent.check_permission_mode(mode)
            conversation = await agent.resolve_conversation(
                session.thread.id,
                conversation_address=session.thread.key.address(
                    self.sender.channel_user_id
                ),
            )
            await agent.set_permission_mode(conversation, mode)

    async def modes(self, session: AcpSession) -> schema.SessionModeState | None:
        agent = self.tentacle.octomate.agents[session.selection.agent_id]
        if not agent.permission_modes:
            return None
        conversation = await agent.resolve_conversation(
            session.thread.id,
            conversation_address=session.thread.key.address(
                self.sender.channel_user_id
            ),
        )
        current = conversation.permission_mode or agent.default_permission_mode
        if current is None:
            return None
        return schema.SessionModeState(
            current_mode_id=current,
            available_modes=[
                schema.SessionMode(
                    id=mode.value, name=mode.name, description=mode.description
                )
                for mode in agent.permission_modes
            ],
        )

    async def reopen(
        self, request: schema.LoadSessionRequest | schema.ResumeSessionRequest
    ) -> schema.LoadSessionResponse | schema.ResumeSessionResponse:
        app = self.tentacle.octomate
        if request.mcp_servers:
            raise ValueError("Session-supplied MCP servers are not supported")
        thread_id = TypeAdapter(UUID7).validate_python(request.session_id)
        thread = await app.threads.get(thread_id, with_messages=True)
        if (
            thread is None
            or thread.channel_tentacle_id != self.tentacle.id
            or thread.chat_id != str(self.sender.user_id)
        ):
            raise ValueError("Session is unavailable")
        if thread.owner_id is None or thread.owner_id != self.sender.user_id:
            raise PermissionError("Only the thread owner may control this task")
        await AcpProvider.resolve_workspace(request.cwd, request.additional_directories)
        if request.additional_directories:
            raise ValueError("Server sessions use only their managed workspace")
        if thread.id in self.tentacle.clients:
            owner = self.tentacle.clients[thread.id]
            if not owner.disconnected:
                raise ValueError("Session is already attached to an ACP connection")
            await owner.closed.wait()
        session = AcpSession(thread)
        if session.selection not in self.routes.values():
            raise ValueError("The session's selected model is unavailable")
        # No await between checking and claiming the attachment.
        if thread.id in self.tentacle.clients:
            raise ValueError("Session is already attached to an ACP connection")
        self.tentacle.clients[thread.id] = self
        self.sessions[str(thread.id)] = session
        if isinstance(request, schema.LoadSessionRequest):
            for message in thread.messages:
                text = message.message_text or "\n".join(
                    str(segment) for segment in message.segments
                )
                if text:
                    update = (
                        schema.UserMessageChunk(
                            session_update="user_message_chunk",
                            content=acp.text_block(text),
                        )
                        if message.direction == "inbound"
                        else acp.update_agent_message_text(text)
                    )
                    await self.update(str(thread.id), update)
            return schema.LoadSessionResponse(
                config_options=await self.config_options(session),
                modes=await self.modes(session),
            )
        return schema.ResumeSessionResponse(
            config_options=await self.config_options(session),
            modes=await self.modes(session),
        )

    async def list_sessions(
        self, request: schema.ListSessionsRequest
    ) -> schema.ListSessionsResponse:
        app = self.tentacle.octomate
        owner_id = self.sender.user_id
        if owner_id is None:
            raise ValueError("Listing sessions requires a registered owner")
        offset = int(request.cursor or "0")
        if offset < 0:
            raise ValueError("Invalid session cursor")
        cwd = (
            (await AcpProvider.resolve_workspace(request.cwd))[0]
            if request.cwd
            else None
        )
        requested_project = (
            await app.projects.resolve(owner_id, Path(cwd))
            if cwd and not Path(cwd).is_relative_to(app.workspaces.volumes_dir)
            else None
        )
        rows = await app.threads.list_threads(
            self.tentacle.id, chat_id=str(self.sender.user_id), limit=100, offset=offset
        )
        sessions: list[schema.SessionInfo] = []
        for thread in rows:
            project = await app.projects.get(owner_id, thread=thread)
            volume = await app.volumes.find(
                owner_id, thread.id, project.id if project is not None else None
            )
            if volume is None:
                continue
            workspace = str(volume.path)
            if (
                cwd
                and cwd != workspace
                and (
                    project is None
                    or requested_project is None
                    or project.id != requested_project.id
                )
            ):
                continue
            sessions.append(
                schema.SessionInfo(
                    session_id=str(thread.id),
                    cwd=workspace,
                    title=thread.title,
                    updated_at=thread.updated_at.isoformat(),
                )
            )
        return schema.ListSessionsResponse(
            sessions=sessions,
            next_cursor=str(offset + len(rows)) if len(rows) == 100 else None,
        )

    async def prompt(self, request: schema.PromptRequest) -> schema.PromptResponse:
        app = self.tentacle.octomate
        session = self.session(request.session_id)
        if session.prompt_scope is not None or session.thread.key in app.awake_since:
            raise StillAwake()
        segments = prompt_segments(request)
        if session.selection not in self.routes.values():
            raise ValueError("The selected model is unavailable")
        with CancelScope() as scope:
            session.prompt_scope = scope
            try:
                await self.run_prompt(session, segments)
            finally:
                session.prompt_scope = None
        return schema.PromptResponse(
            stop_reason="cancelled" if scope.cancel_called else "end_turn"
        )

    async def settle(self, session: AcpSession) -> None:
        """Interrupt via the signal nerve and observe cleanup before detaching."""
        if not session.running:
            return
        app = self.tentacle.octomate
        with CancelScope(shield=True):
            async with self.nerves.events.subscribe(
                ThreadTopic(session.thread.key), replay=0
            ) as events:
                if session.thread.key in app.awake_since:
                    for agent_id in app.agents:
                        self.nerves.signals.deliver(
                            AgentTopic(agent_id),
                            AsleepSignal(thread=session.thread.key),
                        )
                    async for impulse in events:
                        if isinstance(impulse.event, ReflexAsleepEvent):
                            break
                session.running = False

    async def run_prompt(
        self, session: AcpSession, segments: list[MessageSegment]
    ) -> None:
        app = self.tentacle.octomate
        event = MessageEvent(
            tentacle_id=self.tentacle.id,
            chat_type="thread",
            chat_id=session.thread.chat_id,
            channel_thread_id=session.thread.channel_thread_id,
            user_id=self.sender.channel_user_id,
            sender=self.sender,
            message_id=uuid7().hex,
            segments=segments,
        )
        translator = AcpTranslator()
        try:
            inbound = await app.threads.record_inbound(event)
            signal: UserMessageSignal | DeferredActionBatchResponse = UserMessageSignal(
                [event],
                trigger_message=inbound,
            )
            while True:
                response = await self.drive(session, signal, translator)
                if response is None:
                    return
                signal = response
        finally:
            await self.settle(session)

    async def drive(
        self,
        session: AcpSession,
        signal: UserMessageSignal | DeferredActionBatchResponse,
        translator: AcpTranslator,
    ) -> DeferredActionBatchResponse | None:
        async with self.nerves.events.subscribe(
            ThreadTopic(session.thread.key)
        ) as stream:
            recipient = session.selection.agent_id
            if isinstance(signal, DeferredActionBatchResponse):
                batch = await self.tentacle.octomate.deferred_actions.get_batch(
                    signal.batch_id
                )
                recipient = batch.agent_tentacle_id
            self.nerves.signals.dispatch(AgentTopic(recipient), signal)
            session.running = True
            response = await self.read_events(session, stream, translator)
            session.running = False
        return response

    async def read_events(
        self,
        session: AcpSession,
        stream: ObjectReceiveStream[Impulse],
        translator: AcpTranslator,
    ) -> DeferredActionBatchResponse | None:
        """Translate the turn and answer live actions before awaiting its completion."""
        app = self.tentacle.octomate
        response: DeferredActionBatchResponse | None = None
        async for impulse in stream:
            event = impulse.event
            if isinstance(event, ReflexAsleepEvent):
                return response
            if isinstance(event, ActionBatchEvent):
                answer = await self.answer(str(session.thread.id), event)
                batch = await app.deferred_actions.get_batch(answer.batch_id)
                if batch.response_mode == "live":
                    self.nerves.signals.dispatch(
                        AgentTopic(batch.agent_tentacle_id), answer
                    )
                else:
                    response = answer
            for update in translator.translate(event):
                await self.update(str(session.thread.id), update)
        raise RuntimeError("The event stream ended before the turn settled")

    async def answer(
        self, session_id: str, event: ActionBatchEvent
    ) -> DeferredActionBatchResponse:
        response = DeferredActionBatchResponse(
            batch_id=TypeAdapter(UUID7).validate_python(event.batch_id),
            responder_id=self.sender.channel_user_id,
        )
        for approval in event.approvals:
            request = schema.RequestPermissionRequest(
                session_id=session_id,
                tool_call=schema.ToolCallUpdate(
                    tool_call_id=approval.tool_call_id,
                    title=approval.args.title,
                    status="pending",
                    raw_input=approval.args.args,
                    content=[
                        schema.ContentToolCallContent(
                            type="content",
                            content=acp.text_block(approval.args.description),
                        )
                    ]
                    if approval.args.description
                    else None,
                ),
                options=[
                    schema.PermissionOption(
                        option_id="allow", name="Allow once", kind="allow_once"
                    ),
                    schema.PermissionOption(
                        option_id="deny", name="Deny", kind="reject_once"
                    ),
                ],
            )
            result = schema.RequestPermissionResponse.model_validate(
                await self.connection.send_request(
                    "session/request_permission",
                    json_value_adapter.validate_python(
                        request.model_dump(
                            mode="json", by_alias=True, exclude_none=True
                        )
                    ),
                )
            )
            response.approvals[approval.id] = (
                result.outcome.outcome == "selected"
                and result.outcome.option_id == "allow"
            )
        for question in event.questions:
            elicitation = self.capabilities.elicitation
            if elicitation is None or elicitation.form is None:
                raise ValueError(
                    "This agent asked a question; the client must support form elicitation"
                )
            choices = question.args.get("choices") or []
            description = question.args.get("hint", "")
            if choices:
                description += "\nSuggested answers: " + "; ".join(choices)
            request = schema.CreateFormSessionElicitationRequest(
                session_id=session_id,
                tool_call_id=question.tool_call_id,
                message=question.args["question"],
                mode="form",
                requested_schema=schema.ElicitationSchema(
                    type="object",
                    properties={
                        "answer": schema.ElicitationStringPropertySchema(
                            type="string", description=description
                        )
                    },
                    required=["answer"],
                ),
            )
            result = TypeAdapter(schema.CreateElicitationResponse).validate_python(
                await self.connection.send_request(
                    "elicitation/create",
                    json_value_adapter.validate_python(
                        request.model_dump(
                            mode="json", by_alias=True, exclude_none=True
                        )
                    ),
                )
            )
            if isinstance(result, schema.AcceptElicitationResponse):
                response.answers[question.id] = TypeAdapter(
                    QuestionAnswer
                ).validate_python((result.content or {}).get("answer"))
            else:
                response.answers[question.id] = ""
        return response

    async def close(self) -> None:
        """Cancel active prompts before releasing this connection's attachments."""
        for session in self.sessions.values():
            if session.prompt_scope is not None:
                session.prompt_scope.cancel()
            await self.settle(session)
        for session in self.sessions.values():
            self.tentacle.clients.pop(session.thread.id, None)
        self.sessions.clear()
        self.closed.set()

tentacle instance-attribute

tentacle: AcpChannelTentacle

sender instance-attribute

sender: UserProfile

connection instance-attribute

connection: Connection

nerves instance-attribute

nerves: Nerves

initialized class-attribute instance-attribute

initialized: bool = False

capabilities class-attribute instance-attribute

capabilities: ClientCapabilities = field(
    default_factory=lambda: schema.ClientCapabilities()
)

sessions class-attribute instance-attribute

sessions: dict[str, AcpSession] = field(
    default_factory=dict
)

disconnected class-attribute instance-attribute

disconnected: bool = False

closed class-attribute instance-attribute

closed: Event = field(default_factory=asyncio.Event)

routes property

routes: dict[str, AgentRouteKey]

session

session(session_id: str) -> AcpSession
Source code in octomate/tentacles/acp/broker.py
def session(self, session_id: str) -> AcpSession:
    session = self.sessions.get(session_id)
    if session is None:
        raise ValueError("Session is not attached to this connection")
    return session

config_options async

config_options(
    session: AcpSession,
) -> list[
    schema.SessionConfigOptionSelect
    | schema.SessionConfigOptionBoolean
]
Source code in octomate/tentacles/acp/broker.py
async def config_options(
    self, session: AcpSession
) -> list[schema.SessionConfigOptionSelect | schema.SessionConfigOptionBoolean]:
    options: list[
        schema.SessionConfigOptionSelect | schema.SessionConfigOptionBoolean
    ] = [
        schema.SessionConfigOptionSelect(
            id="model",
            name="Model",
            category="model",
            type="select",
            current_value=f"{session.selection.agent_id}:{session.selection.model or ''}",
            options=[
                schema.SessionConfigSelectOption(
                    value=value,
                    name=f"{route.agent_id} / {route.model or 'Default'}",
                )
                for value, route in self.routes.items()
            ],
        )
    ]
    modes = await self.modes(session)
    if modes is not None:
        options.append(
            schema.SessionConfigOptionSelect(
                id="mode",
                name="Permissions",
                category="mode",
                type="select",
                current_value=modes.current_mode_id,
                options=[
                    schema.SessionConfigSelectOption(
                        value=mode.id, name=mode.name, description=mode.description
                    )
                    for mode in modes.available_modes
                ],
            )
        )
    return options

handle async

handle(
    method: str,
    params: JsonValue | None,
    notification: bool,
) -> JsonValue | None

Validate protocol payloads once, then dispatch typed session operations.

Source code in octomate/tentacles/acp/broker.py
async def handle(
    self, method: str, params: JsonValue | None, notification: bool
) -> JsonValue | None:
    """Validate protocol payloads once, then dispatch typed session operations."""
    if notification:
        if method == "session/cancel" and self.initialized:
            request = schema.CancelNotification.model_validate(params)
            session = self.sessions.get(request.session_id)
            if session is not None and session.prompt_scope is not None:
                session.prompt_scope.cancel()
        return None
    try:
        response = await self.request(method, params)
    except (ValueError, PermissionError, StillAwake) as error:
        raise acp.RequestError.invalid_params({"reason": str(error)}) from error
    return json_value_adapter.validate_python(
        response.model_dump(mode="json", by_alias=True, exclude_none=True)
    )

request async

request(
    method: str, params: JsonValue | None
) -> (
    schema.InitializeResponse
    | schema.NewSessionResponse
    | schema.LoadSessionResponse
    | schema.ResumeSessionResponse
    | schema.ListSessionsResponse
    | schema.PromptResponse
    | schema.SetSessionConfigOptionResponse
    | schema.SetSessionModeResponse
)
Source code in octomate/tentacles/acp/broker.py
async def request(
    self, method: str, params: JsonValue | None
) -> (
    schema.InitializeResponse
    | schema.NewSessionResponse
    | schema.LoadSessionResponse
    | schema.ResumeSessionResponse
    | schema.ListSessionsResponse
    | schema.PromptResponse
    | schema.SetSessionConfigOptionResponse
    | schema.SetSessionModeResponse
):
    if method == "initialize":
        if self.initialized:
            raise acp.RequestError.invalid_request(
                {"reason": "Already initialized"}
            )
        request = schema.InitializeRequest.model_validate(params)
        self.capabilities = (
            request.client_capabilities or schema.ClientCapabilities()
        )
        self.initialized = True
        return schema.InitializeResponse(
            protocol_version=acp.PROTOCOL_VERSION,
            agent_info=schema.Implementation(name="octomate", version="1"),
            auth_methods=[],
            agent_capabilities=schema.AgentCapabilities(
                auth=None,
                load_session=True,
                session_capabilities=schema.SessionCapabilities(
                    list=schema.SessionListCapabilities(),
                    resume=schema.SessionResumeCapabilities(),
                ),
                mcp_capabilities=schema.McpCapabilities(),
                prompt_capabilities=schema.PromptCapabilities(),
            ),
        )
    if not self.initialized:
        raise acp.RequestError.invalid_request({"reason": "Initialize first"})
    if method == "session/new":
        return await self.new_session(
            schema.NewSessionRequest.model_validate(params)
        )
    if method in {"session/load", "session/resume"}:
        request_type = (
            schema.LoadSessionRequest
            if method == "session/load"
            else schema.ResumeSessionRequest
        )
        return await self.reopen(request_type.model_validate(params))
    if method == "session/list":
        return await self.list_sessions(
            schema.ListSessionsRequest.model_validate(params)
        )
    if method == "session/prompt":
        return await self.prompt(schema.PromptRequest.model_validate(params))
    if method == "session/set_config_option":
        request = schema.SetSessionConfigOptionSelectRequest.model_validate(
            params, strict=True
        )
        session = self.session(request.session_id)
        if request.config_id == "model" and request.value in self.routes:
            await self.select(session, self.routes[request.value])
        elif request.config_id == "mode":
            await self.set_mode(session, request.value)
        else:
            raise ValueError("Unknown configuration option")
        options = await self.config_options(session)
        await self.update(
            request.session_id,
            schema.ConfigOptionUpdate(
                session_update="config_option_update", config_options=options
            ),
        )
        return schema.SetSessionConfigOptionResponse(config_options=options)
    if method == "session/set_mode":
        request = schema.SetSessionModeRequest.model_validate(params)
        session = self.session(request.session_id)
        await self.set_mode(session, request.mode_id)
        await self.update(
            request.session_id,
            schema.ConfigOptionUpdate(
                session_update="config_option_update",
                config_options=await self.config_options(session),
            ),
        )
        return schema.SetSessionModeResponse()
    raise acp.RequestError.method_not_found(method)

update async

update(
    session_id: str,
    update: AcpUpdate
    | UserMessageChunk
    | ConfigOptionUpdate,
) -> None
Source code in octomate/tentacles/acp/broker.py
async def update(
    self,
    session_id: str,
    update: AcpUpdate | schema.UserMessageChunk | schema.ConfigOptionUpdate,
) -> None:
    payload = schema.SessionNotification(session_id=session_id, update=update)
    await self.connection.send_notification(
        "session/update",
        json_value_adapter.validate_python(
            payload.model_dump(mode="json", by_alias=True, exclude_none=True)
        ),
    )

new_session async

new_session(
    request: NewSessionRequest,
) -> schema.NewSessionResponse
Source code in octomate/tentacles/acp/broker.py
async def new_session(
    self, request: schema.NewSessionRequest
) -> schema.NewSessionResponse:
    app = self.tentacle.octomate
    if request.mcp_servers:
        raise ValueError("Session-supplied MCP servers are not supported")
    if not self.routes:
        raise ValueError("No agent models are available")
    cwd, additional = await AcpProvider.resolve_workspace(
        request.cwd, request.additional_directories
    )
    if additional:
        raise ValueError("Server sessions use only their managed workspace")
    owner_id = self.sender.user_id
    if owner_id is None:
        raise ValueError("Creating a session requires a registered owner")
    project = await app.projects.resolve(owner_id, Path(cwd))
    selection = next(iter(self.routes.values()))
    thread = await app.threads.ensure(
        ThreadKey(
            channel_tentacle_id=self.tentacle.id,
            chat_type="thread",
            chat_id=str(self.sender.user_id),
            channel_thread_id=uuid7().hex,
        ),
        project=project,
        new=True,
        owner_id=self.sender.user_id,
    )
    await app.workspaces.resolve(thread.id, project, self.sender.user_id)
    session = AcpSession(thread)
    await self.select(session, selection)
    self.sessions[str(thread.id)] = session
    self.tentacle.clients[thread.id] = self
    return schema.NewSessionResponse(
        session_id=str(thread.id),
        config_options=await self.config_options(session),
        modes=await self.modes(session),
    )

select async

select(
    session: AcpSession, selection: AgentRouteKey
) -> None
Source code in octomate/tentacles/acp/broker.py
async def select(self, session: AcpSession, selection: AgentRouteKey) -> None:
    async with session.settings_lock:
        app = self.tentacle.octomate
        agent = app.agents[selection.agent_id]
        conversation = await agent.resolve_conversation(
            session.thread.id,
            conversation_address=session.thread.key.address(
                self.sender.channel_user_id
            ),
        )
        if (
            session.thread.active_agent_tentacle_id,
            session.thread.active_model,
        ) != selection:
            await app.threads.record_handoff(
                session.thread,
                to_agent_tentacle_id=selection.agent_id,
                to_model=selection.model,
                source_agent_tentacle_id=session.thread.active_agent_tentacle_id,
                target_conversation_id=conversation.id,
                reason="The ACP caller selected this model.",
            )

set_mode async

set_mode(session: AcpSession, mode: str) -> None
Source code in octomate/tentacles/acp/broker.py
async def set_mode(self, session: AcpSession, mode: str) -> None:
    async with session.settings_lock:
        agent = self.tentacle.octomate.agents[session.selection.agent_id]
        agent.check_permission_mode(mode)
        conversation = await agent.resolve_conversation(
            session.thread.id,
            conversation_address=session.thread.key.address(
                self.sender.channel_user_id
            ),
        )
        await agent.set_permission_mode(conversation, mode)

modes async

modes(
    session: AcpSession,
) -> schema.SessionModeState | None
Source code in octomate/tentacles/acp/broker.py
async def modes(self, session: AcpSession) -> schema.SessionModeState | None:
    agent = self.tentacle.octomate.agents[session.selection.agent_id]
    if not agent.permission_modes:
        return None
    conversation = await agent.resolve_conversation(
        session.thread.id,
        conversation_address=session.thread.key.address(
            self.sender.channel_user_id
        ),
    )
    current = conversation.permission_mode or agent.default_permission_mode
    if current is None:
        return None
    return schema.SessionModeState(
        current_mode_id=current,
        available_modes=[
            schema.SessionMode(
                id=mode.value, name=mode.name, description=mode.description
            )
            for mode in agent.permission_modes
        ],
    )

reopen async

reopen(
    request: LoadSessionRequest | ResumeSessionRequest,
) -> (
    schema.LoadSessionResponse
    | schema.ResumeSessionResponse
)
Source code in octomate/tentacles/acp/broker.py
async def reopen(
    self, request: schema.LoadSessionRequest | schema.ResumeSessionRequest
) -> schema.LoadSessionResponse | schema.ResumeSessionResponse:
    app = self.tentacle.octomate
    if request.mcp_servers:
        raise ValueError("Session-supplied MCP servers are not supported")
    thread_id = TypeAdapter(UUID7).validate_python(request.session_id)
    thread = await app.threads.get(thread_id, with_messages=True)
    if (
        thread is None
        or thread.channel_tentacle_id != self.tentacle.id
        or thread.chat_id != str(self.sender.user_id)
    ):
        raise ValueError("Session is unavailable")
    if thread.owner_id is None or thread.owner_id != self.sender.user_id:
        raise PermissionError("Only the thread owner may control this task")
    await AcpProvider.resolve_workspace(request.cwd, request.additional_directories)
    if request.additional_directories:
        raise ValueError("Server sessions use only their managed workspace")
    if thread.id in self.tentacle.clients:
        owner = self.tentacle.clients[thread.id]
        if not owner.disconnected:
            raise ValueError("Session is already attached to an ACP connection")
        await owner.closed.wait()
    session = AcpSession(thread)
    if session.selection not in self.routes.values():
        raise ValueError("The session's selected model is unavailable")
    # No await between checking and claiming the attachment.
    if thread.id in self.tentacle.clients:
        raise ValueError("Session is already attached to an ACP connection")
    self.tentacle.clients[thread.id] = self
    self.sessions[str(thread.id)] = session
    if isinstance(request, schema.LoadSessionRequest):
        for message in thread.messages:
            text = message.message_text or "\n".join(
                str(segment) for segment in message.segments
            )
            if text:
                update = (
                    schema.UserMessageChunk(
                        session_update="user_message_chunk",
                        content=acp.text_block(text),
                    )
                    if message.direction == "inbound"
                    else acp.update_agent_message_text(text)
                )
                await self.update(str(thread.id), update)
        return schema.LoadSessionResponse(
            config_options=await self.config_options(session),
            modes=await self.modes(session),
        )
    return schema.ResumeSessionResponse(
        config_options=await self.config_options(session),
        modes=await self.modes(session),
    )

list_sessions async

list_sessions(
    request: ListSessionsRequest,
) -> schema.ListSessionsResponse
Source code in octomate/tentacles/acp/broker.py
async def list_sessions(
    self, request: schema.ListSessionsRequest
) -> schema.ListSessionsResponse:
    app = self.tentacle.octomate
    owner_id = self.sender.user_id
    if owner_id is None:
        raise ValueError("Listing sessions requires a registered owner")
    offset = int(request.cursor or "0")
    if offset < 0:
        raise ValueError("Invalid session cursor")
    cwd = (
        (await AcpProvider.resolve_workspace(request.cwd))[0]
        if request.cwd
        else None
    )
    requested_project = (
        await app.projects.resolve(owner_id, Path(cwd))
        if cwd and not Path(cwd).is_relative_to(app.workspaces.volumes_dir)
        else None
    )
    rows = await app.threads.list_threads(
        self.tentacle.id, chat_id=str(self.sender.user_id), limit=100, offset=offset
    )
    sessions: list[schema.SessionInfo] = []
    for thread in rows:
        project = await app.projects.get(owner_id, thread=thread)
        volume = await app.volumes.find(
            owner_id, thread.id, project.id if project is not None else None
        )
        if volume is None:
            continue
        workspace = str(volume.path)
        if (
            cwd
            and cwd != workspace
            and (
                project is None
                or requested_project is None
                or project.id != requested_project.id
            )
        ):
            continue
        sessions.append(
            schema.SessionInfo(
                session_id=str(thread.id),
                cwd=workspace,
                title=thread.title,
                updated_at=thread.updated_at.isoformat(),
            )
        )
    return schema.ListSessionsResponse(
        sessions=sessions,
        next_cursor=str(offset + len(rows)) if len(rows) == 100 else None,
    )

prompt async

prompt(request: PromptRequest) -> schema.PromptResponse
Source code in octomate/tentacles/acp/broker.py
async def prompt(self, request: schema.PromptRequest) -> schema.PromptResponse:
    app = self.tentacle.octomate
    session = self.session(request.session_id)
    if session.prompt_scope is not None or session.thread.key in app.awake_since:
        raise StillAwake()
    segments = prompt_segments(request)
    if session.selection not in self.routes.values():
        raise ValueError("The selected model is unavailable")
    with CancelScope() as scope:
        session.prompt_scope = scope
        try:
            await self.run_prompt(session, segments)
        finally:
            session.prompt_scope = None
    return schema.PromptResponse(
        stop_reason="cancelled" if scope.cancel_called else "end_turn"
    )

settle async

settle(session: AcpSession) -> None

Interrupt via the signal nerve and observe cleanup before detaching.

Source code in octomate/tentacles/acp/broker.py
async def settle(self, session: AcpSession) -> None:
    """Interrupt via the signal nerve and observe cleanup before detaching."""
    if not session.running:
        return
    app = self.tentacle.octomate
    with CancelScope(shield=True):
        async with self.nerves.events.subscribe(
            ThreadTopic(session.thread.key), replay=0
        ) as events:
            if session.thread.key in app.awake_since:
                for agent_id in app.agents:
                    self.nerves.signals.deliver(
                        AgentTopic(agent_id),
                        AsleepSignal(thread=session.thread.key),
                    )
                async for impulse in events:
                    if isinstance(impulse.event, ReflexAsleepEvent):
                        break
            session.running = False

run_prompt async

run_prompt(
    session: AcpSession, segments: list[MessageSegment]
) -> None
Source code in octomate/tentacles/acp/broker.py
async def run_prompt(
    self, session: AcpSession, segments: list[MessageSegment]
) -> None:
    app = self.tentacle.octomate
    event = MessageEvent(
        tentacle_id=self.tentacle.id,
        chat_type="thread",
        chat_id=session.thread.chat_id,
        channel_thread_id=session.thread.channel_thread_id,
        user_id=self.sender.channel_user_id,
        sender=self.sender,
        message_id=uuid7().hex,
        segments=segments,
    )
    translator = AcpTranslator()
    try:
        inbound = await app.threads.record_inbound(event)
        signal: UserMessageSignal | DeferredActionBatchResponse = UserMessageSignal(
            [event],
            trigger_message=inbound,
        )
        while True:
            response = await self.drive(session, signal, translator)
            if response is None:
                return
            signal = response
    finally:
        await self.settle(session)

drive async

drive(
    session: AcpSession,
    signal: UserMessageSignal | DeferredActionBatchResponse,
    translator: AcpTranslator,
) -> DeferredActionBatchResponse | None
Source code in octomate/tentacles/acp/broker.py
async def drive(
    self,
    session: AcpSession,
    signal: UserMessageSignal | DeferredActionBatchResponse,
    translator: AcpTranslator,
) -> DeferredActionBatchResponse | None:
    async with self.nerves.events.subscribe(
        ThreadTopic(session.thread.key)
    ) as stream:
        recipient = session.selection.agent_id
        if isinstance(signal, DeferredActionBatchResponse):
            batch = await self.tentacle.octomate.deferred_actions.get_batch(
                signal.batch_id
            )
            recipient = batch.agent_tentacle_id
        self.nerves.signals.dispatch(AgentTopic(recipient), signal)
        session.running = True
        response = await self.read_events(session, stream, translator)
        session.running = False
    return response

read_events async

read_events(
    session: AcpSession,
    stream: ObjectReceiveStream[Impulse],
    translator: AcpTranslator,
) -> DeferredActionBatchResponse | None

Translate the turn and answer live actions before awaiting its completion.

Source code in octomate/tentacles/acp/broker.py
async def read_events(
    self,
    session: AcpSession,
    stream: ObjectReceiveStream[Impulse],
    translator: AcpTranslator,
) -> DeferredActionBatchResponse | None:
    """Translate the turn and answer live actions before awaiting its completion."""
    app = self.tentacle.octomate
    response: DeferredActionBatchResponse | None = None
    async for impulse in stream:
        event = impulse.event
        if isinstance(event, ReflexAsleepEvent):
            return response
        if isinstance(event, ActionBatchEvent):
            answer = await self.answer(str(session.thread.id), event)
            batch = await app.deferred_actions.get_batch(answer.batch_id)
            if batch.response_mode == "live":
                self.nerves.signals.dispatch(
                    AgentTopic(batch.agent_tentacle_id), answer
                )
            else:
                response = answer
        for update in translator.translate(event):
            await self.update(str(session.thread.id), update)
    raise RuntimeError("The event stream ended before the turn settled")

answer async

answer(
    session_id: str, event: ActionBatchEvent
) -> DeferredActionBatchResponse
Source code in octomate/tentacles/acp/broker.py
async def answer(
    self, session_id: str, event: ActionBatchEvent
) -> DeferredActionBatchResponse:
    response = DeferredActionBatchResponse(
        batch_id=TypeAdapter(UUID7).validate_python(event.batch_id),
        responder_id=self.sender.channel_user_id,
    )
    for approval in event.approvals:
        request = schema.RequestPermissionRequest(
            session_id=session_id,
            tool_call=schema.ToolCallUpdate(
                tool_call_id=approval.tool_call_id,
                title=approval.args.title,
                status="pending",
                raw_input=approval.args.args,
                content=[
                    schema.ContentToolCallContent(
                        type="content",
                        content=acp.text_block(approval.args.description),
                    )
                ]
                if approval.args.description
                else None,
            ),
            options=[
                schema.PermissionOption(
                    option_id="allow", name="Allow once", kind="allow_once"
                ),
                schema.PermissionOption(
                    option_id="deny", name="Deny", kind="reject_once"
                ),
            ],
        )
        result = schema.RequestPermissionResponse.model_validate(
            await self.connection.send_request(
                "session/request_permission",
                json_value_adapter.validate_python(
                    request.model_dump(
                        mode="json", by_alias=True, exclude_none=True
                    )
                ),
            )
        )
        response.approvals[approval.id] = (
            result.outcome.outcome == "selected"
            and result.outcome.option_id == "allow"
        )
    for question in event.questions:
        elicitation = self.capabilities.elicitation
        if elicitation is None or elicitation.form is None:
            raise ValueError(
                "This agent asked a question; the client must support form elicitation"
            )
        choices = question.args.get("choices") or []
        description = question.args.get("hint", "")
        if choices:
            description += "\nSuggested answers: " + "; ".join(choices)
        request = schema.CreateFormSessionElicitationRequest(
            session_id=session_id,
            tool_call_id=question.tool_call_id,
            message=question.args["question"],
            mode="form",
            requested_schema=schema.ElicitationSchema(
                type="object",
                properties={
                    "answer": schema.ElicitationStringPropertySchema(
                        type="string", description=description
                    )
                },
                required=["answer"],
            ),
        )
        result = TypeAdapter(schema.CreateElicitationResponse).validate_python(
            await self.connection.send_request(
                "elicitation/create",
                json_value_adapter.validate_python(
                    request.model_dump(
                        mode="json", by_alias=True, exclude_none=True
                    )
                ),
            )
        )
        if isinstance(result, schema.AcceptElicitationResponse):
            response.answers[question.id] = TypeAdapter(
                QuestionAnswer
            ).validate_python((result.content or {}).get("answer"))
        else:
            response.answers[question.id] = ""
    return response

close async

close() -> None

Cancel active prompts before releasing this connection's attachments.

Source code in octomate/tentacles/acp/broker.py
async def close(self) -> None:
    """Cancel active prompts before releasing this connection's attachments."""
    for session in self.sessions.values():
        if session.prompt_scope is not None:
            session.prompt_scope.cancel()
        await self.settle(session)
    for session in self.sessions.values():
        self.tentacle.clients.pop(session.thread.id, None)
    self.sessions.clear()
    self.closed.set()

octomate.tentacles.acp.routes

ACP v1 at WS /api/acp, exposing Octomate as one agent.

The Authorization header carries an acp-scoped bearer. Send one JSON-RPC object per text frame; this is a custom WebSocket transport, not Streamable HTTP. Initialize, create or reopen a session, and select a returned model option using session/set_config_option with configId: "model". Provider names never occur in the URL. See AcpBroker for session ownership, workspace and MCP contracts.

build_acp_router

build_acp_router(tentacle: AcpChannelTentacle) -> APIRouter

Bind authentication and connections to the registered ACP instance.

Source code in octomate/tentacles/acp/routes.py
def build_acp_router(tentacle: AcpChannelTentacle) -> APIRouter:
    """Bind authentication and connections to the registered ACP instance."""
    router = APIRouter(prefix="/api/acp", tags=[tentacle.type])

    @router.websocket("")
    async def acp_connection(
        websocket: WebSocket,
        nerves: Annotated[Nerves, Depends(nervous_system)],
        sender: Annotated[UserProfile, Depends(acp_sender(tentacle))],
    ) -> None:
        """Serve the authenticated caller through registered agents and the reflex."""

        async def handle(
            method: str, params: JsonValue | None, notification: bool
        ) -> JsonValue | None:
            return await broker.handle(method, params, notification)

        await websocket.accept()
        async with websocket_connection(websocket, handle) as connection:
            broker = AcpBroker(tentacle, sender, connection, nerves)

            async def shutdown() -> None:
                broker.disconnected = True
                with CancelScope(shield=True):
                    try:
                        await connection.close()
                    finally:
                        await broker.close()

            try:
                await connection.main_loop()
            finally:
                await shutdown()

    return router

octomate.tentacles.acp.transport

Carry ACP JSON-RPC through the SDK's stream connection.

stdio_connection async

stdio_connection(
    handler: AcpClientHandler,
    command: str,
    *args: str,
    habitat: Habitat | None = None,
    cwd: str | None = None,
    env: dict[str, str] | None = None,
) -> AsyncGenerator[Connection]

Own the provider process in its execution environment, preserving ACP bytes.

Source code in octomate/tentacles/acp/transport.py
@asynccontextmanager
async def stdio_connection(
    handler: AcpClientHandler,
    command: str,
    *args: str,
    habitat: Habitat | None = None,
    cwd: str | None = None,
    env: dict[str, str] | None = None,
) -> AsyncGenerator[Connection]:
    """Own the provider process in its execution environment, preserving ACP bytes."""
    if not isinstance(habitat, HostedHabitat):
        async with acp.spawn_stdio_connection(
            handler,
            command,
            *args,
            env=env,
            stderr=None,
            limit=DEFAULT_STDIO_BUFFER_LIMIT_BYTES,
        ) as (connection, _process):
            yield connection
        return
    if cwd is None:
        raise ValueError("Habitat ACP connections require a guest working directory")
    async with (
        habitat.resident(command, *args, workdir=cwd, env=env) as stream,
        stream_connection(stream, handler) as connection,
    ):
        yield connection

stream_connection async

stream_connection(
    stream: ByteStream, handler: AcpClientHandler
) -> AsyncGenerator[Connection]

Bridge a habitat byte stream to the SDK's public asyncio stream interface.

Source code in octomate/tentacles/acp/transport.py
@asynccontextmanager
async def stream_connection(
    stream: ByteStream, handler: AcpClientHandler
) -> AsyncGenerator[Connection]:
    """Bridge a habitat byte stream to the SDK's public asyncio stream interface."""

    async def receive() -> None:
        try:
            while True:
                incoming.write(await stream.receive())
                await incoming.drain()
        except anyio.EndOfStream:
            incoming.write_eof()
        except Exception as error:
            reader.set_exception(error)

    async def send() -> None:
        try:
            while data := await outgoing.read(65536):
                await stream.send(data)
            await stream.send_eof()
        except Exception as error:
            reader.set_exception(error)

    local, peer = socket.socketpair()
    writers: list[asyncio.StreamWriter] = []
    receiving: asyncio.Task[None] | None = None
    sending: asyncio.Task[None] | None = None
    with local, peer:
        try:
            reader, writer = await asyncio.open_connection(
                sock=local, limit=DEFAULT_STDIO_BUFFER_LIMIT_BYTES
            )
            writers.append(writer)
            outgoing, incoming = await asyncio.open_connection(
                sock=peer, limit=DEFAULT_STDIO_BUFFER_LIMIT_BYTES
            )
            writers.append(incoming)
            receiving = asyncio.create_task(receive())
            sending = asyncio.create_task(send())
            async with Connection(handler, writer, reader) as connection:
                yield connection
        finally:
            with CancelScope(shield=True):
                for writer in writers:
                    writer.close()
                if sending is not None:
                    await sending
                if receiving is not None:
                    receiving.cancel()
                    await asyncio.gather(receiving, return_exceptions=True)
                await asyncio.gather(*(writer.wait_closed() for writer in writers))

websocket_connection async

websocket_connection(
    websocket: WebSocket, handler: AcpClientHandler
) -> AsyncGenerator[Connection]

Adapt one JSON object per text frame to the SDK's newline-delimited streams.

A local socket pair supplies real asyncio streams without a TCP listener or SDK-private hooks. The SDK owns request IDs, callbacks and dispatch. Call main_loop on the yielded connection to serve until the WebSocket closes. Malformed JSON, non-object payloads and binary frames close with code 1008.

Source code in octomate/tentacles/acp/transport.py
@asynccontextmanager
async def websocket_connection(
    websocket: WebSocket, handler: AcpClientHandler
) -> AsyncGenerator[Connection]:
    """Adapt one JSON object per text frame to the SDK's newline-delimited streams.

    A local socket pair supplies real asyncio streams without a TCP listener or
    SDK-private hooks. The SDK owns request IDs, callbacks and dispatch. Call
    `main_loop` on the yielded connection to serve until the WebSocket closes.
    Malformed JSON, non-object payloads and binary frames close with code 1008.
    """
    stack = AsyncExitStack()
    try:
        sockets = socket.socketpair()
        for endpoint in sockets:
            stack.callback(endpoint.close)
        streams: list[tuple[asyncio.StreamReader, asyncio.StreamWriter]] = []
        for endpoint in sockets:
            reader, writer = await asyncio.open_connection(
                sock=endpoint, limit=DEFAULT_STDIO_BUFFER_LIMIT_BYTES
            )
            stack.push_async_callback(writer.wait_closed)
            stack.callback(writer.close)
            streams.append((reader, writer))
        (reader, writer), (outgoing, incoming) = streams
        connection = await stack.enter_async_context(
            Connection(handler, writer, reader, listening=False)
        )

        async def receive() -> None:
            try:
                while True:
                    message = await websocket.receive()
                    if message["type"] == "websocket.disconnect":
                        return
                    payload = json_value_adapter.validate_json(
                        message.get("text") or ""
                    )
                    if not isinstance(payload, dict) or payload.get("jsonrpc") != "2.0":
                        raise ValueError("Expected a JSON-RPC object")
                    incoming.write(to_json(payload) + b"\n")
                    await incoming.drain()
            except (ValidationError, ValueError):
                await websocket.close(
                    code=1008, reason="Expected a JSON-RPC text frame"
                )
            finally:
                incoming.write_eof()

        async def send() -> None:
            while line := await outgoing.readline():
                await websocket.send_text(line.decode().rstrip("\n"))

        async with asyncio.TaskGroup() as tasks:
            receiving = tasks.create_task(receive())
            sending = tasks.create_task(send())
            try:
                yield connection
            finally:
                receiving.cancel()
                sending.cancel()
    finally:
        with CancelScope(shield=True):
            await stack.aclose()

octomate.tentacles.acp.auth

Authenticate the project ACP endpoint before accepting a connection.

acp_sender

acp_sender(
    tentacle: AcpChannelTentacle,
) -> Callable[[str | None], Awaitable[UserProfile]]

Bind the ACP bearer dependency to the tentacle mounted by the router.

A router uses this dependency before accepting a WebSocket. Only the Authorization header supplies a credential; browser cookies and query parameters cannot authorize agent execution. The bearer verifier accepts scoped API keys and resource-bound OAuth tokens, checking scope, expiry and revocation on each connection attempt.

The returned profile is transient. Authenticating creates no thread, session or ledger entry and grants no authority over another connection's sessions.

Source code in octomate/tentacles/acp/auth.py
def acp_sender(
    tentacle: AcpChannelTentacle,
) -> Callable[[str | None], Awaitable[UserProfile]]:
    """Bind the ACP bearer dependency to the tentacle mounted by the router.

    A router uses this dependency before accepting a WebSocket.
    Only the Authorization header supplies a credential; browser cookies
    and query parameters cannot authorize agent execution. The bearer
    verifier accepts scoped API keys and resource-bound OAuth tokens, checking
    scope, expiry and revocation on each connection attempt.

    The returned profile is transient. Authenticating creates no thread, session
    or ledger entry and grants no authority over another connection's sessions.
    """

    async def sender(
        authorization: Annotated[str | None, Header()] = None,
    ) -> UserProfile:
        app = tentacle.octomate
        scheme, _, token = (authorization or "").partition(" ")
        username = (
            await app.bearers.owner(token, scope="acp")
            if scheme.lower() == "bearer" and token
            else None
        )
        if username is None:
            raise HTTPException(
                status_code=401,
                detail="Invalid ACP credentials",
                headers={"WWW-Authenticate": "Bearer"},
            )
        profile = await app.users.native_profile(tentacle.id, username)
        if profile is None:
            raise RuntimeError("Verified ACP bearer has no registered owner")
        return profile

    return sender

octomate.tentacles.acp.client

Own installed ACP harness connections and their provider sessions.

The installed adapters speak ACP over stdio. The SDK owns framing, request IDs and concurrent callbacks; the transport owns the local or habitat process. A caller handles agent requests and notifications directly; the nerve is not a request/reply transport.

This is the client foundation, not a registered agent or a public API. It neither creates managed workspaces nor persists transcripts. Authentication, session access checks and ledger projection belong to the caller that exposes a session.

AcpClientHandler

AcpClientHandler = Callable[
    [str, JsonValue | None, bool],
    Awaitable[JsonValue | None],
]

NativeAcpSession dataclass

A provider-owned session, retaining its ACP response and workspace.

The session ID is opaque and scoped to its configured harness. This binding does not itself register an Octomate thread or grant access to one.

Source code in octomate/tentacles/acp/client.py
@dataclass(frozen=True)
class NativeAcpSession[
    ResponseT: schema.NewSessionResponse
    | schema.LoadSessionResponse
    | schema.ResumeSessionResponse
]:
    """A provider-owned session, retaining its ACP response and workspace.

    The session ID is opaque and scoped to its configured harness. This binding
    does not itself register an Octomate thread or grant access to one.
    """

    provider: AcpProvider
    cwd: str  # Canonical server workspace path.
    session_id: str  # Native identity supplied by creation or an authorized reopen.
    response: ResponseT  # Includes provider modes and extensions.

    @property
    def mode_option(self) -> schema.SessionConfigOptionSelect | None:
        """Prefer the mode config selector over the legacy session modes API."""
        return next(
            (
                option
                for option in self.response.config_options or []
                if isinstance(option, schema.SessionConfigOptionSelect)
                and option.category == "mode"
            ),
            None,
        )

    @property
    def permission_modes(self) -> tuple[PermissionMode, ...]:
        """Keep provider mode ids, labels, and scope descriptions intact."""
        if (option := self.mode_option) is not None:
            return tuple(
                PermissionMode(
                    value=value.value, name=value.name, description=value.description
                )
                for entry in option.options
                for value in (
                    entry.options
                    if isinstance(entry, schema.SessionConfigSelectGroup)
                    else [entry]
                )
            )
        return (
            tuple(
                PermissionMode(
                    value=mode.id, name=mode.name, description=mode.description
                )
                for mode in self.response.modes.available_modes
            )
            if self.response.modes is not None
            else ()
        )

    @property
    def permission_mode(self) -> str | None:
        if (option := self.mode_option) is not None:
            return option.current_value
        return self.response.modes.current_mode_id if self.response.modes else None

    async def select_mode(self, connection: Connection, mode: str | None) -> None:
        """Apply an explicit provider mode before prompting, including on reload."""
        if mode is None:
            return
        if mode not in {option.value for option in self.permission_modes}:
            raise ValueError(f"The ACP session does not offer mode {mode!r}")
        if mode == self.permission_mode:
            return
        if (option := self.mode_option) is not None:
            response = await request_model(
                connection,
                acp.AGENT_METHODS["session_set_config_option"],
                schema.SetSessionConfigOptionSelectRequest(
                    session_id=self.session_id, config_id=option.id, value=mode
                ),
                schema.SetSessionConfigOptionResponse,
            )
            self.response.config_options = response.config_options
            return
        await request_model(
            connection,
            acp.AGENT_METHODS["session_set_mode"],
            schema.SetSessionModeRequest(session_id=self.session_id, mode_id=mode),
            schema.SetSessionModeResponse,
        )
        assert self.response.modes is not None
        self.response.modes.current_mode_id = mode

    @property
    def model_option(self) -> schema.SessionConfigOptionSelect | None:
        """The first advertised model selector, including uncategorized `model`."""
        return next(
            (
                option
                for option in self.response.config_options or []
                if isinstance(option, schema.SessionConfigOptionSelect)
                and (option.category == "model" or option.id == "model")
            ),
            None,
        )

    @property
    def models(self) -> list[schema.SessionConfigSelectOption]:
        """Flatten the protocol's grouped or ungrouped model choices."""
        option = self.model_option
        return (
            [
                value
                for entry in option.options
                for value in (
                    entry.options
                    if isinstance(entry, schema.SessionConfigSelectGroup)
                    else [entry]
                )
            ]
            if option is not None
            else []
        )

    @property
    def effort_option(self) -> schema.SessionConfigOptionSelect | None:
        """The first advertised reasoning selector, using its semantic category."""
        return next(
            (
                option
                for option in self.response.config_options or []
                if isinstance(option, schema.SessionConfigOptionSelect)
                and option.category == "thought_level"
            ),
            None,
        )

    @property
    def efforts(self) -> tuple[str, ...]:
        """The current model's reasoning levels, in the provider's order."""
        option = self.effort_option
        return (
            tuple(
                value.value
                for entry in option.options
                for value in (
                    entry.options
                    if isinstance(entry, schema.SessionConfigSelectGroup)
                    else [entry]
                )
            )
            if option is not None
            else ()
        )

    async def select_model(
        self, connection: Connection, model: str | None
    ) -> str | None:
        """Validate against this session's choices before changing its model."""
        option = self.model_option
        if option is None:
            if model not in (None, "default"):
                raise ValueError("The ACP provider has no model selector")
            return None
        if model is None:
            return option.current_value
        if model not in {value.value for value in self.models}:
            raise ValueError(f"The ACP session does not offer model {model!r}")
        if model != option.current_value:
            response = await request_model(
                connection,
                acp.AGENT_METHODS["session_set_config_option"],
                schema.SetSessionConfigOptionSelectRequest(
                    session_id=self.session_id, config_id=option.id, value=model
                ),
                schema.SetSessionConfigOptionResponse,
            )
            self.response.config_options = response.config_options
        return model

    async def select_effort(self, connection: Connection, effort: str | None) -> None:
        """Apply an explicit effort after model selection has refreshed its choices.

        Omitting effort preserves the provider session's current setting.
        """
        if effort is None:
            return
        option = self.effort_option
        if option is None or effort not in self.efforts:
            raise ValueError(f"The ACP session does not offer effort {effort!r}")
        if effort != option.current_value:
            response = await request_model(
                connection,
                acp.AGENT_METHODS["session_set_config_option"],
                schema.SetSessionConfigOptionSelectRequest(
                    session_id=self.session_id, config_id=option.id, value=effort
                ),
                schema.SetSessionConfigOptionResponse,
            )
            self.response.config_options = response.config_options

provider instance-attribute

provider: AcpProvider

cwd instance-attribute

cwd: str

session_id instance-attribute

session_id: str

response instance-attribute

response: ResponseT

mode_option property

mode_option: SessionConfigOptionSelect | None

Prefer the mode config selector over the legacy session modes API.

permission_modes property

permission_modes: tuple[PermissionMode, ...]

Keep provider mode ids, labels, and scope descriptions intact.

permission_mode property

permission_mode: str | None

model_option property

model_option: SessionConfigOptionSelect | None

The first advertised model selector, including uncategorized model.

models property

models: list[SessionConfigSelectOption]

Flatten the protocol's grouped or ungrouped model choices.

effort_option property

effort_option: SessionConfigOptionSelect | None

The first advertised reasoning selector, using its semantic category.

efforts property

efforts: tuple[str, ...]

The current model's reasoning levels, in the provider's order.

select_mode async

select_mode(
    connection: Connection, mode: str | None
) -> None

Apply an explicit provider mode before prompting, including on reload.

Source code in octomate/tentacles/acp/client.py
async def select_mode(self, connection: Connection, mode: str | None) -> None:
    """Apply an explicit provider mode before prompting, including on reload."""
    if mode is None:
        return
    if mode not in {option.value for option in self.permission_modes}:
        raise ValueError(f"The ACP session does not offer mode {mode!r}")
    if mode == self.permission_mode:
        return
    if (option := self.mode_option) is not None:
        response = await request_model(
            connection,
            acp.AGENT_METHODS["session_set_config_option"],
            schema.SetSessionConfigOptionSelectRequest(
                session_id=self.session_id, config_id=option.id, value=mode
            ),
            schema.SetSessionConfigOptionResponse,
        )
        self.response.config_options = response.config_options
        return
    await request_model(
        connection,
        acp.AGENT_METHODS["session_set_mode"],
        schema.SetSessionModeRequest(session_id=self.session_id, mode_id=mode),
        schema.SetSessionModeResponse,
    )
    assert self.response.modes is not None
    self.response.modes.current_mode_id = mode

select_model async

select_model(
    connection: Connection, model: str | None
) -> str | None

Validate against this session's choices before changing its model.

Source code in octomate/tentacles/acp/client.py
async def select_model(
    self, connection: Connection, model: str | None
) -> str | None:
    """Validate against this session's choices before changing its model."""
    option = self.model_option
    if option is None:
        if model not in (None, "default"):
            raise ValueError("The ACP provider has no model selector")
        return None
    if model is None:
        return option.current_value
    if model not in {value.value for value in self.models}:
        raise ValueError(f"The ACP session does not offer model {model!r}")
    if model != option.current_value:
        response = await request_model(
            connection,
            acp.AGENT_METHODS["session_set_config_option"],
            schema.SetSessionConfigOptionSelectRequest(
                session_id=self.session_id, config_id=option.id, value=model
            ),
            schema.SetSessionConfigOptionResponse,
        )
        self.response.config_options = response.config_options
    return model

select_effort async

select_effort(
    connection: Connection, effort: str | None
) -> None

Apply an explicit effort after model selection has refreshed its choices.

Omitting effort preserves the provider session's current setting.

Source code in octomate/tentacles/acp/client.py
async def select_effort(self, connection: Connection, effort: str | None) -> None:
    """Apply an explicit effort after model selection has refreshed its choices.

    Omitting effort preserves the provider session's current setting.
    """
    if effort is None:
        return
    option = self.effort_option
    if option is None or effort not in self.efforts:
        raise ValueError(f"The ACP session does not offer effort {effort!r}")
    if effort != option.current_value:
        response = await request_model(
            connection,
            acp.AGENT_METHODS["session_set_config_option"],
            schema.SetSessionConfigOptionSelectRequest(
                session_id=self.session_id, config_id=option.id, value=effort
            ),
            schema.SetSessionConfigOptionResponse,
        )
        self.response.config_options = response.config_options

NativeAcpClient dataclass

One initialized adapter connection, which may own several native sessions.

Use the SDK connection for ACP requests and notifications. Keeping the typed request models at that boundary preserves _meta without flattening its keys into method arguments. The peer's initialization response remains available for capability negotiation before a caller exposes any optional operations.

Source code in octomate/tentacles/acp/client.py
@dataclass(frozen=True)
class NativeAcpClient:
    """One initialized adapter connection, which may own several native sessions.

    Use the SDK connection for ACP requests and notifications. Keeping the typed
    request models at that boundary preserves `_meta` without flattening its keys
    into method arguments. The peer's initialization response remains available
    for capability negotiation before a caller exposes any optional operations.
    """

    provider: AcpProvider
    connection: Connection  # Live only inside the connect context.
    initialization: schema.InitializeResponse
    habitat: Habitat | None = None  # Owns provider execution and path interpretation.

    @classmethod
    @asynccontextmanager
    async def connect(
        cls,
        provider: AcpProvider,
        handler: AcpClientHandler,
        initialize: schema.InitializeRequest,
        *,
        env: dict[str, str] | None = None,
        habitat: Habitat | None = None,
        cwd: str | None = None,
    ) -> AsyncGenerator[Self]:
        """Start an installed adapter and negotiate ACP v1 before yielding.

        `handler` receives the method, JSON parameters and notification flag for
        agent-to-client traffic, including permissions. `initialize` declares
        only capabilities that handler implements. Local processes augment the
        SDK's minimal inherited environment; habitat processes receive explicit
        environment overrides. Local stderr is inherited; habitat failures retain
        their stderr through the habitat. Stdout is exclusively protocol traffic.

        Exiting closes this connection and its process, including on failed
        initialization or cancellation. It does not delete provider sessions.
        """
        if initialize.protocol_version != acp.PROTOCOL_VERSION:
            raise ValueError("The native ACP client requires protocol version 1")
        async with stdio_connection(
            handler,
            provider.command,
            *provider.args,
            env={
                **{
                    name: value.get_secret_value()
                    for name, value in provider.env.items()
                },
                **(env or {}),
            },
            habitat=habitat,
            cwd=cwd,
        ) as connection:
            response = await request_model(
                connection,
                acp.AGENT_METHODS["initialize"],
                initialize,
                schema.InitializeResponse,
            )
            if response.protocol_version != initialize.protocol_version:
                raise ValueError(
                    f"ACP agent selected unsupported protocol {response.protocol_version}"
                )
            if provider.auth_method is not None:
                if provider.auth_method not in {
                    method.id for method in response.auth_methods or []
                }:
                    raise ValueError(
                        "The ACP provider does not offer this authentication method"
                    )
                await request_model(
                    connection,
                    acp.AGENT_METHODS["authenticate"],
                    schema.AuthenticateRequest(method_id=provider.auth_method),
                    schema.AuthenticateResponse,
                )
            yield cls(provider, connection, response, habitat)

    async def new_session(
        self, request: schema.NewSessionRequest
    ) -> NativeAcpSession[schema.NewSessionResponse]:
        """Create a native session using the supplied workspace and MCP settings.

        The agent tentacle supplies the managed server workspace.
        HTTP MCP settings and extensions cross the SDK boundary intact, without
        mutating the caller's request. MCP process commands are refused.
        """
        if any(
            not isinstance(server, schema.HttpMcpServer)
            for server in request.mcp_servers
        ):
            raise ValueError("Only HTTP MCP servers are supported")
        if isinstance(self.habitat, HostedHabitat):
            if any(
                not PurePosixPath(path).is_absolute()
                for path in [request.cwd, *(request.additional_directories or [])]
            ):
                raise ValueError("ACP workspace paths must be absolute")
        else:
            cwd, additional_directories = await self.provider.resolve_workspace(
                request.cwd,
                request.additional_directories,
            )
            request = request.model_copy(
                update={"cwd": cwd, "additional_directories": additional_directories}
            )
        response = await request_model(
            self.connection,
            acp.AGENT_METHODS["session_new"],
            request,
            schema.NewSessionResponse,
        )
        return NativeAcpSession(
            self.provider, request.cwd, response.session_id, response
        )

provider instance-attribute

provider: AcpProvider

connection instance-attribute

connection: Connection

initialization instance-attribute

initialization: InitializeResponse

habitat class-attribute instance-attribute

habitat: Habitat | None = None

connect async classmethod

connect(
    provider: AcpProvider,
    handler: AcpClientHandler,
    initialize: InitializeRequest,
    *,
    env: dict[str, str] | None = None,
    habitat: Habitat | None = None,
    cwd: str | None = None,
) -> AsyncGenerator[Self]

Start an installed adapter and negotiate ACP v1 before yielding.

handler receives the method, JSON parameters and notification flag for agent-to-client traffic, including permissions. initialize declares only capabilities that handler implements. Local processes augment the SDK's minimal inherited environment; habitat processes receive explicit environment overrides. Local stderr is inherited; habitat failures retain their stderr through the habitat. Stdout is exclusively protocol traffic.

Exiting closes this connection and its process, including on failed initialization or cancellation. It does not delete provider sessions.

Source code in octomate/tentacles/acp/client.py
@classmethod
@asynccontextmanager
async def connect(
    cls,
    provider: AcpProvider,
    handler: AcpClientHandler,
    initialize: schema.InitializeRequest,
    *,
    env: dict[str, str] | None = None,
    habitat: Habitat | None = None,
    cwd: str | None = None,
) -> AsyncGenerator[Self]:
    """Start an installed adapter and negotiate ACP v1 before yielding.

    `handler` receives the method, JSON parameters and notification flag for
    agent-to-client traffic, including permissions. `initialize` declares
    only capabilities that handler implements. Local processes augment the
    SDK's minimal inherited environment; habitat processes receive explicit
    environment overrides. Local stderr is inherited; habitat failures retain
    their stderr through the habitat. Stdout is exclusively protocol traffic.

    Exiting closes this connection and its process, including on failed
    initialization or cancellation. It does not delete provider sessions.
    """
    if initialize.protocol_version != acp.PROTOCOL_VERSION:
        raise ValueError("The native ACP client requires protocol version 1")
    async with stdio_connection(
        handler,
        provider.command,
        *provider.args,
        env={
            **{
                name: value.get_secret_value()
                for name, value in provider.env.items()
            },
            **(env or {}),
        },
        habitat=habitat,
        cwd=cwd,
    ) as connection:
        response = await request_model(
            connection,
            acp.AGENT_METHODS["initialize"],
            initialize,
            schema.InitializeResponse,
        )
        if response.protocol_version != initialize.protocol_version:
            raise ValueError(
                f"ACP agent selected unsupported protocol {response.protocol_version}"
            )
        if provider.auth_method is not None:
            if provider.auth_method not in {
                method.id for method in response.auth_methods or []
            }:
                raise ValueError(
                    "The ACP provider does not offer this authentication method"
                )
            await request_model(
                connection,
                acp.AGENT_METHODS["authenticate"],
                schema.AuthenticateRequest(method_id=provider.auth_method),
                schema.AuthenticateResponse,
            )
        yield cls(provider, connection, response, habitat)

new_session async

new_session(
    request: NewSessionRequest,
) -> NativeAcpSession[schema.NewSessionResponse]

Create a native session using the supplied workspace and MCP settings.

The agent tentacle supplies the managed server workspace. HTTP MCP settings and extensions cross the SDK boundary intact, without mutating the caller's request. MCP process commands are refused.

Source code in octomate/tentacles/acp/client.py
async def new_session(
    self, request: schema.NewSessionRequest
) -> NativeAcpSession[schema.NewSessionResponse]:
    """Create a native session using the supplied workspace and MCP settings.

    The agent tentacle supplies the managed server workspace.
    HTTP MCP settings and extensions cross the SDK boundary intact, without
    mutating the caller's request. MCP process commands are refused.
    """
    if any(
        not isinstance(server, schema.HttpMcpServer)
        for server in request.mcp_servers
    ):
        raise ValueError("Only HTTP MCP servers are supported")
    if isinstance(self.habitat, HostedHabitat):
        if any(
            not PurePosixPath(path).is_absolute()
            for path in [request.cwd, *(request.additional_directories or [])]
        ):
            raise ValueError("ACP workspace paths must be absolute")
    else:
        cwd, additional_directories = await self.provider.resolve_workspace(
            request.cwd,
            request.additional_directories,
        )
        request = request.model_copy(
            update={"cwd": cwd, "additional_directories": additional_directories}
        )
    response = await request_model(
        self.connection,
        acp.AGENT_METHODS["session_new"],
        request,
        schema.NewSessionResponse,
    )
    return NativeAcpSession(
        self.provider, request.cwd, response.session_id, response
    )

octomate.tentacles.acp.history

The conversation visible through ACP, folded into a driven run's messages.

ACP exposes presentation content, not native model turns. Each prompt becomes one request and its output one response, labelled with source=acp. Original content and updates are retained in metadata; model names, usage and native turn IDs are not inferred. Reported context snapshots are independent of billing usage. Tool titles are presentation names, not executable tools.

ContentBlock

ContentBlock = (
    TextContentBlock
    | ImageContentBlock
    | AudioContentBlock
    | ResourceContentBlock
    | EmbeddedResourceContentBlock
)

AcpHistory dataclass

Accumulate one prompt in wire order, producing the same live and stored content.

A changed message ID or content kind ends a text part. Tool updates replace supplied fields, retaining omitted fields. Raw updates also preserve plans, settings, diffs, terminals and provider metadata without inventing model parts.

Source code in octomate/tentacles/acp/history.py
@dataclass
class AcpHistory:
    """Accumulate one prompt in wire order, producing the same live and stored content.

    A changed message ID or content kind ends a text part. Tool updates replace
    supplied fields, retaining omitted fields. Raw updates also preserve plans,
    settings, diffs, terminals and provider metadata without inventing model parts.
    """

    prompt: schema.PromptRequest
    request: ModelRequest = field(init=False)
    response: ModelResponse = field(init=False)
    parts: list[ModelResponsePart] = field(default_factory=list)
    updates: list[JsonValue] = field(default_factory=list)
    tools: dict[str, schema.ToolCall] = field(default_factory=dict)
    calls: dict[str, NativeToolCallPart] = field(default_factory=dict)
    returns: dict[str, NativeToolReturnPart] = field(default_factory=dict)
    streaming: int | None = None  # The response part currently receiving chunks.
    message_id: str | None = None  # ACP's optional boundary, not a native turn ID.
    context_window: int | None = None  # Last reported context capacity.
    context_used: int | None = None  # Context occupancy, not billed input.

    def __post_init__(self) -> None:
        self.request = ModelRequest(
            parts=[
                UserPromptPart(content=[content_value(b) for b in self.prompt.prompt])
            ],
            metadata={
                "source": "acp",
                "prompt": json_value_adapter.validate_json(
                    self.prompt.model_dump_json(by_alias=True, exclude_none=True)
                ),
            },
        )
        self.response = ModelResponse(
            parts=self.parts,
            provider_name="acp",
            metadata={"source": "acp", "updates": self.updates},
        )

    @property
    def messages(self) -> list[ModelMessage]:
        return [self.request, self.response] if self.updates else [self.request]

    @property
    def answer(self) -> str:
        """The visible reply for the ledger; media stays intact in model history."""
        return "\n\n".join(
            part.content
            if isinstance(part, TextPart)
            else f"[{part.content.media_type}]"
            for part in self.parts
            if isinstance(part, TextPart | FilePart)
        )

    def end_part(self) -> list[AgentStreamEvent]:
        if self.streaming is None:
            return []
        index, self.streaming = self.streaming, None
        return [PartEndEvent(index=index, part=replace(self.parts[index]))]

    def feed(self, notification: schema.SessionNotification) -> list[AgentStreamEvent]:
        """Fold a validated update and return its live events in arrival order."""
        update = notification.update
        self.updates.append(
            json_value_adapter.validate_json(
                update.model_dump_json(by_alias=True, exclude_none=True)
            )
        )
        if isinstance(update, schema.UsageUpdate):
            self.context_window = update.size if update.size > 0 else None
            self.context_used = update.used
            return []
        if isinstance(update, schema.ToolCallStart | schema.ToolCallProgress):
            return self.end_part() + self.tool(update)
        if not isinstance(update, schema.AgentMessageChunk | schema.AgentThoughtChunk):
            return []
        value = content_value(update.content)
        thought = isinstance(update, schema.AgentThoughtChunk)
        previous = self.parts[self.streaming] if self.streaming is not None else None
        if isinstance(value, BinaryContent) and thought:
            value = f"[{value.media_type}]"
        if (
            isinstance(value, str)
            and self.streaming is not None
            and update.message_id == self.message_id
        ):
            if isinstance(previous, TextPart) and not thought:
                previous.content += value
                return [
                    PartDeltaEvent(
                        index=self.streaming, delta=TextPartDelta(content_delta=value)
                    )
                ]
            if isinstance(previous, ThinkingPart) and thought:
                previous.content += value
                return [
                    PartDeltaEvent(
                        index=self.streaming,
                        delta=ThinkingPartDelta(content_delta=value),
                    )
                ]
        events = self.end_part()
        if isinstance(value, BinaryContent):
            part = FilePart(content=value, provider_name="acp")
            index = len(self.parts)
            self.parts.append(part)
            return [
                *events,
                PartStartEvent(index=index, part=part),
                PartEndEvent(index=index, part=part),
            ]
        part = ThinkingPart(content=value) if thought else TextPart(content=value)
        self.streaming = len(self.parts)
        self.message_id = update.message_id
        self.parts.append(part)
        return [*events, PartStartEvent(index=self.streaming, part=replace(part))]

    def tool(
        self, update: schema.ToolCallStart | schema.ToolCallProgress
    ) -> list[AgentStreamEvent]:
        """Merge a tool's partial updates and retain its native call/result pair."""
        key = update.tool_call_id
        previous = self.tools.get(key)
        tool = schema.ToolCall.model_validate(
            (previous.model_dump() if previous is not None else {})
            | update.model_dump(exclude_unset=True, exclude_none=True)
        )
        self.tools[key] = tool
        raw_input = json_value_adapter.validate_python(tool.raw_input)
        args = (
            raw_input
            if isinstance(raw_input, dict | str) or raw_input is None
            else json.dumps(raw_input)
        )
        events: list[AgentStreamEvent] = []
        if key not in self.calls:
            call = NativeToolCallPart(
                tool_name=tool.title, args=args, tool_call_id=key, provider_name="acp"
            )
            self.calls[key] = call
            self.parts.append(call)
            events.append(
                FunctionToolCallEvent(
                    part=ToolCallPart(tool_name=tool.title, args=args, tool_call_id=key)
                )
            )
        else:
            self.calls[key].tool_name = tool.title
            self.calls[key].args = args
        self.calls[key].provider_details = {
            "acp": json_value_adapter.validate_json(
                tool.model_dump_json(by_alias=True, exclude_none=True)
            )
        }
        if tool.status not in ("completed", "failed"):
            return events
        output = json_value_adapter.validate_python(tool.raw_output)
        if output is None:
            output = [
                json_value_adapter.validate_json(
                    c.model_dump_json(by_alias=True, exclude_none=True)
                )
                for c in tool.content or []
            ]
        outcome = "failed" if tool.status == "failed" else "success"
        if key not in self.returns:
            result = NativeToolReturnPart(
                tool_name=tool.title,
                content=output,
                tool_call_id=key,
                outcome=outcome,
                provider_name="acp",
            )
            self.returns[key] = result
            self.parts.append(result)
        else:
            self.returns[key].content = output
            self.returns[key].outcome = outcome
        events.append(
            FunctionToolResultEvent(
                part=ToolReturnPart(
                    tool_name=tool.title,
                    content=output,
                    tool_call_id=key,
                    outcome=outcome,
                )
            )
        )
        return events

prompt instance-attribute

prompt: PromptRequest

request class-attribute instance-attribute

request: ModelRequest = field(init=False)

response class-attribute instance-attribute

response: ModelResponse = field(init=False)

parts class-attribute instance-attribute

parts: list[ModelResponsePart] = field(default_factory=list)

updates class-attribute instance-attribute

updates: list[JsonValue] = field(default_factory=list)

tools class-attribute instance-attribute

tools: dict[str, ToolCall] = field(default_factory=dict)

calls class-attribute instance-attribute

calls: dict[str, NativeToolCallPart] = field(
    default_factory=dict
)

returns class-attribute instance-attribute

returns: dict[str, NativeToolReturnPart] = field(
    default_factory=dict
)

streaming class-attribute instance-attribute

streaming: int | None = None

message_id class-attribute instance-attribute

message_id: str | None = None

context_window class-attribute instance-attribute

context_window: int | None = None

context_used class-attribute instance-attribute

context_used: int | None = None

messages property

messages: list[ModelMessage]

answer property

answer: str

The visible reply for the ledger; media stays intact in model history.

end_part

end_part() -> list[AgentStreamEvent]
Source code in octomate/tentacles/acp/history.py
def end_part(self) -> list[AgentStreamEvent]:
    if self.streaming is None:
        return []
    index, self.streaming = self.streaming, None
    return [PartEndEvent(index=index, part=replace(self.parts[index]))]

feed

feed(
    notification: SessionNotification,
) -> list[AgentStreamEvent]

Fold a validated update and return its live events in arrival order.

Source code in octomate/tentacles/acp/history.py
def feed(self, notification: schema.SessionNotification) -> list[AgentStreamEvent]:
    """Fold a validated update and return its live events in arrival order."""
    update = notification.update
    self.updates.append(
        json_value_adapter.validate_json(
            update.model_dump_json(by_alias=True, exclude_none=True)
        )
    )
    if isinstance(update, schema.UsageUpdate):
        self.context_window = update.size if update.size > 0 else None
        self.context_used = update.used
        return []
    if isinstance(update, schema.ToolCallStart | schema.ToolCallProgress):
        return self.end_part() + self.tool(update)
    if not isinstance(update, schema.AgentMessageChunk | schema.AgentThoughtChunk):
        return []
    value = content_value(update.content)
    thought = isinstance(update, schema.AgentThoughtChunk)
    previous = self.parts[self.streaming] if self.streaming is not None else None
    if isinstance(value, BinaryContent) and thought:
        value = f"[{value.media_type}]"
    if (
        isinstance(value, str)
        and self.streaming is not None
        and update.message_id == self.message_id
    ):
        if isinstance(previous, TextPart) and not thought:
            previous.content += value
            return [
                PartDeltaEvent(
                    index=self.streaming, delta=TextPartDelta(content_delta=value)
                )
            ]
        if isinstance(previous, ThinkingPart) and thought:
            previous.content += value
            return [
                PartDeltaEvent(
                    index=self.streaming,
                    delta=ThinkingPartDelta(content_delta=value),
                )
            ]
    events = self.end_part()
    if isinstance(value, BinaryContent):
        part = FilePart(content=value, provider_name="acp")
        index = len(self.parts)
        self.parts.append(part)
        return [
            *events,
            PartStartEvent(index=index, part=part),
            PartEndEvent(index=index, part=part),
        ]
    part = ThinkingPart(content=value) if thought else TextPart(content=value)
    self.streaming = len(self.parts)
    self.message_id = update.message_id
    self.parts.append(part)
    return [*events, PartStartEvent(index=self.streaming, part=replace(part))]

tool

tool(
    update: ToolCallStart | ToolCallProgress,
) -> list[AgentStreamEvent]

Merge a tool's partial updates and retain its native call/result pair.

Source code in octomate/tentacles/acp/history.py
def tool(
    self, update: schema.ToolCallStart | schema.ToolCallProgress
) -> list[AgentStreamEvent]:
    """Merge a tool's partial updates and retain its native call/result pair."""
    key = update.tool_call_id
    previous = self.tools.get(key)
    tool = schema.ToolCall.model_validate(
        (previous.model_dump() if previous is not None else {})
        | update.model_dump(exclude_unset=True, exclude_none=True)
    )
    self.tools[key] = tool
    raw_input = json_value_adapter.validate_python(tool.raw_input)
    args = (
        raw_input
        if isinstance(raw_input, dict | str) or raw_input is None
        else json.dumps(raw_input)
    )
    events: list[AgentStreamEvent] = []
    if key not in self.calls:
        call = NativeToolCallPart(
            tool_name=tool.title, args=args, tool_call_id=key, provider_name="acp"
        )
        self.calls[key] = call
        self.parts.append(call)
        events.append(
            FunctionToolCallEvent(
                part=ToolCallPart(tool_name=tool.title, args=args, tool_call_id=key)
            )
        )
    else:
        self.calls[key].tool_name = tool.title
        self.calls[key].args = args
    self.calls[key].provider_details = {
        "acp": json_value_adapter.validate_json(
            tool.model_dump_json(by_alias=True, exclude_none=True)
        )
    }
    if tool.status not in ("completed", "failed"):
        return events
    output = json_value_adapter.validate_python(tool.raw_output)
    if output is None:
        output = [
            json_value_adapter.validate_json(
                c.model_dump_json(by_alias=True, exclude_none=True)
            )
            for c in tool.content or []
        ]
    outcome = "failed" if tool.status == "failed" else "success"
    if key not in self.returns:
        result = NativeToolReturnPart(
            tool_name=tool.title,
            content=output,
            tool_call_id=key,
            outcome=outcome,
            provider_name="acp",
        )
        self.returns[key] = result
        self.parts.append(result)
    else:
        self.returns[key].content = output
        self.returns[key].outcome = outcome
    events.append(
        FunctionToolResultEvent(
            part=ToolReturnPart(
                tool_name=tool.title,
                content=output,
                tool_call_id=key,
                outcome=outcome,
            )
        )
    )
    return events

content_value

content_value(block: ContentBlock) -> str | BinaryContent

Keep media inline and resource links inert; never read a path or URL.

Source code in octomate/tentacles/acp/history.py
def content_value(block: ContentBlock) -> str | BinaryContent:
    """Keep media inline and resource links inert; never read a path or URL."""
    match block:
        case schema.TextContentBlock():
            return block.text
        case schema.ResourceContentBlock():
            label = block.title or block.name
            return f"{label} ({block.uri})" if label else block.uri
        case schema.ImageContentBlock() | schema.AudioContentBlock():
            return BinaryContent(
                data=base64.b64decode(block.data, validate=True),
                media_type=block.mime_type,
            )
        case schema.EmbeddedResourceContentBlock(
            resource=schema.TextResourceContents()
        ):
            return block.resource.text
        case schema.EmbeddedResourceContentBlock():
            return BinaryContent(
                data=base64.b64decode(block.resource.blob, validate=True),
                media_type=block.resource.mime_type or "application/octet-stream",
            )

octomate.tentacles.acp.adapter

Translate ACP prompts and run output without owning execution or transport.

Follows Pydantic AI Harness's ACP adapter for text, thinking and function tools, and adds Octomate's segment output and non-streaming results. Segments use their existing text representation; reply handles are omitted. Output-tool events are not rendered: their validated answer arrives through the result events.

Create one translator per prompt and retain it across deferred resumes. Run starts reset output tracking; tool IDs remain known across resumes. Other events produce no updates here: routing, actions, plans and session lifecycle need their own handling before this translator can serve a complete ACP channel.

TEXT_CHUNK_BYTES module-attribute

TEXT_CHUNK_BYTES = 48 * 1024

RAW_PAYLOAD_BYTES module-attribute

RAW_PAYLOAD_BYTES = 16 * 1024

json_value_adapter module-attribute

json_value_adapter = TypeAdapter(JsonValue)

AcpUpdate

AcpUpdate = (
    AgentMessageChunk
    | AgentThoughtChunk
    | ToolCallStart
    | ToolCallProgress
)

AcpTranslator dataclass

Present one prompt's run events as typed ACP session-update payloads.

The caller supplies the session ID when sending each update. Text starts carry content too; part ends contain accumulated content and must not be replayed. Function-tool execution events, rather than streamed argument fragments, announce tools. A repeated call ID after approval is announced only once.

Source code in octomate/tentacles/acp/adapter.py
@dataclass
class AcpTranslator:
    """Present one prompt's run events as typed ACP session-update payloads.

    The caller supplies the session ID when sending each update. Text starts carry
    content too; part ends contain accumulated content and must not be replayed.
    Function-tool execution events, rather than streamed argument fragments, announce
    tools. A repeated call ID after approval is announced only once.
    """

    started_tools: set[str] = field(default_factory=set)  # IDs announced this prompt.
    answered: bool = False  # Whether the current model response has emitted an answer.

    def translate(self, event: WireEvent) -> list[AcpUpdate]:
        """Return zero or more updates, preserving stream order and tool-call IDs."""
        match event:
            case RunStartedEvent():
                self.answered = False
            case PartStartEvent(part=TextPart(content=text)):
                return self.text_updates(text)
            case PartDeltaEvent(delta=TextPartDelta(content_delta=text)):
                return self.text_updates(text)
            case PartStartEvent(part=ThinkingPart(content=text)):
                return self.text_updates(text, thought=True)
            case PartDeltaEvent(delta=ThinkingPartDelta(content_delta=text)):
                return self.text_updates(text or "", thought=True)
            case ResultTextDeltaEvent(delta=text):
                return self.text_updates(text)
            case ResultSegmentEvent(segment=ReplySegment()):
                return []
            case ResultSegmentEvent(segment=segment):
                return self.text_updates(str(segment))
            case FunctionToolCallEvent(part=part):
                if part.tool_call_id in self.started_tools:
                    return [
                        acp.update_tool_call(
                            tool_call_id=part.tool_call_id, status="in_progress"
                        )
                    ]
                update = acp.start_tool_call(
                    tool_call_id=part.tool_call_id,
                    title=part.tool_name,
                    status="in_progress",
                    raw_input=tool_payload(part),
                )
                self.started_tools.add(part.tool_call_id)
                return [update]
            case FunctionToolResultEvent(part=part):
                # Commentary before a tool is not the next model response's answer.
                self.answered = False
                failed = isinstance(part, RetryPromptPart) or part.outcome != "success"
                return [
                    acp.update_tool_call(
                        tool_call_id=part.tool_call_id,
                        status="failed" if failed else "completed",
                        raw_output=tool_payload(part),
                    )
                ]
            case RunResultEvent(output=output) if not self.answered:
                if isinstance(output, str):
                    return self.text_updates(output)
                return [
                    update
                    for segment in output or []
                    if not isinstance(segment, ReplySegment)
                    for update in self.text_updates(str(segment))
                ]
        return []

    def text_updates(self, text: str, *, thought: bool = False) -> list[AcpUpdate]:
        """Split text by its JSON-escaped size, without losing Unicode or whitespace."""
        updates: list[AcpUpdate] = []
        chunk: list[str] = []
        size = 0
        for char in text:
            escaped_size = len(json.dumps(char)) - 2
            if chunk and size + escaped_size > TEXT_CHUNK_BYTES:
                updates.append(
                    acp.update_agent_thought_text("".join(chunk))
                    if thought
                    else acp.update_agent_message_text("".join(chunk))
                )
                chunk = []
                size = 0
            chunk.append(char)
            size += escaped_size
        if chunk:
            updates.append(
                acp.update_agent_thought_text("".join(chunk))
                if thought
                else acp.update_agent_message_text("".join(chunk))
            )
        if text and not thought:
            self.answered = True
        return updates

started_tools class-attribute instance-attribute

started_tools: set[str] = field(default_factory=set)

answered class-attribute instance-attribute

answered: bool = False

translate

translate(event: WireEvent) -> list[AcpUpdate]

Return zero or more updates, preserving stream order and tool-call IDs.

Source code in octomate/tentacles/acp/adapter.py
def translate(self, event: WireEvent) -> list[AcpUpdate]:
    """Return zero or more updates, preserving stream order and tool-call IDs."""
    match event:
        case RunStartedEvent():
            self.answered = False
        case PartStartEvent(part=TextPart(content=text)):
            return self.text_updates(text)
        case PartDeltaEvent(delta=TextPartDelta(content_delta=text)):
            return self.text_updates(text)
        case PartStartEvent(part=ThinkingPart(content=text)):
            return self.text_updates(text, thought=True)
        case PartDeltaEvent(delta=ThinkingPartDelta(content_delta=text)):
            return self.text_updates(text or "", thought=True)
        case ResultTextDeltaEvent(delta=text):
            return self.text_updates(text)
        case ResultSegmentEvent(segment=ReplySegment()):
            return []
        case ResultSegmentEvent(segment=segment):
            return self.text_updates(str(segment))
        case FunctionToolCallEvent(part=part):
            if part.tool_call_id in self.started_tools:
                return [
                    acp.update_tool_call(
                        tool_call_id=part.tool_call_id, status="in_progress"
                    )
                ]
            update = acp.start_tool_call(
                tool_call_id=part.tool_call_id,
                title=part.tool_name,
                status="in_progress",
                raw_input=tool_payload(part),
            )
            self.started_tools.add(part.tool_call_id)
            return [update]
        case FunctionToolResultEvent(part=part):
            # Commentary before a tool is not the next model response's answer.
            self.answered = False
            failed = isinstance(part, RetryPromptPart) or part.outcome != "success"
            return [
                acp.update_tool_call(
                    tool_call_id=part.tool_call_id,
                    status="failed" if failed else "completed",
                    raw_output=tool_payload(part),
                )
            ]
        case RunResultEvent(output=output) if not self.answered:
            if isinstance(output, str):
                return self.text_updates(output)
            return [
                update
                for segment in output or []
                if not isinstance(segment, ReplySegment)
                for update in self.text_updates(str(segment))
            ]
    return []

text_updates

text_updates(
    text: str, *, thought: bool = False
) -> list[AcpUpdate]

Split text by its JSON-escaped size, without losing Unicode or whitespace.

Source code in octomate/tentacles/acp/adapter.py
def text_updates(self, text: str, *, thought: bool = False) -> list[AcpUpdate]:
    """Split text by its JSON-escaped size, without losing Unicode or whitespace."""
    updates: list[AcpUpdate] = []
    chunk: list[str] = []
    size = 0
    for char in text:
        escaped_size = len(json.dumps(char)) - 2
        if chunk and size + escaped_size > TEXT_CHUNK_BYTES:
            updates.append(
                acp.update_agent_thought_text("".join(chunk))
                if thought
                else acp.update_agent_message_text("".join(chunk))
            )
            chunk = []
            size = 0
        chunk.append(char)
        size += escaped_size
    if chunk:
        updates.append(
            acp.update_agent_thought_text("".join(chunk))
            if thought
            else acp.update_agent_message_text("".join(chunk))
        )
    if text and not thought:
        self.answered = True
    return updates

prompt_segments

prompt_segments(
    request: PromptRequest,
) -> list[MessageSegment]

Translate the mandatory ACP prompt content into Octomate message segments.

Text blocks retain their whitespace and order. Resource links use Pydantic AI Harness's presentation: the title or name followed by the URI, or the URI alone when neither label is present. A link is context, not a local file to open or a URL to fetch during translation.

Image, audio and embedded-resource blocks require optional capabilities this adapter does not yet provide. Reject the whole request instead of dropping unsupported content. Empty and whitespace-only prompts are rejected before a caller records an inbound message or starts a run.

Source code in octomate/tentacles/acp/adapter.py
def prompt_segments(request: schema.PromptRequest) -> list[MessageSegment]:
    """Translate the mandatory ACP prompt content into Octomate message segments.

    Text blocks retain their whitespace and order. Resource links use Pydantic AI
    Harness's presentation: the title or name followed by the URI, or the URI alone
    when neither label is present. A link is context, not a local file to open or a
    URL to fetch during translation.

    Image, audio and embedded-resource blocks require optional capabilities this
    adapter does not yet provide. Reject the whole request instead of dropping
    unsupported content. Empty and whitespace-only prompts are rejected before a
    caller records an inbound message or starts a run.
    """
    segments: list[MessageSegment] = []
    for block in request.prompt:
        match block:
            case schema.TextContentBlock(text=text):
                pass
            case schema.ResourceContentBlock():
                label = block.title or block.name
                text = f"{label} ({block.uri})" if label else block.uri
            case _:
                raise acp.RequestError.invalid_params(
                    {"reason": f"Unsupported prompt content: {block.type}"}
                )
        segments.append(TextSegment(data={"text": text}))
    if not any(str(segment).strip() for segment in segments):
        raise acp.RequestError.invalid_params({"reason": "Prompt carried no text"})
    return segments

tool_payload

tool_payload(
    part: ToolCallPart | ToolReturnPart | RetryPromptPart,
) -> JsonValue

Serialize tool data with an explicit oversized-data preview.

Raw bytes use base64; Pydantic models retain their own serialization settings. The limit measures ASCII-escaped JSON, as used by the ACP SDK's transport. Unsupported Python values raise a serialization error rather than becoming reprs. Only the presentation is bounded; the original event and ledger stay intact.

Source code in octomate/tentacles/acp/adapter.py
def tool_payload(part: ToolCallPart | ToolReturnPart | RetryPromptPart) -> JsonValue:
    """Serialize tool data with an explicit oversized-data preview.

    Raw bytes use base64; Pydantic models retain their own serialization settings.
    The limit measures ASCII-escaped JSON, as used by the ACP SDK's transport.
    Unsupported Python values raise a serialization error rather than becoming reprs.
    Only the presentation is bounded; the original event and ledger stay intact.
    """
    match part:
        case ToolCallPart():
            value = part.args
        case RetryPromptPart():
            value = part.model_response()
        case ToolReturnPart():
            value = part.content
    payload = json_value_adapter.validate_json(to_json(value, bytes_mode="base64"))
    serialized = json.dumps(payload)
    if len(serialized) <= RAW_PAYLOAD_BYTES:
        return payload
    return {
        "truncated": True,
        "original_length": len(serialized),
        "preview": serialized[:RAW_PAYLOAD_BYTES],
    }