diff --git a/.agents/notes/implemented/bug-fix/2026-07-20-error-cause-chain-diagnostics.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-07-20-error-cause-chain-diagnostics.i18n.yaml new file mode 100644 index 0000000000..630a1b05e6 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-07-20-error-cause-chain-diagnostics.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write +2026-07-20-error-cause-chain-diagnostics.md: 2d860d0e966158dd9ec12b45f88e3b031e1cb35a +2026-07-20-error-cause-chain-diagnostics.zh.md: 6eac19dd08d50e4662d53889577b5e3ddabaafdd diff --git a/.agents/notes/implemented/bug-fix/2026-07-20-error-cause-chain-diagnostics.md b/.agents/notes/implemented/bug-fix/2026-07-20-error-cause-chain-diagnostics.md new file mode 100644 index 0000000000..2d860d0e96 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-07-20-error-cause-chain-diagnostics.md @@ -0,0 +1,37 @@ +# Agent Note: Render error cause chains at every diagnostic seam + +Status: implemented + +English | [中文](2026-07-20-error-cause-chain-diagnostics.zh.md) + +## Problem + +A TUI run against an unreachable DeepSeek endpoint failed with the single notice `fetch failed` and no further detail. Two independent gaps produced that dead end: + +1. undici's `fetch` wraps every transport failure (DNS, refused connection, TLS, proxy) in a bare `TypeError: fetch failed` whose actionable detail — `ECONNREFUSED`, `bad port`, the Happy Eyeballs AggregateError — lives on `error.cause`. Every diagnostic seam in the harness rendered only `error.message` (or `String(error)`, which is equivalent for Errors), so the wrapper masked the diagnosis in the TUI notice, the durable `turn/end` reason, and every logger line. +2. The readline front door (`dsh-stdio`) rendered no failure reason at all: a `turn/end` with `reason.kind === 'error'` printed nothing but the next `> ` prompt, so the same failure in `demo:repl` was pure silence. + +## Decision + +- `dsh-llm` exports `errorChain(value)`: renders a thrown value with its full `cause` chain (`outer: inner: …`) and AggregateError members (`msg [m1; m2]`), with circular-cause and hostile-coercion containment. It is a diagnostic-surface renderer only; routing stays on `HarnessError.code`. +- The DeepSeek adapter wraps a pre-response transport failure in `LlmError('NETWORK')` naming the configured `baseURL` and chaining the original `TypeError` as `cause`. An aborted request keeps its `DOMException` so the loop still classifies it as cancellation, not a provider failure. +- Every diagnostic seam renders through `errorChain` instead of `error.message`/`String(error)`: the agent-loop's durable `turn/end` error message (`errorData`), its logger warnings, the TUI's `agent/error` notice and startup-failure line, and `dsh-stdio`'s startup-failure log lines. The per-package `renderThrown` copies in `dsh-agent-loop`, `dsh-stdio`, and `dsh-tui` are deleted in favor of the one shared renderer. +- `dsh-stdio` renders failure `turn/end` reasons: `[turn failed ] `, `[turn aborted] `, `[turn rejected] `, `[turn interrupted by a previous process exit]`, and the output-token-limit notice. Unknown merge-extended kinds fall through as ordinary turn ends. + +`errorChain` lives in `dsh-llm` beside `HarnessError` for the same reason the base class does: it is the leaf package every consumer already imports, so sharing costs no new dependency edge. + +## Alternatives considered + +**Chain rendering inside each error's constructor (bake the cause into `message`).** Rejected: it double-renders once consumers also walk `cause` (the first draft of the adapter fix produced `… fetch failed: bad port: fetch failed: bad port`), and it destroys the structured chain for consumers that want to route on the inner error. + +**A `cause`-aware logger exporter only.** Rejected: the durable `turn/end` reason and the TUI notice are not logger lines; the masked message would persist in the session log — the single durable record of an in-turn failure — and in the primary UI surface. + +**Per-package `renderThrown` upgrades.** Rejected: three packages already carried near-identical private copies; upgrading each separately entrenches the duplication the shared renderer removes. + +## Consequences + +- A transport failure now reads `DeepSeek API request to failed: fetch failed: connect ECONNREFUSED …` in the TUI notice, the readline transcript, and the persisted session log, at the cost of longer diagnostic strings. +- Durable `turn/end` error messages include cause detail. Existing snapshot fixtures replay byte-identically because their scripted errors carry no `cause` (for such errors `errorChain(err)` equals `err.message`); only unit-test expectation strings changed. A fixture recorded from a real transport failure would carry the chain. +- `errorChain` renders `message` without the class name (`String(error)` rendered `Error: `), so a bare `TypeError` in a log line loses its type label unless its message is empty (then the name is the fallback). The chain detail was judged worth more than the class name at these seams. +- `dsh-stdio` output for failed turns is no longer silent; piped consumers that parsed the transcript see new `[turn …]` lines. +- Remaining `renderThrown` copies in `dsh-subagent`, `dsh-workflow`, `dsh-skill`, `dsh-workflow-workerthread`, and `cli-demo` still render without the chain; they wrap package-local errors that carry their own messages, and can adopt `errorChain` when their diagnostics prove insufficient. diff --git a/.agents/notes/implemented/bug-fix/2026-07-20-error-cause-chain-diagnostics.zh.md b/.agents/notes/implemented/bug-fix/2026-07-20-error-cause-chain-diagnostics.zh.md new file mode 100644 index 0000000000..6eac19dd08 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-07-20-error-cause-chain-diagnostics.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 在每个诊断接缝处渲染错误 cause 链 + +Status: implemented + +[English](2026-07-20-error-cause-chain-diagnostics.md) | 中文 + +## Problem + +TUI 连接不可达的 DeepSeek 端点时,失败只显示一条 `fetch failed` 通知,没有任何进一步细节。两个独立缺口共同造成了这个死胡同: + +1. undici 的 `fetch` 把所有传输层失败(DNS、连接被拒、TLS、代理)包装成裸的 `TypeError: fetch failed`,可操作的细节——`ECONNREFUSED`、`bad port`、Happy Eyeballs 的 AggregateError——都在 `error.cause` 上。harness 里的每个诊断接缝都只渲染 `error.message`(或对 Error 等价的 `String(error)`),于是包装层在 TUI 通知、持久化的 `turn/end` reason 和所有日志行里都掩盖了诊断信息。 +2. readline 前门(`dsh-stdio`)完全不渲染失败原因:`reason.kind === 'error'` 的 `turn/end` 只打印下一个 `> ` 提示符,同样的失败在 `demo:repl` 里就是纯粹的沉默。 + +## Decision + +- `dsh-llm` 导出 `errorChain(value)`:渲染抛出值及其完整 `cause` 链(`outer: inner: …`)与 AggregateError 成员(`msg [m1; m2]`),并容错循环 cause 和恶意强制转换。它只是诊断表面的渲染器;路由仍然基于 `HarnessError.code`。 +- DeepSeek 适配器把拿到响应之前的传输失败包装成 `LlmError('NETWORK')`,写明配置的 `baseURL` 并把原始 `TypeError` 链为 `cause`。被中止的请求保留其 `DOMException`,使循环仍将其归类为取消而非 provider 失败。 +- 每个诊断接缝改用 `errorChain` 而非 `error.message`/`String(error)`:agent-loop 的持久化 `turn/end` 错误消息(`errorData`)、其日志警告、TUI 的 `agent/error` 通知与启动失败行、以及 `dsh-stdio` 的启动失败日志行。`dsh-agent-loop`、`dsh-stdio`、`dsh-tui` 里各自的 `renderThrown` 副本被删除,统一使用这一个共享渲染器。 +- `dsh-stdio` 渲染失败的 `turn/end` reason:`[turn failed ] `、`[turn aborted] `、`[turn rejected] `、`[turn interrupted by a previous process exit]` 以及输出 token 上限通知。未知的 merge 扩展 kind 按普通 turn 结束处理。 + +`errorChain` 与 `HarnessError` 一样放在 `dsh-llm` 里,理由相同:它是每个消费者都已导入的叶子包,共享不增加新的依赖边。 + +## Alternatives considered + +**在每个错误的构造函数里渲染链(把 cause 烤进 `message`)。** 否决:当消费者同时遍历 `cause` 时会双重渲染(适配器修复的第一版产出了 `… fetch failed: bad port: fetch failed: bad port`),并且破坏了想按内层错误路由的消费者所需的结构化链。 + +**只做一个感知 `cause` 的日志导出器。** 否决:持久化的 `turn/end` reason 和 TUI 通知不是日志行;被掩盖的消息会留在会话日志——回合内失败的唯一持久记录——以及主要 UI 表面里。 + +**逐包升级 `renderThrown`。** 否决:三个包已经各自持有几乎相同的私有副本;分别升级只会固化共享渲染器所要消除的重复。 + +## Consequences + +- 传输失败现在在 TUI 通知、readline transcript 和持久化会话日志里显示为 `DeepSeek API request to failed: fetch failed: connect ECONNREFUSED …`,代价是更长的诊断字符串。 +- 持久化的 `turn/end` 错误消息包含 cause 细节。现有 snapshot fixture 字节级一致地回放,因为其脚本化错误不带 `cause`(对这类错误 `errorChain(err)` 等于 `err.message`);只有单元测试的期望字符串有变化。从真实传输失败录制的 fixture 会携带完整链。 +- `errorChain` 渲染 `message` 而不带类名(`String(error)` 会渲染 `Error: `),因此日志行里的裸 `TypeError` 会丢失类型标签,除非消息为空(此时回退到类名)。在这些接缝上,链细节被判断为比类名更有价值。 +- `dsh-stdio` 对失败回合的输出不再沉默;解析 transcript 的管道消费者会看到新的 `[turn …]` 行。 +- `dsh-subagent`、`dsh-workflow`、`dsh-skill`、`dsh-workflow-workerthread`、`cli-demo` 里剩余的 `renderThrown` 副本仍不渲染链;它们包装的是自带消息的包内错误,等诊断信息证明不足时再采用 `errorChain`。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 49b5995515..198c9fbbaa 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -103,7 +103,7 @@ export interface Config { Depends on: [`AgentOptions`](core-data-structures/core.md) · [`SessionId`](core-data-structures/core.md) -Source: [`packages/core/agent-loop/src/index.ts:369`](../packages/core/agent-loop/src/index.ts) +Source: [`packages/core/agent-loop/src/index.ts:360`](../packages/core/agent-loop/src/index.ts) ## `@deepseek-ai/dsh-agent-spine-demo` @@ -1249,7 +1249,7 @@ export interface TuiConfig { } ``` -Source: [`packages/ui/tui/src/index.ts:100`](../packages/ui/tui/src/index.ts) +Source: [`packages/ui/tui/src/index.ts:101`](../packages/ui/tui/src/index.ts) ## `@deepseek-ai/dsh-tui-demo` diff --git a/docs/cordis-catalog/events.md b/docs/cordis-catalog/events.md index b78b395959..f0812c7280 100644 --- a/docs/cordis-catalog/events.md +++ b/docs/cordis-catalog/events.md @@ -366,7 +366,7 @@ A declarative agent entry failed before it could publish a live agent. Consumers Types: [SessionId](../core-data-structures/core.md) -Source: [`packages/core/agent-loop/src/index.ts:362`](../../packages/core/agent-loop/src/index.ts) +Source: [`packages/core/agent-loop/src/index.ts:353`](../../packages/core/agent-loop/src/index.ts) ## `approval/*` diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 94d181d110..bad8b6a302 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -44,7 +44,7 @@ async resume(ownerCtx: Context, options: ResumeAgentOptions): Promise { - const rendered = renderThrown(error) + const rendered = errorChain(error) const err = error instanceof Error ? error : new Error(rendered) this.loopCtx.logger.warn(`agent "${this.id}": flush after idle injection failed: ${rendered}`) agentEvents(this.loopCtx, this).emit('agent/error', turn, 0, err) @@ -444,8 +443,3 @@ export class ReactLoopAgent implements Agent { } } } - -/** Render an ordinary thrown value for the error event and log. */ -function renderThrown(value: unknown): string { - return value instanceof Error ? value.message : String(value) -} diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 7268182552..bdaa3f2401 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -20,7 +20,7 @@ import type { ResumeAgentOptions, SessionStartSource, } from '@deepseek-ai/dsh-agent' -import type {} from '@deepseek-ai/dsh-llm' +import { errorChain } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import type { Session, SessionHeader } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-system-prompt' @@ -41,15 +41,6 @@ const INACTIVE_STATES: ReadonlySet = new Set([ FiberState.FAILED, ]) -/** Render an arbitrary thrown value without letting coercion escape containment. */ -function renderThrown(value: unknown): string { - try { - return String(value) - } catch { - return '' - } -} - /** Factory-level ownership of every preparing or live transaction. */ class FactoryOwnership { private accepting = true @@ -475,16 +466,16 @@ export class AgentLoop extends Service implements AgentFactory { error: unknown, ): void { if (!this.ownership.isActive()) return - this.ctx.logger.warn(`agent "${configId}": config-driven ${action} of "${sessionId}" failed: ${renderThrown(error)}`) + this.ctx.logger.warn(`agent "${configId}": config-driven ${action} of "${sessionId}" failed: ${errorChain(error)}`) const args: unknown[] = ['agent-loop/config-start-failed', sessionId, error] for (const callback of this.ctx.events.dispatch('emit', args)) { try { const returned: unknown = callback(...args) void Promise.resolve(returned).catch((listenerError: unknown) => { - this.ctx.logger.warn(`agent "${configId}": config-start-failed listener rejected: ${renderThrown(listenerError)}`) + this.ctx.logger.warn(`agent "${configId}": config-start-failed listener rejected: ${errorChain(listenerError)}`) }) } catch (listenerError: unknown) { - this.ctx.logger.warn(`agent "${configId}": config-start-failed listener threw: ${renderThrown(listenerError)}`) + this.ctx.logger.warn(`agent "${configId}": config-start-failed listener threw: ${errorChain(listenerError)}`) } } } diff --git a/packages/core/agent-loop/src/loop.ts b/packages/core/agent-loop/src/loop.ts index e8008996a9..f7e907ae83 100644 --- a/packages/core/agent-loop/src/loop.ts +++ b/packages/core/agent-loop/src/loop.ts @@ -8,7 +8,7 @@ import type { Context } from 'cordis' import type { ContentBlock, FinishReason, GenerateOptions, LlmCallConfig, Message } from '@deepseek-ai/dsh-llm' import { isDeepStrictEqual } from 'node:util' -import { BlockAssembler, HarnessError, assertNever, deepFreeze, isLlmAdapterFailure } from '@deepseek-ai/dsh-llm' +import { BlockAssembler, HarnessError, assertNever, deepFreeze, errorChain, isLlmAdapterFailure } from '@deepseek-ai/dsh-llm' import { agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' import type { AgentEventDispatch, ContinuationDecision, HookContext, PromptDecision, RequestError, RequestErrorDecision } from '@deepseek-ai/dsh-agent' import { canonicalHeader } from '@deepseek-ai/dsh-session' @@ -56,9 +56,12 @@ function finishError(finish: FinishReason): RequestError | undefined { /** * Build the `{ message, code? }` part of an error payload, omitting the * `code` key entirely when absent (exactOptionalPropertyTypes-correct). + * The durable message renders the full cause chain: `turn/end` is the single + * durable record of an in-turn failure, so a wrapper message alone (e.g. + * `fetch failed`) would lose the diagnosis the session log exists to keep. */ function errorData(err: RequestError): { message: string; code?: string } { - return { message: err.message, ...typeof err.code === 'string' ? { code: err.code } : {} } + return { message: errorChain(err), ...typeof err.code === 'string' ? { code: err.code } : {} } } /** Map a successful max-token finish onto the turn reason; other successful finishes add nothing. */ @@ -166,7 +169,7 @@ export async function runLoop(ctx: Context, handle: LoopHandle): Promise { } catch (error: unknown) { // Pre-turn failure has no durable boundary to close; report it without appending outside a turn. const err = toError(error) - ctx.logger.warn(`agent "${agent.id}": turn ${turn} failed before it started: ${err.message}`) + ctx.logger.warn(`agent "${agent.id}": turn ${turn} failed before it started: ${errorChain(err)}`) try { events.emit('agent/error', turn, 0, err) } catch { /* contained: a throwing agent/error listener must not kill the driver */ } @@ -382,7 +385,7 @@ async function runTurn( ) } catch (recoveryError: unknown) { ctx.logger.warn( - `agent "${agent.id}": request recovery failed at turn ${turn}, step ${step}: ${toError(recoveryError).message}`, + `agent "${agent.id}": request recovery failed at turn ${turn}, step ${step}: ${errorChain(recoveryError)}`, ) } handle.setAbort(undefined) @@ -546,7 +549,7 @@ async function runTurn( } catch (error: unknown) { // The turn is closed, so report the failed flush live rather than append outside a turn. const err = toError(error) - ctx.logger.warn(`agent "${agent.id}": session/flush failed at turn ${turn}: ${err.message}`) + ctx.logger.warn(`agent "${agent.id}": session/flush failed at turn ${turn}: ${errorChain(err)}`) try { events.emit('agent/error', turn, step, err) } catch { diff --git a/packages/core/agent-loop/tests/config-session-id.spec.ts b/packages/core/agent-loop/tests/config-session-id.spec.ts index c7e2d3ac5b..2103dd6831 100644 --- a/packages/core/agent-loop/tests/config-session-id.spec.ts +++ b/packages/core/agent-loop/tests/config-session-id.spec.ts @@ -217,14 +217,14 @@ describe('config-driven session id', () => { }) await expect.poll(() => warn).toHaveBeenCalledWith(expect.stringContaining( - 'config-driven restore of "config-exact-failure" failed: Error: persistence index failed', + 'config-driven restore of "config-exact-failure" failed: persistence index failed', )) expect(failures).toEqual([{ sessionId: SessionId('config-exact-failure'), error: failure }]) expect(warn).toHaveBeenCalledWith( - 'agent "main": config-start-failed listener threw: Error: failure observer failed', + 'agent "main": config-start-failed listener threw: failure observer failed', ) await expect.poll(() => warn).toHaveBeenCalledWith( - 'agent "main": config-start-failed listener rejected: Error: async failure observer failed', + 'agent "main": config-start-failed listener rejected: async failure observer failed', ) expect(ctx.agents.get(SessionId('config-exact-failure'))).toBeUndefined() warn.mockRestore() @@ -256,13 +256,13 @@ describe('config-driven session id', () => { await expect.poll(() => failures).toEqual([unrenderable]) expect(warn).toHaveBeenCalledWith( - 'agent "main": config-driven restore of "config-exact-unrenderable" failed: ', + 'agent "main": config-driven restore of "config-exact-unrenderable" failed: ', ) expect(warn).toHaveBeenCalledWith( - 'agent "main": config-start-failed listener threw: ', + 'agent "main": config-start-failed listener threw: ', ) await expect.poll(() => warn).toHaveBeenCalledWith( - 'agent "main": config-start-failed listener rejected: ', + 'agent "main": config-start-failed listener rejected: ', ) await ctx.fiber.dispose() }) diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 27bf4b626a..ee4c705560 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -42,7 +42,7 @@ Every request carries the shared attribution header from dsh-llm's `attributionH ## Errors -Non-2xx responses throw `LlmError` with stable codes: `AUTH` (401/403), `RATE_LIMIT` (429), `CONTEXT_WINDOW_EXCEEDED` (a 400 whose provider code, type, or message identifies context overflow), `INVALID_REQUEST` (other 400s), `SERVER` (5xx), `HTTP_` otherwise. Protocol violations throw `STREAM_CLOSED` (no `[DONE]`) or `MALFORMED_RESPONSE` (bad JSON payload). Unknown wire `finish_reason`s (e.g. `content_filter`, `insufficient_system_resource`) become `finish {kind: 'error', code: }` chunks. +Non-2xx responses throw `LlmError` with stable codes: `AUTH` (401/403), `RATE_LIMIT` (429), `CONTEXT_WINDOW_EXCEEDED` (a 400 whose provider code, type, or message identifies context overflow), `INVALID_REQUEST` (other 400s), `SERVER` (5xx), `HTTP_` otherwise. A transport failure before any response (DNS, refused connection, TLS, proxy) throws `NETWORK` naming the configured endpoint and chaining fetch's `TypeError: fetch failed` as `cause`, so `errorChain` renders the underlying diagnosis; an abort keeps its `DOMException` so the loop classifies it as cancellation. Protocol violations throw `STREAM_CLOSED` (no `[DONE]`) or `MALFORMED_RESPONSE` (bad JSON payload). Unknown wire `finish_reason`s (e.g. `content_filter`, `insufficient_system_resource`) become `finish {kind: 'error', code: }` chunks. ## Testing diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index 918c8eee82..66520a83d4 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -81,23 +81,43 @@ export class DeepSeekAdapter extends LlmAdapter { async * stream(options: GenerateOptions): AsyncIterable { const body = serializeRequest(options, this.options.defaults ?? {}) + // Prepared outside the try so the NETWORK label below covers exactly the + // transport boundary, never a serialization failure. + const payload = JSON.stringify(body) + const headers = { + 'authorization': `Bearer ${this.options.apiKey}`, + 'content-type': 'application/json', + 'accept': 'text/event-stream', + ...attributionHeaders(), + ...options.sessionId !== undefined + ? { 'x-deepseek-harness-session-id': String(options.sessionId) } + : {}, + } // TODO(http): adopt the Cordis HTTP service when shared transport configuration // outweighs its additional runtime dependencies. - const response = await fetch(`${this.options.baseURL}/chat/completions`, { - method: 'POST', - headers: { - 'authorization': `Bearer ${this.options.apiKey}`, - 'content-type': 'application/json', - 'accept': 'text/event-stream', - ...attributionHeaders(), - ...options.sessionId !== undefined - ? { 'x-deepseek-harness-session-id': String(options.sessionId) } - : {}, - }, - body: JSON.stringify(body), - ...options.signal ? { signal: options.signal } : {}, - }) + let response: Response + try { + response = await fetch(`${this.options.baseURL}/chat/completions`, { + method: 'POST', + headers, + body: payload, + ...options.signal ? { signal: options.signal } : {}, + }) + } catch (error: unknown) { + // An aborted request rethrows its original rejection (the signal's abort + // reason) so the loop classifies it as cancellation, not a provider failure. + if (options.signal?.aborted) throw error + // fetch wraps every transport failure (DNS, refused connection, TLS, + // proxy) in a bare `TypeError: fetch failed` whose actionable detail + // lives on `cause`. Wrapping with the endpoint and chaining the cause + // lets `errorChain` render the full diagnosis at every reporting seam. + throw new LlmError( + `DeepSeek API request to ${this.options.baseURL} failed`, + 'NETWORK', + { cause: error }, + ) + } if (!response.ok) { let message = `DeepSeek API error (HTTP ${response.status})` diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts index 954a0ecebd..b92f96dbda 100644 --- a/packages/llm/llm-deepseek/tests/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts @@ -2,7 +2,7 @@ import { createServer } from 'node:http' import type { IncomingMessage, Server, ServerResponse } from 'node:http' import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' -import LlmService, { CONTEXT_WINDOW_EXCEEDED_CODE, LlmError, userAgent } from '@deepseek-ai/dsh-llm' +import LlmService, { CONTEXT_WINDOW_EXCEEDED_CODE, errorChain, LlmError, userAgent } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import { DeepSeekAdapter } from '@deepseek-ai/dsh-llm-deepseek' @@ -228,6 +228,39 @@ describe('DeepSeekAdapter against a mock server', () => { expect(httpErrorCode(418)).toBe('HTTP_418') }) + it('wraps a transport failure in NETWORK with the fetch cause chain in the message', async () => { + // Port 1 is reserved/unbound: fetch rejects with `TypeError: fetch failed` + // whose actionable detail (ECONNREFUSED) lives on `cause`. + const ctx = await harness('http://127.0.0.1:1') + let caught: unknown + try { + await assemble(ctx, { model: 'deepseek-v4-flash', messages: [] }) + } catch (error: unknown) { + caught = error + } + expect(caught).toBeInstanceOf(LlmError) + const llmError = caught as LlmError + expect(llmError.code).toBe('NETWORK') + expect(llmError.message).toContain('http://127.0.0.1:1') + expect(llmError.cause).toBeInstanceOf(TypeError) + // The chain renderer reaches the transport diagnosis through the cause. + expect(errorChain(llmError)).toMatch(/ECONNREFUSED|EADDRNOTAVAIL|bad port/) + }) + + it('keeps an abort rejection unwrapped so the loop classifies it as cancellation', async () => { + const controller = new AbortController() + controller.abort() + const ctx = await harness('http://127.0.0.1:1') + let caught: unknown + try { + await assemble(ctx, { model: 'deepseek-v4-flash', messages: [], signal: controller.signal }) + } catch (error: unknown) { + caught = error + } + expect(caught).not.toBeInstanceOf(LlmError) + expect((caught as Error).name).toBe('AbortError') + }) + it('throws EMPTY_RESPONSE when the response has no body', async () => { const adapter = new DeepSeekAdapter({ apiKey: 'k', baseURL: 'http://127.0.0.1:1' }) const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue( diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md index f9142dbc52..82ca7f901c 100644 --- a/packages/llm/llm/README.md +++ b/packages/llm/llm/README.md @@ -48,6 +48,7 @@ Every product adapter sends application identity on provider HTTP requests. `att - `BlockAssembler` — incrementally assembles raw chunks into complete content blocks and an assistant message. The agent loop feeds it raw chunks (logging them for replay) while reading the assembled blocks/message for history. - `HarnessError` — base class for the harness error taxonomy: a stable `code` string (distinct from the human `message`) plus `cause` chaining. Lives here, in the leaf package every other imports, so a single base is shared without a new dependency edge. Per-package errors (`LlmError`, `ToolArgsError`, `InvariantError`, …) extend it. `isHarnessError(value)` narrows at seams. - `LlmError` — extends `HarnessError`; its stable `code` string (`NO_ADAPTER`, `DUPLICATE_ADAPTER`, and adapter codes like `AUTH`/`RATE_LIMIT`) is the programmatic failure contract. +- `errorChain(value)` — renders a thrown value with its full `cause` chain and AggregateError members for diagnostic surfaces (UI notices, logger lines, durable `turn/end` messages), so transport wrappers like undici's `TypeError: fetch failed` surface the underlying `ECONNREFUSED`/DNS/TLS detail instead of masking it. Rendering only — route on `code`, never by parsing the result. - `CONTEXT_WINDOW_EXCEEDED_CODE` — the provider-neutral code both DeepSeek adapters use when a request exceeds the model context window, regardless of thrown-HTTP versus in-band finish delivery. `isContextWindowExceededError(detail)` is their shared conservative classifier for OpenAI-compatible provider detail. ### Real adapters diff --git a/packages/llm/llm/src/error.ts b/packages/llm/llm/src/error.ts index 8c1c736492..c351060ee5 100644 --- a/packages/llm/llm/src/error.ts +++ b/packages/llm/llm/src/error.ts @@ -62,6 +62,51 @@ export function isContextWindowExceededError(detail: string): boolean { || EXCEEDS_MODEL_CONTEXT.test(detail) } +/** + * Render a thrown value with its full `cause` chain and AggregateError + * members, so transport wrappers like undici's `TypeError: fetch failed` + * surface the underlying failure instead of masking it. Diagnostic-surface + * rendering only (messages, notices, logs) — never parse the result; route on + * {@link HarnessError.code}. + * @param value - the caught value (`unknown` in catch clauses). + * @returns the outermost message first, each cause appended with `: ` (skipped + * when it repeats the wrapper message verbatim), and AggregateError members + * bracketed and `; `-joined. + */ +export function errorChain(value: unknown): string { + // Tracks the active recursion path (entries removed on exit), so only true + // cycles are flagged and a diamond-shared cause still renders in full. + const path = new Set() + const render = (current: unknown): string => { + if (path.has(current)) return '' + path.add(current) + try { + if (!(current instanceof Error)) return String(current) + const message = current.message === '' ? current.name : current.message + const members = current instanceof AggregateError && current.errors.length > 0 + ? ` [${current.errors.map(render).join('; ')}]` + : '' + const causeText = current.cause === undefined || current.cause === null + ? '' + : render(current.cause) + // Wrappers like `new HarnessError(String(value), code, { cause: value })` + // repeat their cause verbatim; rendering it again would only add noise. + const cause = causeText === '' || causeText === message ? '' : `: ${causeText}` + return `${message}${members}${cause}` + } catch { + // Only hostile coercion or hostile accessors (a throwing toString / + // Symbol.toPrimitive on a non-Error, or a throwing message/name/cause/ + // errors getter on an Error subclass): this renderer feeds UI notices + // and logs, so nothing may escape. Inner frames catch their own throws, + // so only the hostile node collapses, not the whole chain. + return '' + } finally { + path.delete(current) + } + } + return render(value) +} + /** * Narrow an arbitrary thrown value to a HarnessError (for `instanceof` at seams). * @param value - the caught value (`unknown` in catch clauses). diff --git a/packages/llm/llm/tests/service.spec.ts b/packages/llm/llm/tests/service.spec.ts index 6e14d749ba..67b90d1c2f 100644 --- a/packages/llm/llm/tests/service.spec.ts +++ b/packages/llm/llm/tests/service.spec.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { Context } from 'cordis' import LlmService, { + errorChain, GenerateOptions, HarnessError, isContextWindowExceededError, @@ -80,6 +81,50 @@ describe('LlmService', () => { expect(isContextWindowExceededError('context window size must be positive')).toBe(false) }) + it('errorChain renders the full cause chain of a wrapped transport failure', () => { + const chain = new TypeError('fetch failed', { cause: new Error('connect ECONNREFUSED 127.0.0.1:443') }) + expect(errorChain(chain)).toBe('fetch failed: connect ECONNREFUSED 127.0.0.1:443') + }) + + it('errorChain renders AggregateError members (Happy Eyeballs multi-address failures)', () => { + const aggregate = new AggregateError( + [new Error('connect ECONNREFUSED ::1:443'), new Error('connect ECONNREFUSED 127.0.0.1:443')], + '', + ) + const wrapped = new TypeError('fetch failed', { cause: aggregate }) + expect(errorChain(wrapped)).toBe( + 'fetch failed: AggregateError [connect ECONNREFUSED ::1:443; connect ECONNREFUSED 127.0.0.1:443]', + ) + }) + + it('errorChain survives non-Error values, hostile coercion, and circular causes', () => { + expect(errorChain('plain string')).toBe('plain string') + expect(errorChain({ toString: () => { throw new Error('hostile') } })).toBe('') + const circular = new Error('outer') + circular.cause = circular + expect(errorChain(circular)).toBe('outer: ') + // A hostile accessor collapses only its own node, not the whole chain. + const hostileNode = new Error('node') + Object.defineProperty(hostileNode, 'message', { get() { throw new Error('hostile getter') } }) + expect(errorChain(new Error('outer', { cause: hostileNode }))).toBe('outer: ') + // A diamond-shared (non-cyclic) cause renders in full on both paths. + const shared = new Error('shared') + const diamond = new AggregateError([new Error('a', { cause: shared }), new Error('b', { cause: shared })], 'agg') + expect(errorChain(diamond)).toBe('agg [a: shared; b: shared]') + }) + + it('errorChain falls back to the error name, skips empty aggregates, and stops at null causes', () => { + expect(errorChain(new TypeError('', { cause: null }))).toBe('TypeError') + expect(errorChain(new AggregateError([], 'all failed'))).toBe('all failed') + }) + + it('errorChain collapses a cause that repeats the wrapper message verbatim', () => { + // The `new HarnessError(String(value), code, { cause: value })` normalization + // pattern repeats its cause; rendering it twice would only add noise. + const wrapped = new HarnessError('boom', 'UNKNOWN', { cause: 'boom' }) + expect(errorChain(wrapped)).toBe('boom') + }) + it('routes stream() to the registered adapter', async () => { const ctx = new Context() await ctx.plugin(LlmService) diff --git a/packages/ui/tui/src/index.ts b/packages/ui/tui/src/index.ts index 46e68566d7..35721669fb 100644 --- a/packages/ui/tui/src/index.ts +++ b/packages/ui/tui/src/index.ts @@ -35,6 +35,7 @@ import type { Context } from 'cordis' import z from 'schemastery' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-agent-loop' +import { errorChain } from '@deepseek-ai/dsh-llm' import type { ContentBlock, StreamChunk } from '@deepseek-ai/dsh-llm' import { SessionId, type Session, type SessionEvent, type TodoItem } from '@deepseek-ai/dsh-session' import type { @@ -191,15 +192,6 @@ function displayText(text: string): string { `\\x${control.charCodeAt(0).toString(16).padStart(2, '0')}`) } -/** Render an arbitrary failure without allowing hostile coercion to escape the UI boundary. */ -function renderThrown(value: unknown): string { - try { - return String(value) - } catch { - return '' - } -} - /** * Theme-agnostic palette built from the standard 16-color ANSI set plus SGR * attributes, which every terminal remaps to its active color scheme. Body @@ -1263,7 +1255,9 @@ export function createTuiChat( const disposeError = ctx.on('agent/error', (subject, turn, step, error) => { if (subject !== agent) return liveErrors.add(`${turn}:${step}`) - appendNotice(error.message, 'error') + // Full cause chain: wrapper messages like `fetch failed` carry the + // actionable transport detail on `cause`. + appendNotice(errorChain(error), 'error') }) const disposeAgent = ctx.on('agent/disposed', (subject) => { if (subject !== agent) return @@ -1330,7 +1324,7 @@ export function mountTui(ctx: Context, config: Config, runtime: TuiRuntime): voi if (settled || failedSessionId !== sessionId) return settled = true stopWaiting() - runtime.terminal.write(displayText(`ui-tui: session "${sessionId}" failed to start: ${renderThrown(error)}\n`)) + runtime.terminal.write(displayText(`ui-tui: session "${sessionId}" failed to start: ${errorChain(error)}\n`)) runtime.exit(1) } diff --git a/packages/ui/tui/tests/tui.spec.ts b/packages/ui/tui/tests/tui.spec.ts index 27200e0fa9..8e0df2cc75 100644 --- a/packages/ui/tui/tests/tui.spec.ts +++ b/packages/ui/tui/tests/tui.spec.ts @@ -864,7 +864,7 @@ describe('terminal mounting', () => { expect(terminal.output).toBe('') expect(exit).not.toHaveBeenCalled() ctx.emit('agent-loop/config-start-failed', SessionId('main-session'), new Error('resume \u001b]2;failure-controlled\u0007')) - expect(terminal.output).toBe('ui-tui: session "main-session" failed to start: Error: resume \\x1b]2;failure-controlled\\x07\n') + expect(terminal.output).toBe('ui-tui: session "main-session" failed to start: resume \\x1b]2;failure-controlled\\x07\n') expect(exit).toHaveBeenCalledWith(1) const session = ctx.sessions.create(SessionId('main-session')) @@ -892,7 +892,7 @@ describe('terminal mounting', () => { }) expect(terminal.started).toBe(0) - expect(terminal.output).toBe('ui-tui: session "main-session" failed to start: \n') + expect(terminal.output).toBe('ui-tui: session "main-session" failed to start: \n') expect(exit).toHaveBeenCalledWith(1) await ctx.fiber.dispose() })