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
13 changes: 11 additions & 2 deletions src/agent_comms/cli_bridges/claude_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
)
from agent_comms.execution.turn_phase import ModelWaitPhase, ToolRunningPhase, TurnPhase
from agent_comms.messaging.message_reference import MessageReference
from agent_comms.messaging.messages import Message
from agent_comms.nominal.field_codec import (
MalformedRecord,
ToolCallId,
Expand Down Expand Up @@ -112,6 +113,13 @@ class ClaudeMonitorFrame(MonitorIncomingFrame):
"""What a transcript's XML envelope cannot carry as written: control characters, CR and
the two noncharacters."""

@classmethod
def of_wire(cls, message: Message) -> Self:
"""The frame a remote watch client builds from the wire message alone. The wire names
no files, and a watch client installed before files existed decodes no field that
would, so both ends of a remote watch frame the body without them."""
return cls(message, ())

@staticmethod
def units(line: str) -> int:
return len(line.encode('utf-16-le')) // 2
Expand Down Expand Up @@ -292,11 +300,12 @@ async def confirm(
if message is None:
continue
observed = tuple(line.rstrip() for line in self.lines)
if ClaudeMonitorFrame(message).observed != observed:
frame = ClaudeMonitorFrame(message, await bridge.files_of(message))
if frame.observed != observed:
await bridge.record_mismatch(
delivery, 'Shown lines do not equal the original message')
continue
return await ClaudeMonitorFrame(message).whole_part.confirm(bridge, record)
return await frame.whole_part.confirm(bridge, record)
return ()


Expand Down
4 changes: 2 additions & 2 deletions src/agent_comms/cli_bridges/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
)
from agent_comms.cli_bridges.session_watch import WatchClaim, WatchRecord
from agent_comms.cli_bridges.shared import (
IncomingFrame,
Operation,
Options,
SessionBinding,
Expand Down Expand Up @@ -143,7 +142,8 @@ def pending():
ThreadOutput(transcript, self.comms.agents)))

async def deliver(self, message: Message) -> type[Outcome]:
request = BusInput.for_message(self.thread, message.message_id, IncomingFrame(message).text)
frame = self.incoming_frame(message, await self.files_of(message))
request = BusInput.for_message(self.thread, message.message_id, frame.text)
retries = 0
while True:
try:
Expand Down
8 changes: 7 additions & 1 deletion src/agent_comms/cli_bridges/inbox_watch.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
from agent_comms.errors import RelationViolationError
from agent_comms.execution.child_process import ProcessIdentity
from agent_comms.messaging.agent_inbox import NoWait, TakenInputPosition, TakenInputStart
from agent_comms.messaging.message_files import MessageFile
from agent_comms.messaging.message_reference import MessageReference
from agent_comms.messaging.messages import Message
from agent_comms.messaging.watched import ChangeSignal, FileSource
Expand Down Expand Up @@ -213,6 +214,11 @@ class PushedTranscript(ReceivesWatchReports, TranscriptConfirmsDelivery, ClaudeJ
delivery_kind: ClassVar[type[RemoteWatchHistory]] = RemoteWatchHistory
incoming_frame: ClassVar[type[ClaudeMonitorFrame]] = ClaudeMonitorFrame

async def files_of(self, message: Message) -> tuple[MessageFile, ...]:
"""The session's machine frames the wire message, which names no files, so this side
names none either."""
return ()

def exported(self, path: str) -> tuple[MonitorReadFile, ...]:
"""The file is on the session's machine, wherever its client keeps exports: its name
gives the reference and read_parts judges the lines against the bus message, so the
Expand Down Expand Up @@ -320,7 +326,7 @@ def taken(self, message: Message, ledger: TakingLedger) -> None:
reference.message_id,
reference.seq,
UnconfirmedOutcome,
monitor=ClaudeMonitorFrame(message).shown_evidence(ledger),
monitor=ClaudeMonitorFrame.of_wire(message).shown_evidence(ledger),
)
path = str(CoordinationStore.path_in(comms.root))
with Coordination(path) as store, store.session.writing() as db:
Expand Down
2 changes: 1 addition & 1 deletion src/agent_comms/cli_bridges/inbox_watch_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ async def deliver(self, frame: str, socket: ClientWebSocketResponse) -> None:
The ledger is written first: a freeze between it and the print leaves a message the bus
never replays, never one the session saw twice."""
message = FieldCodec.decode(Delivered, FieldCodec.parse(frame))
_, line = ClaudeMonitorFrame(message).event(self.exports)
_, line = ClaudeMonitorFrame.of_wire(message).event(self.exports)
self.ledger.record(message.reference)
print(line, flush=True)
await socket.send_str(PrintedNow(printed=(message.reference,)).line())
Expand Down
4 changes: 2 additions & 2 deletions src/agent_comms/cli_bridges/opencode.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
CliBridge,
GivenBinding,
GivenThread,
IncomingFrame,
Options,
SessionBinding,
SuppliedSession,
Expand Down Expand Up @@ -235,7 +234,8 @@ async def transcript(self) -> AsyncIterator[RuntimeUpdate]:

async def deliver(self, message: Message) -> type[Outcome]:
async with self.connection() as connection:
await connection.deliver(IncomingFrame(message).text)
frame = self.incoming_frame(message, await self.files_of(message))
await connection.deliver(frame.text)
return PersistedOutcome

async def show_sent(self, result: SendResult) -> None:
Expand Down
32 changes: 23 additions & 9 deletions src/agent_comms/cli_bridges/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
from agent_comms.installer.harness_install import HarnessSession
from agent_comms.installer.native_build_inputs import DetachedChildStdio
from agent_comms.installer.refusals import UpgradeRefused
from agent_comms.messaging.message_files import MessageFile
from agent_comms.messaging.bus import Bus
from agent_comms.messaging.bus_tables import MessageIdentitySource
from agent_comms.messaging.message_reference import (
Expand Down Expand Up @@ -1153,6 +1154,8 @@ def begin(self, bridge: LineMonitorBridge) -> None:
@dataclass(frozen=True)
class IncomingFrame(ABC):
message: Message
files: tuple[MessageFile, ...]
"""The message's files, each named after its body with the read that returns its bytes."""

HEADER = 'Comms in'
HEADER_PREFIX = HEADER + ' · '
Expand All @@ -1167,7 +1170,8 @@ def header(self) -> str:

@property
def text(self) -> str:
return self.header + self.message.body
files = "".join(f"\n{file.mention}" for file in self.files)
return self.header + self.message.body + (f"\n{files}" if files else "")

class BridgeLog(io.TextIOBase):
"""The bridge process's stderr, including tracebacks and partial print writes."""
Expand Down Expand Up @@ -1198,11 +1202,16 @@ class HarnessDeliveryRecords(WaitsOnBusyStore, ABC):
through this parent: neither can store an outcome the other would have had to prove."""

comms: Comms
incoming_frame: ClassVar[type[IncomingFrame]] = IncomingFrame

@property
@abstractmethod
def recipient_lookup(self) -> ThreadLookup: ...

async def files_of(self, message: Message) -> tuple[MessageFile, ...]:
"""The files this route names under a message, each with the read that returns it."""
return await asyncio.to_thread(self.comms.messaging.files.of, (message.reference,))

@property
@abstractmethod
def delivery_kind(self) -> type[HarnessSession]:
Expand Down Expand Up @@ -1245,9 +1254,13 @@ async def attempts(self, message_id: MessageId) -> tuple[HarnessDelivery, ...]:
return await self.coordinator_read(lambda db: tuple(HarnessDelivery.select(
db, bridge=self.delivery_kind, recipient_lookup=self.recipient_lookup, message_id=message_id)))

async def messages(self, references: tuple[MessageReference, ...]) -> tuple[Message, ...]:
"""The messages the bus still holds at these references; a gone one is simply absent."""
return await self.comms.bus.when_open(
partial(self.comms.bus.bus.messages_for_references, references))

async def message(self, reference: MessageReference) -> Message | None:
messages = await self.comms.bus.when_open(
partial(self.comms.bus.bus.messages_for_references, (reference,)))
messages = await self.messages((reference,))
return messages[0] if messages else None

@contextmanager
Expand Down Expand Up @@ -1792,7 +1805,7 @@ async def observed(self, bridge: TranscriptBridge) -> DeliveredInput:
message = await bridge.message(delivery.reference)
if message is None:
continue
if self.text != IncomingFrame(message).text:
if self.text != bridge.incoming_frame(message, await bridge.files_of(message)).text:
raise RelationViolationError("Observed bus input differs from its original delivery")
await bridge.finish(delivery, partial(replace, outcome=DeliveredOutcome, monitor=self.record))
references.extend(message.opening_references(bridge.transcript_thread))
Expand Down Expand Up @@ -1864,10 +1877,11 @@ async def read_export(self, read: ReadResultObserved) -> tuple[MessageReference,
with self.uncertain_on_contention(identity):
for exact in (attempt for attempt in await self.attempts(identity)
if attempt.reference == notice.reference):
message = await self.message(exact.reference)
for part in self.incoming_frame(message).read_parts(rows):
references.extend(await part.confirm(self, read.record))
await self.retire_read(exact, read, notice)
for message in await self.messages((exact.reference,)):
files = await self.files_of(message)
for part in self.incoming_frame(message, files).read_parts(rows):
references.extend(await part.confirm(self, read.record))
await self.retire_read(exact, read, notice)
return tuple(references)


Expand Down Expand Up @@ -1964,7 +1978,7 @@ async def deliver(self, message: Message) -> type[Outcome]:
return await self.reader.deliver(self, message)

async def deliver_to(self, attachment: MonitorAttachment, message: Message) -> type[Outcome]:
frame = self.incoming_frame(message)
frame = self.incoming_frame(message, await self.files_of(message))
receiving = partial(replace, monitor=frame.shown_evidence(TakingLedger()))
attempt = self.attempt(message, UnconfirmedOutcome)
await self.coordinator_write(partial(attempt.apply, receiving))
Expand Down
1 change: 1 addition & 0 deletions src/agent_comms/comms.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class Comms(
NotificationEvidenceSource[CapturedNotificationEvidence],
):
input_dispositions: ClassVar[Callable[[Path], InputLookup[InputAttempt]]] = InputDispositions
messaging: Messaging

def __init__(self, root: CommsRoute) -> None:
super().__init__(root)
Expand Down
18 changes: 16 additions & 2 deletions src/agent_comms/context_segments/wake.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
WireSources,
)
from agent_comms.messaging.bus_publication import Delivered
from agent_comms.messaging.message_files import MessageFile
from agent_comms.messaging.message_notification import SentMessageOutcome
from agent_comms.messaging.task_callbacks import DeliveredContext
from agent_comms.nominal.field_codec import FieldCodec
Expand Down Expand Up @@ -64,8 +65,10 @@ def capture(cls, sources, owner, goals, *, obligations=(), sent_outcomes=()):
work_context=owner.wake_context(goals),
)

def input_segments(self) -> tuple[ContextSegment, ...]:
return (self, *(MessageDelivery(source, assignment, self.owner).segment()
def input_segments(self, files: tuple[MessageFile, ...]) -> tuple[ContextSegment, ...]:
"""This frame, then one delivery per source naming the files its message carries out
of `files`, which the reader read for the whole batch."""
return (self, *(MessageDelivery(source, assignment, self.owner, files).segment()
for source, assignment in self.sources))

def values(self):
Expand Down Expand Up @@ -133,6 +136,8 @@ def capture(cls, delivery: MessageDelivery):

def values(self):
message = self.delivery.source.message
own_files = self.delivery.own_files
files = {"files": [file.mention for file in own_files]} if own_files else {}
return dict(
message=FieldCodec.compact(
{
Expand All @@ -141,6 +146,7 @@ def values(self):
"target": message.target,
"audience": self.delivery.assignment.audience.value,
"body": message.body,
**files,
}, ensure_ascii=True,
),
reply_to=message.exact_reply_target,
Expand All @@ -155,10 +161,18 @@ class MessageDelivery(DeliveredContext):
source: Delivered
assignment: WakeAssignment
owner: Thread
files: tuple[MessageFile, ...]
"""The files of the batch this delivery is read in; the reader supplies them, so framing
reads no store."""

def __post_init__(self) -> None:
self.assignment.require_selected_source(self.source, self.owner)

@property
def own_files(self) -> tuple[MessageFile, ...]:
reference = self.source.message.reference
return tuple(file for file in self.files if file.message == reference)

@property
def provenance(self) -> tuple[WireProvenance, ...]:
return (WireProvenance(self.source.message.reference),)
Expand Down
4 changes: 3 additions & 1 deletion src/agent_comms/execution/queued_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,14 +427,16 @@ def reserve_pending(
document = inputs.dispositions.read(tuple(
source.message.bus_key(owner) for source, _ in accepted
))
files = inputs.comms.messaging.files.of(
source.message.reference for source, _ in accepted)
with Coordination(str(CoordinationStore.path_in(inputs.comms.root))) as store:
for source, assignment in accepted:
message = source.message
key = message.bus_key(owner)
if document.lookup(key).is_stored():
continue
rendered = TurnContext.render_segments(
(MessageDelivery(source, assignment, owner).segment(),)
(MessageDelivery(source, assignment, owner, files).segment(),)
)
row = ReservedInput(
key, message.seq, canonical, context.claimed_identity.claimed_generation,
Expand Down
13 changes: 11 additions & 2 deletions src/agent_comms/execution/selected/turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
PublishingPhase,
)
from agent_comms.messaging.envelope_claim_transitions import WakeClaim
from agent_comms.messaging.message_files import MessageFile
from agent_comms.waking.wake_candidate_index import WakeCandidateIndex


Expand All @@ -75,6 +76,11 @@ def context(self, segments) -> TurnContext:
tuple(segments),
)

def files(self) -> tuple[MessageFile, ...]:
participant = self.participant
return participant.comms.messaging.files.of(
source.delivery.message.reference for source in participant.batch.sources)

def sent_outcomes(self):
return self.participant.sent_outcomes[:SelectedWakeSegment.sent_limit]

Expand All @@ -87,7 +93,10 @@ def triage(self) -> RenderedInput:
sent_outcomes=self.sent_outcomes(),
)
return self.context(
(*frame.input_segments(), SelectedTriageSegment.capture(participant, frame.provenance))
(
*frame.input_segments(self.files()),
SelectedTriageSegment.capture(participant, frame.provenance),
)
).render()

async def full(self, assignments, obligations, action: SelectedAction) -> RenderedInput:
Expand Down Expand Up @@ -116,7 +125,7 @@ async def full(self, assignments, obligations, action: SelectedAction) -> Render
)
return self.context(
(
*frame.input_segments(),
*frame.input_segments(self.files()),
*awareness,
SelectedWorkSegment.capture(participant, action, frame.provenance),
participant.batch.response_segment(),
Expand Down
Loading
Loading