ModelTrajectorySearch.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import { createContext } from "react";
  2. import type { ZCodeModelTrajectoryMessage, ZCodeModelTrajectoryRecord } from "@zcode/services";
  3. import {
  4. trajectoryToolCallInputs,
  5. trajectoryToolMetadata,
  6. trajectoryToolOutputs,
  7. } from "@/ModelTrajectoryToolPayload.js";
  8. export type TrajectorySearchField = "content" | "tool-name" | "tool-id";
  9. export interface TrajectorySearchMatch {
  10. key: string;
  11. callKey: string;
  12. callIndex: number;
  13. expansionKey: string;
  14. field: TrajectorySearchField;
  15. fieldMatchIndex: number;
  16. sourceStart: number;
  17. sourceEnd: number;
  18. sourceText: string;
  19. }
  20. export interface TrajectorySearchIndex {
  21. query: string;
  22. matches: TrajectorySearchMatch[];
  23. }
  24. export interface TrajectorySearchTimelineItem {
  25. key: string;
  26. record: ZCodeModelTrajectoryRecord;
  27. inputMessages: ZCodeModelTrajectoryMessage[];
  28. }
  29. interface SearchTarget {
  30. callKey: string;
  31. callIndex: number;
  32. expansionKey: string;
  33. field: TrajectorySearchField;
  34. text: string;
  35. }
  36. export const TrajectorySearchRevealContext = createContext<string | null>(null);
  37. export function buildTrajectorySearchIndex(
  38. items: readonly TrajectorySearchTimelineItem[],
  39. query: string,
  40. ): TrajectorySearchIndex {
  41. const normalizedQuery = normalizeTrajectorySearchText(query).text.trim();
  42. if (!normalizedQuery) return { query: "", matches: [] };
  43. const matches: TrajectorySearchMatch[] = [];
  44. for (const target of buildSearchTargets(items)) {
  45. const sourceMatches = findTrajectoryTextMatches(target.text, normalizedQuery);
  46. sourceMatches.forEach(({ sourceStart, sourceEnd }, fieldMatchIndex) => {
  47. matches.push({
  48. ...target,
  49. key: `${target.expansionKey}:${target.field}:${fieldMatchIndex}:${sourceStart}`,
  50. fieldMatchIndex,
  51. sourceStart,
  52. sourceEnd,
  53. sourceText: target.text,
  54. });
  55. });
  56. }
  57. return { query: normalizedQuery, matches };
  58. }
  59. function buildSearchTargets(items: readonly TrajectorySearchTimelineItem[]): SearchTarget[] {
  60. return items.flatMap((item, callIndex) => {
  61. const targets = item.inputMessages.flatMap((message, messageIndex) =>
  62. messageTargets(item.key, callIndex, `${item.key}:input:${messageIndex}`, message),
  63. );
  64. const response = item.record.response;
  65. if (!response) return targets;
  66. if (response.reasoningText) {
  67. targets.push(
  68. contentTarget(item.key, callIndex, `${item.key}:output:reasoning`, response.reasoningText),
  69. );
  70. }
  71. if (response.text) {
  72. targets.push(contentTarget(item.key, callIndex, `${item.key}:output:message`, response.text));
  73. }
  74. response.toolCalls.forEach((toolCall, toolCallIndex) => {
  75. targets.push(
  76. ...messageTargets(
  77. item.key,
  78. callIndex,
  79. `${item.key}:output:${toolCall.kind}:${toolCallIndex}`,
  80. { role: "assistant", parts: [toolCall] },
  81. ),
  82. );
  83. });
  84. return targets;
  85. });
  86. }
  87. function messageTargets(
  88. callKey: string,
  89. callIndex: number,
  90. expansionKey: string,
  91. message: ZCodeModelTrajectoryMessage,
  92. ): SearchTarget[] {
  93. const metadata = trajectoryToolMetadata(message);
  94. const content = message.parts.some((part) => part.kind === "tool-result")
  95. ? trajectoryToolOutputs(message).join("\n\n")
  96. : message.parts.some((part) => part.kind === "tool-call")
  97. ? trajectoryToolCallInputs(message).join("\n\n")
  98. : message.parts
  99. .flatMap((part) => ("text" in part && typeof part.text === "string" ? [part.text] : []))
  100. .join("\n\n");
  101. return [
  102. ...(content ? [contentTarget(callKey, callIndex, expansionKey, content)] : []),
  103. ...(metadata.names
  104. ? [{ callKey, callIndex, expansionKey, field: "tool-name" as const, text: metadata.names }]
  105. : []),
  106. ...(metadata.ids
  107. ? [{ callKey, callIndex, expansionKey, field: "tool-id" as const, text: metadata.ids }]
  108. : []),
  109. ];
  110. }
  111. function contentTarget(
  112. callKey: string,
  113. callIndex: number,
  114. expansionKey: string,
  115. text: string,
  116. ): SearchTarget {
  117. return { callKey, callIndex, expansionKey, field: "content", text };
  118. }
  119. export function findTrajectoryTextMatches(
  120. source: string,
  121. normalizedQuery: string,
  122. ): Array<{ sourceStart: number; sourceEnd: number }> {
  123. const normalizedSource = normalizeTrajectorySearchText(source);
  124. const matches: Array<{ sourceStart: number; sourceEnd: number }> = [];
  125. let searchStart = 0;
  126. while (searchStart < normalizedSource.text.length) {
  127. const matchStart = normalizedSource.text.indexOf(normalizedQuery, searchStart);
  128. if (matchStart === -1) break;
  129. const matchEnd = matchStart + normalizedQuery.length;
  130. const sourceStart = normalizedSource.starts[matchStart] ?? 0;
  131. matches.push({
  132. sourceStart,
  133. sourceEnd: normalizedSource.ends[matchEnd - 1] ?? sourceStart,
  134. });
  135. searchStart = matchEnd;
  136. }
  137. return matches;
  138. }
  139. export function normalizeTrajectorySearchText(source: string): {
  140. text: string;
  141. starts: number[];
  142. ends: number[];
  143. } {
  144. let text = "";
  145. const starts: number[] = [];
  146. const ends: number[] = [];
  147. let inWhitespace = false;
  148. for (let index = 0; index < source.length; index += 1) {
  149. const character = source[index] ?? "";
  150. if (/\s/.test(character)) {
  151. if (!inWhitespace) {
  152. text += " ";
  153. starts.push(index);
  154. ends.push(index + 1);
  155. inWhitespace = true;
  156. } else {
  157. ends[ends.length - 1] = index + 1;
  158. }
  159. continue;
  160. }
  161. inWhitespace = false;
  162. const normalizedCharacter = character.toLocaleLowerCase();
  163. text += normalizedCharacter;
  164. for (let offset = 0; offset < normalizedCharacter.length; offset += 1) {
  165. starts.push(index);
  166. ends.push(index + 1);
  167. }
  168. }
  169. return { text, starts, ends };
  170. }