From 08c155e145a0be72728cfb856fc7705b6919b4b4 Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Mon, 9 Nov 2026 15:27:37 +0800 Subject: [PATCH] refactor(office): record structured error name and code for Office tool failures Office tool failures now throw HarnessError subclasses so tool/result keeps error.name and error.code: - OfficeKitError failures map to OfficeToolError OFFICE_* codes at the tool boundary, keeping the OfficeKitError as cause. - A model route without image input is OfficeToolError MODEL_DOES_NOT_SUPPORT_IMAGES; oversized images are OFFICE_OUTPUT_TOO_LARGE; a remote workspace is OFFICE_UNSUPPORTED_REMOTE_WORKSPACE. - Missing Agent, attachment store, or model route is ToolContextUnavailableError. - Missing or non-regular inputs are FsError FS_NOT_FOUND / FS_NOT_REGULAR_FILE. - Hand-checked argument rules are ToolArgsError INVALID_ARGS. - Attachment store refusals keep their AttachmentError code. Refs #7869 --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/module-graph.md | 3 +- docs/module-graph.zh.md | 3 +- packages/document/office-kit/README.i18n.yaml | 4 +- packages/document/office-kit/README.md | 2 +- packages/document/office-kit/README.zh.md | 2 +- packages/document/office-kit/src/errors.ts | 6 +- .../document/tool-office/README.i18n.yaml | 4 +- packages/document/tool-office/README.md | 2 + packages/document/tool-office/README.zh.md | 2 + packages/document/tool-office/package.json | 2 + packages/document/tool-office/src/error.ts | 75 ++++++++++ packages/document/tool-office/src/formats.ts | 33 ++--- packages/document/tool-office/src/index.ts | 40 ++++-- .../tool-office/tests/tool-office.spec.ts | 129 +++++++++++++----- packages/document/tool-office/tsconfig.json | 3 + pnpm-lock.yaml | 3 + .../session.v4.jsonl | 2 +- 19 files changed, 240 insertions(+), 79 deletions(-) create mode 100644 packages/document/tool-office/src/error.ts diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7e0c8d57f9..fa07aeb7d5 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -4368,7 +4368,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-office` - `inject`: `tools` · `fs` · `workingDirectory` · `agents` -- `source`: [`packages/document/tool-office/src/index.ts:38`](../packages/document/tool-office/src/index.ts) +- `source`: [`packages/document/tool-office/src/index.ts:41`](../packages/document/tool-office/src/index.ts) ```ts config-catalog /** Activation skills and render bounds; lower deployment attachment limits take precedence. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index a91edffcf0..2964d32a2d 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -4370,7 +4370,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-office` - `inject`: `tools` · `fs` · `workingDirectory` · `agents` -- `source`: [`packages/document/tool-office/src/index.ts:38`](../packages/document/tool-office/src/index.ts) +- `source`: [`packages/document/tool-office/src/index.ts:41`](../packages/document/tool-office/src/index.ts) ```ts config-catalog /** Activation skills and render bounds; lower deployment attachment limits take precedence. */ diff --git a/docs/module-graph.md b/docs/module-graph.md index 7b28621265..dcfbb93654 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -1421,6 +1421,7 @@ flowchart TD pkg_session_reference --> pkg_typert_protocol pkg_tool_office --> pkg_agent pkg_tool_office --> pkg_attachment + pkg_tool_office --> pkg_error pkg_tool_office --> pkg_fs pkg_tool_office --> pkg_llm pkg_tool_office --> pkg_office_kit @@ -1904,7 +1905,7 @@ flowchart TD | [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | -| [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | | [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 4ddd93c256..a25a0eb15c 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -1423,6 +1423,7 @@ flowchart TD pkg_session_reference --> pkg_typert_protocol pkg_tool_office --> pkg_agent pkg_tool_office --> pkg_attachment + pkg_tool_office --> pkg_error pkg_tool_office --> pkg_fs pkg_tool_office --> pkg_llm pkg_tool_office --> pkg_office_kit @@ -1906,7 +1907,7 @@ flowchart TD | [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | -| [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | +| [`tool-office`](../packages/document/tool-office) | `document` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`office-kit`](../packages/document/office-kit), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-worktree`](../packages/experimental/worktree), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | | [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | diff --git a/packages/document/office-kit/README.i18n.yaml b/packages/document/office-kit/README.i18n.yaml index 8e1778a342..665f6ded47 100644 --- a/packages/document/office-kit/README.i18n.yaml +++ b/packages/document/office-kit/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: a134331a31395608 /deepseek-ai-dsh-office-kit/use-this-package: - en: 3a4b3e462240f493 - zh: 336f481e2f14b76b + en: ca507ba54f737e8c + zh: 010db793ed2e5206 /deepseek-ai-dsh-office-kit/understand-the-implementation: en: ddd81007f05f3065 zh: f103b2664f234f49 diff --git a/packages/document/office-kit/README.md b/packages/document/office-kit/README.md index 1d8ae9c885..effabfa25a 100644 --- a/packages/document/office-kit/README.md +++ b/packages/document/office-kit/README.md @@ -27,7 +27,7 @@ Render Office documents as PDFs or PNG images, convert them between formats, and The [Web bundle](../../bundle/web-app/README.md) and the [SDK bundle](../../bundle/sdk-app/README.md) mount this provider as `office-kit`; the [Office tools](../tool-office/README.md) are its model-facing consumers. Independent compositions mount `@deepseek-ai/dsh-office-kit` as a `cordis.yml` row. -Callers submit authorized source identity, version, optional byte size, a deferred bounded read, and input extension; PDF conversions also name a scheduling priority, and image rendering, format conversion, and recalculation run at foreground priority. A changed source version rejects the operation. Cancellation rejects with its reason; failures use `OfficeKitError`. Every result carries the missing fonts; PDF results also carry the conversion generation, which changes on configuration replacement. +Callers submit authorized source identity, version, optional byte size, a deferred bounded read, and input extension; PDF conversions also name a scheduling priority, and image rendering, format conversion, and recalculation run at foreground priority. A changed source version rejects the operation. Cancellation rejects with its reason; failures use `OfficeKitError`, whose lowercase `code` is also the `document-render/failed` reason; [`dsh-tool-office`](../tool-office/README.md#use-this-package) maps it to `OfficeToolError` codes for tool results. Every result carries the missing fonts; PDF results also carry the conversion generation, which changes on configuration replacement. | Method | Operation | Result | |---|---|---| diff --git a/packages/document/office-kit/README.zh.md b/packages/document/office-kit/README.zh.md index 5416322ec2..30ef4f4cf7 100644 --- a/packages/document/office-kit/README.zh.md +++ b/packages/document/office-kit/README.zh.md @@ -27,7 +27,7 @@ kind: "package-reference" [Web bundle](../../bundle/web-app/README.zh.md)和 [SDK bundle](../../bundle/sdk-app/README.zh.md)以 `office-kit` 条目挂载此提供方;[Office 工具](../tool-office/README.zh.md)是其面向模型的消费方。独立组合通过 `cordis.yml` 条目挂载 `@deepseek-ai/dsh-office-kit`。 -调用方提交已授权源的标识、版本、可选字节数、延迟的有界读取、输入扩展名;PDF 转换还指定调度优先级,图片渲染、格式转换和重算以前台优先级运行。源版本变化会拒绝操作。取消以原因为拒绝值,失败使用 `OfficeKitError`。每个结果都携带缺失字体;PDF 结果还携带转换 generation(配置替换后随之改变)。 +调用方提交已授权源的标识、版本、可选字节数、延迟的有界读取、输入扩展名;PDF 转换还指定调度优先级,图片渲染、格式转换和重算以前台优先级运行。源版本变化会拒绝操作。取消以原因为拒绝值,失败使用 `OfficeKitError`,其小写 `code` 也是 `document-render/failed` 的原因;[`dsh-tool-office`](../tool-office/README.zh.md#use-this-package) 在工具结果中把它映射为 `OfficeToolError` 的代码。每个结果都携带缺失字体;PDF 结果还携带转换 generation(配置替换后随之改变)。 | 方法 | 操作 | 结果 | |---|---|---| diff --git a/packages/document/office-kit/src/errors.ts b/packages/document/office-kit/src/errors.ts index a1ee9162e0..e3b750d7cb 100644 --- a/packages/document/office-kit/src/errors.ts +++ b/packages/document/office-kit/src/errors.ts @@ -1,7 +1,11 @@ /** Classified failures shared by conversion and its consumers. */ import type { OfficeKitErrorCode } from './types.ts' -/** Classified conversion failure; engine details stay in the cause. */ +/** + * Classified conversion failure; engine details stay in the cause. `code` is also the `document-render/failed` Remote + * reason the Office preview localizes, so it is not a `HarnessError` code; a consumer that records tool failures maps + * it to its own error class, as `dsh-tool-office` does with `OfficeToolError`. + */ export class OfficeKitError extends Error { /** * @param code - category suitable for a conversion consumer. diff --git a/packages/document/tool-office/README.i18n.yaml b/packages/document/tool-office/README.i18n.yaml index 83379974c7..06d5efe692 100644 --- a/packages/document/tool-office/README.i18n.yaml +++ b/packages/document/tool-office/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-tool-office/use-this-package: - en: 02382bf6886b4b4e - zh: c599bf4eae72e578 + en: 8e43235b282387a3 + zh: 9823ab293840422a /deepseek-ai-dsh-tool-office/understand-the-implementation: en: 05a32b4fde4d8c21 zh: f6ce05a11f5ccb6d diff --git a/packages/document/tool-office/README.md b/packages/document/tool-office/README.md index c1f95b59b5..d0f2aa8d30 100644 --- a/packages/document/tool-office/README.md +++ b/packages/document/tool-office/README.md @@ -52,6 +52,8 @@ Inputs resolve against the Session working directory and use the filesystem back Conversion and recalculation results name a file in the Office kit's private [output store](../office-kit/README.md#use-this-package) under the Harness home; the model copies it with the shell, so the shell's sandbox and approvals govern where it lands. When the filesystem backend cannot read Host files, such as an SSH workspace, these two tools fail before converting; rendering still works. +Failed calls record a structured `name` and `code` on `tool/result`. An Office kit failure becomes `OfficeToolError` with the matching `OfficeToolErrorCode` and keeps the `OfficeKitError` as `cause`: `OFFICE_UNAVAILABLE` (also for an absent Office service), `OFFICE_BUSY`, `OFFICE_INPUT_TOO_LARGE`, `OFFICE_OUTPUT_TOO_LARGE`, `OFFICE_INVALID_DOCUMENT`, `OFFICE_UNSUPPORTED_FORMAT`, `OFFICE_INVALID_REQUEST`, `OFFICE_INVALID_OUTPUT`, `OFFICE_TIMEOUT`, `OFFICE_SOURCE_CHANGED`, or `OFFICE_CONVERSION_FAILED` for the kit code `failed`. The tools also throw `OfficeToolError` with `OFFICE_OUTPUT_TOO_LARGE` for a rendered image above the store's per-image byte limit, `OFFICE_UNSUPPORTED_REMOTE_WORKSPACE` when the execution world cannot read conversion output, and `MODEL_DOES_NOT_SUPPORT_IMAGES` when the model route does not declare image input. Argument checks the schema cannot express, including an input extension the operation does not accept, throw `ToolArgsError` (`INVALID_ARGS`) with the message prefixed by `invalid arguments: `. A call outside an Agent step, a missing attachment store, or an unresolvable model route throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`). A missing input throws `FsError` `FS_NOT_FOUND`, a non-regular input `FS_NOT_REGULAR_FILE`, and other filesystem failures keep their `FsError` codes. An attachment store refusal keeps its `AttachmentError` code, with the operation and path prepended to the message. Other failures, including cancellation, pass through unchanged. + Every request enters the Office kit's shared queue with `foreground` priority, the same class as an open preview. Foreground work runs before background prewarming and can evict queued background jobs, so speculative previews cannot starve tool calls; tool calls and open previews share admission in arrival order. ----- diff --git a/packages/document/tool-office/README.zh.md b/packages/document/tool-office/README.zh.md index 6c2fcfb872..9dc215a874 100644 --- a/packages/document/tool-office/README.zh.md +++ b/packages/document/tool-office/README.zh.md @@ -52,6 +52,8 @@ kind: "package-reference" 转换和重算结果给出 Office 套件私有[输出存储](../office-kit/README.zh.md#use-this-package)中位于 Harness 主目录下的一个文件;模型用 shell 复制它,因此文件落在哪里由 shell 的沙箱和审批决定。文件系统后端无法读取 Host 文件时(例如 SSH 工作区),这两个工具在转换前即失败;渲染不受影响。 +失败的调用在 `tool/result` 上记录结构化的 `name` 和 `code`。Office 套件的失败转为带对应 `OfficeToolErrorCode` 的 `OfficeToolError`,并把 `OfficeKitError` 保留为 `cause`:`OFFICE_UNAVAILABLE`(Office 服务不存在时也是它)、`OFFICE_BUSY`、`OFFICE_INPUT_TOO_LARGE`、`OFFICE_OUTPUT_TOO_LARGE`、`OFFICE_INVALID_DOCUMENT`、`OFFICE_UNSUPPORTED_FORMAT`、`OFFICE_INVALID_REQUEST`、`OFFICE_INVALID_OUTPUT`、`OFFICE_TIMEOUT`、`OFFICE_SOURCE_CHANGED`,套件代码 `failed` 对应 `OFFICE_CONVERSION_FAILED`。工具自身也抛出 `OfficeToolError`:渲染出的图片超过存储的单图字节上限时为 `OFFICE_OUTPUT_TOO_LARGE`,执行环境读不到转换输出时为 `OFFICE_UNSUPPORTED_REMOTE_WORKSPACE`,模型路由未声明图片输入时为 `MODEL_DOES_NOT_SUPPORT_IMAGES`。schema 无法表达的参数检查(包括操作不接受的输入扩展名)抛出 `ToolArgsError`(`INVALID_ARGS`),消息带 `invalid arguments: ` 前缀。不在 Agent step 中调用、没有附件存储或无法解析模型路由时抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`)。输入不存在时抛出 `FsError` `FS_NOT_FOUND`,输入不是普通文件时为 `FS_NOT_REGULAR_FILE`,其他文件系统失败保留各自的 `FsError` 代码。附件存储的拒绝保留其 `AttachmentError` 代码,并在消息前加上操作和路径。其他失败(包括取消)原样传递。 + 每个请求都以 `foreground` 优先级进入 Office 套件的共享队列,与打开的预览同级。前台工作先于后台预热执行,并可驱逐排队中的后台任务,因此推测性预览不会饿死工具调用;工具调用与打开的预览按到达顺序共享准入。 ----- diff --git a/packages/document/tool-office/package.json b/packages/document/tool-office/package.json index 52aeb942e4..9ba2b63fd6 100644 --- a/packages/document/tool-office/package.json +++ b/packages/document/tool-office/package.json @@ -38,6 +38,7 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-office-kit": "workspace:*", @@ -52,6 +53,7 @@ "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-attachment-local": "workspace:*", + "@deepseek-ai/dsh-error": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", diff --git a/packages/document/tool-office/src/error.ts b/packages/document/tool-office/src/error.ts new file mode 100644 index 0000000000..fdeded07ba --- /dev/null +++ b/packages/document/tool-office/src/error.ts @@ -0,0 +1,75 @@ +/** Typed Office tool failures. @module @deepseek-ai/dsh-tool-office/src/error */ + +import { HarnessError } from '@deepseek-ai/dsh-error' +import type { OfficeKitErrorCode } from '@deepseek-ai/dsh-office-kit' + +/** + * Every Office tool failure this package classifies itself: + * + * - `OFFICE_UNAVAILABLE`: the Office service is not mounted, not installed, or was disposed; report it or retry later. + * - `OFFICE_BUSY`: the Office service reached its admission limit; retry after other document operations finish. + * - `OFFICE_INPUT_TOO_LARGE`: the source exceeds the input byte limit; use a smaller file. + * - `OFFICE_OUTPUT_TOO_LARGE`: the output or one rendered image exceeds a byte, count, or pixel limit; select fewer + * pages, a smaller range, or a lower dpi. + * - `OFFICE_INVALID_DOCUMENT`: the source cannot be opened as the declared document type. + * - `OFFICE_UNSUPPORTED_FORMAT`: the engine cannot read the source format or write the requested format. + * - `OFFICE_INVALID_REQUEST`: the engine rejected a page, sheet, range, resolution, or format selection; correct it. + * - `OFFICE_INVALID_OUTPUT`: the engine produced an unreadable or incomplete output. + * - `OFFICE_TIMEOUT`: the conversion exceeded its deadline. + * - `OFFICE_SOURCE_CHANGED`: the source changed after its read was authorized; retry on the current file. + * - `OFFICE_CONVERSION_FAILED`: the engine failed without a more specific class. + * - `OFFICE_UNSUPPORTED_REMOTE_WORKSPACE`: `office_convert` and `office_recalculate` cannot return a file the + * execution world reads, because the workspace is on a remote host. + * - `MODEL_DOES_NOT_SUPPORT_IMAGES`: the calling model route does not declare image input, so `office_render` cannot + * return images; switch to an image-capable model. The value matches the attachment refusal reason of the same + * name. + */ +export const OFFICE_TOOL_ERROR_CODES = [ + 'OFFICE_UNAVAILABLE', + 'OFFICE_BUSY', + 'OFFICE_INPUT_TOO_LARGE', + 'OFFICE_OUTPUT_TOO_LARGE', + 'OFFICE_INVALID_DOCUMENT', + 'OFFICE_UNSUPPORTED_FORMAT', + 'OFFICE_INVALID_REQUEST', + 'OFFICE_INVALID_OUTPUT', + 'OFFICE_TIMEOUT', + 'OFFICE_SOURCE_CHANGED', + 'OFFICE_CONVERSION_FAILED', + 'OFFICE_UNSUPPORTED_REMOTE_WORKSPACE', + 'MODEL_DOES_NOT_SUPPORT_IMAGES', +] as const + +/** One Office tool failure code. */ +export type OfficeToolErrorCode = typeof OFFICE_TOOL_ERROR_CODES[number] + +/** Tool failure code for each Office service failure code; the `OfficeKitError` stays the `cause`. */ +export const OFFICE_KIT_FAILURE_CODES: Readonly> = { + 'unavailable': 'OFFICE_UNAVAILABLE', + 'busy': 'OFFICE_BUSY', + 'input-too-large': 'OFFICE_INPUT_TOO_LARGE', + 'output-too-large': 'OFFICE_OUTPUT_TOO_LARGE', + 'invalid-document': 'OFFICE_INVALID_DOCUMENT', + 'unsupported-format': 'OFFICE_UNSUPPORTED_FORMAT', + 'invalid-request': 'OFFICE_INVALID_REQUEST', + 'invalid-output': 'OFFICE_INVALID_OUTPUT', + 'timeout': 'OFFICE_TIMEOUT', + 'source-changed': 'OFFICE_SOURCE_CHANGED', + 'failed': 'OFFICE_CONVERSION_FAILED', +} + +/** Typed Office tool failure; `code` is one of {@link OFFICE_TOOL_ERROR_CODES}. */ +export class OfficeToolError extends HarnessError { + override readonly code: OfficeToolErrorCode + + /** + * @param message - model-facing refusal naming the operation, the path, and the safe next step. + * @param code - stable failure code. + * @param options - standard `cause` chaining; an Office service failure keeps its `OfficeKitError`. + */ + constructor(message: string, code: OfficeToolErrorCode, options?: ErrorOptions) { + super(message, code, options) + this.name = 'OfficeToolError' + this.code = code + } +} diff --git a/packages/document/tool-office/src/formats.ts b/packages/document/tool-office/src/formats.ts index d544047aee..a1b796d706 100644 --- a/packages/document/tool-office/src/formats.ts +++ b/packages/document/tool-office/src/formats.ts @@ -4,6 +4,7 @@ */ import type { OfficeConversionFormat, OfficeRecalculationFormat } from '@deepseek-ai/dsh-office-kit' +import { ToolArgsError } from '@deepseek-ai/dsh-tools' /** Operation requested by one Office tool call. */ export type OfficeOperationName = 'render' | 'convert' | 'recalculate' @@ -62,7 +63,7 @@ export type OfficeToolName = 'office_render' | 'office_convert' | 'office_recalc * @param tool - called tool. * @param args - call arguments. * @param declared - parameter names of every Office tool. - * @throws Error naming the undeclared key and the Office tools that accept it. + * @throws ToolArgsError naming the undeclared key and the Office tools that accept it. */ export function checkParameterNames( tool: OfficeToolName, args: object, declared: Readonly>, @@ -70,7 +71,7 @@ export function checkParameterNames( for (const key of Object.keys(args)) { if (declared[tool].includes(key)) continue const owners = (Object.keys(declared) as OfficeToolName[]).filter(other => declared[other].includes(key)) - throw new Error(owners.length === 0 ? `${tool} does not accept ${key}` : `${key} applies only to ${owners.join(' or ')}`) + throw new ToolArgsError([owners.length === 0 ? `${tool} does not accept ${key}` : `${key} applies only to ${owners.join(' or ')}`]) } } @@ -90,18 +91,18 @@ export function extensionOf(path: string): string { * @param operation - requested operation. * @param path - input path whose extension names the format. * @returns the family the operation accepts. - * @throws Error naming the accepted formats when the operation does not accept this input. + * @throws ToolArgsError naming the accepted formats when the operation does not accept this input. */ export function inputFamily(operation: OfficeOperationName, path: string): OfficeFamily { const extension = extensionOf(path) const family = FAMILIES[extension] if (operation === 'recalculate') { - if (family !== 'spreadsheet') throw new Error(`cannot recalculate "${path}": recalculate accepts xls, xlsx, or ods workbooks`) + if (family !== 'spreadsheet') throw new ToolArgsError([`cannot recalculate "${path}": recalculate accepts xls, xlsx, or ods workbooks`]) return family } if (family === undefined || (family === 'pdf' && operation === 'convert')) { const accepted = operation === 'render' ? 'doc, docx, odt, xls, xlsx, ods, ppt, pptx, odp, or pdf' : 'doc, docx, odt, xls, xlsx, ods, ppt, pptx, or odp' - throw new Error(`cannot ${operation} "${path}": ${operation} accepts ${accepted} files`) + throw new ToolArgsError([`cannot ${operation} "${path}": ${operation} accepts ${accepted} files`]) } return family } @@ -110,21 +111,21 @@ export function inputFamily(operation: OfficeOperationName, path: string): Offic * Check render selections that the tool schema subset cannot express. * @param args - schema-validated call arguments. * @param family - input family selected by {@link inputFamily}. - * @throws Error naming the misplaced or malformed argument. + * @throws ToolArgsError naming the misplaced or malformed argument. */ export function checkRenderArguments(args: OfficeRenderArgs, family: OfficeFamily): void { if (args.pages !== undefined) { - if (family === 'spreadsheet') throw new Error('pages does not apply to spreadsheets; select sheet and range instead') + if (family === 'spreadsheet') throw new ToolArgsError(['pages does not apply to spreadsheets; select sheet and range instead']) if (args.pages.length === 0 || args.pages.some(page => !Number.isSafeInteger(page) || page < 1) || new Set(args.pages).size !== args.pages.length) { - throw new Error('pages must list distinct one-based page numbers') + throw new ToolArgsError(['pages must list distinct one-based page numbers']) } } - if (family !== 'spreadsheet' && args.sheet !== undefined) throw new Error('sheet applies only to spreadsheets') - if (args.range !== undefined && args.sheet === undefined) throw new Error('range requires sheet') - if (args.sheet !== undefined && args.sheet.trim() === '') throw new Error('sheet must be an exact worksheet name') + if (family !== 'spreadsheet' && args.sheet !== undefined) throw new ToolArgsError(['sheet applies only to spreadsheets']) + if (args.range !== undefined && args.sheet === undefined) throw new ToolArgsError(['range requires sheet']) + if (args.sheet !== undefined && args.sheet.trim() === '') throw new ToolArgsError(['sheet must be an exact worksheet name']) if (args.dpi !== undefined && (!Number.isSafeInteger(args.dpi) || args.dpi < 24 || args.dpi > 600)) { - throw new Error('dpi must be an integer from 24 to 600') + throw new ToolArgsError(['dpi must be an integer from 24 to 600']) } } @@ -132,13 +133,13 @@ export function checkRenderArguments(args: OfficeRenderArgs, family: OfficeFamil * Check conversion formats and worksheet selection against the input family. * @param args - schema-validated conversion arguments. * @param family - input family. - * @throws Error naming the formats available for this input. + * @throws ToolArgsError naming the formats available for this input. */ export function checkConversionArguments(args: OfficeConvertArgs, family: Exclude): void { const accepted = CONVERSION_OUTPUTS[family] if (!accepted.includes(args.format)) { - throw new Error(`cannot convert "${args.input}" to ${args.format}: this file converts to ${accepted.join(', ')}`) + throw new ToolArgsError([`cannot convert "${args.input}" to ${args.format}: this file converts to ${accepted.join(', ')}`]) } - if (args.sheet !== undefined && args.format !== 'csv') throw new Error('sheet applies only to CSV conversion') - if (args.sheet !== undefined && args.sheet.trim() === '') throw new Error('sheet must be an exact worksheet name') + if (args.sheet !== undefined && args.format !== 'csv') throw new ToolArgsError(['sheet applies only to CSV conversion']) + if (args.sheet !== undefined && args.sheet.trim() === '') throw new ToolArgsError(['sheet must be an exact worksheet name']) } diff --git a/packages/document/tool-office/src/index.ts b/packages/document/tool-office/src/index.ts index 000eb33d5a..b7fccf89c4 100644 --- a/packages/document/tool-office/src/index.ts +++ b/packages/document/tool-office/src/index.ts @@ -12,14 +12,14 @@ import { basename } from 'node:path' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import type { Agent } from '@deepseek-ai/dsh-agent' -import type { ImageAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment' -import type { FsInfo, FsTarget } from '@deepseek-ai/dsh-fs' +import { AttachmentError, type ImageAttachmentRef, type ImageMediaType } from '@deepseek-ai/dsh-attachment' +import { FsError, type FsInfo, type FsTarget } from '@deepseek-ai/dsh-fs' import type {} from '@deepseek-ai/dsh-llm' import { SubagentError } from '@deepseek-ai/dsh-subagent' import type {} from '@deepseek-ai/dsh-skill' import { OfficeKitError, OfficeSourceKey, type OfficeDocumentExtension, type OfficeImageInputExtension, type OfficeKit, type OfficeKitSource, type OfficeWorkbookExtension } from '@deepseek-ai/dsh-office-kit' -import { defineTool, type ToolActivationContext, type ToolExecution } from '@deepseek-ai/dsh-tools' +import { defineTool, ToolContextUnavailableError, type ToolActivationContext, type ToolExecution } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-working-directory' import { checkParameterNames, checkRenderArguments, checkConversionArguments, extensionOf, inputFamily, OUTPUT_FORMATS, RECALCULATION_FORMATS, @@ -27,6 +27,9 @@ import { checkParameterNames, checkRenderArguments, checkConversionArguments, ex type OfficeToolName } from './formats.ts' import { renderFileContent, renderImagesContent, type OfficeFileFormats, type OfficeFileValue, type OfficeRenderValue } from './content.ts' +import { OFFICE_KIT_FAILURE_CODES, OfficeToolError } from './error.ts' + +export { OfficeToolError, type OfficeToolErrorCode } from './error.ts' /** Cordis plugin name used by Loader diagnostics. */ export const name = 'tool-office' @@ -225,7 +228,7 @@ export function apply(ctx: Context, config: Config): void { async function prepareInput(ctx: Context, exec: ToolExecution, operation: OfficeOperationName, input: string) { const { agent, signal } = exec // Conditional registrations execute only through a step tool set, which the calling Agent resolves. - if (agent === undefined) throw new Error(`cannot ${operation} "${input}": Office tools run only in an Agent step`) + if (agent === undefined) throw new ToolContextUnavailableError(`cannot ${operation} "${input}": Office tools run only in an Agent step`) const kit = ctx.get('officeKit') if (kit === undefined) { throw officeFailure(operation, input, new OfficeKitError('unavailable', 'The document converter is unavailable.')) @@ -244,8 +247,8 @@ async function readableInput( ): Promise<{ target: FsTarget; info: FsInfo }> { const target = await ctx.fs.resolve(path, options) const info = await ctx.fs.stat(target, options.signal) - if (info === undefined) throw new Error(`cannot read "${target.displayPath}": not found`) - if (info.type !== 'file') throw new Error(`cannot read "${target.displayPath}": not a regular file`) + if (info === undefined) throw new FsError(`cannot read "${target.displayPath}": not found`, 'FS_NOT_FOUND') + if (info.type !== 'file') throw new FsError(`cannot read "${target.displayPath}": not a regular file`, 'FS_NOT_REGULAR_FILE') return { target, info } } @@ -286,14 +289,17 @@ function codeOf(error: unknown): unknown { return typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined } -/** Model-facing failure for a classified Office service error; other failures pass through unchanged. */ +/** + * Model-facing failure for a classified Office service error, with the matching `OfficeToolError` code and the + * service error as `cause`; other failures pass through unchanged. + */ function officeFailure(verb: string, path: string, error: unknown): unknown { if (!(error instanceof OfficeKitError)) return error const hint = error.code === 'unavailable' ? ' Tell the user this operation is unavailable, or retry later if the cause may be temporary; do not substitute system soffice, npx, or another converter.' : error.code === 'busy' ? ' Retry after other document operations finish.' : error.code === 'output-too-large' && verb === 'render' ? ' Select fewer pages, a smaller range, or a lower dpi.' : '' - return new Error(`cannot ${verb} "${path}": ${error.message}${hint}`, { cause: error }) + return new OfficeToolError(`cannot ${verb} "${path}": ${error.message}${hint}`, OFFICE_KIT_FAILURE_CODES[error.code], { cause: error }) } /** @@ -306,10 +312,12 @@ async function assertRenderRoute(ctx: Context, agent: Agent, signal: AbortSignal const model = header?.model ?? agent.options.model const provider = header?.provider ?? agent.options.provider if (llm === undefined || provider === undefined || model === undefined) { - throw new Error(`cannot render "${displayPath}": the current model route could not be resolved`) + throw new ToolContextUnavailableError(`cannot render "${displayPath}": the current model route could not be resolved`) } const { inputModalities = [] } = await llm.resolveModelInfo(provider, model, signal) - if (!inputModalities.includes('image')) throw new Error(`cannot render "${displayPath}": model "${model}" does not accept images`) + if (!inputModalities.includes('image')) { + throw new OfficeToolError(`cannot render "${displayPath}": model "${model}" does not accept images`, 'MODEL_DOES_NOT_SUPPORT_IMAGES') + } } async function render( @@ -318,7 +326,9 @@ async function render( ): Promise { const path = ctx.fs.processPath(target) const attachments = ctx.get('attachments') - if (attachments === undefined) throw new Error(`cannot render "${target.displayPath}": no attachment service is mounted`) + if (attachments === undefined) { + throw new ToolContextUnavailableError(`cannot render "${target.displayPath}": no attachment service is mounted`) + } await assertRenderRoute(ctx, agent, signal, target.displayPath) const limits = attachments.imageLimits let result @@ -339,7 +349,7 @@ async function render( } catch (error) { throw officeFailure('render', target.displayPath, error) } const oversized = result.images.find(image => image.png.byteLength > limits.maxImageBytes) if (oversized !== undefined) { - throw new Error(`cannot render "${target.displayPath}": an image exceeds the ${limits.maxImageBytes}-byte image limit; select a smaller range or a lower dpi`) + throw new OfficeToolError(`cannot render "${target.displayPath}": an image exceeds the ${limits.maxImageBytes}-byte image limit; select a smaller range or a lower dpi`, 'OFFICE_OUTPUT_TOO_LARGE') } const stem = basename(target.displayPath) let refs: readonly ImageAttachmentRef[] @@ -349,7 +359,7 @@ async function render( }))) } catch (error) { if (!attachments.isAttachmentError(error)) throw error - throw new Error(`cannot render "${target.displayPath}": ${error.message}`, { cause: error }) + throw new AttachmentError(`cannot render "${target.displayPath}": ${error.message}`, error.code, { cause: error }) } return { operation: 'render', path, pageCount: result.pageCount, dpi: result.dpi, missingFonts: result.missingFonts, @@ -357,7 +367,7 @@ async function render( // saveImages returns one reference per input, in input order. const ref = refs[index] as ImageAttachmentRef const { mediaType } = ref - // Normalization of a PNG yields PNG, JPEG, or WebP. + // Normalization of a PNG yields PNG, JPEG, or WebP; a GIF is an attachment service defect. if (mediaType === 'image/gif') throw new Error(`cannot render "${target.displayPath}": the attachment service stored a rendered PNG as GIF`) return { ...image.page === undefined ? {} : { page: image.page }, @@ -394,7 +404,7 @@ async function convertFile( ): Promise> { const { format } = args if (ctx.fs.processPathFromHostPath(kit.outputDirectory) === undefined) { - throw new Error(`cannot ${operation} "${target.displayPath}": converted files are not available when the workspace is on a remote host`) + throw new OfficeToolError(`cannot ${operation} "${target.displayPath}": converted files are not available when the workspace is on a remote host`, 'OFFICE_UNSUPPORTED_REMOTE_WORKSPACE') } const extension = extensionOf(args.input) const stem = basename(target.displayPath).replace(/\.[^.]*$/u, '') diff --git a/packages/document/tool-office/tests/tool-office.spec.ts b/packages/document/tool-office/tests/tool-office.spec.ts index 85d33898ba..e6ef146111 100644 --- a/packages/document/tool-office/tests/tool-office.spec.ts +++ b/packages/document/tool-office/tests/tool-office.spec.ts @@ -198,6 +198,17 @@ function text(result: { content: readonly { type: string; text?: string }[] }): return result.content.filter(block => block.type === 'text').map(block => block.text).join('\n') } +/** Structured `name` and `code` the registry records for a failed call; undefined for a success or an unclassified failure. */ +function errorInfo(result: Awaited>): { name: string; code: string } | undefined { + if (!result.isError || result.error.info === undefined) return undefined + const { name, code } = result.error.info + return { name, code } +} + +const contextUnavailable = { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } +const invalidArgs = { name: 'ToolArgsError', code: 'INVALID_ARGS' } +const officeToolError = (code: string) => ({ name: 'OfficeToolError', code }) + describe('office schema', () => { it('declares the model-facing description and parameters', async () => { const { ctx } = await setup() @@ -236,6 +247,7 @@ describe('office schema', () => { const definition = ctx.tools.get(name)! const call = { signal, callId: ToolCallId(`agentless-${name}`), name, arguments: args, deferContext: vi.fn(), concludeTurn: vi.fn() } await expect(definition.execute(args as never, call as never)).rejects.toThrow('Office tools run only in an Agent step') + await expect(definition.execute(args as never, call as never)).rejects.toMatchObject(contextUnavailable) expect(kit.renderImages).not.toHaveBeenCalled() expect(kit.convertTo).not.toHaveBeenCalled() expect(kit.recalculate).not.toHaveBeenCalled() @@ -294,26 +306,30 @@ describe('render', () => { + 'Fonts not installed and substituted: Aptos.\nSheet "Data" A1:B2: 1x1 px\nSheet "Data": 1x1 px') }) + const noImages = officeToolError('MODEL_DOES_NOT_SUPPORT_IMAGES') + it.each([ - ['a text-only model', { model: 'text' }, 'model "text" does not accept images'], - ['a model without declared input modalities', { model: 'legacy' }, 'model "legacy" does not accept images'], - ['an unresolved route', { model: undefined }, 'the current model route could not be resolved'], - ['no attachment service', { attachments: false }, 'no attachment service is mounted'], - ['no model runtime', { llm: false }, 'the current model route could not be resolved'], - ])('refuses %s before rendering', async (_label, options, message) => { + ['a text-only model', { model: 'text' }, 'model "text" does not accept images', noImages], + ['a model without declared input modalities', { model: 'legacy' }, 'model "legacy" does not accept images', noImages], + ['an unresolved route', { model: undefined }, 'the current model route could not be resolved', contextUnavailable], + ['no attachment service', { attachments: false }, 'no attachment service is mounted', contextUnavailable], + ['no model runtime', { llm: false }, 'the current model route could not be resolved', contextUnavailable], + ])('refuses %s before rendering', async (_label, options, message, info) => { const { model, ...setupOptions } = { model: 'vision' as string | undefined, ...options } const { ctx, kit } = await setup(setupOptions) const result = await office(ctx, { operation: 'render', input: 'deck.pptx' }, agentOn(model)) expect(result.isError).toBe(true) expect(text(result)).toContain(message) + expect(errorInfo(result)).toEqual(info) expect(kit.renderImages).not.toHaveBeenCalled() }) it('falls back to the agent route when the Session has no request header', async () => { const { ctx, kit } = await setup() expect((await office(ctx, { operation: 'render', input: 'deck.pptx' }, agentOn(undefined, { provider: 'visual', model: 'vision' }))).isError).toBe(false) - expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }, agentOn(undefined, { provider: 'visual', model: 'text' })))) - .toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": model "text" does not accept images`) + const refused = await office(ctx, { operation: 'render', input: 'deck.pptx' }, agentOn(undefined, { provider: 'visual', model: 'text' })) + expect(text(refused)).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": model "text" does not accept images`) + expect(errorInfo(refused)).toEqual(noImages) expect(kit.renderImages).toHaveBeenCalledOnce() }) @@ -324,6 +340,7 @@ describe('render', () => { const { ctx, kit } = await setup() const result = await office(ctx, { operation: 'render', input: 'deck.pptx' }, agentOn(undefined, route)) expect(text(result)).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": the current model route could not be resolved`) + expect(errorInfo(result)).toEqual(contextUnavailable) expect(kit.renderImages).not.toHaveBeenCalled() }) @@ -332,16 +349,22 @@ describe('render', () => { const limit = ctx.get('attachments')!.imageLimits.maxImageBytes kit.renderImages.mockResolvedValueOnce({ images: [{ png: new Uint8Array(limit + 1), width: 1, height: 1, page: 1 }], pageCount: 1, dpi: 144, missingFonts: [] }) - expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toContain(`exceeds the ${limit}-byte image limit`) + const result = await office(ctx, { operation: 'render', input: 'deck.pptx' }) + expect(text(result)).toContain(`exceeds the ${limit}-byte image limit`) + expect(errorInfo(result)).toEqual(officeToolError('OFFICE_OUTPUT_TOO_LARGE')) }) it('reports attachment refusals and passes other storage failures through', async () => { const { ctx, kit } = await setup() kit.renderImages.mockResolvedValueOnce({ images: [{ png: Buffer.from('not a png'), width: 1, height: 1, page: 1 }], pageCount: 1, dpi: 144, missingFonts: [] }) - expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toContain(`cannot render "${join(dir, 'deck.pptx')}": `) + const refused = await office(ctx, { operation: 'render', input: 'deck.pptx' }) + expect(text(refused)).toContain(`cannot render "${join(dir, 'deck.pptx')}": `) + expect(errorInfo(refused)).toEqual({ name: 'AttachmentError', code: 'INVALID_IMAGE' }) vi.spyOn(ctx.get('attachments')!, 'saveImages').mockRejectedValueOnce(new Error('disk failure')) - expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toContain('disk failure') + const failed = await office(ctx, { operation: 'render', input: 'deck.pptx' }) + expect(text(failed)).toContain('disk failure') + expect(errorInfo(failed)).toBeUndefined() }) it('projects written files and their presentation metadata', async () => { @@ -424,6 +447,7 @@ describe('Office service failures', () => { const result = await office(ctx, args) expect(result.isError).toBe(true) expect(text(result)).toBe(`Error: cannot ${verb} "${args.input}": The document converter is unavailable.${unavailableHint}`) + expect(errorInfo(result)).toEqual(officeToolError('OFFICE_UNAVAILABLE')) } expect(kit.renderImages).not.toHaveBeenCalled() const missing = await office(ctx, { operation: 'convert', input: 'missing.pptx', format: 'pdf' }) @@ -436,26 +460,49 @@ describe('Office service failures', () => { const officeError = (code: OfficeKitErrorCode, message: string) => new OfficeKitError(code, message) - it.each<[OfficeKitErrorCode, string, string]>([ - ['unavailable', 'LibreOffice Kit is not installed.', `deck.pptx": LibreOffice Kit is not installed.${unavailableHint}`], - ['busy', 'The document converter has reached its admission limit.', 'Retry after other document operations finish.'], - ['output-too-large', 'Selected page count exceeds maxPages.', 'Select fewer pages, a smaller range, or a lower dpi.'], - ['invalid-request', 'Selected page lies outside the 3-page document.', 'deck.pptx": Selected page lies outside the 3-page document.'], - ])('reports a %s render failure', async (code, message, expected) => { + it.each<[OfficeKitErrorCode, string, string, string]>([ + ['unavailable', 'LibreOffice Kit is not installed.', `deck.pptx": LibreOffice Kit is not installed.${unavailableHint}`, 'OFFICE_UNAVAILABLE'], + ['busy', 'The document converter has reached its admission limit.', 'Retry after other document operations finish.', 'OFFICE_BUSY'], + ['output-too-large', 'Selected page count exceeds maxPages.', 'Select fewer pages, a smaller range, or a lower dpi.', 'OFFICE_OUTPUT_TOO_LARGE'], + ['invalid-request', 'Selected page lies outside the 3-page document.', 'deck.pptx": Selected page lies outside the 3-page document.', 'OFFICE_INVALID_REQUEST'], + ])('reports a %s render failure', async (code, message, expected, toolCode) => { const { ctx, kit } = await setup() - kit.renderImages.mockRejectedValueOnce(officeError(code, message)) + const cause = officeError(code, message) + kit.renderImages.mockRejectedValueOnce(cause) const result = await office(ctx, { operation: 'render', input: 'deck.pptx' }) expect(result.isError).toBe(true) expect(text(result)).toContain(expected) + expect(errorInfo(result)).toEqual(officeToolError(toolCode)) + }) + + it.each<[OfficeKitErrorCode, string]>([ + ['unavailable', 'OFFICE_UNAVAILABLE'], ['busy', 'OFFICE_BUSY'], ['input-too-large', 'OFFICE_INPUT_TOO_LARGE'], + ['output-too-large', 'OFFICE_OUTPUT_TOO_LARGE'], ['invalid-document', 'OFFICE_INVALID_DOCUMENT'], + ['unsupported-format', 'OFFICE_UNSUPPORTED_FORMAT'], ['invalid-request', 'OFFICE_INVALID_REQUEST'], + ['invalid-output', 'OFFICE_INVALID_OUTPUT'], ['timeout', 'OFFICE_TIMEOUT'], ['source-changed', 'OFFICE_SOURCE_CHANGED'], + ['failed', 'OFFICE_CONVERSION_FAILED'], + ])('classifies a %s conversion failure as %s and keeps the Office service error as its cause', async (code, toolCode) => { + const { ctx, kit } = await setup() + const cause = officeError(code, 'Conversion stopped.') + kit.convertTo.mockRejectedValueOnce(cause) + const definition = ctx.tools.get('office_convert')! + const result = await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' }) + expect(errorInfo(result)).toEqual(officeToolError(toolCode)) + kit.convertTo.mockRejectedValueOnce(cause) + const call = { signal, callId: ToolCallId(`cause-${code}`), name: 'office_convert', agent: agentOn('vision'), deferContext: vi.fn(), concludeTurn: vi.fn() } + await expect(definition.execute({ input: 'deck.pptx', format: 'pdf' }, call as never)).rejects.toMatchObject({ cause }) }) it('reports conversion failures without a render hint and passes unclassified failures through', async () => { const { ctx, kit } = await setup() kit.convertTo.mockRejectedValueOnce(officeError('output-too-large', 'The converter output exceeds its byte limit.')) - expect(text(await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' }))) - .toBe(`Error: cannot convert "${join(dir, 'deck.pptx')}": The converter output exceeds its byte limit.`) + const converted = await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' }) + expect(text(converted)).toBe(`Error: cannot convert "${join(dir, 'deck.pptx')}": The converter output exceeds its byte limit.`) + expect(errorInfo(converted)).toEqual(officeToolError('OFFICE_OUTPUT_TOO_LARGE')) kit.recalculate.mockRejectedValueOnce(new TypeError('unexpected')) - expect(text(await office(ctx, { operation: 'recalculate', input: 'book.xlsx', format: 'xlsx' }))).toContain('unexpected') + const unclassified = await office(ctx, { operation: 'recalculate', input: 'book.xlsx', format: 'xlsx' }) + expect(text(unclassified)).toContain('unexpected') + expect(errorInfo(unclassified)).toBeUndefined() kit.renderImages.mockRejectedValueOnce('engine string') expect((await office(ctx, { operation: 'render', input: 'deck.pptx' })).isError).toBe(true) }) @@ -467,14 +514,15 @@ describe('Office service failures', () => { await readSource(request.source) throw new Error('unreachable') }) - expect(await office(ctx, { operation: 'render', input: 'deck.pptx' })).toMatchObject({ isError: true }) + expect(errorInfo(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toEqual(officeToolError('OFFICE_SOURCE_CHANGED')) expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toContain('Rendered 1 image') kit.renderImages.mockImplementationOnce(async (request) => { await request.source.read(signal, 1) throw new Error('unreachable') }) - expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))) - .toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source exceeds the reserved byte capacity.`) + const grown = await office(ctx, { operation: 'render', input: 'deck.pptx' }) + expect(text(grown)).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source exceeds the reserved byte capacity.`) + expect(errorInfo(grown)).toEqual(officeToolError('OFFICE_INPUT_TOO_LARGE')) kit.renderImages.mockImplementationOnce(async (request) => { vi.spyOn(ctx.fs, 'readBytes').mockImplementationOnce(async () => { await writeFile(join(dir, 'deck.pptx'), 'pptx bytes, then more') @@ -483,7 +531,9 @@ describe('Office service failures', () => { await readSource(request.source) throw new Error('unreachable') }) - expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source changed.`) + const changed = await office(ctx, { operation: 'render', input: 'deck.pptx' }) + expect(text(changed)).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source changed.`) + expect(errorInfo(changed)).toEqual(officeToolError('OFFICE_SOURCE_CHANGED')) kit.renderImages.mockImplementationOnce(async (request) => { vi.spyOn(ctx.fs, 'readBytes').mockRejectedValueOnce(new Error('read failure')) await readSource(request.source) @@ -509,8 +559,10 @@ describe('Office service failures', () => { }) describe('arguments and paths', () => { - /** Refuse `args` with `message` after exactly `resolveCalls` filesystem resolutions. */ - async function expectRefusal(args: Record, message: string, resolveCalls: number): Promise { + /** Refuse `args` with `message` and `info` after exactly `resolveCalls` filesystem resolutions. */ + async function expectRefusal( + args: Record, message: string, info: { name: string; code: string }, resolveCalls: number, + ): Promise { await mkdir(join(dir, 'folder.pptx')) const { ctx, kit } = await setup() const resolve = vi.spyOn(ctx.fs, 'resolve') @@ -518,6 +570,7 @@ describe('arguments and paths', () => { expect(resolve).toHaveBeenCalledTimes(resolveCalls) expect(result.isError).toBe(true) expect(text(result)).toContain(message) + expect(errorInfo(result)).toEqual(info) expect(kit.renderImages).not.toHaveBeenCalled() expect(kit.convertTo).not.toHaveBeenCalled() expect(kit.recalculate).not.toHaveBeenCalled() @@ -560,14 +613,14 @@ describe('arguments and paths', () => { [{ operation: 'convert', input: 'deck.pptx', format: 'xlsx' }, 'deck.pptx" to xlsx: this file converts to pdf, pptx, odp'], [{ operation: 'recalculate', input: 'book.xlsx', format: 'pdf' }, 'format'], ])('refuses %j before reading the filesystem', async (args, message) => { - await expectRefusal(args, message, 0) + await expectRefusal(args, message, invalidArgs, 0) }) it.each([ - [{ operation: 'render', input: 'missing.pptx' }, 'missing.pptx": not found'], - [{ operation: 'render', input: 'folder.pptx' }, 'folder.pptx": not a regular file'], - ])('refuses %j after resolving the input path', async (args, message) => { - await expectRefusal(args, message, 1) + [{ operation: 'render', input: 'missing.pptx' }, 'missing.pptx": not found', 'FS_NOT_FOUND'], + [{ operation: 'render', input: 'folder.pptx' }, 'folder.pptx": not a regular file', 'FS_NOT_REGULAR_FILE'], + ])('refuses %j after resolving the input path', async (args, message, code) => { + await expectRefusal(args, message, { name: 'FsError', code }, 1) }) it('returns the temporary file and the copy instruction for conversions and recalculations', async () => { @@ -606,6 +659,7 @@ describe('arguments and paths', () => { const result = await office(ctx, { operation: 'convert', input: 'locked.docx', format: 'pdf' }) expect(result.isError).toBe(true) expect(text(result)).toContain('permission denied') + expect(errorInfo(result)).toEqual({ name: 'FsError', code: 'FS_PERMISSION_DENIED' }) expect(kit.convertTo).not.toHaveBeenCalled() }) @@ -617,8 +671,9 @@ describe('arguments and paths', () => { await writeFile(join(dir, 'deck.pptx'), 'replaced pptx bytes') return bytes }) - expect(text(await office(ctx, { operation: 'render', input: 'deck.pptx' }))) - .toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source changed.`) + const result = await office(ctx, { operation: 'render', input: 'deck.pptx' }) + expect(text(result)).toBe(`Error: cannot render "${join(dir, 'deck.pptx')}": The source changed.`) + expect(errorInfo(result)).toEqual(officeToolError('OFFICE_SOURCE_CHANGED')) expect(kit.renderImages).not.toHaveBeenCalled() }) @@ -640,8 +695,9 @@ describe('arguments and paths', () => { it('refuses conversions when the execution world cannot read Host files', async () => { const { ctx, kit } = await setup() vi.spyOn(ctx.fs, 'processPathFromHostPath').mockReturnValue(undefined) - expect(text(await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' }))) - .toContain('converted files are not available when the workspace is on a remote host') + const result = await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' }) + expect(text(result)).toContain('converted files are not available when the workspace is on a remote host') + expect(errorInfo(result)).toEqual(officeToolError('OFFICE_UNSUPPORTED_REMOTE_WORKSPACE')) expect(kit.convertTo).not.toHaveBeenCalled() expect((await office(ctx, { operation: 'render', input: 'deck.pptx' })).isError).toBe(false) }) @@ -718,5 +774,6 @@ describe('output lifetime', () => { const converted = await office(ctx, { operation: 'convert', input: 'deck.pptx', format: 'pdf' }) expect(converted.isError).toBe(true) expect(text(converted)).toContain('subagent tree is unavailable') + expect(errorInfo(converted)).toEqual({ name: 'SubagentError', code: 'UNSUPPORTED_CAPABILITY' }) }) }) diff --git a/packages/document/tool-office/tsconfig.json b/packages/document/tool-office/tsconfig.json index 480f080638..2a5a78c2b8 100644 --- a/packages/document/tool-office/tsconfig.json +++ b/packages/document/tool-office/tsconfig.json @@ -14,6 +14,9 @@ { "path": "../../../vendor/schemastery" }, + { + "path": "../../util/error" + }, { "path": "../../core/agent" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1876116909..a658d0eb61 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8441,6 +8441,9 @@ importers: '@deepseek-ai/dsh-attachment-local': specifier: workspace:* version: link:../../attachment/attachment-local + '@deepseek-ai/dsh-error': + specifier: workspace:* + version: link:../../util/error '@deepseek-ai/dsh-fs': specifier: workspace:* version: link:../../fs/fs diff --git a/snapshots/session/office-progressive-native/session.v4.jsonl b/snapshots/session/office-progressive-native/session.v4.jsonl index fe32bf2d08..0a7509ea5f 100644 --- a/snapshots/session/office-progressive-native/session.v4.jsonl +++ b/snapshots/session/office-progressive-native/session.v4.jsonl @@ -27,7 +27,7 @@ {"type":"step/start","data":{"turn":1,"step":3}} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_3","name":"office_render","arguments":"{\"input\":\"report.docx\",\"pages\":[1]}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"stream":[{"type":"chunk","time":1793628044630,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793628044630,"index":0,"dt":[],"id":"call_office_3","name":"office_render","args":["{\"input\":\"report.docx\",\"pages\":[1]}"]},{"type":"chunk","time":1793628044630,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_3","name":"office_render","arguments":"{\"input\":\"report.docx\",\"pages\":[1]}"}}},{"type":"chunk","time":1793628044630,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"call_office_3","name":"office_render","arguments":"{\"input\":\"report.docx\",\"pages\":[1]}"}} -{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_3"},"toolCallId":"call_office_3","content":[{"type":"text","text":"Error: cannot render \"{{cwd}}/report.docx\": model \"deepseek-v4-flash\" does not accept images"}],"isError":true,"id":"{{message:11}}"}},"sourceEventSeqs":[27],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_3"},"toolCallId":"call_office_3","content":[{"type":"text","text":"Error: cannot render \"{{cwd}}/report.docx\": model \"deepseek-v4-flash\" does not accept images"}],"isError":true,"id":"{{message:11}}"},"error":{"name":"OfficeToolError","code":"MODEL_DOES_NOT_SUPPORT_IMAGES"}},"sourceEventSeqs":[27],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} {"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1793628044644,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1793628044645,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1793628044645,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1793628044645,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1793628044645,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}