feat(tools): add ToolContextUnavailableError for missing call context
Tool bodies that lack a calling Agent, an injected service, or an open turn get one shared HarnessError with the TOOL_CONTEXT_UNAVAILABLE code, instead of each tool throwing a plain Error. The stacked per-area refactors adopt it at their call sites. Refs #7869
This commit is contained in:
1 parent
3b9f88dd2e
commit
3f3e9caeae
11 files changed
+51
-12
No files matched your search
@@ -20,7 +20,7 @@ Convert foreign failures where the dependency is owned. Node errno, SDK, protoco
|
||||
The tool registry keeps `error.name` and `error.code` on `tool/result` when the producer supplies them: a `HarnessError` thrown by the tool body, a pre-execute `deny`, guard denial, or post-execute block with `info` (including the registry's approval denials, `ApprovalError` with `APPROVAL_REJECTED`, `APPROVAL_CANCELLED`, or `APPROVAL_UNAVAILABLE`), the registry's own cancellation result (`AbortError` with `ABORTED` or `ABORTED_BEFORE_DISPATCH`, also applied to a signal reason or `AbortError` the body throws after cancellation), or a `tools/execute` wrapper result such as the timeout policy's `TOOL_TIMEOUT`. Any other thrown value, and a guard denial or block without `info`, persist only text that retry policy, UI, and analytics cannot route on. Every expected failure reachable from a tool body therefore throws a `HarnessError`, normally the owning domain's subclass:
|
||||
|
||||
- Hand-checked argument constraints throw `ToolArgsError` (`INVALID_ARGS`) from `dsh-tools`.
|
||||
- Missing composition or caller context, such as an absent Agent, service, or open turn, throws the owning package's error with its own code.
|
||||
- Missing composition or caller context, such as an absent Agent, service, or open turn, throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`) from `dsh-tools`.
|
||||
- Caller cancellation either propagates the signal's reason or an `AbortError`, which the registry classifies as `AbortError` with the `dsh-tools` `TOOL_ABORTED` constant (`ABORTED`), or throws a `HarnessError` with that `name` and code. Never replace it with a different plain `Error`; a failure distinct from the cancellation, such as a cleanup failure, keeps its own class and code.
|
||||
- Dependency failures follow the conversion rule above; filesystem errno maps to `FsError` codes such as `FS_NOT_FOUND`, `FS_PERMISSION_DENIED`, and `FS_IO_ERROR`.
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ Use this guide when adding or reviewing an error class, an error code, or a fail
|
||||
## Choose the class
|
||||
|
||||
1. Reuse the owning domain's existing class when the failure belongs to that domain: `FsError` for filesystem targets, `SearchError` for `glob`/`grep`, `LspError`, `WebError`, `SubagentError`, `TeamError`, `GoalError`, `WorkflowError`, `UserQuestionError`, `SessionQueryError`, the `Sandbox*Error` classes, and `CodeRunFailedError`.
|
||||
2. Use `ToolArgsError` (`INVALID_ARGS`) for argument constraints the parameter schema cannot express, such as an empty string, a range, or a cross-field rule.
|
||||
2. Use `ToolArgsError` (`INVALID_ARGS`) for argument constraints the parameter schema cannot express, such as an empty string, a range, or a cross-field rule, and `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`) for a tool call that lacks a required Agent, service, or open turn.
|
||||
3. Declare a new class only for a new owning domain. Prefer one class with a code union over one class per failure; a separate subclass is justified when consumers must catch it by type or it carries its own structured fields, such as `ToolArgsError.violations`, and it then extends the domain class when one exists so the domain still matches with `instanceof`.
|
||||
4. Never declare a coded class that extends bare `Error`. An existing one is migrated by changing its base class and keeping every `name` and `code`.
|
||||
|
||||
|
||||
@@ -1308,8 +1308,8 @@
|
||||
en: 0080c345c319a4b5
|
||||
zh: de1a8b3ed621ce21
|
||||
/session-persistence-event-catalog/resolved-persistence-types/toolrestriction:
|
||||
en: d44882acca0f367c
|
||||
zh: e938d48f5a38df60
|
||||
en: a8e8f9ff2de055f5
|
||||
zh: ed3f709744159461
|
||||
/session-persistence-event-catalog/resolved-persistence-types/toolresultmessage:
|
||||
en: 2258683c3cfa4ce3
|
||||
zh: 5663aa76c911761b
|
||||
|
||||
@@ -5269,7 +5269,7 @@ Sources: [`packages/llm/llm/src/types.ts:134`](../packages/llm/llm/src/types.ts)
|
||||
|
||||
SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f`
|
||||
|
||||
Sources: [`packages/core/tools/src/contracts.ts:389`](../packages/core/tools/src/contracts.ts)
|
||||
Sources: [`packages/core/tools/src/contracts.ts:409`](../packages/core/tools/src/contracts.ts)
|
||||
|
||||
| Property | Presence | Type |
|
||||
|---|---|---|
|
||||
|
||||
@@ -5271,7 +5271,7 @@ SHA-256: `43e311235aa537df1bacdd92d144df8a952337a76e9ac892cdf670f1a797bad8`
|
||||
|
||||
SHA-256: `3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f`
|
||||
|
||||
来源:[`packages/core/tools/src/contracts.ts:389`](../packages/core/tools/src/contracts.ts)
|
||||
来源:[`packages/core/tools/src/contracts.ts:409`](../packages/core/tools/src/contracts.ts)
|
||||
|
||||
| 属性 | 存在性 | 类型 |
|
||||
|---|---|---|
|
||||
|
||||
Generated
+1
-1
@@ -223,7 +223,7 @@
|
||||
{"digest":"3bec87f9e6ab3da03346f49923d3c51621debc0159df68605e543c3b2a026f90","names":[],"sources":["packages/llm/llm/src/types.ts:497"]},
|
||||
{"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1","names":[],"sources":[]},
|
||||
{"digest":"3c2535ca0a2062f172f15344f8040755002b5ac506cf94fc4ebaa822b15feb8c","names":[],"sources":[]},
|
||||
{"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:389"]},
|
||||
{"digest":"3cfc3a56502da1f8c6153c2c56657bab4b749056968634dd0991d325ec1c919f","names":["packages/core/tools/src/contracts.ts#ToolRestriction"],"sources":["packages/core/tools/src/contracts.ts:409"]},
|
||||
{"digest":"3d7d07060a7be77984feb651ea2bf1925d3e0477911d9d3ed86330d1e8ca6182","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackItem"],"sources":["packages/feedback/message-feedback/src/types.ts:20"]},
|
||||
{"digest":"3e0eff5946255ff05d88a10839c60305135801f97794ea48d409f8503303317e","names":[],"sources":[]},
|
||||
{"digest":"3e2ece4967cfebe95f450a93f45523dff99d6749f6269f2f60f84dfecfcf3693","names":[],"sources":[]},
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 14522295539ea2fb
|
||||
zh: 572c462f2c6b70ad
|
||||
/tools/execution-extensible-waterfalls-plus-monotonic-policy:
|
||||
en: 3c59bceacac56c4f
|
||||
zh: aa1352ce8418ec7a
|
||||
en: be510bb2027f6d2b
|
||||
zh: 1282ab990937f81d
|
||||
/tools/the-enforced-raw-json-schema-subset:
|
||||
en: 28e354bfa2f9cebb
|
||||
zh: be1f75abccf8afdf
|
||||
|
||||
@@ -571,7 +571,7 @@ type PostToolDecision =
|
||||
|
||||
Call `next()` for the default or return a decision to short-circuit. Pre-policy may deny or ask; only `allowed-once` proceeds, while a non-grant, missing approval channel or service, or agent-less request becomes a denial. A deny may attach structured identity and user-facing detail without changing its model-facing reason. Guards may still impose a final denial. Arguments cannot be rewritten because history, audit, UI, and execution must agree.
|
||||
|
||||
Post-policy may replace either content or value, never both. Content replacement preserves the canonical value and existing metadata; value replacement is revalidated and recomputes content/metadata; a block removes the value and becomes an `isError` containing corrective feedback. Content replacement is presentation policy, not confidentiality policy: a listener that must hide the programmatic value blocks or replaces it. `tools/result` receives the frozen execution and result after normalization; observers cannot transform them, and observer failures are contained. Unknown and throwing tools both become structured errors (`ToolNotFoundError` maps to `UNKNOWN_TOOL`), so the call fails without ending the turn.
|
||||
Post-policy may replace either content or value, never both. Content replacement preserves the canonical value and existing metadata; value replacement is revalidated and recomputes content/metadata; a block removes the value and becomes an `isError` containing corrective feedback. Content replacement is presentation policy, not confidentiality policy: a listener that must hide the programmatic value blocks or replaces it. `tools/result` receives the frozen execution and result after normalization; observers cannot transform them, and observer failures are contained. Unknown and throwing tools both become structured errors (`ToolNotFoundError` maps to `UNKNOWN_TOOL`), so the call fails without ending the turn. A tool body whose composition or call lacks a required Agent, service, or open turn throws `ToolContextUnavailableError` (`TOOL_CONTEXT_UNAVAILABLE`).
|
||||
|
||||
## The enforced raw JSON Schema subset
|
||||
|
||||
|
||||
@@ -571,7 +571,7 @@ type PostToolDecision =
|
||||
|
||||
调用 `next()` 获取默认决策,或直接返回一个决策以短路。前置策略可以 deny 或 ask;只有 `allowed-once` 才继续执行,而未授权、缺少审批通道或服务、或无 agent 的请求都会变为拒绝。拒绝可以附带结构化身份与用户可见详情,而不改变其模型可见原因。Guard 仍可施加最终拒绝。参数不可被改写,因为历史记录、审计、UI 和执行必须保持一致。
|
||||
|
||||
后置策略可以替换内容或值,但不能同时替换两者。替换内容会保留规范值和现有元数据;替换值会重新校验并重新计算内容/元数据;阻止会移除值,并转为包含纠正反馈的 `isError`。内容替换是展示策略,而非保密策略;需要隐藏程序化值的监听器必须阻止或替换该值。`tools/result` 在归一化后接收冻结的执行和结果;观察者无法对其进行变换,观察者的失败也会被隔离。未知工具和抛出异常的工具都会变为结构化错误(`ToolNotFoundError` 映射为 `UNKNOWN_TOOL`),调用失败但不终止当前轮次。
|
||||
后置策略可以替换内容或值,但不能同时替换两者。替换内容会保留规范值和现有元数据;替换值会重新校验并重新计算内容/元数据;阻止会移除值,并转为包含纠正反馈的 `isError`。内容替换是展示策略,而非保密策略;需要隐藏程序化值的监听器必须阻止或替换该值。`tools/result` 在归一化后接收冻结的执行和结果;观察者无法对其进行变换,观察者的失败也会被隔离。未知工具和抛出异常的工具都会变为结构化错误(`ToolNotFoundError` 映射为 `UNKNOWN_TOOL`),调用失败但不终止当前轮次。工具主体所需的 Agent、服务或进行中的 turn 不存在时,抛出 `ToolContextUnavailableError`(`TOOL_CONTEXT_UNAVAILABLE`)。
|
||||
|
||||
## 已强制执行的原始 JSON Schema 子集
|
||||
|
||||
|
||||
@@ -318,6 +318,26 @@ export class ToolNotFoundError extends HarnessError {
|
||||
}
|
||||
}
|
||||
|
||||
/** Code of {@link ToolContextUnavailableError}. */
|
||||
export const TOOL_CONTEXT_UNAVAILABLE = 'TOOL_CONTEXT_UNAVAILABLE'
|
||||
|
||||
/**
|
||||
* Thrown by a tool body when its composition or call lacks context the tool
|
||||
* requires, such as a calling Agent, an injected service, or an open turn.
|
||||
* The failure is not an argument the model can correct; `message` names the
|
||||
* missing context.
|
||||
*/
|
||||
export class ToolContextUnavailableError extends HarnessError {
|
||||
/**
|
||||
* @param message - names the tool and the missing context.
|
||||
* @param options - standard `cause` chaining.
|
||||
*/
|
||||
constructor(message: string, options?: ErrorOptions) {
|
||||
super(message, TOOL_CONTEXT_UNAVAILABLE, options)
|
||||
this.name = 'ToolContextUnavailableError'
|
||||
}
|
||||
}
|
||||
|
||||
/** Thrown when a tool body or post-policy value violates its declared output. */
|
||||
export class ToolOutputError extends HarnessError {
|
||||
/** Schema/value violations in validation order. */
|
||||
|
||||
@@ -11,7 +11,7 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
|
||||
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
|
||||
import ApprovalService, { type ApprovalOutcome, type ApprovalRequest } from '@deepseek-ai/dsh-user-approval'
|
||||
import ToolRuntime, { APPROVAL_CANCELLED, APPROVAL_ERROR_NAME, APPROVAL_REJECTED, APPROVAL_UNAVAILABLE, defineTool, JsonSchemaError, parameterSchemaSpecToJsonSchema, validateArgs, ToolArgsError, ToolNotFoundError, TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, type InferArgs, type ParameterSchemaSpec, type PreToolDecision, type PostToolDecision, type JsonSchemaNode, type ToolDefinition, type ToolDispatchExecution, type ToolExecutionResult, type ToolExecutionToken } from '@deepseek-ai/dsh-tools'
|
||||
import ToolRuntime, { TOOL_CONTEXT_UNAVAILABLE, ToolContextUnavailableError, APPROVAL_CANCELLED, APPROVAL_ERROR_NAME, APPROVAL_REJECTED, APPROVAL_UNAVAILABLE, defineTool, JsonSchemaError, parameterSchemaSpecToJsonSchema, validateArgs, ToolArgsError, ToolNotFoundError, TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, type InferArgs, type ParameterSchemaSpec, type PreToolDecision, type PostToolDecision, type JsonSchemaNode, type ToolDefinition, type ToolDispatchExecution, type ToolExecutionResult, type ToolExecutionToken } from '@deepseek-ai/dsh-tools'
|
||||
import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit'
|
||||
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
|
||||
|
||||
@@ -793,6 +793,25 @@ describe('ToolRuntime', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('records ToolContextUnavailableError thrown by a tool body', async () => {
|
||||
const ctx = await setup()
|
||||
ctx.tools.register({
|
||||
...echoTool,
|
||||
name: 'needs-agent',
|
||||
execute() { return Promise.reject(new ToolContextUnavailableError('needs-agent requires a calling agent')) },
|
||||
})
|
||||
|
||||
const result = await executeToolFixture(ctx, {
|
||||
signal: testToolSignal, callId: ToolCallId('needs-agent'), name: 'needs-agent', arguments: {},
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({
|
||||
content: [{ type: 'text', text: 'Error: needs-agent requires a calling agent' }],
|
||||
isError: true,
|
||||
error: { info: { name: 'ToolContextUnavailableError', code: TOOL_CONTEXT_UNAVAILABLE } },
|
||||
})
|
||||
})
|
||||
|
||||
it('ToolNotFoundError carries a stable message and code', async () => {
|
||||
const { HarnessError } = await import('@deepseek-ai/dsh-llm')
|
||||
const err = new ToolNotFoundError('ghost')
|
||||
|
||||
Reference in new issue
Block a user