turn-errors.test.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import { describe, expect, it, vi } from "vitest";
  2. import { SessionEventType } from "@zcode/contracts";
  3. import {
  4. appendTurnOutcomeEvent,
  5. createExternalTurnFaultError,
  6. createTurnFailureError,
  7. projectExecutionErrorPayload,
  8. } from "../src/runtime/helpers/turn-errors.js";
  9. describe("turn abort outcome", () => {
  10. it("external protocol fault 持久化 TurnError,而普通 stop 仍是 TurnComplete(cancelled)", async () => {
  11. const protocolAbort = new AbortController();
  12. protocolAbort.abort(createExternalTurnFaultError("proto.payloadTooLarge"));
  13. const protocolError = createTurnFailureError(
  14. protocolAbort.signal.reason,
  15. protocolAbort.signal,
  16. "Turn execution failed",
  17. );
  18. const protocolEvents: Array<{ type: string; payload: unknown }> = [];
  19. const runtime = {
  20. createEvent: (type: string, payload: unknown) => ({ type, payload }),
  21. appendEvent: vi.fn(async (event: { type: string; payload: unknown }) => {
  22. protocolEvents.push(event);
  23. }),
  24. logger: undefined,
  25. };
  26. await appendTurnOutcomeEvent(runtime as never, {
  27. coreError: protocolError,
  28. events: [],
  29. durationMs: 1,
  30. turnPhase: "model",
  31. traceContext: { traceId: "trace-protocol-fault" } as never,
  32. fallbackMessage: "Turn execution failed",
  33. logEvent: "turn.failed",
  34. logLabel: "Turn",
  35. });
  36. expect(protocolEvents[0]).toMatchObject({
  37. type: SessionEventType.TurnError,
  38. payload: { error: { type: "proto.payloadTooLarge" } },
  39. });
  40. const stopAbort = new AbortController();
  41. stopAbort.abort(new Error("user stop"));
  42. const stopError = createTurnFailureError(
  43. stopAbort.signal.reason,
  44. stopAbort.signal,
  45. "Turn execution failed",
  46. );
  47. const stopEvents: Array<{ type: string; payload: unknown }> = [];
  48. await appendTurnOutcomeEvent(
  49. {
  50. ...runtime,
  51. appendEvent: vi.fn(async (event: { type: string; payload: unknown }) => {
  52. stopEvents.push(event);
  53. }),
  54. } as never,
  55. {
  56. coreError: stopError,
  57. events: [],
  58. durationMs: 1,
  59. turnPhase: "model",
  60. traceContext: { traceId: "trace-stop" } as never,
  61. fallbackMessage: "Turn execution failed",
  62. logEvent: "turn.failed",
  63. logLabel: "Turn",
  64. },
  65. );
  66. expect(stopEvents[0]).toMatchObject({
  67. type: SessionEventType.TurnComplete,
  68. payload: { resultType: "cancelled" },
  69. });
  70. });
  71. });
  72. describe("projectExecutionErrorPayload", () => {
  73. it("does not synthesize underlying fields without an error frame", () => {
  74. expect(projectExecutionErrorPayload(undefined)).toEqual({ message: "Turn execution failed" });
  75. });
  76. it("uses the final wrapper only when no primary frame exists, and bounds cyclic chains", () => {
  77. const wrapper = Object.assign(new Error("wrapper only"), { errorPayloadRole: "wrapper", cause: undefined as unknown });
  78. wrapper.cause = wrapper;
  79. expect(projectExecutionErrorPayload(wrapper).underlyingErrorMessage).toBe("wrapper only");
  80. });
  81. it("keeps message and detail from one deepest non-wrapper frame", () => {
  82. const inner = Object.assign(new Error("inner wrapper"), { errorPayloadRole: "wrapper", detail: "not the chosen frame" });
  83. const outer = Object.assign(new Error("primary failure"), { cause: inner, detail: "primary detail" });
  84. expect(projectExecutionErrorPayload(outer)).toMatchObject({ underlyingErrorMessage: "primary failure", underlyingErrorDetail: "primary detail" });
  85. });
  86. it("uses model/network cause as the visible message and keeps low-level detail", () => {
  87. const socketError = Object.assign(new Error("connect ECONNREFUSED 127.0.0.1:9091"), {
  88. code: "ECONNREFUSED",
  89. });
  90. const apiError = Object.assign(
  91. new Error("Cannot connect to API: connect ECONNREFUSED 127.0.0.1:9091"),
  92. {
  93. cause: socketError,
  94. },
  95. );
  96. const modelError = Object.assign(
  97. new Error("Network connection failed for the provider request."),
  98. {
  99. cause: apiError,
  100. code: "model_request_failed",
  101. context: {
  102. baseURL: "https://secret.example.com/v1/messages?token=secret",
  103. errorPhase: "stream",
  104. exceptionKind: "transport",
  105. exceptionType: "SecretProviderNetworkError",
  106. headers: { authorization: "Bearer secret" },
  107. modelId: "deepseek-v4-flash",
  108. providerKind: "anthropic-messages",
  109. providerId: "default-deepseek",
  110. reason: "network_error",
  111. requestId: "request-1",
  112. responseBody: "private provider response",
  113. retryable: true,
  114. source: "network",
  115. statusCode: 503,
  116. transport: "sse",
  117. },
  118. name: "AiSdkModelAdapterError",
  119. },
  120. );
  121. const turnError = createTurnFailureError(modelError, undefined, "Turn execution failed");
  122. const projection = projectExecutionErrorPayload(turnError);
  123. expect(projection.message).toBe("Network connection failed for the provider request.");
  124. expect(projection.underlyingErrorMessage).toBe(
  125. "connect ECONNREFUSED 127.0.0.1:9091",
  126. );
  127. expect(projection.detail).toContain("Turn execution failed");
  128. expect(projection.detail).toContain(
  129. "Cannot connect to API: connect ECONNREFUSED 127.0.0.1:9091",
  130. );
  131. expect(projection.detail).toContain("provider=default-deepseek");
  132. expect(projection.detail).toContain("model=deepseek-v4-flash");
  133. expect(projection.detail).toContain("request=request-1");
  134. expect(projection.attribution).toEqual({
  135. source: "network",
  136. reason: "network_error",
  137. errorPhase: "stream",
  138. exceptionKind: "transport",
  139. providerId: "default-deepseek",
  140. modelId: "deepseek-v4-flash",
  141. providerKind: "anthropic-messages",
  142. transport: "sse",
  143. statusCode: 503,
  144. retryable: true,
  145. });
  146. expect(projection.attribution).not.toHaveProperty("baseURL");
  147. expect(projection.attribution).not.toHaveProperty("headers");
  148. expect(projection.attribution).not.toHaveProperty("requestId");
  149. expect(projection.attribution).not.toHaveProperty("responseBody");
  150. expect(projection.attribution).not.toHaveProperty("exceptionType");
  151. });
  152. it("surfaces provider business code and structured context in detail", () => {
  153. const modelError = Object.assign(new Error("当前模型不在可用范围内"), {
  154. code: "invalid_model_request",
  155. context: {
  156. providerCode: "3006",
  157. providerId: "account:zai-individual-coding-plan",
  158. modelId: "glm-5",
  159. requestId: "request-allowed-models",
  160. source: "provider",
  161. },
  162. name: "AiSdkModelAdapterError",
  163. });
  164. const turnError = createTurnFailureError(modelError, undefined, "Turn execution failed");
  165. const projection = projectExecutionErrorPayload(turnError);
  166. expect(projection.code).toBe("3006");
  167. expect(projection.detail).toContain("provider_code=3006");
  168. expect(projection.detail).toContain("provider=account:zai-individual-coding-plan");
  169. expect(projection.detail).toContain("model=glm-5");
  170. expect(projection.attribution).toEqual({
  171. source: "provider",
  172. providerId: "account:zai-individual-coding-plan",
  173. modelId: "glm-5",
  174. providerErrorCode: "3006",
  175. });
  176. });
  177. it("keeps the deepest provider detail separate from the composed detail", () => {
  178. const rootError = Object.assign(new Error("Runtime headers request failed"), {
  179. detail: "Runtime headers helper timed out after 10000ms.",
  180. code: "RUNTIME_HEADERS_TIMEOUT",
  181. });
  182. const modelError = Object.assign(new Error("Model request failed"), {
  183. cause: rootError,
  184. code: "MODEL_REQUEST_FAILED",
  185. });
  186. const projection = projectExecutionErrorPayload(
  187. createTurnFailureError(modelError, undefined, "Turn execution failed"),
  188. );
  189. expect(projection.underlyingErrorMessage).toBe("Runtime headers request failed");
  190. expect(projection.underlyingErrorDetail).toBe(
  191. "Runtime headers helper timed out after 10000ms.",
  192. );
  193. expect(projection.detail).toContain("Runtime headers helper timed out after 10000ms.");
  194. });
  195. it("uses a non-wrapper top-level retryable fact when context does not provide one", () => {
  196. const modelError = Object.assign(new Error("Model returned no content"), {
  197. code: "MODEL_ERROR",
  198. context: {
  199. reason: "empty_model_response",
  200. source: "provider",
  201. },
  202. retryable: false,
  203. });
  204. expect(projectExecutionErrorPayload(modelError).attribution).toMatchObject({
  205. retryable: false,
  206. });
  207. });
  208. it("does not parse provider response bodies in the core payload projector", () => {
  209. const modelError = Object.assign(new Error("Provider request failed"), {
  210. code: "model_request_failed",
  211. data: {
  212. error: {
  213. message: "Provider body message should be normalized by the adapter layer",
  214. },
  215. },
  216. responseBody: JSON.stringify({
  217. error: {
  218. message: "Raw response body should not be parsed by core payload projector",
  219. },
  220. }),
  221. });
  222. const projection = projectExecutionErrorPayload(modelError);
  223. expect(projection.message).toBe("Provider request failed");
  224. expect(projection.message).not.toContain("adapter layer");
  225. expect(projection.message).not.toContain("Raw response body");
  226. });
  227. it("surfaces provider business code from ProviderBusinessError fields", () => {
  228. const providerError = Object.assign(
  229. new Error("Security verification failed or the verify token was rejected."),
  230. {
  231. name: "ProviderBusinessError",
  232. isProviderBusinessError: true,
  233. providerCode: "3007",
  234. },
  235. );
  236. const turnError = createTurnFailureError(providerError, undefined, "Turn execution failed");
  237. const projection = projectExecutionErrorPayload(turnError);
  238. expect(projection.code).toBe("3007");
  239. expect(projection.message).toContain("verify token was rejected");
  240. });
  241. });