conversation-telemetry-workflow-facts.test.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. // 动态工作流子代理的埋点事实(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Token telemetry for subagents」):
  2. // 门 1 放行 workflow_child 的用量;DynamicWorkflowRunProgress 派生 workflow.lifecycle;
  3. // 父会话 tool_internal 嵌套用量仍不外送;turn 载荷的 wf 维度透传。
  4. import { describe, expect, it } from "vitest";
  5. import { SessionEventType, type SessionEvent } from "@zcode/contracts";
  6. import { ConversationTelemetryFactNormalizer } from "../src/zcode-protocol-v4/conversation-telemetry-facts.js";
  7. function event(
  8. type: SessionEvent["type"],
  9. payload: unknown,
  10. seq: number,
  11. sessionId = "sess_dwf-run-1-worker_1",
  12. ): SessionEvent {
  13. return {
  14. id: `event-${seq}`,
  15. sessionId,
  16. turnId: "turn",
  17. traceId: "trace",
  18. sequenceNumber: seq,
  19. timestamp: new Date(),
  20. type,
  21. payload,
  22. } as SessionEvent;
  23. }
  24. const usage = {
  25. inputTokens: 120,
  26. outputTokens: 30,
  27. totalTokens: 150,
  28. reasoningTokens: 0,
  29. cacheReadTokens: 0,
  30. cacheWriteTokens: 0,
  31. };
  32. describe("workflow_child 用量进埋点", () => {
  33. it("子会话 ModelComplete(querySource workflow_child) 变 usage.delta", () => {
  34. const normalizer = new ConversationTelemetryFactNormalizer();
  35. const fact = normalizer.normalize(
  36. "sess_dwf-run-1-worker_1",
  37. event(
  38. SessionEventType.ModelComplete,
  39. {
  40. content: "",
  41. stopReason: "end_turn",
  42. usage,
  43. toolCallCount: 0,
  44. querySource: "workflow_child",
  45. },
  46. 1,
  47. ),
  48. );
  49. expect(fact).toMatchObject({ kind: "usage.delta", inputTokens: 120, totalTokens: 150 });
  50. });
  51. it("父会话 tool_internal 且无 querySource 的嵌套用量仍不外送(前台子代理回填,不双计)", () => {
  52. const normalizer = new ConversationTelemetryFactNormalizer();
  53. const fact = normalizer.normalize(
  54. "parent",
  55. event(
  56. SessionEventType.ModelComplete,
  57. { content: "", stopReason: "tool_internal", usage, toolCallCount: 0 },
  58. 1,
  59. "parent",
  60. ),
  61. );
  62. expect(fact).toBeNull();
  63. });
  64. });
  65. describe("DynamicWorkflowRunProgress → workflow.lifecycle", () => {
  66. const actorCreated = (launchInputId?: string) =>
  67. event(
  68. SessionEventType.DynamicWorkflowRunProgress,
  69. {
  70. runId: "dwfrun-1",
  71. toolCallId: "tool-wf",
  72. sequence: 3,
  73. eventType: "actor-created",
  74. payload: { actor: { siteId: "worker", ordinal: 1 }, name: "worker" },
  75. actorSessionId: "sess_dwf-run-1-worker_1",
  76. ...(launchInputId === undefined ? {} : { launchInputId }),
  77. },
  78. 1,
  79. "parent",
  80. );
  81. it("actor-created 带锚点 → actor-spawned,sourceCommandId 是锚点,agentId 是 siteId@ordinal", () => {
  82. const normalizer = new ConversationTelemetryFactNormalizer();
  83. expect(normalizer.normalize("parent", actorCreated("launch-input-1"))).toEqual(
  84. expect.objectContaining({
  85. kind: "workflow.lifecycle",
  86. phase: "actor-spawned",
  87. sourceCommandId: "launch-input-1",
  88. runId: "dwfrun-1",
  89. toolCallId: "tool-wf",
  90. agentId: "worker@1",
  91. childSessionId: "sess_dwf-run-1-worker_1",
  92. sessionId: "parent",
  93. }),
  94. );
  95. });
  96. it("没有锚点(升级前的 run)不发事实", () => {
  97. const normalizer = new ConversationTelemetryFactNormalizer();
  98. expect(normalizer.normalize("parent", actorCreated())).toBeNull();
  99. });
  100. it.each([
  101. ["completed", { status: "completed" }, undefined],
  102. ["errored", { status: "errored", error: { code: "DriverError", message: "boom" } }, "boom"],
  103. [
  104. "stopped by the user",
  105. { status: "stopped", stopReason: "user" },
  106. "Workflow run stopped (user)",
  107. ],
  108. [
  109. "stopped by the provider",
  110. {
  111. status: "stopped",
  112. stopReason: "provider",
  113. error: { code: "ProviderStop", message: "quota exhausted" },
  114. },
  115. "quota exhausted",
  116. ],
  117. ] as const)("run-settled(%s) → run-settled 事实", (_label, payload, errorMessage) => {
  118. const normalizer = new ConversationTelemetryFactNormalizer();
  119. const fact = normalizer.normalize(
  120. "parent",
  121. event(
  122. SessionEventType.DynamicWorkflowRunProgress,
  123. {
  124. runId: "dwfrun-1",
  125. sequence: 9,
  126. eventType: "run-settled",
  127. payload,
  128. launchInputId: "launch-input-1",
  129. },
  130. 2,
  131. "parent",
  132. ),
  133. );
  134. expect(fact).toMatchObject({
  135. kind: "workflow.lifecycle",
  136. phase: "run-settled",
  137. runId: "dwfrun-1",
  138. sourceCommandId: "launch-input-1",
  139. status: payload.status,
  140. });
  141. if (errorMessage === undefined) expect(fact).not.toHaveProperty("errorMessage");
  142. else expect(fact).toMatchObject({ errorMessage });
  143. // stopReason 只在 stopped 时搬运(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Terminal states」)。
  144. if ("stopReason" in payload) expect(fact).toMatchObject({ stopReason: payload.stopReason });
  145. else expect(fact).not.toHaveProperty("stopReason");
  146. });
  147. it("其余引擎事件(node-queued / usage-updated)不进埋点", () => {
  148. const normalizer = new ConversationTelemetryFactNormalizer();
  149. for (const eventType of ["node-queued", "usage-updated", "run-started", "run-launched"]) {
  150. expect(
  151. normalizer.normalize(
  152. "parent",
  153. event(
  154. SessionEventType.DynamicWorkflowRunProgress,
  155. { runId: "dwfrun-1", sequence: 1, eventType, payload: {}, launchInputId: "x" },
  156. 1,
  157. "parent",
  158. ),
  159. ),
  160. ).toBeNull();
  161. }
  162. });
  163. });
  164. describe("turn 载荷的 wf 维度", () => {
  165. it("TurnStarted.backgroundSource workflow 透传;TurnComplete.workflowResultConsumed 透传", () => {
  166. const normalizer = new ConversationTelemetryFactNormalizer();
  167. expect(
  168. normalizer.normalize(
  169. "parent",
  170. event(
  171. SessionEventType.TurnStarted,
  172. {
  173. turnNumber: 1,
  174. input: "notice",
  175. inputId: "wake-1",
  176. inputSource: "background_task",
  177. backgroundSource: "workflow",
  178. messageId: "msg_1",
  179. },
  180. 1,
  181. "parent",
  182. ),
  183. ),
  184. ).toMatchObject({ kind: "turn.started", backgroundSource: "workflow" });
  185. expect(
  186. normalizer.normalize(
  187. "parent",
  188. event(
  189. SessionEventType.TurnComplete,
  190. {
  191. turnNumber: 1,
  192. result: { type: "complete" },
  193. duration: 1,
  194. workflowResultConsumed: true,
  195. },
  196. 2,
  197. "parent",
  198. ),
  199. ),
  200. ).toMatchObject({ kind: "turn.terminal", workflowResultConsumed: true });
  201. });
  202. });