From b4beb1aed9bac4fb8e88cd53870f5c781d774eda Mon Sep 17 00:00:00 2001 From: Ben Davis <45952064+bmdavis419@users.noreply.github.com> Date: Mon, 27 Jul 2026 17:46:58 -0700 Subject: [PATCH] =?UTF-8?q?feat(contracts):=20Hermes=20gateway=20protocol?= =?UTF-8?q?=20v4=20=E2=80=94=20media=20frames=20and=20file=20attachments?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit v4 is a lockstep bump (the v2->v3 precedent): media is part of the contract, not a negotiated option, so capabilities require `attachments: true` and a v3 plugin is rejected at the version gate with upgrade instructions. New surface: - `media.deliver` / `media.deliver.ack` — plugin-initiated media shaped like `home.deliver`: idempotent on deliveryId, kind/label provenance, optional turnId (absent = proactive, lands in Home) and caption, base64 payload bounded at 25MB (HERMES_MEDIA_MAX_BYTES) at the schema so an oversized frame fails at decode. Ack only after durable write. - `turn.start`/`turn.steer` gain optional inline-base64 `attachments`. - `ChatFileAttachment` joins the ChatAttachment union: one generic variant, rendering kind derived from mimeType client-side so new renderable types never need a schema change. Persisted rows admit 25MB (what the wire can deliver); the Upload variant keeps the tighter 10MB send bound. - `thread.notification.deliver` (+ its event payload) carries optional attachments/turnId — media deliveries reuse the notification machinery for dedupe, provenance, and lifecycle reset. Co-Authored-By: Claude Fable 5 --- packages/contracts/src/hermesGateway.test.ts | 78 ++++++++++++++--- packages/contracts/src/hermesGateway.ts | 92 +++++++++++++++++++- packages/contracts/src/orchestration.test.ts | 58 ++++++++++++ packages/contracts/src/orchestration.ts | 74 ++++++++++++++-- 4 files changed, 285 insertions(+), 17 deletions(-) diff --git a/packages/contracts/src/hermesGateway.test.ts b/packages/contracts/src/hermesGateway.test.ts index 5d4013304c..3f4f90bd3e 100644 --- a/packages/contracts/src/hermesGateway.test.ts +++ b/packages/contracts/src/hermesGateway.test.ts @@ -80,7 +80,7 @@ describe("Hermes gateway management contracts", () => { activity: true, approvals: true, userInput: true, - attachments: false, + attachments: true, }, }); expect(connected.status).toBe("connected"); @@ -117,7 +117,7 @@ describe("Hermes gateway handshake", () => { activity: true, approvals: true, userInput: true, - attachments: false, + attachments: true, }, authentication: { type: "enrollment-token", @@ -141,7 +141,7 @@ describe("Hermes gateway handshake", () => { activity: true, approvals: true, userInput: true, - attachments: false, + attachments: true, }, model: "gpt-5.6-terra", authentication: { @@ -171,7 +171,7 @@ describe("Hermes gateway handshake", () => { activity: true, approvals: true, userInput: true, - attachments: false, + attachments: true, }, authentication: { type: "instance-credential", @@ -183,10 +183,12 @@ describe("Hermes gateway handshake", () => { expect(hello.model).toBeUndefined(); }); - it("decodes a future-version hello so the broker can reject it explicitly", () => { + it("decodes an other-version hello so the broker can reject it explicitly", () => { + // A v3 plugin (pre-media) must reach the broker's structured + // `version-incompatible` rejection rather than dying in the frame decoder. const hello = decodeHello({ type: "connection.hello", - requestId: "hello-future", + requestId: "hello-other-version", protocolVersion: 3, pluginVersion: "0.3.0", hermesVersion: "2.0.0", @@ -196,7 +198,7 @@ describe("Hermes gateway handshake", () => { activity: true, approvals: true, userInput: true, - attachments: true, + attachments: false, }, authentication: { type: "enrollment-token", @@ -208,7 +210,9 @@ describe("Hermes gateway handshake", () => { expect(hello.capabilities.protocolVersion).toBe(3); }); - it("reserves attachments for a future protocol version", () => { + it("requires attachments as part of the v4 contract itself", () => { + // Not a negotiated option: a v4 plugin that cannot handle attachments is + // a v3 plugin, and belongs at the version gate instead. expect(() => decodeCapabilities({ protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, @@ -216,7 +220,7 @@ describe("Hermes gateway handshake", () => { activity: true, approvals: true, userInput: true, - attachments: true, + attachments: false, }), ).toThrow(); }); @@ -334,7 +338,7 @@ describe("T3 to Hermes messages", () => { activity: true, approvals: true, userInput: true, - attachments: false, + attachments: true, }, authentication: { type: "instance-credential", instanceId: "hermes", credential: "secret" }, }); @@ -411,6 +415,60 @@ describe("Hermes home deliveries", () => { }); }); +describe("Hermes media deliveries", () => { + const media = { + type: "media.deliver", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + deliveryId: "media-1", + threadId: "thread-home-1", + kind: "cron", + label: "Cron: daily-digest", + name: "digest-chart.png", + mimeType: "image/png", + sizeBytes: 4, + data: "AAAA", + createdAt: "2026-07-27T12:00:00.000Z", + } as const; + + it("decodes turnless media, turn-scoped media, and the acknowledgement", () => { + const proactive = decodePluginMessage(media); + expect(proactive.type).toBe("media.deliver"); + if (proactive.type === "media.deliver") { + expect(proactive.turnId).toBeUndefined(); + expect(proactive.kind).toBe("cron"); + } + + const turnScoped = decodePluginMessage({ ...media, turnId: "turn-1", caption: "Today's run" }); + if (turnScoped.type === "media.deliver") { + expect(turnScoped.turnId).toBe("turn-1"); + expect(turnScoped.caption).toBe("Today's run"); + } + + const ack = decodeT3Message({ + type: "media.deliver.ack", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + deliveryId: "media-1", + }); + expect(ack.type).toBe("media.deliver.ack"); + }); + + it("requires a delivery id, since it is the dedupe key for retries", () => { + expect(() => decodePluginMessage({ ...media, deliveryId: "" })).toThrow(); + }); + + it("rejects empty payloads and zero-byte sizes", () => { + expect(() => decodePluginMessage({ ...media, data: "" })).toThrow(); + expect(() => decodePluginMessage({ ...media, sizeBytes: 0 })).toThrow(); + }); + + it("bounds the base64 payload at the frame ceiling", () => { + // One character past the ceiling for a 25MB file must fail at decode, + // before anything buffers or writes. + const overCeiling = "A".repeat(Math.ceil((25 * 1024 * 1024) / 3) * 4 + 8); + expect(() => decodePluginMessage({ ...media, data: overCeiling })).toThrow(); + }); +}); + describe("Hermes to T3 events", () => { const turnContext = { protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, diff --git a/packages/contracts/src/hermesGateway.ts b/packages/contracts/src/hermesGateway.ts index 925e38d1dd..d4888f7a18 100644 --- a/packages/contracts/src/hermesGateway.ts +++ b/packages/contracts/src/hermesGateway.ts @@ -22,7 +22,19 @@ import { ProviderApprovalDecision, ProviderUserInputAnswers } from "./orchestrat import { ProviderInstanceId } from "./providerInstance.ts"; import { CanonicalItemType, CanonicalRequestType, UserInputQuestion } from "./providerRuntime.ts"; -export const HERMES_GATEWAY_PROTOCOL_VERSION = 3 as const; +export const HERMES_GATEWAY_PROTOCOL_VERSION = 4 as const; + +/** + * Base64 payload ceiling for a single media frame, both directions. + * + * 25MB of raw bytes is ~34MB of base64; the schema bound is on the encoded + * string so an oversized frame fails at decode rather than after buffering. + * Deliberately no chunking protocol — a file that does not fit does not + * send, with a clear error. Chunking is the escape hatch if that ceiling + * ever genuinely hurts. + */ +export const HERMES_MEDIA_MAX_BYTES = 25 * 1024 * 1024; +const HERMES_MEDIA_MAX_BASE64_CHARS = Math.ceil(HERMES_MEDIA_MAX_BYTES / 3) * 4 + 4; export const HermesGatewayProtocolVersion = Schema.Literal(HERMES_GATEWAY_PROTOCOL_VERSION); export type HermesGatewayProtocolVersion = typeof HermesGatewayProtocolVersion.Type; @@ -79,7 +91,10 @@ export const HermesGatewayCapabilities = Schema.Struct({ activity: Schema.Boolean, approvals: Schema.Boolean, userInput: Schema.Boolean, - attachments: Schema.Literal(false), + // Literal by design: attachments are part of the v4 contract itself, not a + // negotiated option. A plugin speaking v4 must handle them; one that cannot + // is a v3 plugin and is rejected at the version gate. + attachments: Schema.Literal(true), }); export type HermesGatewayCapabilities = typeof HermesGatewayCapabilities.Type; @@ -362,6 +377,23 @@ const HermesGatewayTurnText = Schema.String.check( Schema.isMaxLength(120_000), ); +/** + * A file riding a turn frame toward the plugin. Inline base64 on the frame + * itself: no side-channel fetch (the plugin may be on another machine with + * no authenticated route back), no chunking. The adapter enforces the + * per-turn total; the schema bounds each file. + */ +export const HermesGatewayTurnAttachment = Schema.Struct({ + name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)), + mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)), + sizeBytes: PositiveInt, + data: Schema.String.check( + Schema.isMinLength(1), + Schema.isMaxLength(HERMES_MEDIA_MAX_BASE64_CHARS), + ), +}); +export type HermesGatewayTurnAttachment = typeof HermesGatewayTurnAttachment.Type; + export const HermesGatewaySessionEnsure = Schema.Struct({ type: Schema.Literal("session.ensure"), protocolVersion: HermesGatewayProtocolVersion, @@ -377,6 +409,7 @@ export const HermesGatewayTurnStart = Schema.Struct({ requestId: HermesGatewayRequestId, ...HermesGatewayTurnContext.fields, text: HermesGatewayTurnText, + attachments: Schema.optional(Schema.Array(HermesGatewayTurnAttachment)), }); export type HermesGatewayTurnStart = typeof HermesGatewayTurnStart.Type; @@ -386,6 +419,7 @@ export const HermesGatewayTurnSteer = Schema.Struct({ requestId: HermesGatewayRequestId, ...HermesGatewayTurnContext.fields, text: HermesGatewayTurnText, + attachments: Schema.optional(Schema.Array(HermesGatewayTurnAttachment)), }); export type HermesGatewayTurnSteer = typeof HermesGatewayTurnSteer.Type; @@ -726,6 +760,58 @@ export const HermesGatewayHomeDeliverAck = Schema.Struct({ }); export type HermesGatewayHomeDeliverAck = typeof HermesGatewayHomeDeliverAck.Type; +/** + * Hermes-initiated media (an image, video, PDF, or arbitrary file) delivered + * as its own message rather than folded into a streaming turn. + * + * Shaped like `home.deliver` on purpose: self-contained, idempotent on + * `deliveryId`, acked only after the bytes are durably written, so the + * plugin's queued copy survives every disconnect between send and ack. + * + * Scope is carried by which ids are present: + * - `turnId` set — media produced during a live turn; lands in that thread + * sequenced next to the turn's text. + * - `turnId` absent — proactive media (a cron job's chart, an artifact from + * an agent-initiated task). `threadId` is advisory the same way it is for + * `home.deliver`: the server re-resolves the instance's home thread and + * refuses to write anywhere else, so a confused plugin cannot spray files + * into arbitrary threads. `kind`/`label` provenance renders the same + * notification header a text delivery gets. + */ +export const HermesGatewayMediaDeliver = Schema.Struct({ + type: Schema.Literal("media.deliver"), + protocolVersion: HermesGatewayProtocolVersion, + deliveryId: HermesGatewayDeliveryId, + threadId: ThreadId, + turnId: Schema.optional(TurnId), + kind: HermesGatewayHomeDeliveryKind, + /** Human source label rendered as the badge — "Cron: daily-digest". */ + label: TrimmedNonEmptyString.check(Schema.isMaxLength(200)), + name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)), + mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)), + sizeBytes: PositiveInt, + /** Optional caption rendered under the media in the same message row. */ + caption: Schema.optional(Schema.String.check(Schema.isMaxLength(2_000))), + data: Schema.String.check( + Schema.isMinLength(1), + Schema.isMaxLength(HERMES_MEDIA_MAX_BASE64_CHARS), + ), + /** When Hermes produced the media, not when it reached T3. */ + createdAt: IsoDateTime, +}); +export type HermesGatewayMediaDeliver = typeof HermesGatewayMediaDeliver.Type; + +/** + * Sent only after the media's bytes and its message row are durably written — + * the same pessimistic-ack contract as `home.deliver.ack`. + */ +export const HermesGatewayMediaDeliverAck = Schema.Struct({ + type: Schema.Literal("media.deliver.ack"), + protocolVersion: HermesGatewayProtocolVersion, + deliveryId: HermesGatewayDeliveryId, +}); +export type HermesGatewayMediaDeliverAck = typeof HermesGatewayMediaDeliverAck.Type; + export const HermesGatewayProtocolErrorCode = Schema.Literals([ "invalid-message", "unsupported-message", @@ -760,6 +846,7 @@ export const HermesGatewayT3ToPluginMessage = Schema.Union([ HermesGatewaySkillBodyRequest, HermesGatewayPing, HermesGatewayHomeDeliverAck, + HermesGatewayMediaDeliverAck, ]); export type HermesGatewayT3ToPluginMessage = typeof HermesGatewayT3ToPluginMessage.Type; @@ -785,6 +872,7 @@ export const HermesGatewayPluginToT3Message = Schema.Union([ HermesGatewayPong, HermesGatewayProtocolError, HermesGatewayHomeDeliver, + HermesGatewayMediaDeliver, ]); export type HermesGatewayPluginToT3Message = typeof HermesGatewayPluginToT3Message.Type; diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index 1ebc23a483..46c53bb3d1 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -461,6 +461,64 @@ it.effect("decodes thread archived and unarchived events", () => }), ); +it.effect("decodes notification deliveries with and without media fields", () => + Effect.gen(function* () { + const base = { + sequence: 3, + eventId: "event-notify-1", + aggregateKind: "thread", + aggregateId: "thread-1", + type: "thread.notification-delivered", + occurredAt: "2026-01-01T00:00:00.000Z", + commandId: "cmd-notify-1", + causationEventId: null, + correlationId: "cmd-notify-1", + metadata: {}, + } as const; + const payloadBase = { + threadId: "thread-1", + messageId: "message-1", + text: "Digest ready.", + notification: { kind: "cron", label: "Cron: daily-digest", deliveryId: "delivery-1" }, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + } as const; + + // Text deliveries persisted before media shipped carry neither field and + // must keep decoding unchanged. + const textOnly = yield* decodeOrchestrationEvent({ ...base, payload: payloadBase }); + if (textOnly.type !== "thread.notification-delivered") { + assert.fail(`Expected thread.notification-delivered, received ${textOnly.type}.`); + } + assert.isUndefined(textOnly.payload.attachments); + assert.isUndefined(textOnly.payload.turnId); + + const media = yield* decodeOrchestrationEvent({ + ...base, + payload: { + ...payloadBase, + attachments: [ + { + type: "file", + id: "thread-1-2c8b3f1e-0000-4000-8000-000000000001", + name: "chart.mp4", + mimeType: "video/mp4", + // The 25MB wire ceiling must be persistable — above the 10MB + // inbound-upload bound on purpose. + sizeBytes: 20 * 1024 * 1024, + }, + ], + turnId: "turn-live", + }, + }); + if (media.type !== "thread.notification-delivered") { + assert.fail(`Expected thread.notification-delivered, received ${media.type}.`); + } + assert.strictEqual(media.payload.attachments?.[0]?.type, "file"); + assert.strictEqual(media.payload.turnId, "turn-live"); + }), +); + it.effect("decodes thread settled and unsettled events", () => Effect.gen(function* () { const settled = yield* decodeOrchestrationEvent({ diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 0c33209194..f085d2d622 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -142,6 +142,16 @@ export type ProviderUserInputAnswers = typeof ProviderUserInputAnswers.Type; export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000; export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8; export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024; +export const PROVIDER_SEND_TURN_MAX_FILE_BYTES = 10 * 1024 * 1024; +/** + * Ceiling for a *persisted* file attachment row, distinct from the 10MB + * send-turn bound above: outbound Hermes media arrives up to 25MB per frame + * (`HERMES_MEDIA_MAX_BYTES`) and lands as one of these rows, so the persisted + * schema must admit what the wire ceiling admits or the event log becomes + * undecodable for a delivery the server already accepted. Inbound uploads + * stay bounded by the tighter limit on the Upload variant. + */ +export const CHAT_ATTACHMENT_MAX_FILE_BYTES = 25 * 1024 * 1024; const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000; const CHAT_ATTACHMENT_ID_MAX_CHARS = 128; // Correlation id is command id by design in this model. @@ -174,9 +184,39 @@ const UploadChatImageAttachment = Schema.Struct({ }); export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type; -export const ChatAttachment = Schema.Union([ChatImageAttachment]); +/** + * Any non-image file riding a message: video, PDF, archive, arbitrary bytes. + * + * One generic variant on purpose — the rendering kind (video player, PDF + * card, download card) is derived from `mimeType` client-side rather than + * encoded here, so a new renderable type never needs a schema change. The + * mime is deliberately unconstrained beyond length: files flow between the + * user and their own agent, and the asset route already serves with + * `nosniff` + extension-derived content types. + */ +export const ChatFileAttachment = Schema.Struct({ + type: Schema.Literal("file"), + id: ChatAttachmentId, + name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)), + mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)), + sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(CHAT_ATTACHMENT_MAX_FILE_BYTES)), +}); +export type ChatFileAttachment = typeof ChatFileAttachment.Type; + +const UploadChatFileAttachment = Schema.Struct({ + type: Schema.Literal("file"), + name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)), + mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100)), + sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_FILE_BYTES)), + dataUrl: TrimmedNonEmptyString.check( + Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS), + ), +}); +export type UploadChatFileAttachment = typeof UploadChatFileAttachment.Type; + +export const ChatAttachment = Schema.Union([ChatImageAttachment, ChatFileAttachment]); export type ChatAttachment = typeof ChatAttachment.Type; -const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]); +const UploadChatAttachment = Schema.Union([UploadChatImageAttachment, UploadChatFileAttachment]); export type UploadChatAttachment = typeof UploadChatAttachment.Type; export const ProjectScriptIcon = Schema.Literals([ @@ -951,6 +991,15 @@ const ThreadNotificationDeliverCommand = Schema.Struct({ kind: Schema.Literals(["cron", "message", "lifecycle", "handoff", "other"]), label: TrimmedNonEmptyString, text: Schema.String, + /** + * Media deliveries reuse this command rather than getting a sibling: they + * need exactly the notification machinery — `deliveryId` dedupe, provenance, + * the lifecycle reset — plus a file on the row. The web renders the + * notification header only when `turnId` is absent, so turn-scoped media + * reads as a plain assistant message inside its turn. + */ + attachments: Schema.optional(Schema.Array(ChatAttachment)), + turnId: Schema.optional(TurnId), /** When the agent produced the content, which may predate its arrival. */ createdAt: IsoDateTime, }); @@ -1257,15 +1306,30 @@ export const ThreadActivityAppendedPayload = Schema.Struct({ * A proactive agent delivery, materialized as an assistant message row. * * It is a real transcript message — selectable, copyable, part of history — - * distinguished only by carrying `notification` provenance. It has no - * `turnId`: nothing about it belongs to a turn, and attributing it to the - * thread's live turn would fold it away behind that turn's "Worked for …". + * distinguished only by carrying `notification` provenance. A proactive + * delivery has no `turnId`: nothing about it belongs to a turn, and + * attributing it to the thread's live turn would fold it away behind that + * turn's "Worked for …". The exception is turn-scoped media (below), which + * genuinely belongs to a live turn and names it. */ export const ThreadNotificationDeliveredPayload = Schema.Struct({ threadId: ThreadId, messageId: MessageId, text: Schema.String, notification: OrchestrationMessageNotification, + /** + * Media riding the delivery. Same shape and same projection column as a + * turn message's attachments — media deliveries reuse this event rather + * than adding a sibling, so the dedupe/provenance/lifecycle behavior above + * applies to them unchanged. + */ + attachments: Schema.optional(Schema.Array(ChatAttachment)), + /** + * Present only on turn-scoped media: it sequences the row next to its + * turn's text, and its presence is what suppresses the notification header + * client-side. Proactive deliveries stay turnless (see the doc above). + */ + turnId: Schema.optional(TurnId), createdAt: IsoDateTime, updatedAt: IsoDateTime, });