diff --git a/.changeset/composer-file-attachments.md b/.changeset/composer-file-attachments.md new file mode 100644 index 0000000000..b301e3fba3 --- /dev/null +++ b/.changeset/composer-file-attachments.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- +Store any file attached in the composer as a real, read-only original the agent can open (#3153). `POST /api/drafts/:draftId/files` streams one file into `.brain-ui/attachments//`, detects its kind from the bytes and reserves room in a configurable host attachment pool (`BRAIN_UI_ATTACHMENT_POOL_BYTES`, default 1 GiB). It creates no inbox work. Drafts bind originals with `fileIds` and keep a held send's files in an `outgoing` snapshot, and both survive a restart. `chat_message.attachmentRefs` sends them: the host verifies each against its records and its bytes on disk, and gives the agent its read-only path in a `` block without reading the contents. Accepting the message transfers the originals to the conversation. `GET /api/attachments/:fileId` reads one back after a digest check. Unbound uploads are removed after an hour and formerly referenced ones seven days after their last reference went, with race-safe cleanup. `server_hello` advertises `capabilities.composerFiles` and `attachmentLimits`; `SessionDraftLimits` gains the per-draft file envelope (10 files, 25 MB each, 50 MB together), and `maxDraftBytes` now bounds text and legacy images only. Governed workers see the originals read-only, and reading them taints the session as `chat_attachment`. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 7d81e76cca..9eb236200b 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -8,6 +8,13 @@ export "." (./src/index.ts) ALLOWED_IMAGE_MEDIA_TYPES ASK_ANSWER_UPDATE_REQUIRED ASK_RECEIPTS_CAPABILITY + ATTACHMENT_DIR + ATTACHMENT_GRACE_MS + ATTACHMENT_MAX_FILES + ATTACHMENT_MAX_FILE_BYTES + ATTACHMENT_MAX_TOTAL_BYTES + ATTACHMENT_POOL_DEFAULT_BYTES + ATTACHMENT_UNBOUND_TTL_MS type ActionDigestEntry type ActionDigestState type ActionDigestSummary @@ -67,14 +74,22 @@ export "." (./src/index.ts) type AsrEvent type AsrFinal type AsrPartial + type AttachmentErrorCode + type AttachmentErrorResponse + type AttachmentFile + type AttachmentKind + type AttachmentLimits + type AttachmentReader type BillingMode type BrainSearchResult type BrainStats type BudgetObservation type BudgetScope CHAT_DELETION_CAPABILITY + COMPOSER_FILES_CAPABILITY CONVERSATION_CAPABILITY_KEYS CONVERSATION_LIMITS + type ChatAttachmentReference type ChatDeletionNotAdmitted type ChatDeletionOutcome type ChatDeletionReceipt @@ -156,6 +171,7 @@ export "." (./src/index.ts) type DraftErrorCode type DraftErrorResponse type DraftListResponse + type DraftOutgoing type DraftRef type DraftSaveRequest type DraftSaveResponse @@ -473,6 +489,13 @@ export "./client" (./src/client/index.ts) ASK_USER_RANK_PAYLOAD_SCHEMA ASK_USER_RANK_TOOL_NAME ASK_USER_TOOL_NAME + ATTACHMENT_DIR + ATTACHMENT_GRACE_MS + ATTACHMENT_MAX_FILES + ATTACHMENT_MAX_FILE_BYTES + ATTACHMENT_MAX_TOTAL_BYTES + ATTACHMENT_POOL_DEFAULT_BYTES + ATTACHMENT_UNBOUND_TTL_MS type ActionDigestEntry type ActionDigestState type ActionDigestSummary @@ -548,6 +571,12 @@ export "./client" (./src/client/index.ts) type AsrEvent type AsrFinal type AsrPartial + type AttachmentErrorCode + type AttachmentErrorResponse + type AttachmentFile + type AttachmentKind + type AttachmentLimits + type AttachmentReader BLOCK_SCHEMA BRIDGE_MCP_PREFIX BRIDGE_TOOL_CONTRACTS @@ -564,6 +593,7 @@ export "./client" (./src/client/index.ts) CHAT_DELETION_CAPABILITY COMPLETE_SHARE_CONTRACT COMPLETE_SHARE_INPUT_SCHEMA + COMPOSER_FILES_CAPABILITY COMPUTE_CANCEL_CONTRACT COMPUTE_CANCEL_TOOL_NAME COMPUTE_COLLECT_CONTRACT @@ -583,6 +613,7 @@ export "./client" (./src/client/index.ts) COMPUTE_TOOL_CONTRACTS CONVERSATION_CAPABILITY_KEYS CONVERSATION_LIMITS + type ChatAttachmentReference type ChatDeletionNotAdmitted type ChatDeletionOutcome type ChatDeletionReceipt @@ -677,6 +708,7 @@ export "./client" (./src/client/index.ts) type DraftErrorCode type DraftErrorResponse type DraftListResponse + type DraftOutgoing type DraftRef type DraftSaveRequest type DraftSaveResponse @@ -1394,6 +1426,13 @@ export "./protocol" (./src/protocol.ts) ALLOWED_IMAGE_MEDIA_TYPES ASK_ANSWER_UPDATE_REQUIRED ASK_RECEIPTS_CAPABILITY + ATTACHMENT_DIR + ATTACHMENT_GRACE_MS + ATTACHMENT_MAX_FILES + ATTACHMENT_MAX_FILE_BYTES + ATTACHMENT_MAX_TOTAL_BYTES + ATTACHMENT_POOL_DEFAULT_BYTES + ATTACHMENT_UNBOUND_TTL_MS type ActionDigestEntry type ActionDigestState type ActionDigestSummary @@ -1453,14 +1492,22 @@ export "./protocol" (./src/protocol.ts) type AsrEvent type AsrFinal type AsrPartial + type AttachmentErrorCode + type AttachmentErrorResponse + type AttachmentFile + type AttachmentKind + type AttachmentLimits + type AttachmentReader type BillingMode type BrainSearchResult type BrainStats type BudgetObservation type BudgetScope CHAT_DELETION_CAPABILITY + COMPOSER_FILES_CAPABILITY CONVERSATION_CAPABILITY_KEYS CONVERSATION_LIMITS + type ChatAttachmentReference type ChatDeletionNotAdmitted type ChatDeletionOutcome type ChatDeletionReceipt @@ -1540,6 +1587,7 @@ export "./protocol" (./src/protocol.ts) type DraftErrorCode type DraftErrorResponse type DraftListResponse + type DraftOutgoing type DraftRef type DraftSaveRequest type DraftSaveResponse @@ -1839,6 +1887,8 @@ export "./schemas" (./src/schemas.ts) MAX_PROMPT_CHARS MAX_SERVER_FRAME_BYTES type ParseFrameResult + attachmentFileSchema + attachmentLimitsSchema classifySessionRecoveryResponse clientActivitySubscribeSchema clientActivityUnsubscribeSchema @@ -2021,6 +2071,13 @@ export "./server" (./src/server/index.ts) ASK_USER_RANK_PAYLOAD_SCHEMA ASK_USER_RANK_TOOL_NAME ASK_USER_TOOL_NAME + ATTACHMENT_DIR + ATTACHMENT_GRACE_MS + ATTACHMENT_MAX_FILES + ATTACHMENT_MAX_FILE_BYTES + ATTACHMENT_MAX_TOTAL_BYTES + ATTACHMENT_POOL_DEFAULT_BYTES + ATTACHMENT_UNBOUND_TTL_MS type ActionDigestEntry type ActionDigestState type ActionDigestSummary @@ -2099,6 +2156,12 @@ export "./server" (./src/server/index.ts) type AsrEvent type AsrFinal type AsrPartial + type AttachmentErrorCode + type AttachmentErrorResponse + type AttachmentFile + type AttachmentKind + type AttachmentLimits + type AttachmentReader type AutonomousTurnOptions type BBox BLOCK_SCHEMA @@ -2154,6 +2217,7 @@ export "./server" (./src/server/index.ts) CHAT_DELETION_CAPABILITY COMPLETE_SHARE_CONTRACT COMPLETE_SHARE_INPUT_SCHEMA + COMPOSER_FILES_CAPABILITY COMPUTE_CANCEL_CONTRACT COMPUTE_CANCEL_TOOL_NAME COMPUTE_COLLECT_CONTRACT @@ -2173,6 +2237,7 @@ export "./server" (./src/server/index.ts) COMPUTE_TOOL_CONTRACTS CONVERSATION_CAPABILITY_KEYS CONVERSATION_LIMITS + type ChatAttachmentReference type ChatDeletionNotAdmitted type ChatDeletionOutcome type ChatDeletionReceipt @@ -2276,6 +2341,7 @@ export "./server" (./src/server/index.ts) type DraftErrorCode type DraftErrorResponse type DraftListResponse + type DraftOutgoing type DraftRef type DraftSaveRequest type DraftSaveResponse @@ -3441,6 +3507,20 @@ signatures (every public export and the types it is made of) const ASK_USER_RANK_TOOL_NAME: "ask_user_rank"; ASK_USER_TOOL_NAME (packages/ui-sdk/src/tool-contracts/bridge.ts) const ASK_USER_TOOL_NAME: "ask_user"; + ATTACHMENT_DIR (packages/ui-sdk/src/protocol.ts) + const ATTACHMENT_DIR: ".brain-ui/attachments"; + ATTACHMENT_GRACE_MS (packages/ui-sdk/src/protocol.ts) + const ATTACHMENT_GRACE_MS: number; + ATTACHMENT_MAX_FILES (packages/ui-sdk/src/protocol.ts) + const ATTACHMENT_MAX_FILES: 10; + ATTACHMENT_MAX_FILE_BYTES (packages/ui-sdk/src/protocol.ts) + const ATTACHMENT_MAX_FILE_BYTES: 25000000; + ATTACHMENT_MAX_TOTAL_BYTES (packages/ui-sdk/src/protocol.ts) + const ATTACHMENT_MAX_TOTAL_BYTES: 50000000; + ATTACHMENT_POOL_DEFAULT_BYTES (packages/ui-sdk/src/protocol.ts) + const ATTACHMENT_POOL_DEFAULT_BYTES: 1073741824; + ATTACHMENT_UNBOUND_TTL_MS (packages/ui-sdk/src/protocol.ts) + const ATTACHMENT_UNBOUND_TTL_MS: number; ActionDigestEntry (packages/ui-sdk/src/protocol.ts) export interface ActionDigestEntry { itemId: string; @@ -4130,6 +4210,54 @@ signatures (every public export and the types it is made of) type: "partial"; text: string; } + AttachmentErrorCode (packages/ui-sdk/src/protocol.ts) + export type AttachmentErrorCode = "ATTACHMENT_TOO_LARGE" | "ATTACHMENT_CAPACITY" | "ATTACHMENT_INVALID" | "ATTACHMENT_KEY_REUSED" | "ATTACHMENT_NOT_FOUND"; + AttachmentErrorResponse (packages/ui-sdk/src/protocol.ts) + export type AttachmentErrorResponse = { + error: "ATTACHMENT_TOO_LARGE"; + message: string; + limit: number; + bound: "file" | "draftFiles" | "draftCount"; + } | { + error: "ATTACHMENT_CAPACITY"; + message: string; + limit: number; + bound: "pool" | "drafts"; + } | { + error: "ATTACHMENT_INVALID"; + message: string; + } | { + error: "ATTACHMENT_KEY_REUSED"; + message: string; + } | { + error: "ATTACHMENT_NOT_FOUND"; + message: string; + }; + AttachmentFile (packages/ui-sdk/src/protocol.ts) + export interface AttachmentFile { + fileId: string; + name: string; + incomingName?: string; + path: string; + mediaType: string; + bytes: number; + sha256: string; + kind: AttachmentKind; + reader: AttachmentReader; + trackRejected?: true; + track?: SharedFileMeta; + } + AttachmentKind (packages/ui-sdk/src/protocol.ts) + export type AttachmentKind = "pdf" | "text" | "track" | "image" | "archive" | "binary"; + AttachmentLimits (packages/ui-sdk/src/protocol.ts) + export interface AttachmentLimits { + maxFiles: number; + maxFileBytes: number; + maxTotalBytes: number; + poolBytes: number; + } + AttachmentReader (packages/ui-sdk/src/protocol.ts) + export type AttachmentReader = "pdf" | "text" | "track" | "image" | "none"; AutonomousTurnOptions (packages/ui-sdk/src/server/backend.ts) export interface AutonomousTurnOptions { origin: "autonomous"; @@ -6032,6 +6160,8 @@ signatures (every public export and the types it is made of) }, z.core.$strict>], "disposition">>; receiptIds: z.ZodArray; }, z.core.$strict>; + COMPOSER_FILES_CAPABILITY (packages/ui-sdk/src/protocol.ts) + const COMPOSER_FILES_CAPABILITY: "composerFiles"; COMPUTE_CANCEL_CONTRACT (packages/ui-sdk/src/tool-contracts/compute.ts) const COMPUTE_CANCEL_CONTRACT: import("./contract.js").ToolContract<"brain_compute_cancel", z.ZodObject<{ job: z.ZodString; @@ -6186,6 +6316,11 @@ signatures (every public export and the types it is made of) has(cacheName: string): Promise; open(cacheName: string): Promise; } + ChatAttachmentReference (packages/ui-sdk/src/protocol.ts) + export interface ChatAttachmentReference { + kind: "attachment"; + fileId: string; + } ChatDeletionNotAdmitted (packages/ui-sdk/src/protocol.ts) export interface ChatDeletionNotAdmitted { error: "CHAT_DELETION_NOT_ADMITTED"; @@ -6230,6 +6365,7 @@ signatures (every public export and the types it is made of) export interface ChatImageAttachment { data: string; mediaType: (typeof ALLOWED_IMAGE_MEDIA_TYPES)[number]; + fileId?: string; } ChatSession (packages/ui-sdk/src/protocol.ts) export interface ChatSession { @@ -6322,6 +6458,7 @@ signatures (every public export and the types it is made of) providerId?: string; attachments?: ChatImageAttachment[]; files?: ChatFileAttachment[]; + attachmentRefs?: ChatAttachmentReference[]; thinkingLevel?: ThinkingLevel; requestId?: string; draftId?: string; @@ -6963,6 +7100,8 @@ signatures (every public export and the types it is made of) updatedAt: number; text: string; attachments: DraftAttachment[]; + files?: AttachmentFile[]; + outgoing?: DraftOutgoing | null; } DraftAttachment (packages/ui-sdk/src/protocol.ts) export interface DraftAttachment { @@ -6999,7 +7138,7 @@ signatures (every public export and the types it is made of) error: "DRAFT_TOO_LARGE"; message: string; limit: number; - bound: "text" | "draft" | "image" | "images" | "imageCount"; + bound: "text" | "draft" | "image" | "images" | "imageCount" | "draftFiles" | "draftCount"; } | { error: "DRAFT_CAPACITY"; message: string; @@ -7028,6 +7167,13 @@ signatures (every public export and the types it is made of) export interface DraftListResponse { drafts: DraftSummary[]; } + DraftOutgoing (packages/ui-sdk/src/protocol.ts) + export interface DraftOutgoing { + requestId: string; + text: string; + fileIds: string[]; + state: "held" | "dispatched"; + } DraftRef (packages/ui-sdk/src/protocol.ts) export interface DraftRef { draftId: string; @@ -7038,6 +7184,8 @@ signatures (every public export and the types it is made of) sessionId: string | null; text: string; attachmentIds: string[]; + fileIds?: string[]; + outgoing?: DraftOutgoing | null; } DraftSaveResponse (packages/ui-sdk/src/protocol.ts) export interface DraftSaveResponse { @@ -7052,6 +7200,7 @@ signatures (every public export and the types it is made of) updatedAt: number; preview: string; attachmentCount: number; + fileCount?: number; } ENV_VARS (packages/ui-sdk/src/config/env-vars.ts) const ENV_VARS: readonly [{ @@ -10485,6 +10634,7 @@ signatures (every public export and the types it is made of) principalKey?: string; capabilities?: Record; sessionDraftLimits?: SessionDraftLimits; + attachmentLimits?: AttachmentLimits; } ServerLocalExchangeResult (packages/ui-sdk/src/protocol.ts) export interface ServerLocalExchangeResult extends SessionScoped { @@ -10698,10 +10848,14 @@ signatures (every public export and the types it is made of) maxDraftBytes: number; maxDrafts: number; maxTotalBytes: number; + maxDraftFiles?: number; + maxDraftFileBytes?: number; + maxDraftFilesBytes?: number; } SessionHistoryMessage (packages/ui-sdk/src/protocol.ts) export interface SessionHistoryMessage { files?: SharedFileMeta[]; + attachmentFiles?: AttachmentFile[]; role: "user" | "assistant"; content: string; thinking?: string; @@ -12046,6 +12200,15 @@ signatures (every public export and the types it is made of) export function assertTurnPosture(req: Pick & Partial>, supportsAutonomous?: boolean, supportsRestricted?: boolean): void; assertVersionRequirements (packages/ui-sdk/src/server/version-requirements.ts) export function assertVersionRequirements(check: VersionRequirementCheck): void; + attachmentFileSchema (packages/ui-sdk/src/track-schemas.ts) + const attachmentFileSchema: z.ZodType; + attachmentLimitsSchema (packages/ui-sdk/src/schemas.ts) + const attachmentLimitsSchema: z.ZodObject<{ + maxFileBytes: z.ZodNumber; + maxFiles: z.ZodNumber; + maxTotalBytes: z.ZodNumber; + poolBytes: z.ZodNumber; + }, z.core.$loose>; bashLockKey (packages/ui-sdk/src/server/lock-keys.ts) export function bashLockKey(command: string): string | null; brainApplicationInput (packages/ui-sdk/src/server/brain-application.ts) @@ -12215,8 +12378,13 @@ signatures (every public export and the types it is made of) }, z.core.$loose>; clientChatMessageSchema (packages/ui-sdk/src/schemas.ts) const clientChatMessageSchema: z.ZodObject<{ + attachmentRefs: z.ZodOptional; + }, z.core.$strip>>>; attachments: z.ZodOptional; mediaType: z.ZodEnum<{ "image/gif": "image/gif"; "image/jpeg": "image/jpeg"; @@ -12554,8 +12722,13 @@ signatures (every public export and the types it is made of) protocolRev: z.ZodNumber; type: z.ZodLiteral<"client_hello">; }, z.core.$loose>, z.ZodObject<{ + attachmentRefs: z.ZodOptional; + }, z.core.$strip>>>; attachments: z.ZodOptional; mediaType: z.ZodEnum<{ "image/gif": "image/gif"; "image/jpeg": "image/jpeg"; @@ -13258,6 +13431,7 @@ signatures (every public export and the types it is made of) drafts: z.ZodArray; preview: z.ZodString; revision: z.ZodNumber; sessionId: z.ZodNullable; @@ -13288,6 +13462,16 @@ signatures (every public export and the types it is made of) name: z.ZodNullable; }, z.core.$loose>>; draftId: z.ZodString; + files: z.ZodOptional>>>; + outgoing: z.ZodOptional; + requestId: z.ZodString; + state: z.ZodEnum<{ + dispatched: "dispatched"; + held: "held"; + }>; + text: z.ZodString; + }, z.core.$loose>>>; revision: z.ZodNumber; sessionId: z.ZodNullable; text: z.ZodString; @@ -13297,6 +13481,7 @@ signatures (every public export and the types it is made of) const draftSummarySchema: z.ZodObject<{ attachmentCount: z.ZodNumber; draftId: z.ZodString; + fileCount: z.ZodOptional; preview: z.ZodString; revision: z.ZodNumber; sessionId: z.ZodNullable; @@ -17729,6 +17914,12 @@ signatures (every public export and the types it is made of) }, z.core.$loose>; serverHelloSchema (packages/ui-sdk/src/schemas.ts) const serverHelloSchema: z.ZodObject<{ + attachmentLimits: z.ZodCatch>>; capabilities: z.ZodOptional>; conversationProfile: z.ZodCatch; + maxDraftFiles: z.ZodOptional; + maxDraftFilesBytes: z.ZodOptional; maxDrafts: z.ZodNumber; maxTextBytes: z.ZodNumber; maxTotalBytes: z.ZodNumber; @@ -18400,6 +18594,12 @@ signatures (every public export and the types it is made of) turnId: z.ZodOptional; type: z.ZodLiteral<"retry_receipt">; }, z.core.$loose>, z.ZodObject<{ + attachmentLimits: z.ZodCatch>>; capabilities: z.ZodOptional>; conversationProfile: z.ZodCatch; + maxDraftFiles: z.ZodOptional; + maxDraftFilesBytes: z.ZodOptional; maxDrafts: z.ZodNumber; maxTextBytes: z.ZodNumber; maxTotalBytes: z.ZodNumber; @@ -18672,6 +18875,7 @@ signatures (every public export and the types it is made of) append: z.ZodOptional; messages: z.ZodArray; + attachmentFiles: z.ZodCatch>>>>; blocks: z.ZodOptional; messages: z.ZodArray; + attachmentFiles: z.ZodCatch>>>>; blocks: z.ZodOptional; + maxDraftFiles: z.ZodOptional; + maxDraftFilesBytes: z.ZodOptional; maxDrafts: z.ZodNumber; maxTextBytes: z.ZodNumber; maxTotalBytes: z.ZodNumber; diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 4ab50a379b..8976890d17 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -1033,6 +1033,7 @@ signatures (every public export and the types it is made of) detail: z.ZodNullable; source: z.ZodEnum<{ apify_result: "apify_result"; + chat_attachment: "chat_attachment"; compute_output: "compute_output"; egress_connection: "egress_connection"; fetching_command: "fetching_command"; @@ -1365,6 +1366,10 @@ signatures (every public export and the types it is made of) export interface MaintenanceTempDomain { statePath: string; } + MessageAttachment (packages/ui-server/src/attachments/context.ts) + export type MessageAttachment = AttachmentFile & { + inline?: boolean; + }; MetricPoint (packages/ui-server/src/observability/types.ts) export interface MetricPoint { name: string; @@ -1837,6 +1842,7 @@ signatures (every public export and the types it is made of) sourceCommit: string; allowedOrigins: string[]; maxConcurrentSessions: number; + attachmentPoolBytes: number; turnTimeoutMs: number | null; logLevel: Severity; wsRate: { @@ -1916,6 +1922,7 @@ signatures (every public export and the types it is made of) thinkingLevel?: ThinkingLevel; turnId: string; files?: import("@schlessera/brain-ui-sdk/protocol").SharedFileMeta[]; + attachmentFiles?: import("../attachments/context.js").MessageAttachment[]; }): void; recordEffectiveThinkingLevel?(sessionId: string, turnId: string, level: ThinkingLevel): void; attachMessageSources?(sessionId: string, messages: SessionHistoryMessage[], strict?: boolean): SessionHistoryMessage[]; diff --git a/docs/decisions/chat-attachments.md b/docs/decisions/chat-attachments.md index bc89a7baff..c9884e6309 100644 --- a/docs/decisions/chat-attachments.md +++ b/docs/decisions/chat-attachments.md @@ -1,12 +1,12 @@ # Generic chat attachments -**Decided by the maintainer on 2026-10-29 and 2026-11-02**, before runtime -implementation. The rulings are linked in each section below. This record -holds approved policy only. Nothing in it is implemented yet. The -[source-backed design](../plans/chat-attachments.md) turns the rulings into -routes, schemas, bounds and proof briefs. Its numbered recommendations are not -rulings until they are confirmed at review. Open work is epic #3150 in the -tracker. +**Decided by the maintainer on 2026-10-29 and 2026-11-02.** The rulings are +linked in each section below. The +[source-backed design](../plans/chat-attachments.md) turns them into routes, +schemas, bounds and proof briefs; its six §13 recommendations were approved +at review on 2026-11-02. Admission, storage, ownership and cleanup are built +([what #3153 built](#what-3153-built)); content reading and the composer are +open work in epic #3150. ## Sources and one pipeline @@ -104,6 +104,51 @@ and [desktop menu A](https://github.com/schlessera/brain-kit/issues/3155#issueco and reduced motion gets static glyphs. #3281 owns the shared component ([ruling](https://github.com/schlessera/brain-kit/issues/3155#issuecomment-6575242784)). +## What #3153 built + +The server side of admission, storage, ownership and cleanup, as the design's +§4 and §6 describe, with these concrete choices: + +- **Records and transactions.** The `attachment_files`, `attachment_refs`, + `attachment_reservations` and `attachment_receipts` tables sit in the + operational database beside the drafts, and every mutation runs on the + draft store's write channel. A save, an acceptance and a sweep mark + therefore see one serialized state. Reference owners are `draft` and + `outgoing` (both keyed by the draft id; a draft has at most one outgoing + snapshot) and `message` (keyed by the session id). The design's compound + owner ids were simplified this way because a draft id may itself contain + `:`, and one reference per session protects a file as well as one per turn. +- **References on the wire.** A message names its originals in a new optional + `chat_message.attachmentRefs` field, not as a new variant of the existing + `files` union the design sketched. Adding a variant would retype + `ChatFileAttachment[]` for TypeScript readers, which the contract counts as + breaking. The separate field is additive and carries the same reference. +- **What the provider sees.** The `` block says the + contents have not been read and that the agent may open an original at its + path. It does not name `read_attachment`, because that tool belongs to + #3154 and is not registered yet. Once it is, new messages may name it; + recorded messages keep the text they were sent with. +- **Accounting.** The pool charges recorded originals in every state, + reservations and legacy draft image BLOBs. A save charges the draft + sub-limit only for originals no live draft or snapshot already references. + A reservation is the declared `Content-Length`, or 25,000,000 bytes without + one, and the commit replaces it with the real size in the same transaction + that re-checks the pool. +- **Cleanup safety.** The sweep's mark re-selects by clock and requires no + reference; a reference insert requires `stored` in its own transaction. + Rebinding also clears the clock, so two independent guards keep a rebound + file. The mutation proof in the PR breaks each. +- **Governed read-only mount.** `.brain-ui/attachments/` is mounted read-only + for governed workers through the same resolver that mounts protected paths, + but it is not a protected path: no policy names it, the turn manifest does + not list it, and nothing is quarantined when the host writes it during a + turn. The ordinary profile relies on the digest check alone. +- **Session deletion.** The store's `releaseSession` removes a chat's + `message` references and starts their seven-day clocks. Calling it from chat + deletion belongs to #3231's flow. +- **Kept as before.** `/share`, `/track-upload`, staged-track references, + inline images and D52's tab-only legacy track path behave as they did. + ## Rejected alternatives The rejected options were offered in the rulings above: diff --git a/docs/decisions/design-kit/sessions-and-drafts.md b/docs/decisions/design-kit/sessions-and-drafts.md index f26f15f42c..657aa9f405 100644 --- a/docs/decisions/design-kit/sessions-and-drafts.md +++ b/docs/decisions/design-kit/sessions-and-drafts.md @@ -668,7 +668,7 @@ question-answer rules are independent. > **2026-11-02 — Generic attachment originals, maintainer amendment (#3150).** -> Approved, not yet implemented. For the new generic composer path, staged +> Approved; the host side is implemented by #3153. For the new generic composer path, staged > files stop being tab-only. Every attachment, images included, is a > filesystem original owned by the exact acknowledged draft revision, then by > the conversation that accepted the send. A saved draft and its file bindings @@ -683,7 +683,14 @@ question-answer rules are independent. > this record is unchanged. The rulings are in > [chat-attachments.md](../chat-attachments.md), and the proposed schema and > lifecycle in [the design](../../plans/chat-attachments.md#6-admission-storage-and-ownership-3153). -> The implementation records what it built here. +> #3153 built it this way: a save's `fileIds` bind originals to that exact +> revision and its `outgoing` snapshot owns a held or unconfirmed send's +> files, both in the host's operational database, so they survive a reload, +> a closed tab and a restart. `Draft.files` lists only bound files that are +> still stored, so nothing restores as saved that the host does not hold. An +> accepted send gives the conversation its own reference before the revision +> is consumed; newer revisions and other drafts are untouched. Nothing is +> resent automatically. The composer that uses this is #3155's. > **2026-10-07 — Drafts kept on this device across a reload, implemented by > #1014.** Every draft in the root's store, with its images, and the work diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 1ca8f34ba3..1ff08001aa 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -680,7 +680,11 @@ makes in the brain. - **`CLAUDE.md`, `AGENTS.md`, `.claude/skills/`, `.agents/`.** Changing them as you go is exactly the flexibility ruling 1 restores. The journal records those changes and can revert them. -- **`.brain-ui/`.** Agents file staged shares from it. +- **`.brain-ui/`.** Agents file staged shares from it. One subtree is + mounted read-only in the governed profile without becoming a protected + path: `.brain-ui/attachments/`, where the host keeps chat attachment + originals (#3153). No policy names it, and the host keeps writing it during + a turn without a quarantine. ### How the mounts enforce it @@ -2503,9 +2507,9 @@ coordinator. The server checks the handle's mount ID against the worker's own mount table: it must be the top mount at the brain path. It then runs the unchanged comparison of brain, pins, empty masks and the private index relative to the handle (`function requireWorkerBrainMount`, -`packages/ui-sdk/src/server/worker-protection.ts:370-379`; +`packages/ui-sdk/src/server/worker-protection.ts:379-388`; `export function verifyWorkerFolderMounts`, -`packages/ui-sdk/src/server/worker-protection.ts:382-423`). +`packages/ui-sdk/src/server/worker-protection.ts:391-432`). The server returns the handle before release, and the coordinator refuses to release the start gate, or open a second view, while one is held (`if operation == 'release':`, @@ -3092,7 +3096,7 @@ that runs in it can rewrite that account. The load set is therefore not computed. It is enforced by what the worker can see: the brain path is an empty tmpfs with only the policy's protected paths bound back read-only (`WorkerProviderMasks.visible`; `if (masks.visible)`, -`packages/ui-sdk/src/server/worker-protection.ts:207-227`). An import, a +`packages/ui-sdk/src/server/worker-protection.ts:216-236`). An import, a local module, a `tsconfig.json` alias or a data file outside them is simply absent, so the configuration loads only from what no governed turn can change, or does not load, and its own error, which names the file, becomes diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index 012b31ecfe..747efb4331 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -58,6 +58,7 @@ row's real mounting check. They do not establish mounting by themselves. | `GET /api/activity/runs` | `mounted supported handler: GET /api/activity/runs` | R | | `GET /api/activity/runs/:runId` | `mounted supported handler: GET /api/activity/runs/:runId` | R | | `GET /api/activity/stats` | `mounted supported handler: GET /api/activity/stats` | R | +| `GET /api/attachments/:fileId` | `mounted supported handler: GET /api/attachments/:fileId` | X | | `POST /api/auth/login` | `mounted supported handler: POST /api/auth/login` | A, P, Z | | `POST /api/auth/logout` | `mounted supported handler: POST /api/auth/logout` | A, P | | `GET /api/auth/methods` | `mounted supported handler: GET /api/auth/methods` | P | @@ -90,6 +91,7 @@ row's real mounting check. They do not establish mounting by themselves. | `DELETE /api/drafts/:draftId` | `mounted supported handler: DELETE /api/drafts/:draftId` | X | | `POST /api/drafts/:draftId/attachments` | `mounted supported handler: POST /api/drafts/:draftId/attachments` | X | | `POST /api/drafts/:draftId/bind` | `mounted supported handler: POST /api/drafts/:draftId/bind` | X | +| `POST /api/drafts/:draftId/files` | `mounted supported handler: POST /api/drafts/:draftId/files` | X | | `GET /api/files/content` | `mounted supported handler: GET /api/files/content` | F, V | | `GET /api/geo/coastline` | `mounted supported handler: GET /api/geo/coastline` | G, V | | `GET /api/governance/events` | `mounted supported handler: GET /api/governance/events` | GV | diff --git a/docs/http-api.md b/docs/http-api.md index 8d13a5b322..02a4a81196 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, session-recovery interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark and chat-deletion routes mounted by `createApp`: 169 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark and chat-deletion routes mounted by `createApp`: 171 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -87,6 +87,8 @@ client code has a gap. Source owners are listed after the table. | DELETE | `/api/drafts/:draftId` | S | Delete a draft, leaving a tombstone | Paired composer and independent clients (#979, D52); preserve revisions, receipts, tombstones, limits and the no-execution boundary. | | POST | `/api/drafts/:draftId/attachments` | S | Store one draft image | Paired composer and independent clients (#979, D52); preserve revisions, receipts, tombstones, limits and the no-execution boundary. | | POST | `/api/drafts/:draftId/bind` | S | Bind a draft to the session its accepted first message started | Paired composer and independent clients (#979, D52); preserve revisions, receipts, tombstones, limits and the no-execution boundary. | +| POST | `/api/drafts/:draftId/files` | S | Store one composer file as a durable, read-only original | Composer file attachments (#3153); preserve streaming admission, idempotency receipts, draft and pool bounds and the no-execution boundary. | +| GET | `/api/attachments/:fileId` | S | Read back one referenced composer original after checking its digest | Composer file attachments (#3153); preserve reference-only authorization, digest checking and the download headers. | | GET | `/api/files/content` | S | Read content metadata/text or raw bytes | Independent content clients and SDK service-worker policy; raw API media remains network-only. | | GET | `/api/files/html` | I | Serve an HTML file for the sandboxed, script-running preview | React file viewer iframe and "Open in new tab" link (#1084); browser-rendered UI transport. Its isolation headers are specified below. | | GET | `/api/files/resolve` | I | Resolve ancestor navigation and existence | React file browser; view/navigation helpers are paired UI transport. | @@ -202,7 +204,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 169 declared endpoints are mounted regardless of backend, renderer or +All 171 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. @@ -1018,6 +1020,87 @@ each with `limit` and `bound`; 428 `DRAFT_PRECONDITION_REQUIRED` when `Content-Length` says. A refused or failed request leaves the committed draft unchanged. + + +## Composer file attachments (additive, 0.45.0, #3153) + +Advertised by `server_hello.capabilities.composerFiles`; the frame rules are +in the [integration contract](integration-contract/wire.md#composer-file-attachments-additive-0450-3153). +Both routes sit behind the same authentication and same-origin rules as the +draft routes, and answer `Cache-Control: no-store`. The upload creates no +inbox item, queue job or triage. `/share` and `/track-upload` are unchanged. + +### `POST /api/drafts/:draftId/files` + +The raw bytes of one file, streamed; nothing is buffered whole. Headers: +`Idempotency-Key` (required, 1-128 of `A-Za-z0-9._:-`), `Content-Type` (a +hint), `X-File-Name` (a hint, percent-encoded UTF-8, at most 1,024 bytes +encoded) and `Content-Length` (optional, used for early refusal and as the +pool reservation; without it the reservation is 25,000,000 bytes). + +The host reserves pool room, streams the bytes to a partial directory while +counting and hashing them, detects the kind from the stored bytes and +publishes the file read-only at `.brain-ui/attachments//` by one +atomic rename. Detection is by signature first (`%PDF-`; JPEG, PNG, GIF, +WebP; HEIC/HEIF; ZIP, gzip, 7z, RAR), then strict UTF-8 text, then the shared +track parser for text up to 20 MiB. Anything else is `binary`. A name or MIME +type is only a hint: it never makes a file a track or a PDF. +`trackRejected: true` says a track hint did not parse. Upload never claims the +contents were read. + +`201` returns an `AttachmentFile`. Repeating a key with the same draft, name +hint, media hint and bytes returns `200` with the same file, without storing a +second copy. + +| Status | `error` | `bound` / meaning | +| --- | --- | --- | +| 413 | `ATTACHMENT_TOO_LARGE` | `file` (25,000,000), `draftFiles` (50,000,000), `draftCount` (10) | +| 507 | `ATTACHMENT_CAPACITY` | `pool` (the configured `BRAIN_UI_ATTACHMENT_POOL_BYTES`) | +| 410 | `DRAFT_DELETED` | the draft was deleted or sent | +| 400 | `ATTACHMENT_INVALID` | an empty file, a malformed header, or an `X-` header claiming authority, a path or a kind | +| 409 | `ATTACHMENT_KEY_REUSED` | the key named a different upload | +| 503 | `busy` | three composer uploads are already running; retry | + +`draftCount` and `draftFiles` count everything the draft's revision and +outgoing snapshot reference, plus uploads for the same draft that no save has +bound yet and that are under an hour old. The pool counts every recorded +original in any state, every live reservation and the legacy draft images. +Reservations are taken in one immediate transaction, so concurrent uploads +cannot multiply the cap. At capacity nothing is removed to make room. + +`PUT /api/drafts/:draftId` accepts `fileIds` (at most 10) and `outgoing` +(`{ requestId, text, fileIds, state: "held" | "dispatched" }`, `null` to +clear, absent to keep). A save binds exactly the listed files to the revision +and the snapshot's files to the snapshot. Each listed file must be `stored` +and minted for this draft, or the save is 400 `ATTACHMENT_INVALID`. At most +10 attachments are listed, legacy images included, and at most 50,000,000 +original bytes together (413 `DRAFT_TOO_LARGE`, `bound` `draftCount` or +`draftFiles`). The old `maxDraftBytes` ceiling bounds text and legacy images +only. `GET` returns `files` (only files still stored) and `outgoing`. + +### `GET /api/attachments/:fileId` + +Streams one original up to 25,000,000 bytes, after checking its recorded size +and SHA-256 through no link. Any live reference authorizes the read: a draft +revision, an outgoing snapshot or a sent message. Answers carry +`Content-Security-Policy: default-src 'none'`, `X-Content-Type-Options: +nosniff`, and `Content-Disposition: attachment` for every kind except an image +preview. `404 ATTACHMENT_NOT_FOUND` for an unknown, unreferenced or missing +file; `409 ATTACHMENT_CHANGED` when the bytes no longer match, with none of +them served. The raw file route keeps its 10,485,760-byte cap. + +### Lifetime + +An upload no save or message ever bound is removed an hour after upload. An +original that was referenced is removed seven days after its last reference +went; rebinding cancels that. A sweep runs at boot and every ten minutes. It +marks eligible files in one transaction and only then unlinks them, so a +rebind that loses the race is refused rather than binding a deleted file. At +boot, reservations and partial uploads of an earlier process are discarded, a +record whose directory is gone becomes `missing`, and a directory with no +record is adopted, charged, with a fresh seven days. Clocks are the server's +stored wall clock, never file times. + ## Session recovery (additive, #964) **GET /api/sessions/:id/recovery** is protected and read-only: it never @@ -1356,7 +1439,7 @@ read by any authenticated principal. | `strict_fallback` | 1 | `path`, `reason` | A turn ran under `strict` instead of `governed` because a protected path is a `symlink`, a `hardlink` or a `mount_point`. | | `revert_conflict` | 1 | `conflicts`, `restored` | A revert skipped paths that changed after the reverted turn. Each conflict is `{ path, state }`, with `state` one of `changed`, `deleted`, `created` or `type_changed`; `restored` counts the paths it did restore. | | `outward_action` | 1 | `tool`, `input`, `inputTruncated`, `action`, `target`, `historyRewrite`, `tainted`, `decision`, `rule` | An action outside the brain in the user's name, allowed or not. `action` is `git_push`, `gh_write`, `mcp_tool`, `http_write`, `outward_host_connect` or `compute_run` (a hosted external compute job start, #3108, its `target` the instance id); `decision` is `policy_allowed`, `approved`, `declined` or `refused`; `rule` is the matching `outward.allow` rule or `null`. | -| `taint` | 1 | `source`, `tool`, `detail` | The untrusted input that tainted the session. `source` is `web_fetch`, `web_search`, `staged_share`, `workspace_read`, `mcp_document`, `user_marked`, `egress_connection`, `fetching_command`, `unclassified_command`, additively since #3162 `apify_result` (Apify catalog text or Actor results returned to a turn; `tool` names the `brain_apify_*` operation), or `compute_output` (a collected external compute job's output, #3108). | +| `taint` | 1 | `source`, `tool`, `detail` | The untrusted input that tainted the session. `source` is `web_fetch`, `web_search`, `staged_share`, `chat_attachment`, `workspace_read`, `mcp_document`, `user_marked`, `egress_connection`, `fetching_command`, `unclassified_command`, additively since #3162 `apify_result` (Apify catalog text or Actor results returned to a turn; `tool` names the `brain_apify_*` operation), or `compute_output` (a collected external compute job's output, #3108). | | `provider_unavailable` | 1 | `provider`, `capability`, `command`, `degradedTo` | A worker command needed a provider whose key the host withheld from the worker. Recorded from the token the CLI prints ([CLI contract](integration-contract/cli.md#withheld-provider-keys-additive-0440-1666)), one event per distinct token in a tool result and at most 20 per turn. `capability` is `embeddings`, `completions`, `reranking` or `image`; `command` is the shell command, or the tool's name for any other tool; `degradedTo` names the fallback used (`keyword_search`, `keyword_index`, `lifecycle_order`) or is `null`. The token is text in tool output, so the event is a diagnostic, not proof. | | `resource_limit` | 1 | `limits`, `fatal` | A worker hit a resource limit. Each limit is `{ limit, source, value, events }`: `limit` is `processes`, `memory`, `pids`, `file_size`, `data`, `cpu` or `open_files`; `source` is `rlimit` or `cgroup`; `value` is the configured limit; `events` counts the hits the source reported, or is `null`. `fatal` says whether the worker died of it. | | `roadblock` | 1 | `category`, `family`, `signature`, `failures`, `resolution`, `remedy`, `waste`, `eventIds` | One classified roadblock episode, written when its turn ends ([classification](decisions/governed-writable-workers.md#roadblocks)). An episode opens at a failed step and closes at the next successful call of the same `family`, or at turn end. `family` is the tool family: `shell:` (with the subcommand for multi-command programs, such as `shell:git push`), `file_write`, `file_read`, `search`, `web`, `brain_write`, `subagent`, `mcp::` or `tool:`; a governance event with no call has `budget`, `scope`, `network`, `policy` or `outward`. `category` is `tool_error`, `shell_nonzero`, `fs_denied`, `permission_denied`, `policy_block`, `budget`, `scope_cap`, `network_refused` or `retry`. It is `retry` when the episode repeated a near-identical failed input, and otherwise the first failure's category. `signature` is the grouping key `\|\| ` of the first failure, for example `file_write\|.brain/*\|fs_denied EROFS .brain/*`. The target is the command's program and, for multi-command programs, its subcommand (`