diff --git a/src/agent_comms/cli_bridges/claude_protocol.py b/src/agent_comms/cli_bridges/claude_protocol.py index 5361284ee8..07b76d0f0e 100644 --- a/src/agent_comms/cli_bridges/claude_protocol.py +++ b/src/agent_comms/cli_bridges/claude_protocol.py @@ -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, @@ -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 @@ -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 () diff --git a/src/agent_comms/cli_bridges/codex.py b/src/agent_comms/cli_bridges/codex.py index ed69df7dce..0fadfa5c62 100755 --- a/src/agent_comms/cli_bridges/codex.py +++ b/src/agent_comms/cli_bridges/codex.py @@ -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, @@ -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: diff --git a/src/agent_comms/cli_bridges/inbox_watch.py b/src/agent_comms/cli_bridges/inbox_watch.py index 6ad4b8fe6f..a956da500e 100644 --- a/src/agent_comms/cli_bridges/inbox_watch.py +++ b/src/agent_comms/cli_bridges/inbox_watch.py @@ -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 @@ -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 @@ -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: diff --git a/src/agent_comms/cli_bridges/inbox_watch_client.py b/src/agent_comms/cli_bridges/inbox_watch_client.py index f8a3455ebb..89112075be 100644 --- a/src/agent_comms/cli_bridges/inbox_watch_client.py +++ b/src/agent_comms/cli_bridges/inbox_watch_client.py @@ -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()) diff --git a/src/agent_comms/cli_bridges/opencode.py b/src/agent_comms/cli_bridges/opencode.py index 5a147606e8..95a1eeb6cf 100755 --- a/src/agent_comms/cli_bridges/opencode.py +++ b/src/agent_comms/cli_bridges/opencode.py @@ -35,7 +35,6 @@ CliBridge, GivenBinding, GivenThread, - IncomingFrame, Options, SessionBinding, SuppliedSession, @@ -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: diff --git a/src/agent_comms/cli_bridges/shared.py b/src/agent_comms/cli_bridges/shared.py index 899cb517a0..2758ea4836 100644 --- a/src/agent_comms/cli_bridges/shared.py +++ b/src/agent_comms/cli_bridges/shared.py @@ -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 ( @@ -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 + ' · ' @@ -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.""" @@ -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]: @@ -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 @@ -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)) @@ -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) @@ -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)) diff --git a/src/agent_comms/comms.py b/src/agent_comms/comms.py index c41d2cfc58..30c1ae673b 100644 --- a/src/agent_comms/comms.py +++ b/src/agent_comms/comms.py @@ -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) diff --git a/src/agent_comms/context_segments/wake.py b/src/agent_comms/context_segments/wake.py index abcb2287dd..1436362a99 100644 --- a/src/agent_comms/context_segments/wake.py +++ b/src/agent_comms/context_segments/wake.py @@ -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 @@ -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): @@ -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( { @@ -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, @@ -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),) diff --git a/src/agent_comms/execution/queued_input.py b/src/agent_comms/execution/queued_input.py index b42c415ce0..c930cec966 100644 --- a/src/agent_comms/execution/queued_input.py +++ b/src/agent_comms/execution/queued_input.py @@ -427,6 +427,8 @@ 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 @@ -434,7 +436,7 @@ def reserve_pending( 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, diff --git a/src/agent_comms/execution/selected/turn.py b/src/agent_comms/execution/selected/turn.py index eb91d1cee4..40f96de62d 100644 --- a/src/agent_comms/execution/selected/turn.py +++ b/src/agent_comms/execution/selected/turn.py @@ -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 @@ -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] @@ -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: @@ -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(), diff --git a/src/agent_comms/messaging/message_files.py b/src/agent_comms/messaging/message_files.py new file mode 100644 index 0000000000..5bbff5bea0 --- /dev/null +++ b/src/agent_comms/messaging/message_files.py @@ -0,0 +1,260 @@ +"""The files a message carries: what a sender uploads, the record each reader lists, and the +store that keeps both. + +A message's envelope never names its files. They are rows keyed by the message's reference, +so a reader that predates them decodes every message, and every page, unchanged. The bytes +are stored once per SHA-256, which only deduplicates storage: a reader reaches a file +through a message it may read, never through its digest. +""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import re +from collections.abc import Iterable +from dataclasses import dataclass +from pathlib import Path, PurePath +from typing import Annotated, ClassVar + +from agent_comms.messaging.message_reference import MessageReference +from agent_comms.nominal.field_codec import MessageId, WireName, WireOmitDefault +from agent_comms.storage.typed_table import ( + Column, + DurableStore, + ForeignKey, + StoreRows, + TypedTable, + WithoutRowid, +) +from agent_comms.transport.request import tool_field +from agent_comms.transport.tool_result import ToolResult +from agent_comms_hooks import ToolRefusedError + +MAX_MESSAGE_FILE_BYTES = 8 * 1024 * 1024 +"""The most file bytes one message carries, all its files together.""" + +MAX_FILE_NAME_LENGTH = 255 +REFUSED_NAME_CHARACTERS = frozenset("\\\0") +"""A backslash is a directory on Windows; NUL ends a path on every system.""" + +MIME_TYPE = re.compile(r"[a-z0-9][a-z0-9!#$&^_.+-]*/[a-z0-9][a-z0-9!#$&^_.+-]*") + + +def base64_length(size: int) -> int: + """How many base64 characters encode ``size`` bytes.""" + return 4 * ((size + 2) // 3) + + +MAX_MESSAGE_FILE_TEXT = base64_length(MAX_MESSAGE_FILE_BYTES) +"""The most base64 text one message's files are sent as.""" + +MAX_SEND_REQUEST_BYTES = MAX_MESSAGE_FILE_TEXT + 1024 * 1024 +"""The most bytes one request carrying a message and its files is posted as: the files' +text and a megabyte for the rest of the request.""" + + +def require_file_name(name: str) -> None: + """A file's name names one file and no directory: 1 to 255 characters, its own last path + part, not only dots, and no backslash or NUL.""" + if not name.strip() or len(name) > MAX_FILE_NAME_LENGTH: + raise ValueError("A file name is 1 to 255 characters.") + if PurePath(name).name != name or not name.strip("."): + raise ValueError("A file name names no directory.") + if not REFUSED_NAME_CHARACTERS.isdisjoint(name): + raise ValueError("A file name holds no backslash or NUL.") + + +@dataclass(frozen=True, slots=True) +class FileUpload: + """One file a sender attaches: its name, its MIME type and its bytes as base64.""" + + name: str + mime_type: Annotated[str, WireName("mimeType")] + data: str + + def __post_init__(self) -> None: + require_file_name(self.name) + if not MIME_TYPE.fullmatch(self.mime_type): + raise ValueError(f"Unsupported file type: {self.mime_type!r}") + if len(self.data) > MAX_MESSAGE_FILE_TEXT: + raise ValueError("Files exceed the 8 MiB message limit.") + if not self.content: + raise ValueError("File data is empty.") + if self.size > MAX_MESSAGE_FILE_BYTES: + raise ValueError("Files exceed the 8 MiB message limit.") + + @classmethod + def of(cls, name: str, mime_type: str, content: bytes) -> FileUpload: + """The upload of bytes a picker returned, named by the last part of their name.""" + return cls(PurePath(name).name, mime_type, base64.b64encode(content).decode("ascii")) + + @property + def content(self) -> bytes: + try: + return base64.b64decode(self.data, validate=True) + except (ValueError, binascii.Error) as error: + raise ValueError("File data must be valid base64.") from error + + @property + def size(self) -> int: + return len(self.data) * 3 // 4 - (len(self.data) - len(self.data.rstrip("="))) + + @property + def sha256(self) -> str: + return hashlib.sha256(self.content).hexdigest() + + @staticmethod + def require_bounded(uploads: tuple[FileUpload, ...]) -> None: + """One message's files fit its limit together.""" + if sum(upload.size for upload in uploads) > MAX_MESSAGE_FILE_BYTES: + raise ValueError("Files exceed the 8 MiB message limit.") + + +@dataclass(frozen=True, kw_only=True) +class SendsFiles: + """A send that may carry files. An empty list is left off the wire, so a send with no + files is the request a Core that predates files decodes.""" + + files: Annotated[ + tuple[FileUpload, ...], + *tool_field("Files the message carries: name, mimeType and base64 data; 8 MiB in all"), + WireOmitDefault(), + ] = () + + +@dataclass(frozen=True, slots=True) +class MessageFile: + """One file a message carries, as every reader lists it.""" + + message: MessageReference + position: int + name: str + mime_type: Annotated[str, WireName("mimeType")] + size: int + sha256: str + + def __post_init__(self) -> None: + require_file_name(self.name) + + @property + def mention(self) -> str: + """How an agent's delivered message names it, with the read that returns its bytes.""" + return ( + f"File {self.position}: {self.name} ({self.mime_type}, {self.size} bytes); " + f"comms_message_file message={self.message.name} position={self.position}" + ) + + +@dataclass(frozen=True, slots=True) +class MessageFilesRead(ToolResult): + """The files of the messages a read named that its caller may read.""" + + files: tuple[MessageFile, ...] + + +@dataclass(frozen=True, slots=True) +class MessageFileContent(ToolResult): + """One message file and its bytes as base64.""" + + file: MessageFile + data: str + + +class MessageFilesRows(StoreRows): + """The tables of MessageFiles; each row declares itself one.""" + + +@dataclass(frozen=True, slots=True) +class FileContentRow(MessageFilesRows, WithoutRowid, TypedTable): + """Bytes stored once per digest, as the base64 text the sender uploaded.""" + + sha256: Annotated[str, Column(primary_key=True)] + data: str + + +@dataclass(frozen=True, slots=True) +class MessageFileRow(MessageFilesRows, WithoutRowid, TypedTable): + seq: Annotated[int, Column(primary_key=True)] + position: Annotated[int, Column(primary_key=True)] + message_id: MessageId + name: str + mime_type: str + size: int + sha256: str + + @classmethod + def references(cls) -> tuple[ForeignKey, ...]: + return (ForeignKey(columns=("sha256",), target=FileContentRow, target_columns=("sha256",)),) + + @property + def file(self) -> MessageFile: + return MessageFile( + MessageReference(self.seq, self.message_id), + self.position, + self.name, + self.mime_type, + self.size, + self.sha256, + ) + + +@dataclass(frozen=True, slots=True) +class MessageFiles(DurableStore): + """Every message's files. Files belong to messages, which outlive thread declarations.""" + + root: Path + filename: ClassVar[str] = "message_files.sqlite3" + tables = MessageFilesRows + + def keep(self, uploads: tuple[FileUpload, ...]) -> None: + """Store the bytes before the message that carries them is published, so a failed + write publishes nothing.""" + if not uploads: + return + FileUpload.require_bounded(uploads) + with self.writing() as db: + for upload in uploads: + FileContentRow(upload.sha256, upload.data).insert_if_absent(db) + + def attach(self, message: MessageReference, uploads: tuple[FileUpload, ...]) -> None: + """Name kept bytes as the files of a published message, in the order they were sent.""" + if not uploads: + return + with self.writing() as db: + for position, upload in enumerate(uploads): + MessageFileRow( + message.seq, + position, + message.message_id, + upload.name, + upload.mime_type, + upload.size, + upload.sha256, + ).insert(db) + + def of(self, messages: Iterable[MessageReference]) -> tuple[MessageFile, ...]: + """The files of these messages, in bus and send order.""" + references = frozenset(messages) + if not references: + return () + with self.snapshot() as db: + rows = MessageFileRow.select( + db, + where="{seq} IN (" + ", ".join("?" for _ in references) + ")", + parameters=tuple(reference.seq for reference in references), + order_by=("seq", "position"), + ) + return tuple(row.file for row in rows if row.file.message in references) + + def content(self, file: MessageFile) -> MessageFileContent: + with self.snapshot() as db: + (row,) = FileContentRow.select(db, sha256=file.sha256) + return MessageFileContent(file, row.data) + + def require(self, message: MessageReference, position: int) -> MessageFile: + for file in self.of((message,)): + if file.position == position: + return file + raise ToolRefusedError(f"Message {message.name} has no file {position}.") diff --git a/src/agent_comms/messaging/sending.py b/src/agent_comms/messaging/sending.py index 40c3146479..8773bfc3a1 100644 --- a/src/agent_comms/messaging/sending.py +++ b/src/agent_comms/messaging/sending.py @@ -26,6 +26,7 @@ ) from agent_comms.messaging.initial_origin import HumanOrigin, InitialOrigin from agent_comms.messaging.message_bus import MessageBus +from agent_comms.messaging.message_files import FileUpload, MessageFiles from agent_comms.messaging.message_reference import MessageReference from agent_comms.messaging.message_send_reads import PresenceMessageSender from agent_comms.messaging.messages import ( @@ -98,15 +99,25 @@ def __init__(self, root: Path, registry: Registration, bus: MessageBus, goals: G self.bus = bus self.goals = goals + @property + def files(self) -> MessageFiles: + return MessageFiles(self.root) + def _publish(self, message: Message, origin: InitialOrigin, - *, destination: NamedTarget) -> Message: - """Record the meaning of a committed ordinary send beyond its bus transaction.""" + *, destination: NamedTarget, files: tuple[FileUpload, ...] = ()) -> Message: + """Record the meaning of a committed ordinary send beyond its bus transaction. + + Its files' bytes are kept before the message is published and named as its files once + it has a reference, so a message is never published over bytes that failed to write.""" + self.files.keep(files) try: committed = self.bus.publisher.publish_ordinary( message, origin=origin, destination=destination) except CommittedMessageError as error: + self.files.attach(error.record.reference, files) origin.complete(self.goals, error.record) raise + self.files.attach(committed.reference, files) return origin.complete(self.goals, committed) def send( @@ -123,6 +134,7 @@ def send( origin: AutomatedOrigin = AgentOrigin(), source_turn: SourceTurn = NoSourceTurn(), answerer: AnswerAuthority = SenderReceipts(), + files: tuple[FileUpload, ...] = (), ) -> SendResult: """Return the committed envelope and its separate wording-correction outcome.""" type.require_sendable() @@ -151,7 +163,8 @@ def send( report=report, answers=tuple(dict.fromkeys((*answers, *self._answered_by(owner, target, source_turn)))), ) - committed = self._publish(message, origin, destination=CommandTarget.named(target)) + committed = self._publish( + message, origin, destination=CommandTarget.named(target), files=files) correction: CorrectionResult try: todos.correct(owner.incarnation, committed.message_id, body) @@ -182,10 +195,11 @@ def user_identity(self, worktree: Checkout) -> Thread: return self.registry.user_thread().or_create(lambda: self.registry.claim_user(worktree)) def send_user_message(self, target: NamedTarget, body: str, *, worktree: Checkout, - task: TaskAttachment = NoTaskAttachment()) -> Message: + task: TaskAttachment = NoTaskAttachment(), + files: tuple[FileUpload, ...] = ()) -> Message: """Cooperative local UI send, not cryptographic same-UID authentication.""" user = self.user_identity(worktree) - return self._publish_user(user, target, body, task) + return self._publish_user(user, target, body, task, files=files) def send_owner_notice(self, target: NamedTarget, body: str, notice: TaskAttachment, *, role: MessageRole) -> Message: @@ -226,8 +240,9 @@ def _pin_constraint(self, recipient, subject, declaration, *, worktree: Checkout task, role=NoticeRole()) def _publish_user(self, user: Thread, target: NamedTarget, body: str, - task: TaskAttachment, *, role: MessageRole = ConversationRole()) -> Message: + task: TaskAttachment, *, role: MessageRole = ConversationRole(), + files: tuple[FileUpload, ...] = ()) -> Message: return self._publish( Message(user.name, target.name, body, InfoKind, task=task, role=role), - HumanOrigin.of(user), destination=target, + HumanOrigin.of(user), destination=target, files=files, ) diff --git a/src/agent_comms/transport/connector.py b/src/agent_comms/transport/connector.py index 5b4a248b80..3b4669acc2 100644 --- a/src/agent_comms/transport/connector.py +++ b/src/agent_comms/transport/connector.py @@ -64,6 +64,7 @@ from agent_comms.installer.active_route import CommsRoute, resolve_comms_route from agent_comms.messaging.bus_identity import BusIdentityStore from agent_comms.messaging.channel_targets import NamedTarget +from agent_comms.messaging.message_files import MAX_SEND_REQUEST_BYTES from agent_comms.messaging.messages import QuestionKind from agent_comms.messaging.send_result import MessagePublished from agent_comms.messaging.task_sources import OwnerRequestAttachment @@ -674,7 +675,7 @@ def cancel_call(self, request_id: JsonRpcId) -> None: def application(self) -> web.Application: self.store.read() # Refuse an unreadable store before binding any port. - app = web.Application(middlewares=[self.log_route]) + app = web.Application(middlewares=[self.log_route], client_max_size=MAX_SEND_REQUEST_BYTES) app.cleanup_ctx.append(self.watch_orders) app.on_shutdown.append(self.begin_shutdown) app.on_shutdown.append(self.stop_calls) diff --git a/src/agent_comms/transport/native_tool_transport.py b/src/agent_comms/transport/native_tool_transport.py index b0d45bc8d2..52c95dd0cd 100644 --- a/src/agent_comms/transport/native_tool_transport.py +++ b/src/agent_comms/transport/native_tool_transport.py @@ -19,6 +19,7 @@ from agent_comms.coordination.database import CoordinationStore from agent_comms.errors import RelationViolationError from agent_comms.execution.child_process import join_retirement +from agent_comms.messaging.message_files import MAX_SEND_REQUEST_BYTES from agent_comms.nominal.field_codec import FieldCodec, InputId, MalformedRecord, Token256Text from agent_comms.nominal.lifecycle_capability import Complete from agent_comms.pi_payloads import AssistantMessage @@ -296,7 +297,7 @@ def or_else(self, factory: Callable[[], NativeToolMode]) -> NativeToolMode: class ToolTransport(Generic[Call]): """A child-bound request policy. An instance always has its authenticated PID.""" - max_request = 1024 * 1024 + max_request = MAX_SEND_REQUEST_BYTES turn: TurnSession @property diff --git a/src/agent_comms/transport/tools/send.py b/src/agent_comms/transport/tools/send.py index fc3e2468d9..72deabb34d 100644 --- a/src/agent_comms/transport/tools/send.py +++ b/src/agent_comms/transport/tools/send.py @@ -13,6 +13,7 @@ from agent_comms.comms import Comms from agent_comms.coordination.tables.refusals import SendRefusal from agent_comms.messaging.channel_targets import CommandTarget, NamedTarget +from agent_comms.messaging.message_files import SendsFiles from agent_comms.messaging.message_reference import MessageReference from agent_comms.messaging.messages import InfoKind, MessageKind, SendableMessageKind from agent_comms.messaging.send_result import MessagePublished @@ -26,7 +27,7 @@ from agent_comms_hooks import ToolRefusedError @dataclass(frozen=True, kw_only=True) -class SendTool(PublishingTool[ThreadCaller, MessagePublished]): +class SendTool(SendsFiles, PublishingTool[ThreadCaller, MessagePublished]): label = "Comms Send" description = ( "Send a message to another thread or channel. Address specific threads with " @@ -62,7 +63,7 @@ def publish(self, comms: Comms, caller: ThreadCaller) -> MessagePublished: result = comms.messaging.send( sender, target.name, body, self.type, report=self.report, task=self.attachment(comms, target), origin=caller.origin(), - answers=self.answers) + answers=self.answers, files=self.files) except ToolRefusedError as error: # The caller hears the refusal now; the record waits for the wire lock on its own. threading.Thread(target=SendRefusal.record, diff --git a/src/agent_comms/transport/tools/served.py b/src/agent_comms/transport/tools/served.py index eb71f610ac..2fc87f71d1 100644 --- a/src/agent_comms/transport/tools/served.py +++ b/src/agent_comms/transport/tools/served.py @@ -55,7 +55,8 @@ from agent_comms.messaging.channels import Channel, SavedView, ViewMatch, ViewPredicate from agent_comms.messaging.display_references import ReferenceNames from agent_comms.messaging.exporting import WireExportProvenance -from agent_comms.messaging.historical_views import ConversationRevision +from agent_comms.messaging.historical_views import ChannelHistory, ConversationRevision, DMHistory +from agent_comms.messaging.message_files import MessageFileContent, MessageFilesRead from agent_comms.messaging.history_result import HistoryPageResult from agent_comms.messaging.message_notification import MessageNotification from agent_comms.messaging.message_page import MessagePage @@ -190,7 +191,10 @@ CommsThreadConfigurationTool, CommsThreadPresentationTool, CommsThreadRelationshipsTool, + CommsMessageFilesTool, + CommsMessageFileTool, CommsUserSendTool, + MessageFileRead, CommsWireRevisionTool, ContextInspectionRead, HistoricalThreadsRead, @@ -1027,10 +1031,55 @@ class ServedCommsUserSendTool(PublishingToolRequest[ToolCaller, MessagePublished def publish(self, comms: Comms, caller: ToolCaller) -> MessagePublished: caller.require_human() message = comms.messaging.send_user_message( - CommandTarget.named(self.target), self.body, worktree=Checkout(comms.root)) + CommandTarget.named(self.target), self.body, worktree=Checkout(comms.root), + files=self.files) return MessagePublished.from_send(SendResult(message, CorrectionComplete())) +class ServedMessageFileRead(MessageFileRead): + """Files are read through their messages, by the rule that reads the messages: the + conversation's display scope, captured for this caller, must include every one.""" + + def readable(self, comms: Comms, caller: ToolCaller, + references: tuple[MessageReference, ...]) -> tuple[MessageReference, ...]: + target = CommandTarget.named( + CommandTarget.named(self.conversation).canonical_name( + lambda name: comms.registry.require(name).name)) + scope = target.history_view( + caller.history_viewer(self.participant), comms.bus.require_channel, + ChannelHistory, DMHistory, + ).capture(comms.registry.snapshot()) + found = {message.reference: message + for message in comms.bus.bus.messages_for_references(references)} + refused = tuple(reference.name for reference in references + if reference not in found or not scope.includes(found[reference])) + if refused: + raise ToolRefusedError( + f"Not in {self.conversation} as you may read it: {', '.join(refused)}") + return references + + +class ServedCommsMessageFilesTool( + ServedMessageFileRead, CoreRead[MessageFilesRead], CommsMessageFilesTool, +): + """Serving CommsMessageFilesTool.""" + + def apply(self, comms: Comms, caller: ToolCaller) -> MessageFilesRead: + return MessageFilesRead( + comms.messaging.files.of(self.readable(comms, caller, self.messages))) + + +class ServedCommsMessageFileTool( + ServedMessageFileRead, CoreRead[MessageFileContent], CommsMessageFileTool, +): + """Serving CommsMessageFileTool.""" + + def apply(self, comms: Comms, caller: ToolCaller) -> MessageFileContent: + (message,) = self.readable(comms, caller, (self.message,)) + files = comms.messaging.files + return files.content(files.require(message, self.position)) + + class ServedCommsMarkThreadViewReadTool(HumanToolRequest[ThreadViewMarked], CommsMarkThreadViewReadTool): """Serving CommsMarkThreadViewReadTool.""" diff --git a/src/agent_comms/transport/tools/sidebar.py b/src/agent_comms/transport/tools/sidebar.py index 5a4bec5029..fdf7634dfc 100644 --- a/src/agent_comms/transport/tools/sidebar.py +++ b/src/agent_comms/transport/tools/sidebar.py @@ -59,6 +59,12 @@ HistoricalThread, UnobservedConversation, ) +from agent_comms.messaging.message_files import ( + MessageFileContent, + MessageFilesRead, + SendsFiles, +) +from agent_comms.messaging.message_reference import MessageReference from agent_comms.messaging.message_page import NEWEST_PAGE, MessagePage, PageBounds from agent_comms.messaging.page_traversal import LatestSequence from agent_comms.messaging.send_result import MessagePublished @@ -585,7 +591,7 @@ class CommsThreadRelationshipsTool(ReadRequest[ThreadCommsSnapshot]): @dataclass(frozen=True, kw_only=True) -class CommsUserSendTool(ToolRequest[MessagePublished]): +class CommsUserSendTool(SendsFiles, ToolRequest[MessagePublished]): """Local and connector UI input use the existing durable human publication.""" label = "Send human input" @@ -597,6 +603,41 @@ class CommsUserSendTool(ToolRequest[MessagePublished]): body: Annotated[str, *tool_field("Human input text")] +@dataclass(frozen=True, kw_only=True) +class MessageFileRead: + """A read of message files names the conversation its caller reads them in; a message + outside what that reader may read is refused, as its page would be.""" + + conversation: Annotated[ + str, *tool_field("The #channel, or the DM's other participant, the messages are in")] + participant: Annotated[ + str, *tool_field("Participant reading a DM; omit to use the caller")] = "" + + +@dataclass(frozen=True, kw_only=True) +class CommsMessageFilesTool(MessageFileRead, ReadRequest[MessageFilesRead]): + """The files a page's messages carry, read beside the page; the page itself never names them.""" + + label = "Message files" + description = ( + "List the files these messages carry: name, MIME type, size and SHA-256 for each. " + "Every message must be in the conversation you may read.") + messages: Annotated[ + tuple[MessageReference, ...], *tool_field("The messages whose files to list")] + + +@dataclass(frozen=True, kw_only=True) +class CommsMessageFileTool(MessageFileRead, ReadRequest[MessageFileContent]): + """One file of one message, with its bytes.""" + + label = "Message file" + description = ( + "Read one file a message carries, with its bytes as base64. The message must be in " + "the conversation you may read.") + message: Annotated[MessageReference, *tool_field("The message that carries the file")] + position: Annotated[int, *tool_field("The file's position among the message's files, from 0")] + + @dataclass(frozen=True, kw_only=True) class CommsWireRevisionTool(ReadRequest[WireRevision]): """What every wire view derives from; an equal revision shows the same thing.""" diff --git a/tests/test_codex_delivery_reporting.py b/tests/test_codex_delivery_reporting.py index 150a525b65..b835141497 100644 --- a/tests/test_codex_delivery_reporting.py +++ b/tests/test_codex_delivery_reporting.py @@ -8,7 +8,9 @@ from agent_comms.cli_bridges.harness_delivery_states import AcceptedOutcome, DeliveredOutcome, ObservedBridgeInput, UnconfirmedOutcome from agent_comms.cli_bridges.runtime_updates import FailedTurn, FinishedTurn, ThreadOutput from agent_comms.cli_bridges.shared import Binding, IncomingFrame, StoredBinding, Watch +from agent_comms.errors import RelationViolationError from agent_comms.execution.turn_item import NativeItemId, NativeTurnId +from agent_comms.messaging.message_files import FileUpload from agent_comms.messaging.notification_evidence import AllOutcomes from agent_comms.messaging.notification_progress import HarnessConsumedProgress from agent_comms.projects.checkouts import Checkout @@ -34,7 +36,7 @@ async def test_original_input_proof_survives_either_acceptance_order(tmp_path, e 'threadId': 'codex-thread', 'turnId': 'actual-turn', 'completedAtMs': 2000, 'item': {'type': 'userMessage', 'id': 'actual-input', 'clientId': BusClientId(message.message_id).external, - 'content': [{'type': 'text', 'text': IncomingFrame(message).text}]}, + 'content': [{'type': 'text', 'text': IncomingFrame(message, ()).text}]}, })) if echo_first: await observed.observed(bridge) @@ -50,6 +52,34 @@ async def test_original_input_proof_survives_either_acceptance_order(tmp_path, e assert current.label == current.timed_state(HarnessConsumedProgress.label, 2000) +async def test_a_bridge_frames_a_message_with_its_files_and_refuses_an_echo_without_them(tmp_path): + root, _, comms, initial, people = _root(tmp_path, direct=True) + message = initial.message + upload = FileUpload('shot.png', 'image/png', 'iVBORw==') + comms.messaging.files.keep((upload,)) + comms.messaging.files.attach(message.reference, (upload,)) + binding = Binding(root=str(root), owner=people[2].incarnation, thread='codex-thread', start=Binding.bus_head(str(root))) + with Binding.open(tmp_path / 'bridge') as db: + options = CodexOptions(Watch(), StoredBinding(), tmp_path / 'bridge', tmp_path, str(tmp_path / 'unused.sock')) + bridge = CodexBridge(options, binding.address(), db) + await options.operation.prepare(bridge) + frame = bridge.incoming_frame(message, await bridge.files_of(message)) + (file,) = comms.messaging.files.of((message.reference,)) + assert frame.text == IncomingFrame(message, (file,)).text + assert frame.text.endswith('\n\n' + file.mention) + original = bridge.attempt(message, UnconfirmedOutcome) + assert await bridge.coordinator_write(original.begin) + stream = ItemStream('codex-thread') + body_only = stream.receive(RpcNotification(method='item/completed', params={ + 'threadId': 'codex-thread', 'turnId': 'actual-turn', 'completedAtMs': 2000, + 'item': {'type': 'userMessage', 'id': 'actual-input', + 'clientId': BusClientId(message.message_id).external, + 'content': [{'type': 'text', 'text': IncomingFrame(message, ()).text}]}, + })) + with pytest.raises(RelationViolationError): + await body_only.observed(bridge) + + def test_failed_turn_retains_the_original_error_without_an_answer(tmp_path): comms = installed_comms(tmp_path / 'root') comms.registry.declare(ExternalThread('cli', frozenset(), Checkout(tmp_path))) diff --git a/tests/test_coordinated_runtime.py b/tests/test_coordinated_runtime.py index e83717c5ca..b849544369 100644 --- a/tests/test_coordinated_runtime.py +++ b/tests/test_coordinated_runtime.py @@ -22,6 +22,7 @@ from agent_comms.execution.pi_vocabulary import HighThinkingLevel from agent_comms.execution.turn_context import TurnContext from agent_comms.messaging.channel_targets import CommandTarget +from agent_comms.messaging.message_files import FileUpload from agent_comms.messaging.message_notification import MessageNotification from agent_comms.messaging.notification_progress import HumanReadProgress from agent_comms.nominal.field_codec import FieldCodec @@ -101,13 +102,33 @@ def test_triage_frame_is_read_only_and_does_not_promote_message_body(tmp_path: P assignment = sealed_cohort_assignments(store, lookup)[0] frame = TurnContext.render_segments(SelectedWakeSegment.capture( ((initial, assignment),), people[1], comms.goals, - ).input_segments()).text + ).input_segments(())).text assert f'"source_seq":{initial.message.seq}' in frame assert '"wake_mode":"bounded_triage"' in frame assert f'"body":{json.dumps(initial.message.body)}' in frame assert len(read_history(comms, "#team")) == 1 +def test_delivered_frame_names_each_file_with_the_read_that_returns_it(tmp_path: Path) -> None: + root, _root_id, comms, initial, people = _root(tmp_path) + upload = FileUpload("trace.txt", "text/plain", "dHJhY2U=") + comms.messaging.files.keep((upload,)) + comms.messaging.files.attach(initial.message.reference, (upload,)) + with Coordination(str(root / "coordination.sqlite3")) as store: + assignment = sealed_cohort_assignments(store, people[1].incarnation.lookup)[0] + files = comms.messaging.files.of((initial.message.reference,)) + frame = TurnContext.render_segments(SelectedWakeSegment.capture( + ((initial, assignment),), people[1], comms.goals, + ).input_segments(files)).text + (file,) = files + assert json.dumps(file.mention)[1:-1] in frame + assert f"message={initial.message.reference.name} position=0" in file.mention + unrelated = TurnContext.render_segments(SelectedWakeSegment.capture( + ((initial, assignment),), people[1], comms.goals, + ).input_segments(())).text + assert "comms_message_file" not in unrelated + + def test_channel_wake_frame_carries_effective_goal_execution(tmp_path: Path) -> None: root, _root_id, comms, initial, people = _root(tmp_path) comms.goals.update_goal("alpha", SetGoalAction(text="Restore subscribers")) @@ -117,7 +138,7 @@ def test_channel_wake_frame_carries_effective_goal_execution(tmp_path: Path) -> assignment = sealed_cohort_assignments(store, lookup)[0] frame = TurnContext.render_segments(SelectedWakeSegment.capture( ((initial, assignment),), comms.registry.require("alpha"), comms.goals, - ).input_segments()).text + ).input_segments(())).text context = json.loads(next( line.removeprefix("work_context: ") for line in frame.splitlines() if line.startswith("work_context: ") @@ -143,7 +164,7 @@ def test_wake_frame_includes_bounded_changed_sent_outcomes(tmp_path: Path) -> No assert sent_outcome is not None frame = TurnContext.render_segments(SelectedWakeSegment.capture( ((initial, assignment),), people[1], _comms.goals, sent_outcomes=(sent_outcome,) - ).input_segments()).text + ).input_segments(())).text assert 'recent_sent_outcomes: [{"source_seq":' in frame assert '"state":"Read"' in frame assert replace(notification, changed=False).sent_outcome() is None @@ -162,8 +183,8 @@ def test_selected_and_following_use_the_original_question_contract(tmp_path: Pat sealed_cohort_assignments(store, people[1].incarnation.lookup)} sources = ((peer, assignments[peer.message.seq]), (original, assignments[question.seq])) frame = SelectedWakeSegment.capture(sources, people[1], comms.goals) - metadata, peer_segment, question_segment = frame.input_segments() - following = MessageDelivery(original, assignments[question.seq], people[1]).segment() + metadata, peer_segment, question_segment = frame.input_segments(()) + following = MessageDelivery(original, assignments[question.seq], people[1], ()).segment() assert metadata is frame and frame.sources == sources assert tuple(reference for source in metadata.provenance for reference in source.bus_references()) == () diff --git a/tests/test_inbox_watch.py b/tests/test_inbox_watch.py index 17d57307d1..73480e71db 100644 --- a/tests/test_inbox_watch.py +++ b/tests/test_inbox_watch.py @@ -851,10 +851,10 @@ async def test_a_pushed_message_is_delivered_only_once_the_transcript_shows_it( await inbox_emptied(comms, "cloud") assert {attempt_outcome(comms, message) for message in (shown, mangled, wrapped)} == {"unconfirmed"} - await socket.send_str(monitor_event_record(ClaudeMonitorFrame(shown).shown_inline())) + await socket.send_str(monitor_event_record(ClaudeMonitorFrame(shown, ()).shown_inline())) await socket.send_str(monitor_event_record( - ClaudeMonitorFrame(mangled).shown_inline().replace("wrong", "otherwise"))) - await socket.send_str(monitor_event_record(ClaudeMonitorFrame(wrapped).shown_inline())) + ClaudeMonitorFrame(mangled, ()).shown_inline().replace("wrong", "otherwise"))) + await socket.send_str(monitor_event_record(ClaudeMonitorFrame(wrapped, ()).shown_inline())) async with asyncio.timeout(20): while {attempt_outcome(comms, shown), attempt_outcome(comms, wrapped)} != {"delivered"}: await asyncio.sleep(0.05) @@ -1050,13 +1050,13 @@ async def test_a_cloud_message_sent_as_a_file_is_delivered_once_its_read_shows_i for _ in range(2): await frame(socket) await inbox_emptied(comms, "cloud") - assert not ClaudeMonitorFrame(whole).fits_one_event + assert not ClaudeMonitorFrame(whole, ()).fits_one_event def numbered(lines: tuple[str, ...]) -> str: return "\n".join(f"{number}\t{line}" for number, line in enumerate(lines, 1)) - for message, lines in ((whole, ClaudeMonitorFrame(whole).export_lines), - (forged, ClaudeMonitorFrame(whole).export_lines)): + for message, lines in ((whole, ClaudeMonitorFrame(whole, ()).export_lines), + (forged, ClaudeMonitorFrame(whole, ()).export_lines)): path = f"/elsewhere/state/messages/{message.reference.name}.txt" for record in read_records(path, numbered(lines)): await socket.send_str(record) @@ -1090,7 +1090,7 @@ async def test_a_cloud_message_sent_as_a_file_is_delivered_once_a_cat_shows_it( await inbox_emptied(comms, "cloud") for message in (whole, edited): path = f"/elsewhere/state/messages/{message.reference.name}.txt" - for record in cat_records(path, "\n".join(ClaudeMonitorFrame(whole).export_lines)): + for record in cat_records(path, "\n".join(ClaudeMonitorFrame(whole, ()).export_lines)): await socket.send_str(record) async with asyncio.timeout(20): while attempt_outcome(comms, whole) != "delivered": diff --git a/tests/test_message_files.py b/tests/test_message_files.py new file mode 100644 index 0000000000..414fc6cc65 --- /dev/null +++ b/tests/test_message_files.py @@ -0,0 +1,205 @@ +"""A message's files: uploaded with the send, listed and read through the message, never on +its envelope, and carried by every installation.""" + +from __future__ import annotations + +import base64 +import json +import os +import sqlite3 +from contextlib import closing +from pathlib import Path + +import pytest +from aiohttp.test_utils import TestClient, TestServer + +from agent_comms.comms import Comms +from agent_comms.messaging.channel_targets import CommandTarget +from agent_comms.messaging.message_files import ( + MAX_MESSAGE_FILE_BYTES, + FileUpload, + MessageFileContent, + MessageFiles, + MessageFilesRead, +) +from agent_comms.messaging.message_page import MessagePage +from agent_comms.messaging.send_result import MessagePublished +from agent_comms.nominal.field_codec import FieldCodec +from agent_comms.projects.checkouts import Checkout +from agent_comms.registry.threads import NativeThread +from agent_comms.storage.locked_store import DurableFile, SQLiteFile +from agent_comms.storage.typed_table import ReconciledFile +from agent_comms.transport.connector import Connector +from agent_comms.transport.connector_store import ConnectorStore, UiAccess +from agent_comms.transport.mcp import ToolsCallMessage, ToolsCallReply +from agent_comms.transport.request import ToolCall, ToolRequest +from agent_comms.transport.tool_caller import HumanCaller, ThreadCaller +from agent_comms.transport.tools.send import CommsSendTool +from agent_comms.transport.tools.served import ( + ServedCommsConversationPageTool, + ServedCommsMessageFilesTool, + ServedCommsMessageFileTool, + ServedCommsUserSendTool, +) +from agent_comms.transport.tools.sidebar import ( + CommsMessageFilesTool, + CommsMessageFileTool, + CommsUserSendTool, +) +from agent_comms_hooks import ToolRefusedError +from bus_record_fixture import prepare_native_comms + + +def upload(name: str, content: bytes, mime_type: str = "application/octet-stream") -> FileUpload: + return FileUpload(name, mime_type, base64.b64encode(content).decode("ascii")) + + +@pytest.fixture +def threads(comms: Comms) -> Comms: + prepare_native_comms(comms) + for name, tags in (("recipient", {"general"}), ("outsider", set())): + comms.registry.declare(NativeThread(name, frozenset(tags), Checkout(comms.root))) + return comms + + +def user(comms: Comms) -> str: + return comms.messaging.user_identity(Checkout(comms.root)).name + + +def send_human(comms: Comms, target: str, body: str, *files: FileUpload) -> MessagePublished: + return HumanCaller().invoke(ServedCommsUserSendTool(target=target, body=body, files=files), comms) + + +async def post[R](client: TestClient, token: str, request: ToolRequest[R], number: int) -> R: + call = ToolsCallMessage(jsonrpc="2.0", id=number, params=ToolCall( + request.declared_name, FieldCodec.encode_fields(request))) + response = await client.post("/mcp", json=FieldCodec.encode(call), + headers={"Authorization": f"Bearer {token}"}) + assert response.status == 200 + reply = FieldCodec.decode(ToolsCallReply, await response.json()).result + assert reply.is_error is False, reply.content + return FieldCodec.decode(request.result_type(), reply.structured_content) + + +async def test_a_file_sent_from_a_remote_ui_is_the_file_its_recipient_reads( + threads: Comms, tmp_path: Path, +) -> None: + """Over the connector, as the phone sends: a file over the transport's default 1 MiB body + rides the human send, the UI lists it beside its page, and the agent it went to reads the + same bytes back through the message.""" + comms = threads + content = os.urandom(2 * 1024 * 1024 + 3) + sent = upload("trace.bin", content) + store = ConnectorStore.at(tmp_path / "auth") + namespace = comms.registry.store.privacy().namespace + token = store.update(lambda grants: grants.ui_issued(namespace, 60, UiAccess)).token + async with TestServer(Connector(store, "http://127.0.0.1:18766", comms.root).application()) as server: + async with TestClient(server) as client: + published = await post(client, token, CommsUserSendTool( + target="recipient", body="the trace", files=(sent,)), 1) + me = user(comms) + listed = await post(client, token, CommsMessageFilesTool( + conversation="recipient", participant=me, messages=(published.message.source,)), 2) + (file,) = listed.files + assert (file.message, file.position, file.name, file.size) == ( + published.message.source, 0, "trace.bin", len(content)) + read = await post(client, token, CommsMessageFileTool( + conversation="recipient", participant=me, message=file.message, position=0), 3) + assert base64.b64decode(read.data) == content + assert read.file == file + fetched = ThreadCaller("recipient").invoke(ServedCommsMessageFileTool( + conversation=me, message=published.message.source, position=0), comms) + assert isinstance(fetched, MessageFileContent) + assert base64.b64decode(fetched.data) == content + (stored,) = comms.bus.inbox("recipient").page.messages + assert stored.body == "the trace" + + +def test_an_agent_send_carries_files_and_a_send_without_files_names_none(threads: Comms) -> None: + comms = threads + sent = CommsSendTool(target="recipient", body="the log", files=(upload("log.txt", b"line\n", "text/plain"),)) + published = ThreadCaller("outsider").invoke(sent, comms) + assert "files" not in FieldCodec.encode(CommsSendTool(target="recipient", body="none")) + listed = ThreadCaller("recipient").invoke(ServedCommsMessageFilesTool( + conversation="outsider", messages=(published.message.source,)), comms) + assert isinstance(listed, MessageFilesRead) + assert [(file.name, file.mime_type, file.size) for file in listed.files] == [("log.txt", "text/plain", 5)] + + +def test_files_over_the_message_limit_are_refused_before_anything_is_written(threads: Comms) -> None: + comms = threads + with pytest.raises(ValueError): + upload("big.bin", b"x" * (MAX_MESSAGE_FILE_BYTES + 1)) + with pytest.raises(ValueError): + FieldCodec.decode(CommsUserSendTool, { + "to": "recipient", "body": "big", + "files": [{"name": "big.bin", "mimeType": "application/octet-stream", + "data": base64.b64encode(b"x" * (MAX_MESSAGE_FILE_BYTES + 1)).decode()}], + }) + before = comms.bus.bus.revision() + half = MAX_MESSAGE_FILE_BYTES // 2 + 1 + with pytest.raises(ValueError): + send_human(comms, "recipient", "two halves", upload("a.bin", b"a" * half), upload("b.bin", b"b" * half)) + assert comms.bus.bus.revision() == before + assert not MessageFiles(comms.root).path.exists() + for name, mime_type, data in (("../escape", "text/plain", "aGk="), ("..", "text/plain", "aGk="), + (".", "text/plain", "aGk="), ("a\\b", "text/plain", "aGk="), + ("note.txt", "not a type", "aGk="), + ("note.txt", "text/plain", "not base64!"), ("empty.txt", "text/plain", "")): + with pytest.raises(ValueError): + FileUpload(name, mime_type, data) + + +def test_a_reader_outside_the_conversation_is_refused_its_files(threads: Comms) -> None: + """Files are read by the rule that reads their message: a DM's files only by its + participants, a channel's by whoever reads the channel.""" + comms = threads + published = send_human(comms, "recipient", "for you", upload("secret.txt", b"secret", "text/plain")) + me = user(comms) + for request in ( + ServedCommsMessageFileTool(conversation=me, message=published.message.source, position=0), + ServedCommsMessageFilesTool(conversation=me, messages=(published.message.source,)), + ServedCommsMessageFileTool(conversation="#general", message=published.message.source, position=0), + ): + with pytest.raises(ToolRefusedError): + ThreadCaller("outsider").invoke(request, comms) + with pytest.raises(ToolRefusedError): + ThreadCaller("recipient").invoke(ServedCommsMessageFileTool( + conversation=me, message=published.message.source, position=1), comms) + posted = ThreadCaller("recipient").invoke(CommsSendTool( + target="#general", body="for all", files=(upload("notes.txt", b"notes", "text/plain"),)), comms) + read = ThreadCaller("outsider").invoke(ServedCommsMessageFileTool( + conversation="#general", message=posted.message.source, position=0), comms) + assert base64.b64decode(read.data) == b"notes" + + +def test_a_page_of_messages_with_files_is_the_page_a_reader_before_files_decodes(threads: Comms) -> None: + """Files are rows beside the bus, so the page and every message on it encode exactly as + they did before files existed: no key a decoder that rejects unknown fields could refuse. + tools/old_reader_decodes_files.py runs the installed runtime's own decoder over the same + page.""" + comms = threads + send_human(comms, "recipient", "with a file", upload("a.png", b"\x89PNG", "image/png")) + send_human(comms, "recipient", "without one") + page = HumanCaller().invoke(ServedCommsConversationPageTool( + conversation=CommandTarget.named("recipient"), project=Checkout(comms.root)), comms) + encoded = json.dumps(FieldCodec.encode(page)) + assert '"files"' not in encoded and "mimeType" not in encoded + decoded = FieldCodec.decode(MessagePage, json.loads(encoded)) + assert [message.body for message in decoded.messages] == ["with a file", "without one"] + + +def test_message_files_are_a_carried_bus_file_the_installer_reconciles(threads: Comms) -> None: + comms = threads + published = send_human(comms, "recipient", "kept", upload("kept.txt", b"kept", "text/plain")) + path = MessageFiles(comms.root).path + assert path in DurableFile.paths_in(comms.root) + assert ReconciledFile.existing_in(comms.root)[path] is MessageFiles + with closing(MessageFiles.writer(path, isolation_level=None)) as db: + with SQLiteFile.write_transaction(db): + MessageFiles.carry_schema(db) + assert not MessageFiles.schema_differs(db) + (file,) = MessageFiles(comms.root).of((published.message.source,)) + assert base64.b64decode(MessageFiles(comms.root).content(file).data) == b"kept" + with closing(sqlite3.connect(path)) as db: + assert db.execute("SELECT count(*) FROM file_content").fetchone() == (1,) diff --git a/tests/test_monitor_delivery.py b/tests/test_monitor_delivery.py index fe6433761e..a9bdc76aef 100644 --- a/tests/test_monitor_delivery.py +++ b/tests/test_monitor_delivery.py @@ -182,7 +182,8 @@ def emitted_delivery(bridge): async def emit(body, target='viewer'): message = bridge.comms.messaging.send('claude-code', target, body).message delivery = replace(bridge.attempt(message, EmittedOutcome), - monitor=ReceivingMonitor(len(bridge.incoming_frame(message).parts))) + monitor=ReceivingMonitor(len(bridge.incoming_frame( + message, await bridge.files_of(message)).parts))) assert await bridge.coordinator_write(lambda _, db: delivery.first_write(db)) return message return emit @@ -599,7 +600,7 @@ async def test_a_larger_message_is_one_notice_and_one_whole_read_confirms_it(bri assert stat.S_IMODE(export.stat().st_mode) == 0o600 text = export.read_text(newline='') lines = text.split('\n')[:-1] - assert lines[0] == ClaudeMonitorFrame(message).header.removesuffix('\n') + assert lines[0] == ClaudeMonitorFrame(message, ()).header.removesuffix('\n') assert '\n'.join(lines[1:]) == body # The notice frees its own reservation and proves nothing about the body. await observe(bridge, notification(line, record_id=transcript_record('notice')).updates( @@ -829,7 +830,7 @@ async def test_an_uncertain_export_stays_and_reopening_never_replays_it(bridge): @pytest.mark.parametrize('sender', ['claude-code', 'a · b " 😀']) def test_frame_parts_rebuild_the_body_and_cut_only_at_line_ends(body, sender): message=Message(sender=sender,target='viewer',type=InfoKind,body=body,timestamp=1.,seq=1) - frame=ClaudeMonitorFrame(message) + frame=ClaudeMonitorFrame(message, ()) shown_rows=tuple(enumerate(frame.export_lines,1)) assert ''.join(part.body for part in frame.read_parts(shown_rows))==body assert all(part.sender==sender for part in frame.read_parts(shown_rows)) @@ -841,7 +842,7 @@ def test_frame_parts_rebuild_the_body_and_cut_only_at_line_ends(body, sender): def test_a_heartbeat_sized_message_is_one_readable_file_not_fragments(): body='\n'.join(f'row {number} '+'word '*40 for number in range(40)) message=Message(sender='user',target='viewer',type=InfoKind,body=body,timestamp=1.,seq=1) - frame=ClaudeMonitorFrame(message) + frame=ClaudeMonitorFrame(message, ()) assert frame.export_lines[1:]==tuple(body.split('\n')) assert sum(line.startswith(frame.HEADER) for line in frame.export_lines)==1 @@ -1158,7 +1159,7 @@ def test_only_the_one_empty_row_after_the_final_lf_is_the_read_terminator(rows, this message, so that read confirms nothing.""" message = Message(sender='peer', target='viewer', type=InfoKind, body='one\ntwo', timestamp=1., seq=1) - frame = ClaudeMonitorFrame(message) + frame = ClaudeMonitorFrame(message, ()) physical = (*frame.export_lines, '', '') read = tuple((number, physical[number - 1]) for number in rows) assert tuple(part.body for part in frame.read_parts(read)) == parts diff --git a/tools/old_reader_decode.py b/tools/old_reader_decode.py new file mode 100644 index 0000000000..b0348f73d6 --- /dev/null +++ b/tools/old_reader_decode.py @@ -0,0 +1,40 @@ +"""The older reader's half of tools/old_reader_decodes_files.py: run by an interpreter whose +installed agent_comms predates message files, it decodes the records on stdin with that +installed codec and prints the file it decoded with, then the bodies it read. + +It imports only declarations an installation before message files already has. +""" + +from __future__ import annotations + +import json +import sys + +import agent_comms +from agent_comms.messaging.history_result import ChannelHistoryPageResult +from agent_comms.messaging.message_page import MessagePage +from agent_comms.nominal.field_codec import FieldCodec +from agent_comms.transport.tools.inbox import InboxPageRead +from agent_comms.transport.tools.sidebar import CommsUserSendTool + + +def main() -> None: + page, history, inbox, request = json.load(sys.stdin) + decoded_page = FieldCodec.decode(MessagePage, page) + decoded_history = FieldCodec.decode(ChannelHistoryPageResult, history) + decoded_inbox = FieldCodec.decode(InboxPageRead, inbox) + print( + json.dumps( + [ + agent_comms.__file__, + [message.body for message in decoded_page.messages], + [message.body for message in decoded_history.messages], + [message.body for message in decoded_inbox.messages], + FieldCodec.decode(CommsUserSendTool, request).body, + ] + ) + ) + + +if __name__ == "__main__": + main() diff --git a/tools/old_reader_decodes_files.py b/tools/old_reader_decodes_files.py new file mode 100644 index 0000000000..847eb098c4 --- /dev/null +++ b/tools/old_reader_decodes_files.py @@ -0,0 +1,119 @@ +"""Prove that a reader installed before message files decodes what this checkout publishes. + +Run with this checkout's source on the path and the older interpreter as the argument: + + PYTHONPATH=src python tools/old_reader_decodes_files.py \ + "$(head -1 ~/.local/bin/toad | cut -c3-)" + +This checkout builds a scratch bus, sends a human DM and an agent channel message that carry +files, and a send with none. It then encodes what an older client reads: the DM's +conversation page, the channel's history page, the recipient's inbox and the file-free send +request. The older interpreter runs tools/old_reader_decode.py, which decodes each one with +its own installed agent_comms (no PYTHONPATH) and prints the bodies it read. The script +exits non-zero unless every decode succeeds, keeps every body, and ran on an agent_comms +outside this checkout. +""" + +from __future__ import annotations + +import base64 +import json +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +from agent_comms.comms import wire +from agent_comms.messaging.bus import Bus +from agent_comms.messaging.channel_targets import CommandTarget +from agent_comms.messaging.message_files import FileUpload +from agent_comms.nominal.field_codec import FieldCodec +from agent_comms.projects.checkouts import Checkout +from agent_comms.projects.storage_rules import StorageRule +from agent_comms.registry.registry_store import RegistryStore +from agent_comms.registry.threads import NativeThread +from agent_comms.transport.tool_caller import HumanCaller, ThreadCaller +from agent_comms.transport.tools.inbox import CommsInboxTool +from agent_comms.transport.tools.send import CommsSendTool +from agent_comms.transport.tools.served import ( + CommsHistoryTool, + ServedCommsConversationPageTool, + ServedCommsUserSendTool, +) +from agent_comms.transport.tools.sidebar import CommsUserSendTool + +EXPECTED = ( + ["a DM with a file", "a DM without one"], + ["a channel message with a file"], + ["a DM with a file", "a DM without one"], + "no files", +) + + +def upload(name: str, content: bytes, mime_type: str) -> FileUpload: + return FileUpload(name, mime_type, base64.b64encode(content).decode("ascii")) + + +def published(root: Path) -> list[object]: + """The page, history, inbox and file-free request an older client reads, encoded.""" + Bus.install(Bus.path_in(root)) + StorageRule(floor_gib=0).prepare_isolated(root) + RegistryStore.at(root).prepare_native_root() + comms = wire(root) + comms.registry.declare(NativeThread("recipient", frozenset({"general"}), Checkout(root))) + human, recipient = HumanCaller(), ThreadCaller("recipient") + image = upload("shot.png", os.urandom(4096), "image/png") + human.invoke( + ServedCommsUserSendTool(target="recipient", body="a DM with a file", files=(image,)), + comms, + ) + human.invoke(ServedCommsUserSendTool(target="recipient", body="a DM without one"), comms) + log = upload("log.txt", b"line\n", "text/plain") + recipient.invoke( + CommsSendTool(target="#general", body="a channel message with a file", files=(log,)), + comms, + ) + page = human.invoke( + ServedCommsConversationPageTool( + conversation=CommandTarget.named("recipient"), project=Checkout(root) + ), + comms, + ) + history = CommsHistoryTool(peer="#general").apply(comms, recipient) + inbox = CommsInboxTool(thread="recipient").apply(comms, recipient) + request = CommsUserSendTool(target="recipient", body="no files") + return [FieldCodec.encode(record) for record in (page, history, inbox, request)] + + +def main(older: str) -> int: + with tempfile.TemporaryDirectory() as scratch: + records = published(Path(scratch) / "bus") + environment = os.environ.copy() + environment.pop("PYTHONPATH", None) + decoded = subprocess.run( + [older, str(Path(__file__).with_name("old_reader_decode.py"))], + input=json.dumps(records), + capture_output=True, + text=True, + env=environment, + check=False, + cwd="/", + ) + sys.stdout.write(decoded.stdout) + sys.stderr.write(decoded.stderr) + if decoded.returncode: + return decoded.returncode + installed, *bodies = json.loads(decoded.stdout) + if tuple(bodies) != EXPECTED: + sys.stderr.write(f"decoded {bodies}, expected {list(EXPECTED)}\n") + return 1 + if Path(installed).is_relative_to(Path(__file__).resolve().parents[1]): + sys.stderr.write("the older interpreter decoded with this checkout, not its own install\n") + return 1 + print("older reader decoded every record") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1]))