| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362 |
- import { describe, expect, it } from "vitest";
- import {
- conversationTelemetryFactSchema,
- commandAckSchema,
- parseCommandEnvelope,
- } from "../src/zcode-protocol-v4/index.js";
- const base = {
- version: 1 as const,
- eventId: "event-1",
- eventSeq: 1,
- occurredAt: 1_700_000_000_000,
- sessionId: "session-1",
- };
- describe("ConversationTelemetryFact schema", () => {
- it("Skill 名称字段允许新旧事实往返且拒绝非法类型", () => {
- const fact = {
- ...base,
- kind: "tool.lifecycle",
- phase: "completed",
- toolCallId: "skill",
- toolName: "Skill",
- };
- expect(conversationTelemetryFactSchema.parse(fact)).not.toHaveProperty("skillName");
- expect(
- conversationTelemetryFactSchema.parse(
- JSON.parse(JSON.stringify({ ...fact, skillName: "local-skill" })),
- ),
- ).toMatchObject({ skillName: "local-skill" });
- for (const skillName of [
- "",
- 123,
- null,
- {},
- "/private/key",
- "demo\nsecret",
- "demo ",
- "https://example.com",
- "sk-" + "a".repeat(49),
- "a".repeat(65),
- ]) {
- expect(conversationTelemetryFactSchema.safeParse({ ...fact, skillName }).success).toBe(false);
- }
- expect(
- conversationTelemetryFactSchema.safeParse({ ...fact, skillName: "demo", args: "private" })
- .success,
- ).toBe(false);
- });
- it("Memory 元数据保持 boolean 且兼容旧 ACK/fact", () => {
- const ack = { commandId: "command-1", status: "accepted", revisionAtDecision: 0 };
- const fact = { ...base, kind: "turn.started" };
- for (const [schema, value] of [
- [commandAckSchema, ack],
- [conversationTelemetryFactSchema, fact],
- ] as const) {
- expect(schema.parse(value)).not.toHaveProperty("memoryEnabled");
- for (const memoryEnabled of [true, false]) {
- expect(schema.parse({ ...value, memoryEnabled })).toMatchObject({ memoryEnabled });
- }
- expect(schema.safeParse({ ...value, memoryEnabled: "false" }).success).toBe(false);
- }
- });
- it("只允许定时任务 admission 与 CronCreate 关联 ID,不接收任务正文", () => {
- const started = conversationTelemetryFactSchema.parse({
- ...base,
- kind: "turn.started",
- sourceCommandId: "automation-1:1700000000000",
- automationId: "automation-1",
- taskTrigger: "schedule",
- scheduledAt: 1_700_000_000_000,
- });
- expect(started).toMatchObject({ automationId: "automation-1", taskTrigger: "schedule" });
- expect(() =>
- conversationTelemetryFactSchema.parse({ ...started, prompt: "private" }),
- ).toThrow();
- const tool = conversationTelemetryFactSchema.parse({
- ...base,
- kind: "tool.lifecycle",
- phase: "completed",
- toolCallId: "cron-create-1",
- toolName: "CronCreate",
- automationId: "automation-1",
- });
- expect(tool).toMatchObject({ automationId: "automation-1" });
- expect(() => conversationTelemetryFactSchema.parse({ ...tool, output: "private" })).toThrow();
- });
- it("Off-Peak admission 只接收稳定 task ID,且与 automation 互斥", () => {
- const started = conversationTelemetryFactSchema.parse({
- ...base,
- kind: "turn.started",
- sourceCommandId: "message-run-1",
- offPeakTaskId: "offpeak-1",
- offPeakRunType: "init",
- });
- expect(started).toMatchObject({ offPeakTaskId: "offpeak-1", offPeakRunType: "init" });
- expect(() =>
- conversationTelemetryFactSchema.parse({
- ...base,
- kind: "turn.started",
- sourceCommandId: "message-run-2",
- offPeakRunType: "resume",
- }),
- ).toThrow();
- expect(() =>
- conversationTelemetryFactSchema.parse({
- ...started,
- automationId: "automation-1",
- }),
- ).toThrow();
- for (const forbidden of [
- { prompt: "private prompt" },
- { workspacePath: "/private/workspace" },
- { ticketId: "private-ticket" },
- { responseBody: "private response" },
- ]) {
- expect(() => conversationTelemetryFactSchema.parse({ ...started, ...forbidden })).toThrow();
- }
- });
- it("只接受 provider hostname,不允许 URL、header、prompt 或工具正文穿透", () => {
- const valid = conversationTelemetryFactSchema.parse({
- ...base,
- kind: "model.request.status",
- requestId: "request-1",
- status: "model_request_started",
- providerId: "zcode-plan",
- modelId: "model-1",
- providerHostname: "example.com",
- transport: "sse",
- attempt: 1,
- maxAttempts: 3,
- });
- expect(valid).toMatchObject({ providerHostname: "example.com" });
- for (const forbidden of [
- { baseURL: "https://example.com/private?q=token" },
- { requestHeaders: { authorization: "secret" } },
- { requestHeaderCount: 3 },
- { responseHeaderCount: 4 },
- { prompt: "private prompt" },
- { responseBody: "private response" },
- { message: "upstream response body" },
- { finishReason: "provider-private-reason" },
- { providerHostname: "https://example.com/private?q=token" },
- { providerHostname: "example.com:443" },
- { providerHostname: "user@example.com" },
- { providerHostname: "example.com/path" },
- { providerHostname: "example.com query" },
- ]) {
- expect(() => conversationTelemetryFactSchema.parse({ ...valid, ...forbidden })).toThrow();
- }
- expect(() =>
- conversationTelemetryFactSchema.parse({
- ...valid,
- providerHostname: "[2001:db8::1]",
- }),
- ).not.toThrow();
- });
- it("tool fact 只接收 allowlist perf,拒绝 input/output", () => {
- const valid = conversationTelemetryFactSchema.parse({
- ...base,
- kind: "tool.lifecycle",
- phase: "completed",
- toolCallId: "tool-1",
- toolName: "Read",
- performance: {
- totalMs: 20,
- fileCount: 1,
- workspaceKind: "local",
- commandName: "git",
- commandCount: 1,
- commandStatus: "completed",
- },
- });
- expect(valid.kind).toBe("tool.lifecycle");
- expect(() =>
- conversationTelemetryFactSchema.parse({
- ...valid,
- input: { path: "/secret" },
- }),
- ).toThrow();
- expect(() =>
- conversationTelemetryFactSchema.parse({
- ...valid,
- performance: { totalMs: 20, rawOutput: "secret" },
- }),
- ).toThrow();
- });
- it("subagent fact 只接收父子会话关联,不允许正文", () => {
- const valid = conversationTelemetryFactSchema.parse({
- ...base,
- kind: "subagent.lifecycle",
- phase: "spawned",
- agentId: "agent-1",
- agentType: "explore",
- childSessionId: "child-session-1",
- parentToolCallId: "parent-tool-1",
- background: false,
- status: "running",
- });
- expect(valid).toMatchObject({
- agentId: "agent-1",
- childSessionId: "child-session-1",
- background: false,
- });
- expect(() =>
- conversationTelemetryFactSchema.parse({
- ...valid,
- prompt: "private",
- }),
- ).toThrow();
- });
- it("stream fact 只保留 parent id,不允许正文;usage 不接收 V4 文件摘要", () => {
- const stream = conversationTelemetryFactSchema.parse({
- ...base,
- kind: "stream.chunk",
- channel: "text",
- chunkLength: 20,
- firstChunk: true,
- parentToolCallId: "parent-agent-tool",
- });
- expect(stream).toMatchObject({ parentToolCallId: "parent-agent-tool" });
- expect(() =>
- conversationTelemetryFactSchema.parse({ ...stream, content: "private" }),
- ).toThrow();
- const usage = conversationTelemetryFactSchema.parse({
- ...base,
- kind: "usage.delta",
- inputTokens: 1,
- outputTokens: 2,
- totalTokens: 3,
- reasoningTokens: 0,
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- });
- expect(() =>
- conversationTelemetryFactSchema.parse({
- ...usage,
- fileAdditions: 10,
- fileCount: 1,
- }),
- ).toThrow();
- });
- it("workflow.lifecycle 只带 run / 子代理 id 与状态;phase 决定必填", () => {
- const spawned = conversationTelemetryFactSchema.parse({
- ...base,
- kind: "workflow.lifecycle",
- phase: "actor-spawned",
- runId: "dwfrun-1",
- toolCallId: "tool-1",
- agentId: "agent#1@1",
- childSessionId: "sess_dwf-1",
- sourceCommandId: "launch-input-1",
- });
- expect(spawned).toMatchObject({ phase: "actor-spawned", childSessionId: "sess_dwf-1" });
- const settled = conversationTelemetryFactSchema.parse({
- ...base,
- kind: "workflow.lifecycle",
- phase: "run-settled",
- runId: "dwfrun-1",
- status: "stopped",
- stopReason: "user",
- errorMessage: "Workflow run stopped (user)",
- });
- expect(settled).toMatchObject({ status: "stopped", stopReason: "user" });
- // actor-spawned 缺子会话 id 不成立;run-settled 缺状态不成立;正文字段一律拒绝。
- expect(() =>
- conversationTelemetryFactSchema.parse({
- ...base,
- kind: "workflow.lifecycle",
- phase: "actor-spawned",
- runId: "dwfrun-1",
- agentId: "agent#1@1",
- }),
- ).toThrow();
- expect(() =>
- conversationTelemetryFactSchema.parse({
- ...base,
- kind: "workflow.lifecycle",
- phase: "run-settled",
- runId: "dwfrun-1",
- }),
- ).toThrow();
- expect(() =>
- conversationTelemetryFactSchema.parse({ ...spawned, scriptText: "export const x = 1" }),
- ).toThrow();
- });
- it("turn.started 接受 workflow 唤起来源;turn.terminal 接受 workflowResultConsumed", () => {
- expect(
- conversationTelemetryFactSchema.parse({
- ...base,
- kind: "turn.started",
- inputSource: "background_task",
- backgroundSource: "workflow",
- }),
- ).toMatchObject({ backgroundSource: "workflow" });
- expect(
- conversationTelemetryFactSchema.parse({
- ...base,
- kind: "turn.terminal",
- status: "success",
- workflowResultConsumed: true,
- }),
- ).toMatchObject({ workflowResultConsumed: true });
- });
- });
- describe("setAssistantFeedback command schema", () => {
- it("复用 row target CAS,feedback null 表示清除", () => {
- const parsed = parseCommandEnvelope({
- commandId: "command-1",
- clientId: "desktop-1",
- sessionId: "session-1",
- baseRevision: 3,
- baseLogEpoch: "epoch-1",
- type: "setAssistantFeedback",
- payload: {
- target: { rowId: 7, entityId: "assistant-message-1" },
- feedback: null,
- },
- issuedAt: 1_700_000_000_000,
- });
- expect(parsed.ok).toBe(true);
- });
- it("缺少 revision/logEpoch 或伪造 target 字段时拒绝", () => {
- const envelope = {
- commandId: "command-1",
- clientId: "desktop-1",
- sessionId: "session-1",
- type: "setAssistantFeedback" as const,
- payload: {
- target: { rowId: 7, entityId: "assistant-message-1" },
- feedback: "like",
- },
- issuedAt: 1_700_000_000_000,
- };
- expect(parseCommandEnvelope(envelope).ok).toBe(false);
- expect(
- parseCommandEnvelope({
- ...envelope,
- baseRevision: 3,
- baseLogEpoch: "epoch-1",
- payload: {
- ...envelope.payload,
- target: { ...envelope.payload.target, messageId: "x" },
- },
- }).ok,
- ).toBe(false);
- });
- });
|