Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions src/agent_comms/agent_event_updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,7 @@ async def on_tool_start(self, event: events.ToolStart) -> None:
kind=AcpToolAction.kind(event.kind),
status="in_progress",
)
if event.args is not None:
start_update.raw_input = event.args
event.apply_raw_input(start_update)
await client.publish_update(
session_id=session_id,
update=start_update,
Expand Down
5 changes: 5 additions & 0 deletions src/agent_comms/agent_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,11 @@ def from_call(cls, call_id: ToolCallId, name: str, arguments: object) -> ToolSta
title = ToolDeclaration.caption(name, ToolDeclaration.record(name, arguments, call_id=call_id))
return cls(call_id, name, title, arguments, declaration.declared_action())

def apply_raw_input(self, start_update) -> None:
"""Attach raw input args to the tool-call start update when present."""
if self.args is not None:
start_update.raw_input = self.args


@dataclass(frozen=True)
class ToolProgress(ToolEvent):
Expand Down
37 changes: 32 additions & 5 deletions src/agent_comms/cli_bridges/claude_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,36 @@ def untracked_tool_result(self, tool_id: str) -> tuple[RuntimeUpdate, ...]:
return (ActiveItem(self.id, NativeItemId(tool_id), ModelWaitPhase()),)


class ReportedVersion(ABC):
"""An optional Claude protocol version reported by the peer."""

@abstractmethod
def version_reported(self, owner: ClaudeSession) -> tuple[RuntimeUpdate, ...]:
...

@classmethod
def from_optional(cls, value: str | None) -> ReportedVersion:
return AbsentReportedVersion() if value is None else HeldReportedVersion(value)


@dataclass(frozen=True)
class AbsentReportedVersion(ReportedVersion):
"""Absent `ReportedVersion` carrying no value."""

def version_reported(self, owner: ClaudeSession) -> tuple[RuntimeUpdate, ...]:
return ()


@dataclass(frozen=True)
class HeldReportedVersion(ReportedVersion):
"""Held `ReportedVersion` carrying its present value."""

value: str

def version_reported(self, owner: ClaudeSession) -> tuple[RuntimeUpdate, ...]:
return tuple((update for offered in owner.offered_tools.on_version(self.value) for update in owner.offered(offered)))


@dataclass
class ClaudeSession:
turn: ClaudeTurn = field(default_factory=UnknownTurn)
Expand All @@ -533,11 +563,8 @@ class ClaudeSession:
offered_tools: OfferedTools = field(default_factory=UnobservedTools)
answered_by: TranscriptModelUsage = field(default_factory=TranscriptModelUsage)

def version_reported(self, version: str | None) -> tuple[RuntimeUpdate, ...]:
if version is None:
return ()
return tuple(update for offered in self.offered_tools.on_version(version)
for update in self.offered(offered))
def version_reported(self, version: ReportedVersion) -> tuple[RuntimeUpdate, ...]:
return version.version_reported(self)

def offered(self, offered: OfferedTools) -> tuple[RuntimeUpdate, ...]:
self.offered_tools = offered
Expand Down
3 changes: 2 additions & 1 deletion src/agent_comms/cli_bridges/claude_transcript.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
ClaudeMonitorFrame,
ClaudeRecord,
ClaudeSession,
ReportedVersion,
SubagentProgress,
)
from agent_comms.cli_bridges.cli_protocol import TaggedWire
Expand Down Expand Up @@ -78,7 +79,7 @@ def record_updates(self, record: ClaudeRecord, state: ClaudeSession, offset: int
raw: bytes) -> Iterator[RuntimeUpdate]:
if (located := state.located(record.cwd)) is not None:
yield located
for update in (*state.version_reported(record.version), *record.updates(state)):
for update in (*state.version_reported(ReportedVersion.from_optional(record.version)), *record.updates(state)):
yield from update.during(state.phase)


Expand Down
10 changes: 7 additions & 3 deletions src/agent_comms/cli_bridges/cli_arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ def declarations(self) -> tuple[type[CliCommand], ...]:
class _CommandParsingArguments(argparse.Namespace):
command: str | None

def resolve_parsing(self) -> CommandParsing:
"""Resolve parsed arguments into a selected command or empty parsing."""
if self.command is None:
return CommandParsing()
return SelectedCommand.from_name(self.command)


class CliArguments(argparse.Namespace):
root: LaunchRequest
Expand Down Expand Up @@ -96,9 +102,7 @@ def command_parsing(self, arguments: Sequence[str]) -> CommandParsing:
# cause, five clauses into the line.
selection.add_argument("command", nargs="?", default=None, help=argparse.SUPPRESS)
args, _ = selection.parse_known_args(arguments, namespace=_CommandParsingArguments())
if args.command is None:
return CommandParsing()
return SelectedCommand.from_name(args.command)
return args.resolve_parsing()

def exit(self, status: int = 0, message: object = None) -> Never:
raise CliParserExit(status, NoCliParserText())
Expand Down
7 changes: 7 additions & 0 deletions src/agent_comms/cli_bridges/opencode_parts.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ class MessageTime(WireModel):
created: int | float
completed: int | float | None = None

async def snapshot_when_completed(self, info, stream) -> tuple[RuntimeUpdate, ...]:
"""Fetch and snapshot the OpenCode message once this timestamp records completion."""
if self.completed is None:
return ()
saved = await stream.connection.message(info.id)
return stream.snapshot(saved)


class RoleHeader(WireHeader):
@model_validator(mode='before')
Expand Down
6 changes: 1 addition & 5 deletions src/agent_comms/cli_bridges/opencode_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,7 @@ async def receive(self, stream: OpenCodeStream) -> tuple[RuntimeUpdate, ...]:
if info.sessionID != stream.connection.session:
return ()
stream.messages[info.id] = info
if info.time.completed is None:
return ()
# Completion also covers an item that began before we subscribed.
saved = await stream.connection.message(info.id)
return stream.snapshot(saved)
return await info.time.snapshot_when_completed(info, stream)


class StatusChanged(OpenCodeEvent, declared_name='session.status'):
Expand Down
4 changes: 2 additions & 2 deletions src/agent_comms/cli_bridges/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -1182,9 +1182,9 @@ def routed(cls, reply_route: str) -> type[Self]:
@property
def route(self) -> str:
"""The reply line, under a message whose sender hears each reply (a person)."""
if not self.reply_route or not self.message.sender_role.hears_each_reply():
if not self.reply_route:
return ''
return '\n' + self.reply_route.format(target=self.message.exact_reply_target)
return self.message.sender_role.format_reply_route(self)

OWED_PREFIX: ClassVar[str] = 'Comms owed · '
"""How a reminder starts: no header (`HEADER_PREFIX`), so a transcript reads it as text
Expand Down
31 changes: 29 additions & 2 deletions src/agent_comms/cli_verbs/cli_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import argparse
import re
import shlex
from abc import ABC
from dataclasses import dataclass
from typing import Annotated

Expand Down Expand Up @@ -42,8 +43,34 @@ def _tag_choice_text(value: str | None) -> str | None:
return value


def _tag_text(value: frozenset[str] | None) -> str | None:
return None if value is None else ', '.join(sorted(value))
class TagSet(ABC):
"""An optional set of thread tags formatted for CLI output."""

def _tag_text(self) -> str | None:
pass

@classmethod
def from_optional(cls, value: frozenset[str] | None) -> TagSet:
return AbsentTagSet() if value is None else HeldTagSet(value)


@dataclass(frozen=True)
class AbsentTagSet(TagSet):
"""Absent `TagSet` carrying no value."""


@dataclass(frozen=True)
class HeldTagSet(TagSet):
"""Held `TagSet` carrying its present value."""

value: frozenset[str]

def _tag_text(self) -> str | None:
return ', '.join(sorted(self.value))


def _tag_text(value: TagSet) -> str | None:
return value._tag_text()


def _shell_words(value: str) -> list[str]:
Expand Down
10 changes: 3 additions & 7 deletions src/agent_comms/cli_verbs/target_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,6 @@ def of(cls, plan: field_codec.FieldPlan, value: object) -> TargetField:
)
return editor(plan, value)

@property
def annotation(self) -> object:
return self.plan.annotation

@property
def name(self) -> str:
return self.plan.key
Expand Down Expand Up @@ -68,7 +64,7 @@ def with_offered(self, options: tuple[CatalogChoice, ...]) -> TargetField:
return self

def value_schema(self) -> dict[str, JsonValue]:
return FieldCodec.value_schema(self.annotation)
return FieldCodec.value_schema(self.plan.annotation)

def json_schema(self) -> dict[str, JsonValue]:
return {**self.value_schema(), 'multiline': self.multiline,
Expand Down Expand Up @@ -104,7 +100,7 @@ def with_offered(self, options: tuple[CatalogChoice, ...]) -> ChoiceTargetField:

async def prepare(self, catalogs: ConfigCatalogSource,
selection: object) -> ChoiceTargetField:
decoder = field_codec.compile_decoder(self.annotation)
decoder = field_codec.compile_decoder(self.plan.annotation)
options = (CatalogChoice(
name=label, value=decoder.encode_editor(decoder.decode(value)))
for label, value in decoder.editor_choices())
Expand Down Expand Up @@ -145,5 +141,5 @@ async def prepare(self, catalogs: ConfigCatalogSource,
return replace(self, options=tuple(options))

def value_schema(self) -> dict[str, JsonValue]:
return {**FieldCodec.value_schema(self.annotation),
return {**FieldCodec.value_schema(self.plan.annotation),
'configuration': FieldCodec.encode(self.catalog)}
4 changes: 2 additions & 2 deletions src/agent_comms/cli_verbs/thread_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from agent_comms.cli_verbs.cli_verb import CliBus
from agent_comms.cli_support.named import NamedCliCommand
from agent_comms.cli_verbs.cli_command import TargetActionCommand
from agent_comms.cli_verbs.cli_commands import ThreadTagsResult, _tag_text, _tags
from agent_comms.cli_verbs.cli_commands import TagSet, ThreadTagsResult, _tag_text, _tags
from agent_comms.messaging.channel_targets import SurroundingChannel
from agent_comms.nominal.field_codec import Argument, EditorFormat, Normalize
from agent_comms.registry.catalog_document import CatalogAccess
Expand All @@ -22,7 +22,7 @@ class ThreadTagsCliCommand(NamedCliCommand, TargetActionCommand[ThreadTagsResult
tags: Annotated[
frozenset[str],
Normalize(_tags),
EditorFormat(_tag_text),
EditorFormat(lambda value: _tag_text(TagSet.from_optional(value))),
Argument(
flags=("--tags",), options={"help": "Complete tags, separated by commas"}
),
Expand Down
7 changes: 6 additions & 1 deletion src/agent_comms/coordination/assignment_states.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from agent_comms.coordination.errors import IdentityConflict, CoordinationError
from agent_comms.coordination.vocabulary import CoordinatorVocabulary
from agent_comms.messaging.bus_publication import Delivered
from agent_comms.messaging.frozen_recipient import FrozenRecipient
from agent_comms.messaging.notification_progress import (
CompletedProgress,
Expand Down Expand Up @@ -56,7 +57,6 @@
HistoricalNativeInput,
)
from agent_comms.execution.native_input_record import TriageNativeExecution
from agent_comms.messaging.bus_publication import Delivered
from agent_comms.messaging.message_notification import MessageNotification
from agent_comms.notification_assignment import AssignmentActivity

Expand Down Expand Up @@ -243,6 +243,11 @@ def preengagement(self, disposition: type[AssignmentState]) -> AssignmentState:
raise IdentityConflict("preengagement cannot change frozen wake policy")
return after

def require_unengaged_for(self) -> None:
"""Reject an assignment whose recipient differs or that already holds an execution."""
if self.execution_id is not None:
raise IdentityConflict('claim cannot engage this execution')


class PassiveAssignment(Terminal, AssignmentState):
notification_state = PassiveProgress
Expand Down
6 changes: 1 addition & 5 deletions src/agent_comms/coordination/attempt_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,11 +451,7 @@ def recover_released_triage(
with VerifiedOwnerLoss.observe_owner_release(store, owner, boundary, releases) as loss:
for source, stage in pending:
current = NativeRuntimeInput.require(store.session._connection, input_id=source.input_id)
if current.reference.has_session_proof():
continue
loss.require_input_loss(current)
with boundary.registry_cut.current(), store.session.writing() as db:
stage.fail_claims(store, db)
current.reference.recover_unproven(current, loss, store, stage, boundary)

@classmethod
def recover_released_native_attempt(
Expand Down
36 changes: 31 additions & 5 deletions src/agent_comms/coordination/contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

from abc import ABC
from dataclasses import dataclass
from typing import Final

RESOLVER_VERSION: Final = "resolver-v1"
Expand Down Expand Up @@ -32,11 +34,35 @@ def require_bounded(value: str, field: str, maximum: int) -> None:
raise ValueError(f"{field} exceeds {maximum} characters")


def require_optional_nonempty(value: str | None, field: str, maximum: int) -> None:
if value is None:
return
require_nonempty(value, field)
require_bounded(value, field, maximum)
class OptionalBoundedText(ABC):
"""An optional non-empty bounded text value validated at a coordination contract."""

def require_optional_nonempty(self, field: str, maximum: int) -> None:
pass

@classmethod
def from_optional(cls, value: str | None) -> OptionalBoundedText:
return AbsentOptionalBoundedText() if value is None else HeldOptionalBoundedText(value)


@dataclass(frozen=True)
class AbsentOptionalBoundedText(OptionalBoundedText):
"""Absent `OptionalBoundedText` carrying no value."""


@dataclass(frozen=True)
class HeldOptionalBoundedText(OptionalBoundedText):
"""Held `OptionalBoundedText` carrying its present value."""

value: str

def require_optional_nonempty(self, field: str, maximum: int) -> None:
require_nonempty(self.value, field)
require_bounded(self.value, field, maximum)


def require_optional_nonempty(value: OptionalBoundedText, field: str, maximum: int) -> None:
value.require_optional_nonempty(field, maximum)


def validate_execution_id(execution_id: str) -> None:
Expand Down
8 changes: 3 additions & 5 deletions src/agent_comms/coordination/execution_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,9 @@ def _create(
exact_target = source.delivery.message.exact_reply_target
routes.setdefault(exact_target, None)
assignment.lifecycle.require_engageable()
if (
assignment.recipient_lookup != owner_lookup
or assignment.lifecycle.execution_id is not None
):
raise IdentityConflict("claim cannot engage this execution")
if assignment.recipient_lookup != owner_lookup:
raise IdentityConflict('claim cannot engage this execution')
assignment.lifecycle.require_unengaged_for()
decision = EngagedAssignment.build(
assignment.lifecycle.mode, execution_id, exact_target
)
Expand Down
3 changes: 2 additions & 1 deletion src/agent_comms/coordination/tables/assignments.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
MAX_IDENTIFIER_CHARS,
POLICY_VERSION,
RESOLVER_VERSION,
OptionalBoundedText,
require_bounded,
require_nonempty,
require_optional_nonempty,
Expand Down Expand Up @@ -220,7 +221,7 @@ def __post_init__(self) -> None:
):
require_nonempty(value, field)
require_bounded(value, field, MAX_IDENTIFIER_CHARS)
require_optional_nonempty(self.lifecycle.exact_target, "exact_target", MAX_IDENTIFIER_CHARS)
require_optional_nonempty(OptionalBoundedText.from_optional(self.lifecycle.exact_target), "exact_target", MAX_IDENTIFIER_CHARS)
if self.lifecycle.execution_id is not None:
validate_execution_id(self.lifecycle.execution_id)
if self.wire_seq <= 0 or self.revision <= 0:
Expand Down
2 changes: 1 addition & 1 deletion src/agent_comms/execution/acp_failure.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from agent_comms.execution.session_updates import AgentCommsUpdate
from agent_comms.execution.turn_failure import TurnFailure
from agent_comms.input_attempt import InputAttempt
from agent_comms.input_disposition import InputDocument
from agent_comms.messaging.delivery_presentation import DeliveryPresentation
from agent_comms.nominal.declared_family import DeclaredFamily, UnknownFamilyMember
from agent_comms.nominal.field_codec import (
Expand All @@ -38,7 +39,6 @@

from agent_comms.agent_events import Done, Error
from agent_comms.execution.turn_input_source import OriginalTurnInput
from agent_comms.input_disposition import InputDocument


class DeliveryFailure(DeliveryPresentation, DeclaredFamily, affix="Failure"):
Expand Down
Loading
Loading