From 11a5bf8a55bb11a9ce7ae7e54775776c0dfca395 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 17:06:13 +0800 Subject: [PATCH] refactor(tool-fs): keep attachment store codes in read_image failures The attachment store already classifies its rejections, so read_image no longer translates them into ImageInputError codes. An AttachmentError keeps its name and code; for codes with a known remedy the tool rethrows it with a message naming the file and the next step, and the store error as cause. Other store failures pass through unchanged. ImageInputError keeps only the refusals the tool makes before storing the image: IMAGE_UNSUPPORTED_MODEL and IMAGE_UNSUPPORTED_FORMAT. The removed codes (IMAGE_TYPE_MISMATCH, IMAGE_INVALID, IMAGE_TOO_LARGE, IMAGE_CONVERSION_FAILED, IMAGE_STORE_FAILED) were never released. --- .../attachment-error-codes/guide.i18n.yaml | 4 +- .../attachment-error-codes/guide.md | 2 +- .../attachment-error-codes/guide.zh.md | 2 +- packages/fs/tool-fs/README.i18n.yaml | 8 ++-- packages/fs/tool-fs/README.md | 4 +- packages/fs/tool-fs/README.zh.md | 4 +- packages/fs/tool-fs/src/image-error.ts | 22 ++------- packages/fs/tool-fs/src/read-image.ts | 46 ++++++++++-------- packages/fs/tool-fs/tests/read-image.spec.ts | 48 ++++++++++--------- 9 files changed, 67 insertions(+), 73 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml index 091cae83fa..66e712178e 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.i18n.yaml @@ -9,8 +9,8 @@ en: 4f2b2f0db0646d3b zh: 9467f41336a65c48 /attachment-failures-keep-their-codes/change: - en: daa5a93cf418a352 - zh: 3b391fbb4a87f2b1 + en: 0f8c05c401f15a7d + zh: adf5976a05802bf1 /attachment-failures-keep-their-codes/migration: en: 8599ead7a17bc7eb zh: 1120fd02065567f5 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md index 263ddf5df8..70acc07793 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.md @@ -12,7 +12,7 @@ English | [中文](guide.zh.md) `AttachmentError` from `@deepseek-ai/dsh-attachment` now extends `HarnessError` from `@deepseek-ai/dsh-error`. Its `name` (`AttachmentError`) and every `ATTACHMENT_*` and image admission code are unchanged. Two persisted results change: - When a model request fails because an adapter could not read an image attachment, the failed turn's `turn/end` error previously recorded `code: 'UNKNOWN'`. It now records the `AttachmentError` code, such as `ATTACHMENT_NOT_FOUND`, `ATTACHMENT_CORRUPT`, `ATTACHMENT_READ_FAILED`, or an image admission code such as `INVALID_IMAGE` or `IMAGE_TOO_LARGE`. -- A tool whose body lets an `AttachmentError` escape now records `error: { name: 'AttachmentError', code }` on its `tool/result`; previously the result had no `error`. `read_image` converts attachment failures to `ImageInputError` codes instead. +- A tool whose body lets an `AttachmentError` escape now records `error: { name: 'AttachmentError', code }` on its `tool/result`; previously the result had no `error`. `read_image` also records the `AttachmentError` code and names the file and the next step in the message. `instanceof HarnessError` now matches `AttachmentError`. `isAttachmentError` is unchanged. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md index 674f00805b..7c00e63528 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/attachment-error-codes/guide.zh.md @@ -12,7 +12,7 @@ description: "AttachmentError 现在继承 HarnessError,工具失败与模型 `@deepseek-ai/dsh-attachment` 的 `AttachmentError` 现在继承 `@deepseek-ai/dsh-error` 中的 `HarnessError`。其 `name`(`AttachmentError`)以及所有 `ATTACHMENT_*` 与图像准入错误码均保持不变。两类持久化结果会变化: - 适配器无法读取图像附件而导致模型请求失败时,失败 turn 的 `turn/end` 错误过去记录 `code: 'UNKNOWN'`。现在记录 `AttachmentError` 的错误码,例如 `ATTACHMENT_NOT_FOUND`、`ATTACHMENT_CORRUPT`、`ATTACHMENT_READ_FAILED`,或 `INVALID_IMAGE`、`IMAGE_TOO_LARGE` 等图像准入错误码。 -- 工具主体让 `AttachmentError` 逸出时,其 `tool/result` 现在记录 `error: { name: 'AttachmentError', code }`;过去结果中没有 `error`。`read_image` 则把附件失败转换为 `ImageInputError` 错误码。 +- 工具主体让 `AttachmentError` 逸出时,其 `tool/result` 现在记录 `error: { name: 'AttachmentError', code }`;过去结果中没有 `error`。`read_image` 同样记录 `AttachmentError` 的错误码,并在消息中写明文件与下一步。 `instanceof HarnessError` 现在会匹配 `AttachmentError`。`isAttachmentError` 不变。 diff --git a/packages/fs/tool-fs/README.i18n.yaml b/packages/fs/tool-fs/README.i18n.yaml index e8c96ec826..f9d9c8ac82 100644 --- a/packages/fs/tool-fs/README.i18n.yaml +++ b/packages/fs/tool-fs/README.i18n.yaml @@ -30,8 +30,8 @@ en: 9bddebaf4aff0a8d zh: fea0196162e3fcd1 /deepseek-ai-dsh-tool-fs/use-this-package/failures-and-recovery: - en: 06fe9bd1d49c1d53 - zh: a8a6963daae11267 + en: 4e33f0736e64c72b + zh: b7a0f2386760e08e /deepseek-ai-dsh-tool-fs/understand-the-implementation: en: e30f7038c28e93f8 zh: a3868dbd90367b13 @@ -39,8 +39,8 @@ en: 1f4d7213aa3d0d60 zh: aa6573f96c8b5220 /deepseek-ai-dsh-tool-fs/understand-the-implementation/source-map: - en: 791043de5ce46710 - zh: c5315d0195908f83 + en: 8be089bfe40bb7ab + zh: 7753de2feca62205 /deepseek-ai-dsh-tool-fs/understand-the-implementation/per-tool-flow: en: 35fbee1ef9811806 zh: 17c725e2b742c073 diff --git a/packages/fs/tool-fs/README.md b/packages/fs/tool-fs/README.md index cf3ef031df..93985eeb21 100644 --- a/packages/fs/tool-fs/README.md +++ b/packages/fs/tool-fs/README.md @@ -83,7 +83,7 @@ With the policy plugin mounted, `write` and `edit` obtain their guard from the ` For `apply_patch`, syntax and preflight refusals throw with `isError: true` before any disk change. `FsError` preserves filesystem codes; `PatchToolError extends HarnessError` carries `PATCH_SYNTAX` and `PATCH_SYMLINK_SOURCE`. Once commit starts, the tool returns a value with `isError: false` even on failure or uncertainty, so known partial effects retain their diff metadata; a call cancelled during commit receives the tool registry's abort result like every other tool, and its completed changes remain visible through Review. `phase`, `cancelled`, ordered `operations` and `affectedPaths` describe the commit; each operation retains its index, kind, display paths, patch line, status, diagnostic and known changes. Full `before`/`after` text serves rendering and PTC; the Session stores the rendered result plus `meta.diffs` and `meta.stopped`. Creations store no diff, as for `write`; deletions and move sources store a removal diff only when the provider returned a bounded basis, using `newText: ''` because `FileDiff.newText` cannot be null. -`read_image` refusals throw `ImageInputError extends HarnessError` with an `ImageInputErrorCode`: `IMAGE_UNSUPPORTED_MODEL` (switch to an image-capable model), `IMAGE_UNSUPPORTED_FORMAT` (the extension, file signature, or deployment media types exclude the format; convert the file), `IMAGE_TYPE_MISMATCH` (rename or convert the file), `IMAGE_INVALID` (truncated or corrupt bytes), `IMAGE_TOO_LARGE` (downscale the image), `IMAGE_CONVERSION_FAILED` (a 16-bit PNG could not be normalized; convert it to 8-bit), and `IMAGE_STORE_FAILED` (any other attachment-store failure, kept as `cause`). An empty `file_path` throws `ToolArgsError` (`INVALID_ARGS`); a missing attachment service or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`); filesystem failures keep their `FsError` codes; any store failure other than an `AttachmentError`, such as an `AbortError`, another `HarnessError`, or a defect, passes through unchanged. +`read_image` refusals it makes before storing the image throw `ImageInputError extends HarnessError` with an `ImageInputErrorCode`: `IMAGE_UNSUPPORTED_MODEL` (switch to an image-capable model) or `IMAGE_UNSUPPORTED_FORMAT` (the extension, file signature, or deployment media types exclude the format; convert the file). Refusals from the attachment store keep their `AttachmentError` `name` and `code`, such as `INVALID_IMAGE`, `IMAGE_TYPE_MISMATCH`, or `IMAGE_DIMENSION_TOO_LARGE`; for codes with a known remedy, the message names the file and the next step, and the store error is the `cause`. An empty `file_path` throws `ToolArgsError` (`INVALID_ARGS`); a missing attachment service or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`); filesystem failures keep their `FsError` codes; any other store failure, such as an `AbortError`, another `HarnessError`, or a defect, passes through unchanged. Failures are normalized as `Error: ` with a structured code preserved for callers. Stable messages include the `ToolArgsError` (`INVALID_ARGS`) messages `invalid arguments: file_path must be a non-empty string` and `invalid arguments: limit must be less than or equal to `, `cannot read "": not found`, `cannot read "": not a regular file`, and the image-route refusal `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`. `FS_NOT_OBSERVED` is normalized to `cannot modify "": file has not been read — read the file, then retry`, independent of whether the policy or provider rejected the operation; `FS_STALE_VERSION` retains the provider's reason and appends `— re-read the file, then retry`. After the reread confirms absence, `edit` reports `FS_NOT_FOUND` instead of repeating a stale remedy, while `write` uses guarded creation. @@ -108,7 +108,7 @@ The tools are the executor; policy is an event gate. The tools inject no policy | [`src/index.ts`](src/index.ts) | Plugin entry: `Config`, tool composition, `read_image` attachments gate | | [`src/read.ts`](src/read.ts) | `read` executor: one stat, streaming decision, window build, observation | | [`src/read-image.ts`](src/read-image.ts) | `read_image` executor: route and media-type gates, bounded bytes, attachment save | -| [`src/image-error.ts`](src/image-error.ts) | `ImageInputError` and its closed `read_image` failure codes | +| [`src/image-error.ts`](src/image-error.ts) | `ImageInputError` and the closed codes for refusals `read_image` makes itself | | [`src/write.ts`](src/write.ts) | `write` executor: intent waterfall, atomic write, observation | | [`src/apply-patch.ts`](src/apply-patch.ts), [`apply-patch-output.ts`](src/apply-patch-output.ts) | `apply_patch` registration, strict commit values and compact diagnostics | | [`src/apply-patch-presentation.ts`](src/apply-patch-presentation.ts) | Pure call previews and known result diffs | diff --git a/packages/fs/tool-fs/README.zh.md b/packages/fs/tool-fs/README.zh.md index 09af000f07..ec28bf145c 100644 --- a/packages/fs/tool-fs/README.zh.md +++ b/packages/fs/tool-fs/README.zh.md @@ -83,7 +83,7 @@ kind: "package-reference" `apply_patch` 的语法与预检拒绝在磁盘变更前抛错,结果为 `isError: true`。`FsError` 保留文件系统错误码;`PatchToolError extends HarnessError` 携带 `PATCH_SYNTAX` 和 `PATCH_SYMLINK_SOURCE`。进入提交后,即使失败或结果不确定也返回 `isError: false` 的值,确保已知部分效果的 diff 元数据得以保留;提交期间被取消的调用与其他工具一样收到工具注册表的中止结果,已完成的变更仍可通过 Review 查看。`phase`、`cancelled`、有序 `operations` 与 `affectedPaths` 描述提交;每条操作保留索引、种类、展示路径、补丁行号、状态、诊断与已知变更。完整 `before`/`after` 文本供渲染和 PTC 使用;Session 保存渲染文本以及 `meta.diffs` 与 `meta.stopped`。新建与 `write` 一样不保存 diff;删除与移动源仅在提供方返回有界基线时保存删除 diff,并使用 `newText: ''`,因为 `FileDiff.newText` 不可为 null。 -`read_image` 的拒绝抛出 `ImageInputError extends HarnessError`,错误码为 `ImageInputErrorCode`:`IMAGE_UNSUPPORTED_MODEL`(切换到支持图像的模型)、`IMAGE_UNSUPPORTED_FORMAT`(扩展名、文件签名或部署接受的媒体类型排除了该格式;转换文件)、`IMAGE_TYPE_MISMATCH`(重命名或转换文件)、`IMAGE_INVALID`(字节被截断或损坏)、`IMAGE_TOO_LARGE`(缩小图像)、`IMAGE_CONVERSION_FAILED`(16 位 PNG 无法规范化;转换为 8 位)以及 `IMAGE_STORE_FAILED`(其他附件存储失败,原错误保留为 `cause`)。空 `file_path` 抛出 `ToolArgsError`(`INVALID_ARGS`);缺少附件服务或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`);文件系统失败保留其 `FsError` 错误码;存储抛出的 `AttachmentError` 以外的失败(例如 `AbortError`、其他 `HarnessError` 或缺陷)原样传递。 +`read_image` 在存储图像前自行作出的拒绝抛出 `ImageInputError extends HarnessError`,错误码为 `ImageInputErrorCode`:`IMAGE_UNSUPPORTED_MODEL`(切换到支持图像的模型)或 `IMAGE_UNSUPPORTED_FORMAT`(扩展名、文件签名或部署接受的媒体类型排除了该格式;转换文件)。附件存储作出的拒绝保留其 `AttachmentError` 的 `name` 与 `code`,例如 `INVALID_IMAGE`、`IMAGE_TYPE_MISMATCH` 或 `IMAGE_DIMENSION_TOO_LARGE`;对有明确补救办法的错误码,消息会写明文件与下一步,存储错误作为 `cause`。空 `file_path` 抛出 `ToolArgsError`(`INVALID_ARGS`);缺少附件服务或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`);文件系统失败保留其 `FsError` 错误码;存储抛出的其他失败(例如 `AbortError`、其他 `HarnessError` 或缺陷)原样传递。 失败被规范化为 `Error: `,并为调用方保留结构化错误码。稳定消息包括 `ToolArgsError`(`INVALID_ARGS`)消息 `invalid arguments: file_path must be a non-empty string` 与 `invalid arguments: limit must be less than or equal to `、`cannot read "": not found`、`cannot read "": not a regular file`,以及图像路由拒绝 `cannot read "" as an image: model "" does not declare image input; switch to an image-capable model to read images`。无论拒绝来自策略还是提供方,`FS_NOT_OBSERVED` 都规范化为 `cannot modify "": file has not been read — read the file, then retry`;`FS_STALE_VERSION` 保留提供方原因并追加 `— re-read the file, then retry`。该次重新读取确认缺失后,`edit` 报告 `FS_NOT_FOUND` 而不会重复陈旧恢复指令,`write` 则使用防护创建。 @@ -108,7 +108,7 @@ kind: "package-reference" | [`src/index.ts`](src/index.ts) | 插件入口:`Config`、工具组合、`read_image` 附件门禁 | | [`src/read.ts`](src/read.ts) | `read` 执行器:一次 stat、流式决策、窗口构建、观察 | | [`src/read-image.ts`](src/read-image.ts) | `read_image` 执行器:路由与媒体类型门禁、有界字节、附件保存 | -| [`src/image-error.ts`](src/image-error.ts) | `ImageInputError` 及其封闭的 `read_image` 失败码 | +| [`src/image-error.ts`](src/image-error.ts) | `ImageInputError` 及 `read_image` 自行拒绝时使用的封闭错误码 | | [`src/write.ts`](src/write.ts) | `write` 执行器:意图 waterfall、原子写入、观察 | | [`src/apply-patch.ts`](src/apply-patch.ts)、[`apply-patch-output.ts`](src/apply-patch-output.ts) | `apply_patch` 注册、严格提交值与精简诊断 | | [`src/apply-patch-presentation.ts`](src/apply-patch-presentation.ts) | 纯调用预览与已知结果 diff | diff --git a/packages/fs/tool-fs/src/image-error.ts b/packages/fs/tool-fs/src/image-error.ts index a19a0b0f8d..ccacb48744 100644 --- a/packages/fs/tool-fs/src/image-error.ts +++ b/packages/fs/tool-fs/src/image-error.ts @@ -3,37 +3,23 @@ import { HarnessError } from '@deepseek-ai/dsh-error' /** - * Every machine-routable `read_image` failure code: + * Every `read_image` failure the tool classifies itself, before the attachment store sees the bytes: * * - `IMAGE_UNSUPPORTED_MODEL`: the calling route does not declare image input; switch to an image-capable model. * - `IMAGE_UNSUPPORTED_FORMAT`: the extension, the file signature, or the deployment's accepted media types * exclude the format; convert the file to an accepted format or read another file. - * - `IMAGE_TYPE_MISMATCH`: the extension or file signature declares one format but the bytes decode as another; rename or convert the file. - * - `IMAGE_INVALID`: bytes in a supported format do not decode; the file is truncated or corrupt. - * - `IMAGE_TOO_LARGE`: a side, the decoded pixel count, or the stored byte budget exceeds the deployment limit; - * downscale the image and read the smaller copy. - * - `IMAGE_CONVERSION_FAILED`: a 16-bit PNG could not be normalized to 8-bit sRGB; convert it to an 8-bit format. - * - `IMAGE_STORE_FAILED`: the attachment store could not commit the image for another reason; report the cause - * instead of retrying unchanged. + * + * Failures the attachment store classifies keep their `AttachmentError` codes. */ export const IMAGE_INPUT_ERROR_CODES = [ 'IMAGE_UNSUPPORTED_MODEL', 'IMAGE_UNSUPPORTED_FORMAT', - 'IMAGE_TYPE_MISMATCH', - 'IMAGE_INVALID', - 'IMAGE_TOO_LARGE', - 'IMAGE_CONVERSION_FAILED', - 'IMAGE_STORE_FAILED', ] as const /** One `read_image` failure code. */ export type ImageInputErrorCode = typeof IMAGE_INPUT_ERROR_CODES[number] -/** - * Typed `read_image` failure; `code` is one of {@link IMAGE_INPUT_ERROR_CODES}. `IMAGE_TOO_LARGE` and - * `IMAGE_TYPE_MISMATCH` share their spelling with `AttachmentError` codes, so consumers route on `name` - * and `code` together, and code-only predicates such as `isAttachmentError` do not identify this class. - */ +/** Typed `read_image` failure; `code` is one of {@link IMAGE_INPUT_ERROR_CODES}. */ export class ImageInputError extends HarnessError { override readonly code: ImageInputErrorCode diff --git a/packages/fs/tool-fs/src/read-image.ts b/packages/fs/tool-fs/src/read-image.ts index 9f7d714ed6..be422b38aa 100644 --- a/packages/fs/tool-fs/src/read-image.ts +++ b/packages/fs/tool-fs/src/read-image.ts @@ -215,45 +215,49 @@ interface SaveFailureFacts { } /** - * Classify one `saveImage` rejection as the error `read_image` throws. - * Attachment admission codes become {@link ImageInputError} codes and other - * `AttachmentError` codes become `IMAGE_STORE_FAILED`, keeping the original as - * `cause`. The attachment store reports its own failures as `AttachmentError`, - * so any other value, including cancellation, passes through unchanged. + * Add the read path and the next step to one `saveImage` rejection. The attachment store + * classifies its own failures, so an `AttachmentError` keeps its `name` and `code` and only + * gains a message naming the file and remedy, with the original as `cause`; a code without + * a remedy, and any value that is not an `AttachmentError`, passes through unchanged. * @param error - the value `saveImage` rejected with. - * @param attachments - the store whose limits the refusal names. - * @param facts - the path and media-type facts the refusal names. + * @param attachments - the store whose limits the message names. + * @param facts - the path and media-type facts the message names. * @returns the error to throw from the tool body. */ function saveFailure(error: unknown, attachments: AttachmentStore, facts: SaveFailureFacts): unknown { - const { displayPath, extension, mediaType, sniffed } = facts - const refusal = (detail: string, code: ImageInputError['code']) => - new ImageInputError(`cannot read "${displayPath}": ${detail}`, code, { cause: error }) - const storeFailed = (detail: string) => refusal(`the attachment store could not save the image: ${detail}`, 'IMAGE_STORE_FAILED') if (!(error instanceof AttachmentError)) return error + const detail = saveFailureDetail(error, attachments, facts) + return detail === undefined + ? error + : new AttachmentError(`cannot read "${facts.displayPath}": ${detail}`, error.code, { cause: error }) +} + +/** The model-facing remedy for one attachment rejection, or undefined when the store message stands. */ +function saveFailureDetail(error: AttachmentError, attachments: AttachmentStore, facts: SaveFailureFacts): string | undefined { + const { extension, mediaType, sniffed } = facts // Size refusals stay recoverable tool errors: an oversized image must never // enter durable history, where it would ride every later model request past // provider-side dimension rejections. switch (error.code) { case 'IMAGE_DIMENSION_TOO_LARGE': - return refusal(`at least one image side exceeds the ${attachments.imageLimits.maxImageDimension}px limit; downscale the image and read the smaller copy`, 'IMAGE_TOO_LARGE') + return `at least one image side exceeds the ${attachments.imageLimits.maxImageDimension}px limit; downscale the image and read the smaller copy` case 'IMAGE_TOO_MANY_PIXELS': - return refusal(`the image exceeds the ${attachments.imageLimits.maxImagePixels}-pixel decoded-size limit; downscale the image and read the smaller copy`, 'IMAGE_TOO_LARGE') + return `the image exceeds the ${attachments.imageLimits.maxImagePixels}-pixel decoded-size limit; downscale the image and read the smaller copy` case 'IMAGE_TOO_LARGE': case 'IMAGES_TOO_LARGE': - return refusal('the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy', 'IMAGE_TOO_LARGE') + return 'the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy' case 'UNSUPPORTED_IMAGE_TYPE': - return refusal(`${mediaType} images are not accepted by this deployment`, 'IMAGE_UNSUPPORTED_FORMAT') + return `${mediaType} images are not accepted by this deployment` case 'INVALID_IMAGE': - return refusal('the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt', 'IMAGE_INVALID') + return 'the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt' case 'IMAGE_TYPE_MISMATCH': return sniffed - ? refusal(`the file signature claims ${mediaType}, but the bytes decode as a different image format; the file may be corrupt`, 'IMAGE_TYPE_MISMATCH') - : refusal(`the ${extension} extension declares ${mediaType}, but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats`, 'IMAGE_TYPE_MISMATCH') + ? `the file signature claims ${mediaType}, but the bytes decode as a different image format; the file may be corrupt` + : `the ${extension} extension declares ${mediaType}, but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats` case 'ATTACHMENT_WRITE_FAILED': return /16-bit PNG/iu.test(error.message) - ? refusal('the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry', 'IMAGE_CONVERSION_FAILED') - : storeFailed(error.message) + ? 'the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry' + : undefined case 'TOO_MANY_IMAGES': case 'INVALID_IMAGE_BASE64': case 'INVALID_FILE_BASE64': @@ -263,7 +267,7 @@ function saveFailure(error: unknown, attachments: AttachmentStore, facts: SaveFa case 'ATTACHMENT_READ_FAILED': case 'ATTACHMENT_PROJECTION_UNSUPPORTED': case 'ATTACHMENT_FILES_UNSUPPORTED': - return storeFailed(error.message) + return undefined /* v8 ignore next -- Closed AttachmentErrorCode union; assertNever checks exhaustiveness at compile time. */ default: return assertNever(error.code) diff --git a/packages/fs/tool-fs/tests/read-image.spec.ts b/packages/fs/tool-fs/tests/read-image.spec.ts index bced7b466e..a55bb1c717 100644 --- a/packages/fs/tool-fs/tests/read-image.spec.ts +++ b/packages/fs/tool-fs/tests/read-image.spec.ts @@ -397,7 +397,7 @@ describe('extension-less paths', () => { const result = await readImage(ctx, { file_path: 'broken' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('do not decode as a supported PNG/JPEG/WebP/GIF image') - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_INVALID' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'INVALID_IMAGE' }) }) it('applies the deployment media-type policy to the sniffed format', async () => { @@ -463,7 +463,7 @@ describe('extension-less paths', () => { const result = await readImage(ctx, { file_path: 'sniffed' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('the file signature claims image/png, but the bytes decode as a different image format') - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TYPE_MISMATCH' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'IMAGE_TYPE_MISMATCH' }) }) }) @@ -593,7 +593,7 @@ describe('image admission failures', () => { expect(result.isError).toBe(true) expect(text(result)).toContain('the .jpg extension declares image/jpeg') expect(text(result)).toContain('rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats') - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TYPE_MISMATCH' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'IMAGE_TYPE_MISMATCH' }) }) it('caps an extension-less read at maxImageBytes before format detection', async () => { @@ -620,7 +620,7 @@ describe('image admission failures', () => { const result = await readImage(ctx, { file_path: 'big.png' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('exceeds the 4-pixel decoded-size limit') - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TOO_LARGE' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'IMAGE_TOO_MANY_PIXELS' }) expect(text(result)).toContain('downscale the image and read the smaller copy') }) @@ -630,7 +630,7 @@ describe('image admission failures', () => { const result = await readImage(ctx, { file_path: 'wide.png' }, agentOn('vision-model')) expect(result.isError).toBe(true) expect(text(result)).toContain('at least one image side exceeds the 2px limit') - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_TOO_LARGE' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'IMAGE_DIMENSION_TOO_LARGE' }) expect(text(result)).toContain('downscale the image and read the smaller copy') }) @@ -674,31 +674,35 @@ describe('image admission failures', () => { } it.each([ - ['IMAGE_TOO_LARGE', 'Image cannot be encoded within the configured normalized-image byte cap.', 'IMAGE_TOO_LARGE', + ['IMAGE_TOO_LARGE', 'Image cannot be encoded within the configured normalized-image byte cap.', 'the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy'], - ['IMAGES_TOO_LARGE', 'Image batch exceeds the configured aggregate image-byte limit.', 'IMAGE_TOO_LARGE', + ['IMAGES_TOO_LARGE', 'Image batch exceeds the configured aggregate image-byte limit.', 'the image cannot be stored within the deployment\'s byte limits; downscale the image and read the smaller copy'], - ['UNSUPPORTED_IMAGE_TYPE', 'Image type image/png is not accepted by this deployment.', 'IMAGE_UNSUPPORTED_FORMAT', + ['UNSUPPORTED_IMAGE_TYPE', 'Image type image/png is not accepted by this deployment.', 'image/png images are not accepted by this deployment'], - ['INVALID_IMAGE', 'Unsupported or malformed image data.', 'IMAGE_INVALID', + ['INVALID_IMAGE', 'Unsupported or malformed image data.', 'the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt'], - ['ATTACHMENT_WRITE_FAILED', 'The 16-bit PNG could not be converted to the normalized 8-bit sRGB form.', 'IMAGE_CONVERSION_FAILED', + ['ATTACHMENT_WRITE_FAILED', 'The 16-bit PNG could not be converted to the normalized 8-bit sRGB form.', 'the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry'], - ['ATTACHMENT_WRITE_FAILED', 'Unable to persist attachment.', 'IMAGE_STORE_FAILED', - 'the attachment store could not save the image: Unable to persist attachment.'], - ...([ - 'TOO_MANY_IMAGES', 'INVALID_IMAGE_BASE64', 'INVALID_FILE_BASE64', 'INVALID_ATTACHMENT_REF', 'ATTACHMENT_CORRUPT', - 'ATTACHMENT_NOT_FOUND', 'ATTACHMENT_READ_FAILED', 'ATTACHMENT_PROJECTION_UNSUPPORTED', 'ATTACHMENT_FILES_UNSUPPORTED', - ] as const).map(code => [code, 'Stored attachment failed.', 'IMAGE_STORE_FAILED', - 'the attachment store could not save the image: Stored attachment failed.'] as const), - ] as const)('classifies AttachmentError %s (%s) as %s', async (attachmentCode, message, code, detail) => { - const cause = new AttachmentError(message, attachmentCode) + ] as const)('keeps AttachmentError %s and adds the read path and remedy', async (code, message, detail) => { + const cause = new AttachmentError(message, code) const result = await failingSave(() => cause) expect(result.isError).toBe(true) - expect(result.error?.info).toEqual({ name: 'ImageInputError', code }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code }) expect(text(result)).toBe(`Error: cannot read "${join(dir, 'red.png')}": ${detail}`) }) + it.each([ + 'ATTACHMENT_WRITE_FAILED', 'TOO_MANY_IMAGES', 'INVALID_IMAGE_BASE64', 'INVALID_FILE_BASE64', 'INVALID_ATTACHMENT_REF', + 'ATTACHMENT_CORRUPT', 'ATTACHMENT_NOT_FOUND', 'ATTACHMENT_READ_FAILED', 'ATTACHMENT_PROJECTION_UNSUPPORTED', + 'ATTACHMENT_FILES_UNSUPPORTED', + ] as const)('passes AttachmentError %s without a read remedy through unchanged', async (code) => { + const result = await failingSave(() => new AttachmentError('Stored attachment failed.', code)) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code }) + expect(text(result)).toBe('Error: Stored attachment failed.') + }) + it('passes a store defect, a classified HarnessError, and an AbortError through unchanged', async () => { const defect = await failingSave(() => new Error('unrelated infrastructure failure')) expect(defect.isError).toBe(true) @@ -726,13 +730,13 @@ describe('image admission failures', () => { expect(text(result)).not.toContain('cannot read') }) - it('classifies a save failure that is not cancellation even after the caller aborts', async () => { + it('keeps a save failure that is not cancellation even after the caller aborts', async () => { const controller = new AbortController() const result = await failingSave(() => { controller.abort() return new AttachmentError('Unable to persist attachment.', 'ATTACHMENT_WRITE_FAILED') }, 'red.png', controller.signal) - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_STORE_FAILED' }) + expect(result.error?.info).toEqual({ name: 'AttachmentError', code: 'ATTACHMENT_WRITE_FAILED' }) }) it('reports a missing image file and a directory target through the fs vocabulary', async () => {