edit-prepare-arguments.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * Shared compatibility shim for the `edit` tool's arguments.
  3. *
  4. * Two model-side quirks are normalized before schema validation runs (both
  5. * mirror Pi 0.79's builtin edit tool shim):
  6. *
  7. * 1. Some models (MiniMax-M3 / GLM-5.1) emit `edits` as a JSON string even
  8. * though the public schema is `edits[]` — parse it back into an array.
  9. * 2. Legacy single-edit input (`oldText` / `newText` at the top level) is
  10. * folded into `edits[]`.
  11. *
  12. * One shared implementation is referenced by all three edit defs
  13. * (agent-core base, desktop, cloud); edit-defs-contract tests assert the
  14. * references are identical.
  15. */
  16. export interface PreparedEditArguments {
  17. path: string;
  18. edits: { oldText: string; newText: string }[];
  19. }
  20. export function prepareEditArguments(args: unknown): PreparedEditArguments {
  21. if (!args || typeof args !== 'object' || Array.isArray(args)) {
  22. return args as PreparedEditArguments;
  23. }
  24. const record = args as Record<string, unknown>;
  25. let prepared = record;
  26. if (typeof record.edits === 'string') {
  27. try {
  28. const parsed = JSON.parse(record.edits);
  29. if (Array.isArray(parsed)) {
  30. prepared = { ...record, edits: parsed };
  31. }
  32. } catch {
  33. // Leave invalid JSON untouched so schema validation reports it normally.
  34. }
  35. }
  36. if (typeof prepared.oldText !== 'string' || typeof prepared.newText !== 'string') {
  37. return prepared as unknown as PreparedEditArguments;
  38. }
  39. const edits = Array.isArray(prepared.edits) ? [...prepared.edits] : [];
  40. const { oldText: _oldText, newText: _newText, ...rest } = prepared;
  41. return {
  42. ...rest,
  43. edits: [...edits, { oldText: prepared.oldText, newText: prepared.newText }],
  44. } as PreparedEditArguments;
  45. }