streaming-tool-input-preview.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. export interface ZCodeStreamingToolInputState {
  2. deltaCount?: number;
  3. lastPreviewAt?: number;
  4. lastPreviewRawInputLength?: number;
  5. rawInput: string;
  6. }
  7. export interface ZCodeStreamingToolInputPreview {
  8. complete: boolean;
  9. input: unknown;
  10. rawInput: string;
  11. }
  12. export type ZCodeStreamingToolInputPreviewMode = "active-live" | "background-summary";
  13. export const ZCODE_ACTIVE_STREAMING_TOOL_INPUT_EAGER_DELTA_COUNT = 1;
  14. export const ZCODE_ACTIVE_STREAMING_TOOL_INPUT_PREVIEW_MIN_INTERVAL_MS = 750;
  15. export const ZCODE_ACTIVE_STREAMING_TOOL_INPUT_PREVIEW_MIN_RAW_GROWTH = 8 * 1024;
  16. export const ZCODE_FILE_STREAMING_TOOL_INPUT_PREVIEW_MIN_INTERVAL_MS = 1_000;
  17. export const ZCODE_ACTIVE_STREAMING_TOOL_INPUT_TIME_BUDGET_MAX_RAW_INPUT =
  18. ZCODE_ACTIVE_STREAMING_TOOL_INPUT_PREVIEW_MIN_RAW_GROWTH;
  19. const PARTIAL_JSON_STRING_FIELD_KEYS = [
  20. "file_path",
  21. "filePath",
  22. "path",
  23. "target_path",
  24. "targetPath",
  25. "filename",
  26. "file",
  27. "content",
  28. "new_string",
  29. "newString",
  30. "new_text",
  31. "newText",
  32. "old_string",
  33. "oldString",
  34. "old_text",
  35. "oldText",
  36. "command",
  37. "description",
  38. "title",
  39. "pattern",
  40. "replacement",
  41. // ExitPlanMode 的正文位于 plan 字段。把它纳入半截 JSON 预览后,计划卡片与
  42. // 侧边详情才能从首个流式 chunk 开始更新,而不是等 input_end 才突然出现。
  43. "plan",
  44. // CreateWorkflow 的脚本与名字:流式草稿
  45. // 要在模型还在写脚本时就把站扫出来,半截 script 必须从首个 chunk 起就进预览。
  46. "name",
  47. "script",
  48. ] as const;
  49. export function appendZCodeStreamingToolInputDelta(
  50. state: ZCodeStreamingToolInputState | undefined,
  51. delta: string,
  52. ): ZCodeStreamingToolInputState {
  53. return {
  54. ...state,
  55. deltaCount: (state?.deltaCount ?? 0) + 1,
  56. rawInput: `${state?.rawInput ?? ""}${delta}`,
  57. };
  58. }
  59. export function buildZCodeStreamingToolInputPreview(
  60. rawInput: string,
  61. completeInput?: unknown,
  62. ): ZCodeStreamingToolInputPreview {
  63. if (completeInput !== undefined) {
  64. return {
  65. complete: true,
  66. input: completeInput,
  67. rawInput,
  68. };
  69. }
  70. const parsed = parseCompleteJson(rawInput);
  71. if (parsed.ok) {
  72. return {
  73. complete: true,
  74. input: parsed.value,
  75. rawInput,
  76. };
  77. }
  78. return {
  79. complete: false,
  80. input: readPartialJsonObjectPreview(rawInput) ?? {},
  81. rawInput,
  82. };
  83. }
  84. export function shouldMaterializeZCodeStreamingToolInputPreview(
  85. state: ZCodeStreamingToolInputState,
  86. options: {
  87. mode?: ZCodeStreamingToolInputPreviewMode;
  88. now?: number;
  89. toolName?: string;
  90. } = {},
  91. ): boolean {
  92. if (options.mode === "background-summary") {
  93. return false;
  94. }
  95. const deltaCount = state.deltaCount ?? 0;
  96. if (deltaCount <= ZCODE_ACTIVE_STREAMING_TOOL_INPUT_EAGER_DELTA_COUNT) {
  97. return true;
  98. }
  99. const lastPreviewAt = state.lastPreviewAt ?? 0;
  100. if (isZCodeFileStreamingToolInputPreviewTool(options.toolName)) {
  101. // 性能修复:Write/Edit 的半截 JSON 会触发全量内容恢复和行级 diff。
  102. // 大字节 chunk 不能绕过一秒窗口,否则模型输出越快,UI 反而更新越频繁。
  103. return (
  104. (options.now ?? Date.now()) - lastPreviewAt >=
  105. ZCODE_FILE_STREAMING_TOOL_INPUT_PREVIEW_MIN_INTERVAL_MS
  106. );
  107. }
  108. const lastPreviewRawInputLength = state.lastPreviewRawInputLength ?? 0;
  109. const rawGrowth = state.rawInput.length - lastPreviewRawInputLength;
  110. if (rawGrowth >= ZCODE_ACTIVE_STREAMING_TOOL_INPUT_PREVIEW_MIN_RAW_GROWTH) {
  111. return true;
  112. }
  113. const intervalElapsed =
  114. (options.now ?? Date.now()) - lastPreviewAt >=
  115. ZCODE_ACTIVE_STREAMING_TOOL_INPUT_PREVIEW_MIN_INTERVAL_MS;
  116. if (!intervalElapsed) {
  117. return false;
  118. }
  119. // 性能修复:大 Write/Edit 参数通常会被 provider 以 4KB 左右的慢速 chunk 推送。
  120. // 若只按时间预算,active 任务仍会每个 chunk 解析累计 JSON;超过小输入范围后改由 raw growth 控制。
  121. return state.rawInput.length <= ZCODE_ACTIVE_STREAMING_TOOL_INPUT_TIME_BUDGET_MAX_RAW_INPUT;
  122. }
  123. export function isZCodeFileStreamingToolInputPreviewTool(toolName?: string): boolean {
  124. const normalized = toolName?.trim().toLowerCase();
  125. return normalized === "write" || normalized === "edit";
  126. }
  127. export function markZCodeStreamingToolInputPreviewMaterialized(
  128. state: ZCodeStreamingToolInputState,
  129. now = Date.now(),
  130. ): void {
  131. state.lastPreviewAt = now;
  132. state.lastPreviewRawInputLength = state.rawInput.length;
  133. }
  134. function parseCompleteJson(value: string): { ok: true; value: unknown } | { ok: false } {
  135. try {
  136. return { ok: true, value: JSON.parse(value) as unknown };
  137. } catch {
  138. return { ok: false };
  139. }
  140. }
  141. function readPartialJsonObjectPreview(rawInput: string): Record<string, string> | null {
  142. const preview: Record<string, string> = {};
  143. for (const key of PARTIAL_JSON_STRING_FIELD_KEYS) {
  144. const value = readPartialJsonStringField(rawInput, key);
  145. if (value !== undefined) {
  146. preview[key] = value;
  147. }
  148. }
  149. return Object.keys(preview).length > 0 ? preview : null;
  150. }
  151. function readPartialJsonStringField(rawInput: string, key: string): string | undefined {
  152. const match = new RegExp(`"${escapeRegExp(key)}"\\s*:\\s*"`).exec(rawInput);
  153. if (!match) {
  154. return undefined;
  155. }
  156. let encoded = "";
  157. let escaped = false;
  158. let closed = false;
  159. for (let index = match.index + match[0].length; index < rawInput.length; index += 1) {
  160. const char = rawInput[index] ?? "";
  161. if (escaped) {
  162. encoded += `\\${char}`;
  163. escaped = false;
  164. continue;
  165. }
  166. if (char === "\\") {
  167. escaped = true;
  168. continue;
  169. }
  170. if (char === '"') {
  171. closed = true;
  172. break;
  173. }
  174. encoded += char;
  175. }
  176. if (escaped) {
  177. encoded += "\\";
  178. }
  179. return decodeJsonStringSegment(encoded, closed);
  180. }
  181. function decodeJsonStringSegment(encoded: string, closed: boolean): string {
  182. const normalized = closed ? encoded : trimDanglingJsonEscape(encoded);
  183. try {
  184. return JSON.parse(`"${normalized}"`) as string;
  185. } catch {
  186. return decodeJsonStringSegmentBestEffort(normalized);
  187. }
  188. }
  189. function trimDanglingJsonEscape(value: string): string {
  190. return value.replace(/\\u[0-9a-fA-F]{0,3}$/, "").replace(/\\$/, "");
  191. }
  192. function decodeJsonStringSegmentBestEffort(value: string): string {
  193. return value
  194. .replace(/\\n/g, "\n")
  195. .replace(/\\r/g, "\r")
  196. .replace(/\\t/g, "\t")
  197. .replace(/\\"/g, '"')
  198. .replace(/\\\\/g, "\\");
  199. }
  200. function escapeRegExp(value: string): string {
  201. return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  202. }