| 1 | import { Service } from '@deepseek-ai/cordis' |
| 2 | import { ErrorCode } from '../protocol.ts' |
| 3 | import { IMAGE_LIMITS } from '../protocol.generated.ts' |
| 4 | import { RpcError } from '../rpc.ts' |
| 5 | import type { AdapterHost, DshAdapter } from './adapters.ts' |
| 6 | import { HarnessError } from './dsh-message-compat.js' |
| 7 | |
| 8 | const ATTACHMENT_ID = /^sha256:[0-9a-f]{64}$/ |
| 9 | const IMAGE_INPUT_KEYS = new Set(['data', 'mediaType', 'name']) |
| 10 | const REF_KEYS = new Set(['attachmentId', 'mediaType', 'bytes', 'width', 'height']) |
| 11 | const REQUEST_TARGET_KEYS = new Set(['width', 'height', 'maxBytes']) |
| 12 | const MAX_NAME_LEN = 128 |
| 13 | |
| 14 | const FROZEN_MEDIA_TYPES = Object.freeze([...IMAGE_LIMITS.mediaTypes]) as readonly string[] |
| 15 | const ALLOWED_MEDIA_TYPES = new Set<string>(FROZEN_MEDIA_TYPES) |
| 16 | |
| 17 | export interface ImageLimits { |
| 18 | readonly maxImageBytes: number |
| 19 | readonly maxImagesPerMessage: number |
| 20 | readonly maxMessageImageBytes: number |
| 21 | readonly maxImagePixels: number |
| 22 | readonly maxImageDimension: number |
| 23 | readonly mediaTypes: readonly string[] |
| 24 | } |
| 25 | |
| 26 | export const ATTACHMENT_IMAGE_LIMITS: ImageLimits = Object.freeze({ |
| 27 | maxImageBytes: IMAGE_LIMITS.maxImageBytes, |
| 28 | maxImagesPerMessage: IMAGE_LIMITS.maxImagesPerMessage, |
| 29 | maxMessageImageBytes: IMAGE_LIMITS.maxMessageImageBytes, |
| 30 | maxImagePixels: IMAGE_LIMITS.maxImagePixels, |
| 31 | maxImageDimension: IMAGE_LIMITS.maxImageDimension, |
| 32 | mediaTypes: FROZEN_MEDIA_TYPES, |
| 33 | }) |
| 34 | |
| 35 | export interface ImageAttachmentRef { |
| 36 | attachmentId: string |
| 37 | mediaType?: string |
| 38 | bytes?: number |
| 39 | width?: number |
| 40 | height?: number |
| 41 | } |
| 42 | |
| 43 | export interface StoredImageAttachmentRef { |
| 44 | attachmentId: string |
| 45 | mediaType: string |
| 46 | bytes: number |
| 47 | width: number |
| 48 | height: number |
| 49 | } |
| 50 | |
| 51 | export interface ImageBytesInput { |
| 52 | data: Uint8Array |
| 53 | mediaType: string |
| 54 | name?: string |
| 55 | } |
| 56 | |
| 57 | export interface ValidateImageResult { |
| 58 | ok: true |
| 59 | mediaType: string |
| 60 | bytes: number |
| 61 | width: number |
| 62 | height: number |
| 63 | } |
| 64 | |
| 65 | export interface ReadImageResult { |
| 66 | data: Uint8Array |
| 67 | ref: StoredImageAttachmentRef |
| 68 | } |
| 69 | |
| 70 | export interface ReadImageRequestTarget { |
| 71 | width?: number |
| 72 | height?: number |
| 73 | maxBytes?: number |
| 74 | } |
| 75 | |
| 76 | export interface ReadImageRequestResult { |
| 77 | variantId: string |
| 78 | data: Uint8Array |
| 79 | mediaType: string |
| 80 | } |
| 81 | |
| 82 | export class AttachmentError extends HarnessError { |
| 83 | constructor(code: string, message: string, options?: ErrorOptions) { |
| 84 | super(message, code, options) |
| 85 | this.name = 'AttachmentError' |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | export function isAttachmentError(error: unknown): error is AttachmentError { |
| 90 | return error instanceof AttachmentError || ( |
| 91 | error !== null |
| 92 | && typeof error === 'object' |
| 93 | && (error as { name?: unknown }).name === 'AttachmentError' |
| 94 | && typeof (error as { code?: unknown }).code === 'string' |
| 95 | ) |
| 96 | } |
| 97 | |
| 98 | function invalid(message: string): never { |
| 99 | throw new RpcError(ErrorCode.InvalidParams, message) |
| 100 | } |
| 101 | |
| 102 | function isPlainRecord(value: unknown): value is Record<string, unknown> { |
| 103 | return value !== null && typeof value === 'object' && !Array.isArray(value) && !ArrayBuffer.isView(value) |
| 104 | } |
| 105 | |
| 106 | function checkAllowedKeys(value: Record<string, unknown>, allowed: Set<string>, label: string): void { |
| 107 | for (const key of Object.keys(value)) { |
| 108 | if (!allowed.has(key)) invalid(`${label} contains unsupported field \`${key}\``) |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | function validateSignal(signal: unknown): AbortSignal | undefined { |
| 113 | if (signal === undefined) return undefined |
| 114 | if (!(signal instanceof AbortSignal)) { |
| 115 | invalid('signal must be an AbortSignal') |
| 116 | } |
| 117 | return signal |
| 118 | } |
| 119 | |
| 120 | function checkAborted(signal: AbortSignal | undefined): void { |
| 121 | if (signal?.aborted === true) { |
| 122 | throw new AttachmentError('CANCELLED', 'the attachment operation was aborted') |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | function validateName(name: unknown): string | undefined { |
| 127 | if (name === undefined) return undefined |
| 128 | if (typeof name !== 'string' || name.length === 0 || name.length > MAX_NAME_LEN |
| 129 | || name.startsWith('.') || name.includes('/') || name.includes('\\') |
| 130 | || name.includes('..') || name.includes(':') || /[\x00-\x1f\x7f]/.test(name)) { |
| 131 | invalid('attachment name must be a non-empty basename with no path separators or control characters') |
| 132 | } |
| 133 | return name |
| 134 | } |
| 135 | |
| 136 | function serializeImageBytesInput(input: unknown): { data_base64: string, media_type: string, name?: string } { |
| 137 | if (!isPlainRecord(input)) invalid('image input must be an object') |
| 138 | checkAllowedKeys(input, IMAGE_INPUT_KEYS, 'image input') |
| 139 | const { data, mediaType } = input |
| 140 | if (!(data instanceof Uint8Array)) invalid('image data must be a Uint8Array') |
| 141 | if (typeof mediaType !== 'string' || mediaType.length === 0) invalid('mediaType must be a non-empty string') |
| 142 | if (!ALLOWED_MEDIA_TYPES.has(mediaType)) { |
| 143 | throw new AttachmentError('UNSUPPORTED_IMAGE_TYPE', `unsupported image media type: ${mediaType}`) |
| 144 | } |
| 145 | const byteLength = data.byteLength |
| 146 | if (byteLength === 0) { |
| 147 | throw new AttachmentError('INVALID_IMAGE', 'image payload is empty') |
| 148 | } |
| 149 | if (byteLength > ATTACHMENT_IMAGE_LIMITS.maxImageBytes) { |
| 150 | throw new AttachmentError('IMAGE_TOO_LARGE', `image exceeds the ${ATTACHMENT_IMAGE_LIMITS.maxImageBytes} byte limit`) |
| 151 | } |
| 152 | const name = validateName(input.name) |
| 153 | const data_base64 = Buffer.from(data.buffer, data.byteOffset, byteLength).toString('base64') |
| 154 | return name === undefined ? { data_base64, media_type: mediaType } : { data_base64, media_type: mediaType, name } |
| 155 | } |
| 156 | |
| 157 | function positiveU32(value: unknown, label: string): number { |
| 158 | if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0 || value > 0xffff_ffff) { |
| 159 | invalid(`${label} must be a positive integer`) |
| 160 | } |
| 161 | return value |
| 162 | } |
| 163 | |
| 164 | function positiveSafeInt(value: unknown, label: string): number { |
| 165 | if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { |
| 166 | invalid(`${label} must be a positive integer`) |
| 167 | } |
| 168 | return value |
| 169 | } |
| 170 | |
| 171 | function serializeRef(ref: unknown): Record<string, unknown> { |
| 172 | if (!isPlainRecord(ref)) invalid('attachment reference must be an object') |
| 173 | checkAllowedKeys(ref, REF_KEYS, 'attachment reference') |
| 174 | if (typeof ref.attachmentId !== 'string' || !ATTACHMENT_ID.test(ref.attachmentId)) { |
| 175 | throw new AttachmentError('INVALID_ATTACHMENT_REF', 'invalid attachment id') |
| 176 | } |
| 177 | const wire: Record<string, unknown> = { attachment_id: ref.attachmentId } |
| 178 | if (ref.mediaType !== undefined) { |
| 179 | if (typeof ref.mediaType !== 'string' || ref.mediaType.length === 0) invalid('attachment mediaType must be a string') |
| 180 | wire.media_type = ref.mediaType |
| 181 | } |
| 182 | if (ref.bytes !== undefined) wire.bytes = positiveSafeInt(ref.bytes, 'attachment bytes') |
| 183 | if (ref.width !== undefined) wire.width = positiveU32(ref.width, 'attachment width') |
| 184 | if (ref.height !== undefined) wire.height = positiveU32(ref.height, 'attachment height') |
| 185 | return wire |
| 186 | } |
| 187 | |
| 188 | function serializeRequestTarget(target: unknown): Record<string, number> { |
| 189 | if (target === undefined) return {} |
| 190 | if (!isPlainRecord(target)) invalid('readImageRequest target must be an object') |
| 191 | checkAllowedKeys(target, REQUEST_TARGET_KEYS, 'readImageRequest target') |
| 192 | const wire: Record<string, number> = {} |
| 193 | if (target.width !== undefined) { |
| 194 | const width = positiveU32(target.width, 'width') |
| 195 | if (width > ATTACHMENT_IMAGE_LIMITS.maxImageDimension) { |
| 196 | throw new AttachmentError('IMAGE_DIMENSION_TOO_LARGE', `requested width exceeds the ${ATTACHMENT_IMAGE_LIMITS.maxImageDimension}px limit`) |
| 197 | } |
| 198 | wire.width = width |
| 199 | } |
| 200 | if (target.height !== undefined) { |
| 201 | const height = positiveU32(target.height, 'height') |
| 202 | if (height > ATTACHMENT_IMAGE_LIMITS.maxImageDimension) { |
| 203 | throw new AttachmentError('IMAGE_DIMENSION_TOO_LARGE', `requested height exceeds the ${ATTACHMENT_IMAGE_LIMITS.maxImageDimension}px limit`) |
| 204 | } |
| 205 | wire.height = height |
| 206 | } |
| 207 | if (target.maxBytes !== undefined) { |
| 208 | const maxBytes = positiveSafeInt(target.maxBytes, 'maxBytes') |
| 209 | if (maxBytes > ATTACHMENT_IMAGE_LIMITS.maxImageBytes) { |
| 210 | throw new AttachmentError('IMAGE_TOO_LARGE', `requested maxBytes exceeds the ${ATTACHMENT_IMAGE_LIMITS.maxImageBytes} byte limit`) |
| 211 | } |
| 212 | wire.max_bytes = maxBytes |
| 213 | } |
| 214 | return wire |
| 215 | } |
| 216 | |
| 217 | function parseRefWire(value: unknown, what: string): StoredImageAttachmentRef { |
| 218 | if (!isPlainRecord(value) |
| 219 | || typeof value.attachment_id !== 'string' || !ATTACHMENT_ID.test(value.attachment_id) |
| 220 | || typeof value.media_type !== 'string' || !ALLOWED_MEDIA_TYPES.has(value.media_type) |
| 221 | || typeof value.bytes !== 'number' || !Number.isSafeInteger(value.bytes) || value.bytes <= 0 |
| 222 | || typeof value.width !== 'number' || !Number.isInteger(value.width) || value.width <= 0 |
| 223 | || typeof value.height !== 'number' || !Number.isInteger(value.height) || value.height <= 0) { |
| 224 | throw new RpcError(ErrorCode.Internal, `invalid ${what}`) |
| 225 | } |
| 226 | return { |
| 227 | attachmentId: value.attachment_id, |
| 228 | mediaType: value.media_type, |
| 229 | bytes: value.bytes, |
| 230 | width: value.width, |
| 231 | height: value.height, |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | function mapBrokerError(error: unknown): unknown { |
| 236 | if (error instanceof Error && error.name === 'AbortError') { |
| 237 | return new AttachmentError('CANCELLED', error.message || 'the attachment operation was aborted') |
| 238 | } |
| 239 | if (error !== null && typeof error === 'object') { |
| 240 | const code = (error as { code?: unknown }).code |
| 241 | const message = (error as { message?: unknown }).message |
| 242 | if (code === ErrorCode.Cancelled) { |
| 243 | return new AttachmentError('CANCELLED', typeof message === 'string' && message.length > 0 ? message : 'the attachments broker call was cancelled') |
| 244 | } |
| 245 | if (code === ErrorCode.Refused && typeof message === 'string') { |
| 246 | const match = /^\[([A-Z0-9_]+)\]\s*(.+)$/s.exec(message) |
| 247 | if (match !== null) { |
| 248 | return new AttachmentError(match[1], match[2]) |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | return error |
| 253 | } |
| 254 | |
| 255 | async function callBroker( |
| 256 | host: AdapterHost, |
| 257 | ctx: unknown, |
| 258 | method: string, |
| 259 | input: unknown, |
| 260 | signal?: AbortSignal, |
| 261 | ): Promise<unknown> { |
| 262 | const checkedSignal = validateSignal(signal) |
| 263 | checkAborted(checkedSignal) |
| 264 | const settled = host.broker(ctx, 'attachments', method, input, checkedSignal).catch((error) => { |
| 265 | throw mapBrokerError(error) |
| 266 | }) |
| 267 | settled.catch(() => undefined) |
| 268 | if (checkedSignal === undefined) { |
| 269 | return await settled |
| 270 | } |
| 271 | let onAbort: (() => void) | undefined |
| 272 | try { |
| 273 | const aborted = new Promise<never>((_, reject) => { |
| 274 | onAbort = () => reject(new AttachmentError('CANCELLED', 'the attachment operation was aborted')) |
| 275 | checkedSignal.addEventListener('abort', onAbort, { once: true }) |
| 276 | }) |
| 277 | const result = await Promise.race([settled, aborted]) |
| 278 | checkAborted(checkedSignal) |
| 279 | return result |
| 280 | } finally { |
| 281 | if (onAbort !== undefined) checkedSignal.removeEventListener('abort', onAbort) |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | export const attachmentsAdapter: DshAdapter = { |
| 286 | service: 'attachments', |
| 287 | define(host: AdapterHost) { |
| 288 | class AttachmentsService extends Service { |
| 289 | constructor(ctx: any) { super(ctx, 'attachments') } |
| 290 | |
| 291 | get imageLimits(): ImageLimits { |
| 292 | return ATTACHMENT_IMAGE_LIMITS |
| 293 | } |
| 294 | |
| 295 | imageHostPath(_ref?: unknown, signal?: AbortSignal): undefined { |
| 296 | const checkedSignal = validateSignal(signal) |
| 297 | checkAborted(checkedSignal) |
| 298 | return undefined |
| 299 | } |
| 300 | |
| 301 | async validateImage(input: ImageBytesInput, signal?: AbortSignal): Promise<ValidateImageResult> { |
| 302 | const wire = serializeImageBytesInput(input) |
| 303 | const res = await callBroker(host, this.ctx, 'validate', wire, signal) |
| 304 | if (!isPlainRecord(res) |
| 305 | || res.ok !== true |
| 306 | || typeof res.media_type !== 'string' || !ALLOWED_MEDIA_TYPES.has(res.media_type) |
| 307 | || typeof res.bytes !== 'number' || !Number.isSafeInteger(res.bytes) || res.bytes <= 0 |
| 308 | || typeof res.width !== 'number' || !Number.isInteger(res.width) || res.width <= 0 |
| 309 | || typeof res.height !== 'number' || !Number.isInteger(res.height) || res.height <= 0) { |
| 310 | throw new RpcError(ErrorCode.Internal, 'invalid attachments.validate broker response') |
| 311 | } |
| 312 | return { |
| 313 | ok: true, |
| 314 | mediaType: res.media_type, |
| 315 | bytes: res.bytes, |
| 316 | width: res.width, |
| 317 | height: res.height, |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | async saveImage(input: ImageBytesInput, signal?: AbortSignal): Promise<StoredImageAttachmentRef> { |
| 322 | const wire = serializeImageBytesInput(input) |
| 323 | const res = await callBroker(host, this.ctx, 'save', wire, signal) |
| 324 | if (!isPlainRecord(res)) throw new RpcError(ErrorCode.Internal, 'invalid attachments.save broker response') |
| 325 | return parseRefWire(res.attachment, 'attachments.save attachment reference') |
| 326 | } |
| 327 | |
| 328 | async readImage(ref: ImageAttachmentRef, signal?: AbortSignal): Promise<ReadImageResult> { |
| 329 | const attachment = serializeRef(ref) |
| 330 | const res = await callBroker(host, this.ctx, 'read', { attachment }, signal) |
| 331 | if (!isPlainRecord(res) || typeof res.data_base64 !== 'string') { |
| 332 | throw new RpcError(ErrorCode.Internal, 'invalid attachments.read broker response') |
| 333 | } |
| 334 | return { |
| 335 | data: Buffer.from(res.data_base64, 'base64'), |
| 336 | ref: parseRefWire(res.attachment, 'attachments.read attachment reference'), |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | async readImageRequest( |
| 341 | ref: ImageAttachmentRef, |
| 342 | target?: ReadImageRequestTarget, |
| 343 | signal?: AbortSignal, |
| 344 | ): Promise<ReadImageRequestResult> { |
| 345 | const attachment = serializeRef(ref) |
| 346 | const sizing = serializeRequestTarget(target) |
| 347 | const res = await callBroker(host, this.ctx, 'read_request', { attachment, ...sizing }, signal) |
| 348 | if (!isPlainRecord(res) |
| 349 | || typeof res.variant_id !== 'string' || !ATTACHMENT_ID.test(res.variant_id) |
| 350 | || typeof res.data_base64 !== 'string' |
| 351 | || typeof res.media_type !== 'string' || !ALLOWED_MEDIA_TYPES.has(res.media_type)) { |
| 352 | throw new RpcError(ErrorCode.Internal, 'invalid attachments.read_request broker response') |
| 353 | } |
| 354 | return { |
| 355 | variantId: res.variant_id, |
| 356 | data: Buffer.from(res.data_base64, 'base64'), |
| 357 | mediaType: res.media_type, |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | saveFile(): never { return notAvailable('saveFile') } |
| 362 | admitEncodedFile(): never { return notAvailable('admitEncodedFile') } |
| 363 | saveFileStream(): never { return notAvailable('saveFileStream') } |
| 364 | readFileStream(): never { return notAvailable('readFileStream') } |
| 365 | readFile(): never { return notAvailable('readFile') } |
| 366 | fileHostPath(): never { return notAvailable('fileHostPath') } |
| 367 | } |
| 368 | Object.freeze(AttachmentsService.prototype) |
| 369 | return AttachmentsService |
| 370 | }, |
| 371 | } |
| 372 | |
| 373 | function notAvailable(method: string): never { |
| 374 | throw new RpcError( |
| 375 | ErrorCode.NotAvailable, |
| 376 | `attachments.${method} is not available: Codewhale brokers conversation images only and exposes no generic file store`, |
| 377 | ) |
| 378 | } |
| 379 |