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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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. for (const line of lines) {
  87. assert.doesNotThrow(() => JSON.parse(line), `not valid JSON on its own: ${line}`);
  88. }
  89. // Two events plus the summary. If anything pretty-printed its JSON this count
  90. // would balloon — which is the bug this test exists to catch.
  91. assert.equal(lines.length, 3);
  92. const first = JSON.parse(lines[0] ?? "") as { eventId: string; type: string };
  93. assert.equal(first.eventId, "evt-1");
  94. assert.equal(first.type, "model.streaming");
  95. const summary = JSON.parse(lines[2] ?? "") as {
  96. type: string;
  97. response: string;
  98. sessionId: string;
  99. eventCount: number;
  100. };
  101. assert.equal(summary.type, "result");
  102. assert.equal(summary.response, "the answer");
  103. assert.equal(summary.sessionId, "session-test");
  104. assert.equal(summary.eventCount, 2);
  105. });
  106. test("--output-format json prints the summary, not plain text", async () => {
  107. // Regression: an earlier cut of this change only looked at `options.json`, so
  108. // --output-format json parsed fine and then silently printed plain text.
  109. const ctx = createContext(["--output-format", "json", "--prompt", "hi"]);
  110. assert.equal(await run(ctx, createDeps()), 0);
  111. const out = ctx.stdout.output();
  112. const parsed = JSON.parse(out) as { response: string; sessionId: string };
  113. assert.equal(parsed.response, "the answer");
  114. assert.equal(parsed.sessionId, "session-test");
  115. });
  116. test("--output-format text prints the answer only, overriding --json", async () => {
  117. const ctx = createContext(["--output-format", "text", "--json", "--prompt", "hi"]);
  118. assert.equal(await run(ctx, createDeps()), 0);
  119. assert.equal(ctx.stdout.output(), "the answer\n");
  120. });
  121. test("plain --json keeps working unchanged", async () => {
  122. const ctx = createContext(["--json", "--prompt", "hi"]);
  123. assert.equal(await run(ctx, createDeps()), 0);
  124. const parsed = JSON.parse(ctx.stdout.output()) as { response: string };
  125. assert.equal(parsed.response, "the answer");
  126. });
  127. test("no output-format streams nothing: a default run is unchanged", async () => {
  128. const ctx = createContext(["--prompt", "hi"]);
  129. assert.equal(await run(ctx, createDeps()), 0);
  130. assert.equal(ctx.stdout.output(), "the answer\n");
  131. });
  132. test("an unknown --output-format is rejected instead of falling back to text", async () => {
  133. const ctx = createContext(["--output-format", "ndjson", "--prompt", "hi"]);
  134. const code = await run(ctx, createDeps());
  135. assert.notEqual(code, 0);
  136. assert.match(ctx.stderr.output(), /--output-format must be one of/);
  137. assert.equal(ctx.stdout.output(), "");
  138. });