/** * RFC-0048: agents' signed upload links. `create_upload` declares one file (size, type, SHA-256 and * the asset's text) under `upload_asset`'s scope, mode, approval and limits, and returns a * short-lived PUT link; the agent's shell sends the bytes; `complete_upload` creates the asset. The * bytes never pass through the model. Only HTTP `/mcp` hands out links (`uploads.signedUrl`); the * tools are always listed (ADR-0004) and say so where it is off. */ import type { Asset } from "@cloudhal/core-contracts"; import { InvariantError, NotFoundError } from "@cloudhal/core-ts"; import { formatBytes, MEDIA_LIMITS, MEDIA_TYPES } from "@cloudhal/core-ts/media"; import { ASSET_OUT, cleanName, dailyLimit, FETCH_TYPES, MB, report, TEXT_FIELDS, texts, url, WRITE, } from "./asset-tools.ts"; import { autoSnapshot, id, type JsonSchema, quote, requireSite, SLUG_PATTERN, str, type ToolContext, type ToolDefinition, ToolError, } from "./common.ts"; import { completeRefusal, createRefusal, HASH_COMMANDS, unsupported } from "./upload-hints.ts"; /** RFC-0048 §2.4: 10 minutes to start the PUT, 60 to complete. */ export const LINK_SECONDS = 600; const COMPLETE_SECONDS = 3600; /** RFC-0048 §3.3: open uploads per key and per site. */ const OPEN_PER_KEY = 10; const OPEN_PER_SITE = 50; const DEFAULT_CAP = 25 * MB; /** What `get_mode` reports (`uploads`) and `create_upload` obeys. */ export function uploadCapability(ctx: Pick): { signedUrl: boolean; maxBytes: number; linkSeconds: number; } { const cap = Math.min(ctx.media?.agentUploadBytes ?? DEFAULT_CAP, MEDIA_LIMITS.upload); const signedUrl = ctx.uploads?.verifiable === true && ctx.media?.agentUploads !== false; return { signedUrl, maxBytes: cap, linkSeconds: LINK_SECONDS }; } /** `get_mode`'s `uploads` property. */ export const UPLOADS_MODE_SCHEMA: JsonSchema = { type: "object", additionalProperties: false, description: "RFC-0048: whether this server hands out upload links (create_upload), the cap per file and how long a link lasts to start the PUT.", properties: { signedUrl: { type: "boolean" }, maxBytes: { type: "integer" }, linkSeconds: { type: "integer" }, }, required: ["signedUrl", "maxBytes", "linkSeconds"], }; const nullable = (schema: JsonSchema): JsonSchema => ({ ...schema, type: [schema.type as string, "null"], }); const nullOrString = (description: string): JsonSchema => ({ type: ["string", "null"], description, }); /** §5.1: the declared file, with every optional value also accepted as `null`. */ const CREATE_IN: JsonSchema = { type: "object", additionalProperties: false, properties: { siteId: id, filename: str("The file's name, e.g. ferries.webp (its extension must match the content)", { minLength: 1, maxLength: 255, pattern: "^[^/\\\\\\u0000-\\u001f\\u007f]+$", }), bytes: { type: "integer", minimum: 1, maximum: MEDIA_LIMITS.upload, description: "The file's exact size in bytes (the server's cap may be lower: get_mode)", }, mediaType: { type: "string", enum: [...FETCH_TYPES], description: "The file's type" }, sha256: str(`The file's SHA-256, 64 hex digits (${HASH_COMMANDS})`, { pattern: "^[0-9a-fA-F]{64}$", }), alt: nullable(TEXT_FIELDS.alt as JsonSchema), decorative: nullable(TEXT_FIELDS.decorative as JsonSchema), title: nullable(TEXT_FIELDS.title as JsonSchema), caption: nullable(TEXT_FIELDS.caption as JsonSchema), credit: nullable(TEXT_FIELDS.credit as JsonSchema), license: { anyOf: [TEXT_FIELDS.license as JsonSchema, { type: "null" }] }, locale: nullable(TEXT_FIELDS.locale as JsonSchema), slug: nullable( str("File name in the URL, without extension", { pattern: SLUG_PATTERN, maxLength: 96 }), ), }, required: ["siteId", "filename", "bytes", "mediaType", "sha256"], }; /** §5.1: every key always present, `null` where it does not apply (the strict profile). */ const CREATE_OUT: JsonSchema = { type: "object", additionalProperties: false, properties: { status: { type: "string", enum: ["upload", "existing"] }, uploadId: nullOrString("Pass it to complete_upload after the PUT"), url: nullOrString("PUT the file's bytes here (it is the credential: do not share it)"), method: { type: ["string", "null"], enum: ["PUT", null] }, headers: { type: ["object", "null"], additionalProperties: false, properties: { "content-type": { type: "string" } }, required: ["content-type"], }, expiresAt: nullOrString("Start the PUT before this time (UTC)"), completeBy: nullOrString("Call complete_upload before this time (UTC)"), curl: nullOrString("The PUT as a curl command; replace the file name with its path"), asset: { type: ["object", "null"], description: 'status "existing": the asset that already holds these bytes', }, }, required: [ "status", "uploadId", "url", "method", "headers", "expiresAt", "completeBy", "curl", "asset", ], }; const present = (a: Record) => Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)); /** A single-quoted shell word. */ const shellWord = (text: string) => `'${text.replaceAll("'", "'\\''")}'`; function isImageType(mediaType: unknown): boolean { return typeof mediaType === "string" && MEDIA_TYPES[mediaType]?.kind === "image"; } /** `create_upload` after its precheck: the existing asset, or a new row and its signed link. */ async function openLink(raw: Record, ctx: ToolContext) { const a = present(raw); const cap = uploadCapability(ctx); const links = ctx.uploads; if (!cap.signedUrl || !links) throw unsupported(); const site = await requireSite(ctx, a.siteId as string); const sha256 = (a.sha256 as string).toLowerCase(); const hints = { cap: cap.maxBytes, types: FETCH_TYPES }; let existing: Asset | undefined; try { existing = await ctx.store.assetForUploadedContent(site.id, sha256); } catch (e) { createRefusal(e, hints); } const none = { uploadId: null, url: null, method: null, headers: null, expiresAt: null, completeBy: null, curl: null, }; if (existing) return { status: "existing", ...none, asset: existing }; const filename = cleanName(a.filename as string); try { const upload = await ctx.store.uploads.open( site.id, ctx.principal.actor, { bytes: a.bytes as number, mediaType: a.mediaType as string, sha256, filename, fields: { ...texts(site, a), ...(a.license ? { license: a.license as Asset["license"] } : {}), ...(a.slug ? { slug: a.slug as string } : {}), }, }, { ttlMs: LINK_SECONDS * 1000, completeMs: COMPLETE_SECONDS * 1000, maxOpenPerActor: OPEN_PER_KEY, maxOpenPerSite: OPEN_PER_SITE, maxBytes: cap.maxBytes, now: ctx.now?.(), }, ); const link = `${links.origin}${await links.link(upload)}`; // The audit row's effect names the upload, never the link (RFC-0048 §3.2). ctx.report?.({ upload: { id: upload.id, bytes: upload.bytes, sha256, mediaType: upload.mediaType }, }); return { status: "upload", uploadId: upload.id, url: link, method: "PUT", headers: { "content-type": upload.mediaType }, expiresAt: upload.expiresAt, completeBy: upload.completeBy, curl: `curl --fail-with-body -X PUT -H ${shellWord(`content-type: ${upload.mediaType}`)} --upload-file ${shellWord(filename ?? "file")} ${shellWord(link)}`, asset: null, }; } catch (e) { createRefusal(e, hints); } } export function uploadTools(): ToolDefinition[] { return [ { name: "create_upload", title: "Create an upload link", description: `Get a short-lived link to PUT one file from your machine into the site's media library, without sending its bytes through this conversation (for files on disk when you have a shell; up to the cap in get_mode.uploads, ${DEFAULT_CAP / MB} MB by default). Declare the file's exact size, type and SHA-256 (${HASH_COMMANDS}); then run the returned curl command (or PUT the bytes with that Content-Type and Content-Length) within ${LINK_SECONDS / 60} minutes, and call complete_upload with the uploadId. Only that exact file can be sent with the link, once. Images need alt or decorative: true. Bytes already in the library answer status "existing" with the asset, and need no upload. Without a shell, or for small files, use upload_asset. Nothing is public until the site is published.`, inputSchema: CREATE_IN, outputSchema: CREATE_OUT, annotations: WRITE, scopes: ["asset:upload"], approvalPrompt: async (a, ctx) => { const site = await ctx.store.getSite(a.siteId as string); const name = (a.alt ?? a.title ?? a.filename) as string; const type = MEDIA_TYPES[a.mediaType as string]?.label ?? (a.mediaType as string); const sha = String(a.sha256).toLowerCase().slice(0, 12); return `Add media "${quote(name)}" (${quote(a.filename as string, 80)}, ${formatBytes(a.bytes as number)}, ${type}, sha256 ${sha}…) to "${quote(site?.name ?? (a.siteId as string))}"? It becomes public only when the site is published.`; }, precheck: async (a, ctx) => { const cap = uploadCapability(ctx); if (!cap.signedUrl) throw unsupported(); if (!FETCH_TYPES.includes(a.mediaType as string)) createRefusal( new InvariantError( "unsupported_type", `${String(a.mediaType)} is not accepted from agents`, ), { cap: cap.maxBytes, types: FETCH_TYPES }, ); if ((a.bytes as number) > cap.maxBytes) createRefusal( new InvariantError( "too_large", `this file is ${formatBytes(a.bytes as number)}; upload links take at most ${formatBytes(cap.maxBytes)}`, { bytes: a.bytes, limit: cap.maxBytes }, ), { cap: cap.maxBytes, types: FETCH_TYPES }, ); if ( isImageType(a.mediaType) && !(typeof a.alt === "string" && a.alt.trim()) && a.decorative !== true ) throw new ToolError( "invalid", "images need alt text (what the image shows, for screen readers) or decorative: true", ); await dailyLimit(ctx, a.bytes as number); }, handler: (a, ctx) => openLink(a, ctx), }, { name: "complete_upload", title: "Complete an upload", description: "Turn an upload you sent to a create_upload link into an asset of the site's media library, with the alt text and fields given to create_upload; it answers as upload_asset does. Call it after the PUT succeeded. It needs no second approval (create_upload's covered the file), and calling it again returns the same asset.", inputSchema: { type: "object", additionalProperties: false, properties: { siteId: id, uploadId: id }, required: ["siteId", "uploadId"], }, outputSchema: ASSET_OUT, annotations: { ...WRITE, idempotentHint: true }, scopes: ["asset:upload"], // Refused in `plan`, free in `manual`: the approval at create_upload bound this exact file // (RFC-0048 §3.1, decision 8). The key's status, scopes and mode are checked again here. classify: () => "advisory", handler: async (a, ctx) => { const site = await requireSite(ctx, a.siteId as string); const upload = await ctx.store.uploads.get(a.uploadId as string); if (!upload || upload.siteId !== site.id) completeRefusal(new NotFoundError("upload", a.uploadId as string)); let done: { asset: Asset; existing: boolean }; try { done = await ctx.store.uploads.complete(upload.id, ctx.principal.actor, ctx.now?.()); } catch (e) { completeRefusal(e); } report(ctx, done.asset, { existing: done.existing, uploadId: upload.id, via: "signed-upload", }); const usage = (await ctx.store.assetUsage(site.id, [done.asset.id])).get(done.asset.id)?.total ?? 0; return { asset: done.asset, existing: done.existing, url: url(done.asset), usage, ...(done.existing ? {} : { snapshot: await autoSnapshot(ctx, site.id, "complete_upload") }), }; }, }, ]; }