From c2fd342d33cb214a1fb04e619496d395d044580e Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Fri, 6 Nov 2026 16:19:10 +0800 Subject: [PATCH] fix(fs): address review feedback on read_image and create errors - read_image converts only AttachmentError rejections from saveImage; any other value is a store defect or cancellation and propagates unchanged instead of becoming IMAGE_STORE_FAILED. - ImageInputError is no longer exported from the dsh-tool-fs entry, and its JSDoc notes that two codes share AttachmentError spellings. - str_replace_editor create maps a guarded-creation collision (FS_NOT_OBSERVED after a concurrent create) to FS_ALREADY_EXISTS. - The fs-local directory-swap test asserts FS_NOT_REGULAR_FILE exactly. - The attachment upgrade guide lists the full AttachmentErrorCode set instead of an ATTACHMENT_ prefix. - dsh-error dependency entries sit in sorted position. --- docs/config-catalog.md | 4 ++-- docs/config-catalog.zh.md | 4 ++-- .../attachment-error-codes/guide.i18n.yaml | 8 ++++---- .../attachment-error-codes/guide.md | 4 ++-- .../attachment-error-codes/guide.zh.md | 4 ++-- packages/fs/fs-local/tests/fsio.spec.ts | 2 +- packages/fs/tool-fs/README.i18n.yaml | 4 ++-- packages/fs/tool-fs/README.md | 2 +- packages/fs/tool-fs/README.zh.md | 2 +- packages/fs/tool-fs/package.json | 4 ++-- packages/fs/tool-fs/src/image-error.ts | 6 +++++- packages/fs/tool-fs/src/index.ts | 2 -- packages/fs/tool-fs/src/read-image.ts | 12 ++++-------- packages/fs/tool-fs/tests/read-image.spec.ts | 15 +++++---------- .../fs/tool-str-replace-editor/src/index.ts | 11 ++++++++--- .../tests/tools.spec.ts | 18 ++++++++++++++++++ 16 files changed, 59 insertions(+), 43 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 527e193db9..81170e9d3d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4155,7 +4155,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-fs` - `inject`: `tools` · `fs` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/fs/tool-fs/src/index.ts:29`](../packages/fs/tool-fs/src/index.ts) +- `source`: [`packages/fs/tool-fs/src/index.ts:27`](../packages/fs/tool-fs/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `Config` supplies the defaults). */ @@ -4460,7 +4460,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-str-replace-editor` - `inject`: `tools` · `fs` -- `source`: [`packages/fs/tool-str-replace-editor/src/index.ts:506`](../packages/fs/tool-str-replace-editor/src/index.ts) +- `source`: [`packages/fs/tool-str-replace-editor/src/index.ts:511`](../packages/fs/tool-str-replace-editor/src/index.ts) ```ts config-catalog /** Configuration for the string-replacement editor tool. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 76218f3d03..53619fd6e7 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4157,7 +4157,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-fs` - `inject`: `tools` · `fs` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/fs/tool-fs/src/index.ts:29`](../packages/fs/tool-fs/src/index.ts) +- `source`: [`packages/fs/tool-fs/src/index.ts:27`](../packages/fs/tool-fs/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `Config` supplies the defaults). */ @@ -4462,7 +4462,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-str-replace-editor` - `inject`: `tools` · `fs` -- `source`: [`packages/fs/tool-str-replace-editor/src/index.ts:506`](../packages/fs/tool-str-replace-editor/src/index.ts) +- `source`: [`packages/fs/tool-str-replace-editor/src/index.ts:511`](../packages/fs/tool-str-replace-editor/src/index.ts) ```ts config-catalog /** Configuration for the string-replacement editor tool. */ 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 07aac6cd05..091cae83fa 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: 1e5560d944ebe67d - zh: 235f3ec670b01ae2 + en: daa5a93cf418a352 + zh: 3b391fbb4a87f2b1 /attachment-failures-keep-their-codes/migration: - en: bceb35b3d8c551c4 - zh: e865e7752bec8d13 + 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 8c416e5537..263ddf5df8 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 @@ -11,13 +11,13 @@ 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 attachment code, such as `ATTACHMENT_NOT_FOUND`, `ATTACHMENT_CORRUPT`, or `ATTACHMENT_READ_FAILED`. +- 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. `instanceof HarnessError` now matches `AttachmentError`. `isAttachmentError` is unchanged. ## Migration -1. If analytics or retry rules treat `UNKNOWN` model failures as a catch-all, add the attachment codes or route them by their `ATTACHMENT_` prefix. +1. If analytics or retry rules treat `UNKNOWN` model failures as a catch-all, add the codes of the exported `AttachmentErrorCode` type; in code, identify these failures with `isAttachmentError`. The codes do not share one prefix. 2. If code catches `HarnessError` before `AttachmentError`, move the `AttachmentError` check first wherever the two need different handling. 3. Earlier Session logs keep `UNKNOWN`; readers that compare old and new logs should treat both as the same failure class for attachment reads. 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 3b9ab5145e..674f00805b 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 @@ -11,13 +11,13 @@ description: "AttachmentError 现在继承 HarnessError,工具失败与模型 `@deepseek-ai/dsh-attachment` 的 `AttachmentError` 现在继承 `@deepseek-ai/dsh-error` 中的 `HarnessError`。其 `name`(`AttachmentError`)以及所有 `ATTACHMENT_*` 与图像准入错误码均保持不变。两类持久化结果会变化: -- 适配器无法读取图像附件而导致模型请求失败时,失败 turn 的 `turn/end` 错误过去记录 `code: 'UNKNOWN'`。现在记录附件错误码,例如 `ATTACHMENT_NOT_FOUND`、`ATTACHMENT_CORRUPT` 或 `ATTACHMENT_READ_FAILED`。 +- 适配器无法读取图像附件而导致模型请求失败时,失败 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` 错误码。 `instanceof HarnessError` 现在会匹配 `AttachmentError`。`isAttachmentError` 不变。 ## 迁移 -1. 如果分析或重试规则把 `UNKNOWN` 模型失败当作兜底类别,请加入这些附件错误码,或按 `ATTACHMENT_` 前缀路由。 +1. 如果分析或重试规则把 `UNKNOWN` 模型失败当作兜底类别,请加入导出类型 `AttachmentErrorCode` 中的错误码;代码中用 `isAttachmentError` 识别这些失败。这些错误码没有统一前缀。 2. 如果代码先捕获 `HarnessError` 再捕获 `AttachmentError`,在两者需要不同处理的地方把 `AttachmentError` 检查移到前面。 3. 较早的 Session 日志仍保留 `UNKNOWN`;对比新旧日志的读取方应把附件读取的这两种记录视为同一类失败。 diff --git a/packages/fs/fs-local/tests/fsio.spec.ts b/packages/fs/fs-local/tests/fsio.spec.ts index 980f7a722c..4d4f9a3748 100644 --- a/packages/fs/fs-local/tests/fsio.spec.ts +++ b/packages/fs/fs-local/tests/fsio.spec.ts @@ -1058,7 +1058,7 @@ describe('Node errno classification', () => { }, }).then(() => undefined, (caught: unknown) => caught) expect(failure).toBeInstanceOf(FsError) - expect(['FS_NOT_REGULAR_FILE', 'FS_IO_ERROR']).toContain((failure as FsError).code) + expect(failure).toMatchObject({ name: 'FsError', code: 'FS_NOT_REGULAR_FILE', cause: expect.objectContaining({ code: 'EISDIR' }) as Error }) }) it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('maps unreadable file content to FS_PERMISSION_DENIED', async () => { diff --git a/packages/fs/tool-fs/README.i18n.yaml b/packages/fs/tool-fs/README.i18n.yaml index 15125f4f7e..e8c96ec826 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: 177d25a1e8f7afbd - zh: 0303980d6b2789c3 + en: 06fe9bd1d49c1d53 + zh: a8a6963daae11267 /deepseek-ai-dsh-tool-fs/understand-the-implementation: en: e30f7038c28e93f8 zh: a3868dbd90367b13 diff --git a/packages/fs/tool-fs/README.md b/packages/fs/tool-fs/README.md index d7e519d577..cf3ef031df 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; an `AbortError` or another `HarnessError` from the store passes through unchanged. +`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. 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. diff --git a/packages/fs/tool-fs/README.zh.md b/packages/fs/tool-fs/README.zh.md index 7e81223b57..09af000f07 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` 错误码;存储抛出的 `AbortError` 或其他 `HarnessError` 原样传递。 +`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` 或缺陷)原样传递。 失败被规范化为 `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` 则使用防护创建。 diff --git a/packages/fs/tool-fs/package.json b/packages/fs/tool-fs/package.json index 7c33681fa8..e49dad494a 100644 --- a/packages/fs/tool-fs/package.json +++ b/packages/fs/tool-fs/package.json @@ -39,8 +39,8 @@ "@deepseek-ai/dsh-util-values": "workspace:*" }, "peerDependencies": { - "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-sandbox": "workspace:*", @@ -53,11 +53,11 @@ "@deepseek-ai/dsh-working-directory": "workspace:*" }, "devDependencies": { - "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-agent-loop": "workspace:*", "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-fs-observation-policy": "workspace:*", diff --git a/packages/fs/tool-fs/src/image-error.ts b/packages/fs/tool-fs/src/image-error.ts index b9839110fc..a19a0b0f8d 100644 --- a/packages/fs/tool-fs/src/image-error.ts +++ b/packages/fs/tool-fs/src/image-error.ts @@ -29,7 +29,11 @@ export const IMAGE_INPUT_ERROR_CODES = [ /** 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}. */ +/** + * 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. + */ export class ImageInputError extends HarnessError { override readonly code: ImageInputErrorCode diff --git a/packages/fs/tool-fs/src/index.ts b/packages/fs/tool-fs/src/index.ts index 9e3e3095d5..41e3be251c 100644 --- a/packages/fs/tool-fs/src/index.ts +++ b/packages/fs/tool-fs/src/index.ts @@ -17,8 +17,6 @@ import { applyReadImageTool } from './read-image.ts' import { READ_MAX_BYTES, READ_MAX_LINE_LENGTH } from './read-render.ts' import { FsSandboxController } from './sandbox.ts' -export { ImageInputError, type ImageInputErrorCode } from './image-error.ts' - /** Cordis plugin name used by loader diagnostics. */ export const name = 'tool-fs' diff --git a/packages/fs/tool-fs/src/read-image.ts b/packages/fs/tool-fs/src/read-image.ts index 159cb2409c..9f7d714ed6 100644 --- a/packages/fs/tool-fs/src/read-image.ts +++ b/packages/fs/tool-fs/src/read-image.ts @@ -16,7 +16,6 @@ import type { Context } from '@deepseek-ai/cordis' import { AttachmentError, AttachmentId } from '@deepseek-ai/dsh-attachment' import type { AttachmentStore, ImageAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment' import type { ContentBlock } from '@deepseek-ai/dsh-llm' -import { HarnessError } from '@deepseek-ai/dsh-error' import { defineTool, ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools' import type { GenericCallView, ToolExecution } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-fs' @@ -218,9 +217,9 @@ 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`; any other `HarnessError` - * and an `AbortError` pass through unchanged; every other failure becomes - * `IMAGE_STORE_FAILED`. Converted errors keep the original as `cause`. + * `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. * @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. @@ -231,10 +230,7 @@ function saveFailure(error: unknown, attachments: AttachmentStore, facts: SaveFa 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)) { - if (error instanceof HarnessError || (error instanceof Error && error.name === 'AbortError')) return error - return storeFailed(error instanceof Error ? error.message : String(error)) - } + if (!(error instanceof AttachmentError)) return error // 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. diff --git a/packages/fs/tool-fs/tests/read-image.spec.ts b/packages/fs/tool-fs/tests/read-image.spec.ts index 6c2feac7a4..bced7b466e 100644 --- a/packages/fs/tool-fs/tests/read-image.spec.ts +++ b/packages/fs/tool-fs/tests/read-image.spec.ts @@ -699,18 +699,13 @@ describe('image admission failures', () => { expect(text(result)).toBe(`Error: cannot read "${join(dir, 'red.png')}": ${detail}`) }) - it('wraps a non-attachment save failure as IMAGE_STORE_FAILED', async () => { - const result = await failingSave(() => new Error('unrelated infrastructure failure')) - expect(result.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_STORE_FAILED' }) - expect(text(result)).toBe(`Error: cannot read "${join(dir, 'red.png')}": the attachment store could not save the image: unrelated infrastructure failure`) + 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) + expect(defect.error?.info).toBeUndefined() + expect(text(defect)).toBe('Error: unrelated infrastructure failure') - const nonError = await failingSave(() => 'string failure') - expect(nonError.error?.info).toEqual({ name: 'ImageInputError', code: 'IMAGE_STORE_FAILED' }) - expect(text(nonError)).toContain('the attachment store could not save the image: string failure') - }) - - it('passes a classified HarnessError and an AbortError through unchanged', async () => { const fsFailure = await failingSave(() => new FsError('cannot read "x": permission denied', 'FS_PERMISSION_DENIED')) expect(fsFailure.error?.info).toEqual({ name: 'FsError', code: 'FS_PERMISSION_DENIED' }) expect(text(fsFailure)).toBe('Error: cannot read "x": permission denied') diff --git a/packages/fs/tool-str-replace-editor/src/index.ts b/packages/fs/tool-str-replace-editor/src/index.ts index 099d1a6d73..fa3c5a74e6 100644 --- a/packages/fs/tool-str-replace-editor/src/index.ts +++ b/packages/fs/tool-str-replace-editor/src/index.ts @@ -248,9 +248,12 @@ async function createFile( const content = requiredForCommand(fileText, 'file_text', 'create') const sandboxPolicy = policy.resolve(exec) const target = await resolveTarget(ctx, path, exec.signal) - if (await ctx.fs.stat(target, exec.signal) !== undefined) { - throw new FsError(`File already exists at: ${target.displayPath}. Cannot overwrite files using command \`create\`.`, 'FS_ALREADY_EXISTS') - } + const alreadyExists = (cause?: FsError) => new FsError( + `File already exists at: ${target.displayPath}. Cannot overwrite files using command \`create\`.`, + 'FS_ALREADY_EXISTS', + cause === undefined ? undefined : { cause }, + ) + if (await ctx.fs.stat(target, exec.signal) !== undefined) throw alreadyExists() const intent = await ctx.waterfall( 'fs/write-intent', target, @@ -267,6 +270,8 @@ async function createFile( sandboxPolicy, ) } catch (error: unknown) { + // A file created after the absence check makes guarded creation report it as unread. + if (error instanceof FsError && error.code === 'FS_NOT_OBSERVED') throw alreadyExists(error) throw policy.mapError(error, sandboxPolicy) } ctx.emit('fs/observed', target, { kind: 'present', version: outcome.version }, exec) diff --git a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts index e08c539c59..d780b856fb 100644 --- a/packages/fs/tool-str-replace-editor/tests/tools.spec.ts +++ b/packages/fs/tool-str-replace-editor/tests/tools.spec.ts @@ -632,6 +632,24 @@ describe('tool-str-replace-editor', () => { .rejects.toThrow('the mounted filesystem confines but ctx.sandboxPolicy is missing') }) + it('reports a file created after the absence check as FS_ALREADY_EXISTS', async () => { + const { ctx, root, owner } = await setup() + const path = join(root, 'raced.txt') + await writeFile(path, 'concurrent') + const stat = ctx.fs.stat.bind(ctx.fs) + let first = true + ctx.fs.stat = async (target, signal) => { + if (!first) return stat(target, signal) + first = false + return undefined + } + const result = await call(ctx, owner, { command: 'create', path, file_text: 'mine' }) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'FsError', code: 'FS_ALREADY_EXISTS' }) + expect(text(result)).toContain(`File already exists at: ${path}`) + expect(await readFile(path, 'utf8')).toBe('concurrent') + }) + it('maps unexpected backend write failures for replace and insert', async () => { const { ctx, root, owner } = await setup() const path = join(root, 'backend-error.txt')