zcodeProtocolV4Telemetry.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. conversationTelemetryFactSchema,
  4. commandAckSchema,
  5. parseCommandEnvelope,
  6. } from "../src/zcode-protocol-v4/index.js";
  7. const base = {
  8. version: 1 as const,
  9. eventId: "event-1",
  10. eventSeq: 1,
  11. occurredAt: 1_700_000_000_000,
  12. sessionId: "session-1",
  13. };
  14. describe("ConversationTelemetryFact schema", () => {
  15. it("Skill 名称字段允许新旧事实往返且拒绝非法类型", () => {
  16. const fact = {
  17. ...base,
  18. kind: "tool.lifecycle",
  19. phase: "completed",
  20. toolCallId: "skill",
  21. toolName: "Skill",
  22. };
  23. expect(conversationTelemetryFactSchema.parse(fact)).not.toHaveProperty("skillName");
  24. expect(
  25. conversationTelemetryFactSchema.parse(
  26. JSON.parse(JSON.stringify({ ...fact, skillName: "local-skill" })),
  27. ),
  28. ).toMatchObject({ skillName: "local-skill" });
  29. for (const skillName of [
  30. "",
  31. 123,
  32. null,
  33. {},
  34. "/private/key",
  35. "demo\nsecret",
  36. "demo ",
  37. "https://example.com",
  38. "sk-" + "a".repeat(49),
  39. "a".repeat(65),
  40. ]) {
  41. expect(conversationTelemetryFactSchema.safeParse({ ...fact, skillName }).success).toBe(false);
  42. }
  43. expect(
  44. conversationTelemetryFactSchema.safeParse({ ...fact, skillName: "demo", args: "private" })
  45. .success,
  46. ).toBe(false);
  47. });
  48. it("Memory 元数据保持 boolean 且兼容旧 ACK/fact", () => {
  49. const ack = { commandId: "command-1", status: "accepted", revisionAtDecision: 0 };
  50. const fact = { ...base, kind: "turn.started" };
  51. for (const [schema, value] of [
  52. [commandAckSchema, ack],
  53. [conversationTelemetryFactSchema, fact],
  54. ] as const) {
  55. expect(schema.parse(value)).not.toHaveProperty("memoryEnabled");
  56. for (const memoryEnabled of [true, false]) {
  57. expect(schema.parse({ ...value, memoryEnabled })).toMatchObject({ memoryEnabled });
  58. }
  59. expect(schema.safeParse({ ...value, memoryEnabled: "false" }).success).toBe(false);
  60. }
  61. });
  62. it("只允许定时任务 admission 与 CronCreate 关联 ID,不接收任务正文", () => {
  63. const started = conversationTelemetryFactSchema.parse({
  64. ...base,
  65. kind: "turn.started",
  66. sourceCommandId: "automation-1:1700000000000",
  67. automationId: "automation-1",
  68. taskTrigger: "schedule",
  69. scheduledAt: 1_700_000_000_000,
  70. });
  71. expect(started).toMatchObject({ automationId: "automation-1", taskTrigger: "schedule" });
  72. expect(() =>
  73. conversationTelemetryFactSchema.parse({ ...started, prompt: "private" }),
  74. ).toThrow();
  75. const tool = conversationTelemetryFactSchema.parse({
  76. ...base,
  77. kind: "tool.lifecycle",
  78. phase: "completed",
  79. toolCallId: "cron-create-1",
  80. toolName: "CronCreate",
  81. automationId: "automation-1",
  82. });
  83. expect(tool).toMatchObject({ automationId: "automation-1" });
  84. expect(() => conversationTelemetryFactSchema.parse({ ...tool, output: "private" })).toThrow();
  85. });
  86. it("Off-Peak admission 只接收稳定 task ID,且与 automation 互斥", () => {
  87. const started = conversationTelemetryFactSchema.parse({
  88. ...base,
  89. kind: "turn.started",
  90. sourceCommandId: "message-run-1",
  91. offPeakTaskId: "offpeak-1",
  92. offPeakRunType: "init",
  93. });
  94. expect(started).toMatchObject({ offPeakTaskId: "offpeak-1", offPeakRunType: "init" });
  95. expect(() =>
  96. conversationTelemetryFactSchema.parse({
  97. ...base,
  98. kind: "turn.started",
  99. sourceCommandId: "message-run-2",
  100. offPeakRunType: "resume",
  101. }),
  102. ).toThrow();
  103. expect(() =>
  104. conversationTelemetryFactSchema.parse({
  105. ...started,
  106. automationId: "automation-1",
  107. }),
  108. ).toThrow();
  109. for (const forbidden of [
  110. { prompt: "private prompt" },
  111. { workspacePath: "/private/workspace" },
  112. { ticketId: "private-ticket" },
  113. { responseBody: "private response" },
  114. ]) {
  115. expect(() => conversationTelemetryFactSchema.parse({ ...started, ...forbidden })).toThrow();
  116. }
  117. });
  118. it("只接受 provider hostname,不允许 URL、header、prompt 或工具正文穿透", () => {
  119. const valid = conversationTelemetryFactSchema.parse({
  120. ...base,
  121. kind: "model.request.status",
  122. requestId: "request-1",
  123. status: "model_request_started",
  124. providerId: "zcode-plan",
  125. modelId: "model-1",
  126. providerHostname: "example.com",
  127. transport: "sse",
  128. attempt: 1,
  129. maxAttempts: 3,
  130. });
  131. expect(valid).toMatchObject({ providerHostname: "example.com" });
  132. for (const forbidden of [
  133. { baseURL: "https://example.com/private?q=token" },
  134. { requestHeaders: { authorization: "secret" } },
  135. { requestHeaderCount: 3 },
  136. { responseHeaderCount: 4 },
  137. { prompt: "private prompt" },
  138. { responseBody: "private response" },
  139. { message: "upstream response body" },
  140. { finishReason: "provider-private-reason" },
  141. { providerHostname: "https://example.com/private?q=token" },
  142. { providerHostname: "example.com:443" },
  143. { providerHostname: "user@example.com" },
  144. { providerHostname: "example.com/path" },
  145. { providerHostname: "example.com query" },
  146. ]) {
  147. expect(() => conversationTelemetryFactSchema.parse({ ...valid, ...forbidden })).toThrow();
  148. }
  149. expect(() =>
  150. conversationTelemetryFactSchema.parse({
  151. ...valid,
  152. providerHostname: "[2001:db8::1]",
  153. }),
  154. ).not.toThrow();
  155. });
  156. it("tool fact 只接收 allowlist perf,拒绝 input/output", () => {
  157. const valid = conversationTelemetryFactSchema.parse({
  158. ...base,
  159. kind: "tool.lifecycle",
  160. phase: "completed",
  161. toolCallId: "tool-1",
  162. toolName: "Read",
  163. performance: {
  164. totalMs: 20,
  165. fileCount: 1,
  166. workspaceKind: "local",
  167. commandName: "git",
  168. commandCount: 1,
  169. commandStatus: "completed",
  170. },
  171. });
  172. expect(valid.kind).toBe("tool.lifecycle");
  173. expect(() =>
  174. conversationTelemetryFactSchema.parse({
  175. ...valid,
  176. input: { path: "/secret" },
  177. }),
  178. ).toThrow();
  179. expect(() =>
  180. conversationTelemetryFactSchema.parse({
  181. ...valid,
  182. performance: { totalMs: 20, rawOutput: "secret" },
  183. }),
  184. ).toThrow();
  185. });
  186. it("subagent fact 只接收父子会话关联,不允许正文", () => {
  187. const valid = conversationTelemetryFactSchema.parse({
  188. ...base,
  189. kind: "subagent.lifecycle",
  190. phase: "spawned",
  191. agentId: "agent-1",
  192. agentType: "explore",
  193. childSessionId: "child-session-1",
  194. parentToolCallId: "parent-tool-1",
  195. background: false,
  196. status: "running",
  197. });
  198. expect(valid).toMatchObject({
  199. agentId: "agent-1",
  200. childSessionId: "child-session-1",
  201. background: false,
  202. });
  203. expect(() =>
  204. conversationTelemetryFactSchema.parse({
  205. ...valid,
  206. prompt: "private",
  207. }),
  208. ).toThrow();
  209. });
  210. it("stream fact 只保留 parent id,不允许正文;usage 不接收 V4 文件摘要", () => {
  211. const stream = conversationTelemetryFactSchema.parse({
  212. ...base,
  213. kind: "stream.chunk",
  214. channel: "text",
  215. chunkLength: 20,
  216. firstChunk: true,
  217. parentToolCallId: "parent-agent-tool",
  218. });
  219. expect(stream).toMatchObject({ parentToolCallId: "parent-agent-tool" });
  220. expect(() =>
  221. conversationTelemetryFactSchema.parse({ ...stream, content: "private" }),
  222. ).toThrow();
  223. const usage = conversationTelemetryFactSchema.parse({
  224. ...base,
  225. kind: "usage.delta",
  226. inputTokens: 1,
  227. outputTokens: 2,
  228. totalTokens: 3,
  229. reasoningTokens: 0,
  230. cacheReadTokens: 0,
  231. cacheWriteTokens: 0,
  232. });
  233. expect(() =>
  234. conversationTelemetryFactSchema.parse({
  235. ...usage,
  236. fileAdditions: 10,
  237. fileCount: 1,
  238. }),
  239. ).toThrow();
  240. });
  241. it("workflow.lifecycle 只带 run / 子代理 id 与状态;phase 决定必填", () => {
  242. const spawned = conversationTelemetryFactSchema.parse({
  243. ...base,
  244. kind: "workflow.lifecycle",
  245. phase: "actor-spawned",
  246. runId: "dwfrun-1",
  247. toolCallId: "tool-1",
  248. agentId: "agent#1@1",
  249. childSessionId: "sess_dwf-1",
  250. sourceCommandId: "launch-input-1",
  251. });
  252. expect(spawned).toMatchObject({ phase: "actor-spawned", childSessionId: "sess_dwf-1" });
  253. const settled = conversationTelemetryFactSchema.parse({
  254. ...base,
  255. kind: "workflow.lifecycle",
  256. phase: "run-settled",
  257. runId: "dwfrun-1",
  258. status: "stopped",
  259. stopReason: "user",
  260. errorMessage: "Workflow run stopped (user)",
  261. });
  262. expect(settled).toMatchObject({ status: "stopped", stopReason: "user" });
  263. // actor-spawned 缺子会话 id 不成立;run-settled 缺状态不成立;正文字段一律拒绝。
  264. expect(() =>
  265. conversationTelemetryFactSchema.parse({
  266. ...base,
  267. kind: "workflow.lifecycle",
  268. phase: "actor-spawned",
  269. runId: "dwfrun-1",
  270. agentId: "agent#1@1",
  271. }),
  272. ).toThrow();
  273. expect(() =>
  274. conversationTelemetryFactSchema.parse({
  275. ...base,
  276. kind: "workflow.lifecycle",
  277. phase: "run-settled",
  278. runId: "dwfrun-1",
  279. }),
  280. ).toThrow();
  281. expect(() =>
  282. conversationTelemetryFactSchema.parse({ ...spawned, scriptText: "export const x = 1" }),
  283. ).toThrow();
  284. });
  285. it("turn.started 接受 workflow 唤起来源;turn.terminal 接受 workflowResultConsumed", () => {
  286. expect(
  287. conversationTelemetryFactSchema.parse({
  288. ...base,
  289. kind: "turn.started",
  290. inputSource: "background_task",
  291. backgroundSource: "workflow",
  292. }),
  293. ).toMatchObject({ backgroundSource: "workflow" });
  294. expect(
  295. conversationTelemetryFactSchema.parse({
  296. ...base,
  297. kind: "turn.terminal",
  298. status: "success",
  299. workflowResultConsumed: true,
  300. }),
  301. ).toMatchObject({ workflowResultConsumed: true });
  302. });
  303. });
  304. describe("setAssistantFeedback command schema", () => {
  305. it("复用 row target CAS,feedback null 表示清除", () => {
  306. const parsed = parseCommandEnvelope({
  307. commandId: "command-1",
  308. clientId: "desktop-1",
  309. sessionId: "session-1",
  310. baseRevision: 3,
  311. baseLogEpoch: "epoch-1",
  312. type: "setAssistantFeedback",
  313. payload: {
  314. target: { rowId: 7, entityId: "assistant-message-1" },
  315. feedback: null,
  316. },
  317. issuedAt: 1_700_000_000_000,
  318. });
  319. expect(parsed.ok).toBe(true);
  320. });
  321. it("缺少 revision/logEpoch 或伪造 target 字段时拒绝", () => {
  322. const envelope = {
  323. commandId: "command-1",
  324. clientId: "desktop-1",
  325. sessionId: "session-1",
  326. type: "setAssistantFeedback" as const,
  327. payload: {
  328. target: { rowId: 7, entityId: "assistant-message-1" },
  329. feedback: "like",
  330. },
  331. issuedAt: 1_700_000_000_000,
  332. };
  333. expect(parseCommandEnvelope(envelope).ok).toBe(false);
  334. expect(
  335. parseCommandEnvelope({
  336. ...envelope,
  337. baseRevision: 3,
  338. baseLogEpoch: "epoch-1",
  339. payload: {
  340. ...envelope.payload,
  341. target: { ...envelope.payload.target, messageId: "x" },
  342. },
  343. }).ok,
  344. ).toBe(false);
  345. });
  346. });