model-io.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import { mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { basename, join } from "node:path";
  3. import {
  4. createAnthropicRequestBody,
  5. deriveTrajectoriesFromEntries,
  6. type DerivedTrajectoryResult,
  7. } from "./derive.js";
  8. import { isAppendOnly, isTrajectoryMessageEqual } from "./message-continuity.js";
  9. import type { JsonObject, OpenAiMessage, TrajectoryJsonlEntry } from "./types.js";
  10. const DEFAULT_QUERY_SOURCE = "main_turn";
  11. const SESSION_TITLE_PROMPT_PREFIX = "Generate a concise title for this coding session.";
  12. export interface ModelIoJsonlEntry extends JsonObject {
  13. querySource?: string;
  14. request?: ModelIoRequest;
  15. response?: ModelIoResponse;
  16. type?: string;
  17. }
  18. interface ModelIoRequest extends JsonObject {
  19. body?: JsonObject;
  20. bodyMessageOffset?: number;
  21. bodyMessagesKind?: string;
  22. messageOffset?: number;
  23. messages?: unknown[];
  24. messagesKind?: string;
  25. sdkMessageOffset?: number;
  26. sdkMessages?: unknown[];
  27. sdkMessagesKind?: string;
  28. }
  29. interface ModelIoResponse extends JsonObject {
  30. text?: string;
  31. toolCalls?: unknown[];
  32. }
  33. interface ModelIoToolCall {
  34. id?: string;
  35. input?: unknown;
  36. name?: string;
  37. }
  38. export interface ModelIoTrajectoryOptions {
  39. querySource?: string;
  40. }
  41. export async function writeModelIoAnthropicTrajectory(input: {
  42. inputPath: string;
  43. outDir: string;
  44. querySource?: string;
  45. }): Promise<DerivedTrajectoryResult> {
  46. const result = deriveTrajectoriesFromModelIoEntries(await readModelIoJsonl(input.inputPath), {
  47. querySource: input.querySource,
  48. });
  49. if (result.trajectories.length === 0) {
  50. throw new Error(`No model-io records matched querySource ${input.querySource ?? DEFAULT_QUERY_SOURCE}`);
  51. }
  52. const trajectoriesDir = join(input.outDir, "trajectories");
  53. await mkdir(trajectoriesDir, { recursive: true });
  54. for (const trajectory of result.trajectories) {
  55. await writeFile(
  56. join(trajectoriesDir, `${trajectory.id}.openai_request_body.json`),
  57. `${JSON.stringify(trajectory.requestBody, null, 2)}\n`,
  58. "utf8",
  59. );
  60. await writeFile(
  61. join(trajectoriesDir, `${trajectory.id}.anthropic_request_body.json`),
  62. `${JSON.stringify(createAnthropicRequestBody(trajectory), null, 2)}\n`,
  63. "utf8",
  64. );
  65. }
  66. await writeFile(
  67. join(input.outDir, "anthropic_trajectory.json"),
  68. `${JSON.stringify(createAnthropicRequestBody(result.trajectories[0]!), null, 2)}\n`,
  69. "utf8",
  70. );
  71. await writeFile(
  72. join(input.outDir, "manifest.json"),
  73. `${JSON.stringify(result.manifest, null, 2)}\n`,
  74. "utf8",
  75. );
  76. return result;
  77. }
  78. export function deriveTrajectoriesFromModelIoEntries(
  79. entries: readonly ModelIoJsonlEntry[],
  80. options: ModelIoTrajectoryOptions = {},
  81. ): DerivedTrajectoryResult {
  82. const querySource = options.querySource ?? DEFAULT_QUERY_SOURCE;
  83. const expandedRecords = expandModelIoRecords(
  84. entries.filter((entry) => entry.type === undefined || entry.type === "model_io"),
  85. );
  86. const trajectoryEntries = modelIoRecordsToTrajectoryEntries(
  87. expandedRecords.filter((record) => modelIoQuerySource(record) === querySource),
  88. );
  89. return deriveTrajectoriesFromEntries(trajectoryEntries);
  90. }
  91. async function readModelIoJsonl(inputPath: string): Promise<ModelIoJsonlEntry[]> {
  92. const content = await readFile(inputPath, "utf8");
  93. return content
  94. .split(/\r?\n/u)
  95. .filter((line) => line.trim().length > 0)
  96. .map((line, index) => {
  97. try {
  98. return JSON.parse(line) as ModelIoJsonlEntry;
  99. } catch (error) {
  100. throw new Error(`Invalid model-io JSONL at ${basename(inputPath)}:${index + 1}`, {
  101. cause: error,
  102. });
  103. }
  104. });
  105. }
  106. function expandModelIoRecords(entries: readonly ModelIoJsonlEntry[]): ModelIoJsonlEntry[] {
  107. const expanded: ModelIoJsonlEntry[] = [];
  108. let previous: ModelIoJsonlEntry | undefined;
  109. for (const entry of entries) {
  110. const next = expandModelIoRecord(entry, previous);
  111. expanded.push(next);
  112. previous = next;
  113. }
  114. return expanded;
  115. }
  116. function expandModelIoRecord(
  117. entry: ModelIoJsonlEntry,
  118. previousEntry?: ModelIoJsonlEntry,
  119. ): ModelIoJsonlEntry {
  120. const request = asRecord(entry.request);
  121. if (!request) {
  122. return cloneJsonObject(entry) as ModelIoJsonlEntry;
  123. }
  124. return {
  125. ...cloneJsonObject(entry),
  126. request: expandModelIoRequest(request, asRecord(previousEntry?.request)),
  127. };
  128. }
  129. function expandModelIoRequest(
  130. request: Record<string, unknown>,
  131. previousRequest?: Record<string, unknown>,
  132. ): ModelIoRequest {
  133. const next = { ...cloneJsonObject(request) } as ModelIoRequest;
  134. expandMessageCollection(next, previousRequest, {
  135. collectionKey: "messages",
  136. kindKey: "messagesKind",
  137. offsetKey: "messageOffset",
  138. });
  139. expandMessageCollection(next, previousRequest, {
  140. collectionKey: "sdkMessages",
  141. kindKey: "sdkMessagesKind",
  142. offsetKey: "sdkMessageOffset",
  143. });
  144. const body = asRecord(next.body);
  145. if (body) {
  146. const nextBody = { ...cloneJsonObject(body) } as JsonObject;
  147. expandMessageCollection(
  148. nextBody,
  149. asRecord(asRecord(previousRequest?.body)),
  150. {
  151. collectionKey: "messages",
  152. kindKey: "bodyMessagesKind",
  153. offsetKey: "bodyMessageOffset",
  154. },
  155. next,
  156. );
  157. next.body = nextBody;
  158. }
  159. return next;
  160. }
  161. function expandMessageCollection(
  162. target: JsonObject,
  163. previous: Record<string, unknown> | undefined,
  164. keys: {
  165. collectionKey: string;
  166. kindKey: string;
  167. offsetKey: string;
  168. },
  169. metadataSource: JsonObject = target,
  170. ): void {
  171. if (metadataSource[keys.kindKey] !== "delta") {
  172. return;
  173. }
  174. const deltaMessages = target[keys.collectionKey];
  175. const previousMessages = previous?.[keys.collectionKey];
  176. const offset = asNonNegativeInteger(metadataSource[keys.offsetKey]);
  177. if (!Array.isArray(deltaMessages) || !Array.isArray(previousMessages) || offset === undefined) {
  178. return;
  179. }
  180. target[keys.collectionKey] = [
  181. ...cloneArray(previousMessages.slice(0, offset)),
  182. ...cloneArray(deltaMessages),
  183. ];
  184. }
  185. function modelIoRecordsToTrajectoryEntries(
  186. records: readonly ModelIoJsonlEntry[],
  187. ): TrajectoryJsonlEntry[] {
  188. const entries: TrajectoryJsonlEntry[] = [];
  189. let requestIndex = 0;
  190. const requests = records.flatMap((record) => {
  191. const body = asRecord(record.request?.body);
  192. return body ? [{ body, response: record.response }] : [];
  193. });
  194. for (const [recordIndex, { body, response }] of requests.entries()) {
  195. const messages = body.messages;
  196. if (!Array.isArray(messages)) {
  197. throw new Error("model-io request.body must contain a messages array.");
  198. }
  199. requestIndex += 1;
  200. const { messages: _messages, ...bodyWithoutMessages } = cloneJsonObject(body);
  201. entries.push({
  202. bodyWithoutMessages,
  203. kind: "request",
  204. requestIndex,
  205. });
  206. for (let messageIndex = 0; messageIndex < messages.length; messageIndex += 1) {
  207. const message = messages[messageIndex];
  208. if (!isOpenAiMessage(message)) {
  209. throw new Error(`model-io request message ${messageIndex} is missing role.`);
  210. }
  211. entries.push({
  212. kind: "message",
  213. message: cloneJsonObject(message) as OpenAiMessage,
  214. messageIndex,
  215. requestIndex,
  216. });
  217. }
  218. const assistantMessage = assistantMessageFromModelIoResponse(response);
  219. if (assistantMessage) {
  220. entries.push({
  221. kind: "message",
  222. message: completeAssistantMessage(
  223. assistantMessage,
  224. messages as OpenAiMessage[],
  225. requests[recordIndex + 1]?.body.messages,
  226. ),
  227. requestIndex,
  228. });
  229. }
  230. }
  231. return entries;
  232. }
  233. function completeAssistantMessage(
  234. summary: OpenAiMessage,
  235. previous: readonly OpenAiMessage[],
  236. next: unknown,
  237. ): OpenAiMessage {
  238. if (!Array.isArray(next) || !next.every(isOpenAiMessage) || !isAppendOnly(previous, next)) {
  239. return summary;
  240. }
  241. const recorded = next[previous.length];
  242. if (recorded?.role !== "assistant" || !Array.isArray(recorded.content)) return summary;
  243. // response 摘要没有完整 thinking/签名,直接比较会误分段。
  244. // 只从前缀连续且正文/工具完全匹配的下一请求补全;已有历史的 thinking 仍严格比较。
  245. const comparable = {
  246. ...recorded,
  247. content: recorded.content.filter((block: unknown) => {
  248. const type = asRecord(block)?.type;
  249. return type !== "thinking" && type !== "redacted_thinking";
  250. }),
  251. };
  252. return isTrajectoryMessageEqual(summary, comparable)
  253. ? (cloneJsonObject(recorded) as OpenAiMessage)
  254. : summary;
  255. }
  256. function assistantMessageFromModelIoResponse(
  257. response: ModelIoResponse | undefined,
  258. ): OpenAiMessage | undefined {
  259. if (!response) {
  260. return undefined;
  261. }
  262. const content: unknown[] = [];
  263. if (typeof response.text === "string" && response.text.length > 0) {
  264. content.push({ type: "text", text: response.text });
  265. }
  266. for (const toolCall of normalizedToolCalls(response.toolCalls)) {
  267. content.push({
  268. type: "tool_use",
  269. id: toolCall.id,
  270. name: toolCall.name,
  271. input: cloneJsonValue(toolCall.input ?? {}),
  272. });
  273. }
  274. return content.length > 0 ? { role: "assistant", content } : undefined;
  275. }
  276. function normalizedToolCalls(value: unknown[] | undefined): ModelIoToolCall[] {
  277. if (!Array.isArray(value)) {
  278. return [];
  279. }
  280. return value.flatMap((raw) => {
  281. const toolCall = asRecord(raw);
  282. if (!toolCall) {
  283. return [];
  284. }
  285. const id = typeof toolCall?.id === "string" ? toolCall.id : undefined;
  286. const name = typeof toolCall?.name === "string" ? toolCall.name : undefined;
  287. if (!id || !name) {
  288. return [];
  289. }
  290. return [{ id, input: toolCall.input, name }];
  291. });
  292. }
  293. function modelIoQuerySource(record: ModelIoJsonlEntry): string {
  294. if (typeof record.querySource === "string") {
  295. return record.querySource;
  296. }
  297. const messages = asRecord(record.request?.body)?.messages;
  298. const firstMessage = Array.isArray(messages) ? asRecord(messages[0]) : undefined;
  299. if (firstMessage?.role === "system" || firstMessage?.role === "user") {
  300. const text = messageText(firstMessage.content);
  301. if (text.startsWith(SESSION_TITLE_PROMPT_PREFIX)) {
  302. return "session_title";
  303. }
  304. }
  305. return DEFAULT_QUERY_SOURCE;
  306. }
  307. function messageText(value: unknown): string {
  308. if (typeof value === "string") {
  309. return value;
  310. }
  311. if (!value || typeof value !== "object") {
  312. return "";
  313. }
  314. if (Array.isArray(value)) {
  315. return value.map(messageText).join("\n");
  316. }
  317. const record = value as Record<string, unknown>;
  318. return [record.text, record.content].map(messageText).join("\n");
  319. }
  320. function isOpenAiMessage(value: unknown): value is OpenAiMessage {
  321. return Boolean(
  322. value &&
  323. typeof value === "object" &&
  324. !Array.isArray(value) &&
  325. typeof (value as { role?: unknown }).role === "string",
  326. );
  327. }
  328. function asRecord(value: unknown): Record<string, unknown> | undefined {
  329. return typeof value === "object" && value !== null && !Array.isArray(value)
  330. ? (value as Record<string, unknown>)
  331. : undefined;
  332. }
  333. function asNonNegativeInteger(value: unknown): number | undefined {
  334. return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined;
  335. }
  336. function cloneArray(value: readonly unknown[]): unknown[] {
  337. return JSON.parse(JSON.stringify(value)) as unknown[];
  338. }
  339. function cloneJsonObject(value: Record<string, unknown>): JsonObject {
  340. return JSON.parse(JSON.stringify(value)) as JsonObject;
  341. }
  342. function cloneJsonValue(value: unknown): unknown {
  343. return JSON.parse(JSON.stringify(value));
  344. }