output-format-stream-json.test.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import assert from "node:assert/strict";
  2. import test from "node:test";
  3. import type { RunContext } from "@zcode/shared-types";
  4. import { run } from "../src/run.js";
  5. import type { RunDependencies } from "../src/run.js";
  6. type CapturedWriteStream = NodeJS.WriteStream & {
  7. output: () => string;
  8. };
  9. const createWriteStream = (): CapturedWriteStream => {
  10. let output = "";
  11. return {
  12. output: () => output,
  13. write: (
  14. chunk: string | Uint8Array,
  15. encodingOrCallback?: BufferEncoding | ((err?: Error | null) => void),
  16. callback?: (err?: Error | null) => void,
  17. ): boolean => {
  18. output += typeof chunk === "string" ? chunk : chunk.toString();
  19. const writeCallback =
  20. typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
  21. writeCallback?.();
  22. return true;
  23. },
  24. } as CapturedWriteStream;
  25. };
  26. const createContext = (
  27. argv: string[],
  28. ): RunContext & { stderr: CapturedWriteStream; stdout: CapturedWriteStream } => ({
  29. argv,
  30. stderr: createWriteStream(),
  31. stdin: { isTTY: false } as NodeJS.ReadStream,
  32. stdout: createWriteStream(),
  33. });
  34. const fakeProjection = {
  35. contextUsed: 12,
  36. contextWindow: 1000,
  37. status: "idle",
  38. totalTokenCount: 12,
  39. turnCount: 1,
  40. };
  41. /** Two events, one carrying a newline, so NDJSON framing is actually exercised. */
  42. const fakeEvents = [
  43. { id: "evt-1", type: "model.streaming", text: "first" },
  44. { id: "evt-2", type: "turn.completed", text: "second\nwith a newline" },
  45. ];
  46. const createDeps = (): RunDependencies => ({
  47. createZCodeApp: () =>
  48. ({
  49. getModel: () => "openai/gpt-test",
  50. getThoughtLevel: () => "medium",
  51. sessionId: "session-test",
  52. traceId: "trace-test",
  53. runtime: {} as never,
  54. submitPrompt: async (
  55. _prompt: unknown,
  56. options?: { onEvent?: (event: unknown) => void | Promise<void> },
  57. ) => {
  58. for (const event of fakeEvents) options?.onEvent?.(event);
  59. return {
  60. events: fakeEvents,
  61. projection: fakeProjection as never,
  62. response: "the answer",
  63. traceId: "trace-test" as never,
  64. turnId: "turn-test" as never,
  65. };
  66. },
  67. }) as never,
  68. loadDotenv: () => ({ keys: [], loaded: false }),
  69. startProcessProviderRegistryRuntime: async () =>
  70. ({
  71. dispose: () => {},
  72. runtime: { registryService: {} },
  73. }) as never,
  74. // Stand-in for the bootstrap mapper: the bootstrap module is not loaded when
  75. // createZCodeApp is injected, so streaming needs this to be injectable too.
  76. mapSessionEvent: ((event: { id: string; type: string }) => ({
  77. eventId: event.id,
  78. type: event.type,
  79. })) as never,
  80. });
  81. test("stream-json writes one line per event, then a tagged result line", async () => {
  82. const ctx = createContext(["--output-format", "stream-json", "--prompt", "hi"]);
  83. const code = await run(ctx, createDeps());
  84. assert.equal(code, 0);
  85. const lines = ctx.stdout.output().trim().split("\n");
  86. // Two events plus the summary. If anything pretty-printed its JSON this count
  87. // would balloon — which is the bug this test exists to catch.
  88. assert.equal(lines.length, 3);
  89. const first = JSON.parse(lines[0] ?? "") as { eventId: string; type: string };
  90. assert.equal(first.eventId, "evt-1");
  91. assert.equal(first.type, "model.streaming");
  92. const summary = JSON.parse(lines[2] ?? "") as {
  93. type: string;
  94. response: string;
  95. sessionId: string;
  96. eventCount: number;
  97. };
  98. assert.equal(summary.type, "result");
  99. assert.equal(summary.response, "the answer");
  100. assert.equal(summary.sessionId, "session-test");
  101. assert.equal(summary.eventCount, 2);
  102. });
  103. test("every stream-json line parses on its own", async () => {
  104. const ctx = createContext(["--output-format", "stream-json", "--prompt", "hi"]);
  105. await run(ctx, createDeps());
  106. for (const line of ctx.stdout.output().trim().split("\n")) {
  107. assert.doesNotThrow(() => JSON.parse(line), `not valid JSON on its own: ${line}`);
  108. }
  109. });
  110. test("--output-format json prints the summary, not plain text", async () => {
  111. // Regression: an earlier cut of this change only looked at `options.json`, so
  112. // --output-format json parsed fine and then silently printed plain text.
  113. const ctx = createContext(["--output-format", "json", "--prompt", "hi"]);
  114. assert.equal(await run(ctx, createDeps()), 0);
  115. const out = ctx.stdout.output();
  116. const parsed = JSON.parse(out) as { response: string; sessionId: string };
  117. assert.equal(parsed.response, "the answer");
  118. assert.equal(parsed.sessionId, "session-test");
  119. });
  120. test("--output-format text prints the answer only, overriding --json", async () => {
  121. const ctx = createContext(["--output-format", "text", "--json", "--prompt", "hi"]);
  122. assert.equal(await run(ctx, createDeps()), 0);
  123. assert.equal(ctx.stdout.output(), "the answer\n");
  124. });
  125. test("plain --json keeps working unchanged", async () => {
  126. const ctx = createContext(["--json", "--prompt", "hi"]);
  127. assert.equal(await run(ctx, createDeps()), 0);
  128. const parsed = JSON.parse(ctx.stdout.output()) as { response: string };
  129. assert.equal(parsed.response, "the answer");
  130. });
  131. test("no output-format streams nothing: a default run is unchanged", async () => {
  132. const ctx = createContext(["--prompt", "hi"]);
  133. assert.equal(await run(ctx, createDeps()), 0);
  134. assert.equal(ctx.stdout.output(), "the answer\n");
  135. });
  136. test("an unknown --output-format is rejected instead of falling back to text", async () => {
  137. const ctx = createContext(["--output-format", "ndjson", "--prompt", "hi"]);
  138. const code = await run(ctx, createDeps());
  139. assert.notEqual(code, 0);
  140. assert.match(ctx.stderr.output(), /--output-format must be one of/);
  141. assert.equal(ctx.stdout.output(), "");
  142. });