From 8421590853bbb18b75604bc7502d212a50b60c8e Mon Sep 17 00:00:00 2001 From: sjw1231 Date: Thu, 5 Nov 2026 17:27:17 +0800 Subject: [PATCH] refactor(cua): make NativeError a HarnessError and classify cua tool failures NativeError now extends HarnessError and keeps its name and every native and host code, so cua refusals reach tool/result as structured identity. A missing Agent, attachment store, or model route throws ToolContextUnavailableError; a model without image input fails with NativeError IMAGE_MODEL_UNSUPPORTED; request refinements fail as ToolArgsError; native cancellation after caller cancellation records AbortError / ABORTED. Refs #7869 --- .../tests/provider-lifecycle.spec.ts | 32 +++++++++++++++- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/package.json | 4 +- packages/experimental/cua/src/index.ts | 37 +++++++++++++++---- .../experimental/cua/src/native-client.ts | 16 +++++--- .../cua/tests/native-client.spec.ts | 6 ++- 8 files changed, 81 insertions(+), 22 deletions(-) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 5e7b5893f6..485b13bd27 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -34,7 +34,7 @@ import { expect, it, onTestFinished, vi } from 'vitest' import sharp from 'sharp' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import * as NativeProvider from '../src/index.ts' -import type { NativeClient } from '@deepseek-ai/dsh-cua/native-client' +import { NativeError, type NativeClient } from '@deepseek-ai/dsh-cua/native-client' import type { NativeBuildSpec } from '../src/native-build.ts' const native = vi.hoisted(() => ({ @@ -255,6 +255,7 @@ it.each(['Allow for this session', 'Deny'])('obtains %s before a stopped applica answer.resolve({ answers: [{ id: 'cua-app-access', selected: [choice] }] }) const result = await pending expect(result.isError).toBe(choice === 'Deny') + if (choice === 'Deny') expect(result.error?.info).toEqual({ name: 'NativeError', code: 'APP_ACCESS_DENIED' }) expect(native.request.mock.calls.map(call => call[0])).toEqual(choice === 'Deny' ? ['getApp'] : ['getApp', 'launchApp']) if (choice !== 'Deny') expect(result.value).toMatchObject({ appHandle: 'pending-app', running: true }) }) @@ -268,9 +269,25 @@ it('rejects a launch result that changes the approved handle', async () => { } }).mockResolvedValueOnce({ appHandle: 'another-app', name: 'Fixture', running: true }) const result = await f.execute('getApp', { selector: 'Fixture' }) expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'NativeError', code: 'NATIVE_PROTOCOL' }) expect(JSON.stringify(result.content)).toContain('another handle') }) +it.each([true, false])('classifies native cancellation by whether the caller cancelled (%s)', async (callerCancelled) => { + const f = await setup() + await f.execute() + const controller = new AbortController() + native.request.mockImplementationOnce(async () => { + if (callerCancelled) controller.abort() + throw new NativeError('NATIVE_CANCELLED', 'Operation cancelled; inspect fresh state before retrying input') + }) + const result = await f.execute('listApps', {}, controller.signal) + expect(result.isError).toBe(true) + expect(result.error?.info).toEqual(callerCancelled + ? { name: 'AbortError', code: 'ABORTED' } + : { name: 'NativeError', code: 'NATIVE_CANCELLED' }) +}) + it('rejects a model attempt to call the private launch operation', async () => { const f = await setup() expect((await f.execute('launchApp', { appHandle: 'unapproved' })).isError).toBe(true) @@ -471,11 +488,14 @@ it('reports failed cleanup after waiting for other owners and releasing their Ag it('rejects malformed and unowned operations before acquiring a helper', async () => { const f = await setup() - expect((await f.execute('screenshot', { pid: 9, windowId: 7 })).isError).toBe(true) + const malformed = await f.execute('screenshot', { pid: 9, windowId: 7 }) + expect(malformed.isError).toBe(true) + expect(malformed.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' }) const unowned = await executeToolFixture(f.ctx, { signal: new AbortController().signal, callId: ToolCallId('unowned'), name: 'cua', arguments: { method: 'listApps', params: {} }, }) expect(unowned.isError).toBe(true) + expect(unowned.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(native.instances).toEqual([]) expect(native.request).not.toHaveBeenCalled() }) @@ -487,6 +507,7 @@ it.each([false, true])('rejects an ended Agent with prior helper acquisition %s' const requests = native.request.mock.calls.length const result = await f.execute() expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(JSON.stringify(result.content)).toContain('agent has been disposed') expect(native.instances).toHaveLength(acquired ? 1 : 0) expect(native.request).toHaveBeenCalledTimes(requests) @@ -554,6 +575,7 @@ it('preserves screenshot attachments and invalidates pixel coordinates when wind native.request.mockClear() const click = await f.execute('click', { appHandle: 'app-one', windowId: 7, x: 0, y: 0 }) expect(click.isError).toBe(true) + expect(click.error?.info).toEqual({ name: 'NativeError', code: 'SCREENSHOT_REQUIRED' }) expect(JSON.stringify(click.content)).toContain('SCREENSHOT_REQUIRED') expect(native.request).not.toHaveBeenCalled() }) @@ -624,6 +646,7 @@ it.each([{ pixelWidth: 2 }, { pixelHeight: 2 }])('rejects native screenshot dime native.request.mockResolvedValue({ ...imageMetadata, ...invalid, mimeType: 'image/png', data: imageData }) const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'NativeError', code: 'NATIVE_PROTOCOL' }) expect(JSON.stringify(result.content)).toContain('dimensions disagree') expect(result.content.some(block => block.type === 'image')).toBe(false) }) @@ -634,6 +657,7 @@ it('refuses screenshot capture when no attachment store is mounted', async () => native.request.mockClear() const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' }) expect(JSON.stringify(result.content)).toContain('require an attachment store') expect(native.request).not.toHaveBeenCalled() }) @@ -656,6 +680,9 @@ it.each(['unresolved', 'unknown', 'text-only', 'provider-error'] as const)( expect(result.isError).toBe(true) expect(JSON.stringify(result.content)).toContain(route === 'unresolved' ? 'model route could not be resolved' : route === 'provider-error' ? 'model lookup failed' : 'declare image input') + expect(result.error?.info).toEqual(route === 'unresolved' + ? { name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' } + : route === 'provider-error' ? undefined : { name: 'NativeError', code: 'IMAGE_MODEL_UNSUPPORTED' }) expect(native.request).not.toHaveBeenCalled() expect(saved).not.toHaveBeenCalled() }, @@ -910,6 +937,7 @@ it('rejects an application handle before any helper or consent has been acquired const f = await setup() const result = await f.execute('getState', { appHandle: 'unselected-app' }) expect(result.isError).toBe(true) + expect(result.error?.info).toEqual({ name: 'NativeError', code: 'APP_ACCESS_REQUIRED' }) expect(JSON.stringify(result.content)).toContain('APP_ACCESS_REQUIRED') expect(native.instances).toHaveLength(0) expect(native.request).not.toHaveBeenCalled() diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 40d8ac79c6..2b980c8662 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,8 +15,8 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: ba1f8e6ae51f69d7 - zh: 8f4fde9857bae319 + en: 588271340c0d2969 + zh: b368d49754564764 /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: d92d5948a7941e8d zh: d43491ae6521b87e diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index 1ee0a555d1..edadba8d3b 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -37,7 +37,7 @@ Keyboard methods are available in the scopes a provider declares; the provider o Observation methods emit and return their result. Use `void await app.getAccessibilityTree()` for one visible copy, or use `emit:false` and print the returned text once. `window.getScreenshot()` returns `CuaScreenshot` with `bytes`, `mimeType`, `pixelWidth`, `pixelHeight`, and `windowId`. The image sink receives the same object. Use its MIME type when selecting a file extension or declaring an image; the format can be PNG, JPEG, WebP, or GIF. Each screenshot enters the attachment pipeline once; `emit:false` only suppresses the object sink. -`tools.cua` returns operation values directly. Screenshot values retain the encoded image Base64 and add a durable `attachment` reference for the tool renderer; model content contains coordinate metadata and one image, without the encoded bytes. Before capture, the tool requires an attachment store and a resolved model route declaring image input. Admission and storage failures reject the call. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. +`tools.cua` returns operation values directly. Screenshot values retain the encoded image Base64 and add a durable `attachment` reference for the tool renderer; model content contains coordinate metadata and one image, without the encoded bytes. Before capture, the tool requires an attachment store and a resolved model route declaring image input. Admission and storage failures reject the call. Failed calls carry structured identity: native and host refusals use `NativeError` with the native or host code, such as `APP_ACCESS_DENIED`, `NATIVE_TIMEOUT`, or `IMAGE_MODEL_UNSUPPORTED` for a model without image input; a missing Agent, attachment store, or model route uses `ToolContextUnavailableError`; arguments the schema cannot check use `ToolArgsError`; native cancellation after the caller cancels records `AbortError` with `ABORTED`. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. Application consent precedes launch, observation, capture, and input. Session access is stored by conversation and application identity and survives DSH restart and Computer Use disablement. Other conversations require their own consent. Saved grants require a platform-provided reusable application identity. Refusal and revocation close affected Agent connections, so their old objects require fresh selection. No input is replayed after cancellation, timeout, or reconnect. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index b8592b36eb..5e59834920 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -37,7 +37,7 @@ kind: "package-reference" 观察方法会输出并返回结果。使用 `void await app.getAccessibilityTree()` 只展示一份内容,或使用 `emit:false` 后打印一次返回文本。`window.getScreenshot()` 返回包含 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 的 `CuaScreenshot`,图片输出回调接收同一个对象。选择文件后缀或声明图片时使用其中的 MIME 类型;格式可能是 PNG、JPEG、WebP 或 GIF。每张截图只进入一次附件处理链;`emit:false` 只抑制对象层的输出。 -`tools.cua` 直接返回操作结果。截图结果保留图片 Base64,并增加供工具渲染使用的持久 `attachment` 引用;模型内容只包含坐标元数据和一张图片,不包含编码字节。截图前要求附件服务可用,并确认当前模型支持图片输入。图片接入或保存失败会拒绝调用。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 +`tools.cua` 直接返回操作结果。截图结果保留图片 Base64,并增加供工具渲染使用的持久 `attachment` 引用;模型内容只包含坐标元数据和一张图片,不包含编码字节。截图前要求附件服务可用,并确认当前模型支持图片输入。图片接入或保存失败会拒绝调用。失败调用带有结构化标识:原生与 Host 拒绝使用 `NativeError` 及原生或 Host code,例如 `APP_ACCESS_DENIED`、`NATIVE_TIMEOUT`,模型不支持图片输入时为 `IMAGE_MODEL_UNSUPPORTED`;缺少 Agent、附件服务或模型路由时使用 `ToolContextUnavailableError`;参数 schema 无法检查的参数错误使用 `ToolArgsError`;调用方取消后的原生取消记录为 `AbortError` 与 `ABORTED`。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 应用授权发生在启动、观察、截图和输入之前。会话许可按对话和应用身份持久化,重启 DSH 或关闭 Computer Use 后仍可复用,其他对话需要单独授权。长期许可要求平台提供可复用的应用身份。拒绝或撤销会关闭受影响的 Agent 连接,因此旧对象必须重新选择目标。取消、超时或重新连接后均不重放输入。 diff --git a/packages/experimental/cua/package.json b/packages/experimental/cua/package.json index 440f321935..5e0c3bf604 100644 --- a/packages/experimental/cua/package.json +++ b/packages/experimental/cua/package.json @@ -99,7 +99,9 @@ "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-attachment": "workspace:*", "@deepseek-ai/dsh-scope": "workspace:*", - "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*" + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 43ca13308e..48f31d9a46 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -9,7 +9,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { ComputerUseProviderName } from '@deepseek-ai/dsh-computer-use/brand' import { admitEncodedImages } from '@deepseek-ai/dsh-attachment' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' -import type { ContentBlock } from '@deepseek-ai/dsh-llm' +import { HarnessError, type ContentBlock } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' import { NativeClient, NativeError, type NativeClientConfig, type NativeChannelFactory } from './native-client.ts' @@ -25,7 +25,7 @@ import { CuaCoordinates } from './coordinates.ts' import { createScope, type Scope } from '@deepseek-ai/dsh-scope' import type {} from '@deepseek-ai/dsh-agent-preset-registry' import type { PromptSection } from '@deepseek-ai/dsh-system-prompt' -import type { ToolDefinition, ToolExecution } from '@deepseek-ai/dsh-tools' +import { TOOL_ABORTED, ToolArgsError, ToolContextUnavailableError, type ToolDefinition, type ToolExecution } from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-subprocess' import type {} from '@deepseek-ai/dsh-computer-use' import type {} from '@deepseek-ai/dsh-ptc-runtime' @@ -88,10 +88,24 @@ export const CuaConfig = Schema.object(CuaConfigFields) satisfies Schema): Agent { - if (!execution.agent) throw new Error('dsh-cua requires an agent-owned execution') + if (!execution.agent) throw new ToolContextUnavailableError('dsh-cua requires an agent-owned execution') return execution.agent } +/** Parse the tool request; refinements the parameter schema cannot express fail as argument errors. */ +function parseRequest(schema: z.ZodType, args: unknown): T { + const parsed = schema.safeParse(args) + if (!parsed.success) throw new ToolArgsError(parsed.error.issues.map(issue => `${issue.path.join('.') || ''}: ${issue.message}`)) + return parsed.data +} + +/** Native cancellation after the caller cancelled keeps its diagnostic under the registry's cancellation identity. */ +function callerCancelled(error: NativeError): HarnessError { + const cancelled = new HarnessError(error.message, TOOL_ABORTED, { cause: error }) + cancelled.name = 'AbortError' + return cancelled +} + interface CuaExecution extends ToolExecution { agent: Agent nativeClient: NativeClient @@ -111,16 +125,20 @@ function renderResult(args: unknown, value: JsonValue): ContentBlock[] { /** Resolve the exact calling model and attachment store before requesting a screenshot. */ async function screenshotStore(ctx: Context, execution: Readonly) { const attachments = ctx.get('attachments') - if (!attachments) throw new Error('CUA screenshots require an attachment store') + if (!attachments) throw new ToolContextUnavailableError('CUA screenshots require an attachment store') const agent = execution.agent const routed = agent.session.requestHeader()?.config const provider = routed?.provider ?? agent.options.provider const model = routed?.model ?? agent.options.model const llm = ctx.get('llm') - if (provider === undefined || model === undefined || llm === undefined) throw new Error('CUA screenshot model route could not be resolved') + if (provider === undefined || model === undefined || llm === undefined) { + throw new ToolContextUnavailableError('CUA screenshot model route could not be resolved') + } const info = await llm.resolveModelInfo(provider, model, execution.signal) execution.signal.throwIfAborted() - if (!info.inputModalities?.includes('image')) throw new Error(`CUA screenshots require model "${model}" to declare image input`) + if (!info.inputModalities?.includes('image')) { + throw new NativeError('IMAGE_MODEL_UNSUPPORTED', `CUA screenshots require model "${model}" to declare image input`) + } return { attachments, target: (image: ImageAttachmentRef) => llm.imageRequestTarget(provider, model, image) } } @@ -178,7 +196,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) }>() const closedOwners = new WeakSet() function ownerFor(agent: Agent) { - if (closedOwners.has(agent) || ctx.agents.get(agent.id) !== agent) throw new Error('dsh-cua agent has been disposed') + if (closedOwners.has(agent) || ctx.agents.get(agent.id) !== agent) throw new ToolContextUnavailableError('dsh-cua agent has been disposed') const existing = ownerCleanups.get(agent) if (existing) return existing const controller = new AbortController() @@ -311,7 +329,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) parameters: { ...z.record(z.string(), z.json()).parse(z.toJSONSchema(requestSchema)), type: 'object' }, output: { schema: {}, render: renderResult }, async execute(args, execution) { - const request = requestSchema.parse(args) + const request = parseRequest(requestSchema, args) const agent = executionAgent(execution) execution.signal.throwIfAborted() lifetime.signal.throwIfAborted() @@ -361,6 +379,9 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) pending.set(operation, agent) try { return await operation + } catch (error) { + if (execution.signal.aborted && error instanceof NativeError && error.code === 'NATIVE_CANCELLED') throw callerCancelled(error) + throw error } finally { pending.delete(operation) } diff --git a/packages/experimental/cua/src/native-client.ts b/packages/experimental/cua/src/native-client.ts index d2e70813ec..f723c237bd 100644 --- a/packages/experimental/cua/src/native-client.ts +++ b/packages/experimental/cua/src/native-client.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto' import assert from 'node:assert/strict' import type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import { HarnessError } from '@deepseek-ai/dsh-llm' import type { ToolExecution } from '@deepseek-ai/dsh-tools' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' @@ -18,15 +19,20 @@ const ScreenshotDiagnostic = z.object({ }) const WireReply = z.union([Reply, ScreenshotDiagnostic.extend({ type: z.literal('diagnostic') })]) -/** Native refusal or transport failure with a stable machine-readable code. */ -export class NativeError extends Error { +/** + * Native refusal, transport failure, or host-side CUA refusal with a stable machine-readable code. + * The helper supplies its own codes, such as `APP_ACCESS_DENIED` or `STALE_SNAPSHOT`, so consumers + * tolerate unknown codes; the host adds `NATIVE_*` transport codes, application-access codes, + * and `IMAGE_MODEL_UNSUPPORTED` for a screenshot requested by a model without image input. + */ +export class NativeError extends HarnessError { /** - * @param code - Native error code or a transport-owned NATIVE_* code. + * @param code - Native error code or a host-owned code. * @param message - Actionable diagnostic, without its code prefix. * @param options - Original failure when available. */ - constructor(readonly code: string, message: string, options?: ErrorOptions) { - super(`${code}: ${message}`, options) + constructor(code: string, message: string, options?: ErrorOptions) { + super(`${code}: ${message}`, code, options) this.name = 'NativeError' } } diff --git a/packages/experimental/cua/tests/native-client.spec.ts b/packages/experimental/cua/tests/native-client.spec.ts index 19475f83fe..c6b9acdde0 100644 --- a/packages/experimental/cua/tests/native-client.spec.ts +++ b/packages/experimental/cua/tests/native-client.spec.ts @@ -1,6 +1,6 @@ /** Controlled connection streams exercise the platform-independent native protocol client. */ import { PassThrough, Writable } from 'node:stream' -import { ToolCallId } from '@deepseek-ai/dsh-llm' +import { HarnessError, ToolCallId } from '@deepseek-ai/dsh-llm' import type { NativeChannel } from '../src/native-client.ts' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { z } from 'zod' @@ -227,7 +227,9 @@ describe('native helper transport', () => { it('rejects a pre-cancelled operation without writing or invalidating acquired handles', async () => { const f = fixture() - await expect(f.client.request('click', {}, AbortSignal.abort())).rejects.toMatchObject({ code: 'NATIVE_CANCELLED' }) + const rejected = f.client.request('click', {}, AbortSignal.abort()) + await expect(rejected).rejects.toBeInstanceOf(HarnessError) + await expect(rejected).rejects.toMatchObject({ name: 'NativeError', code: 'NATIVE_CANCELLED' }) expect(f.requests).toEqual([]) expect(f.client.disposed).toBe(false) })