@@ -368,22 +368,22 @@ async function createPatchContent(change: FileUpdateChange): Promise<ToolCallCon
368368
369369 const oldContent = change . kind . type === "add" ? "" : await readFile ( change . path , { encoding : "utf8" } ) . catch ( ( ) => null ) ;
370370 if ( oldContent === null ) {
371- return null ;
371+ return isUnifiedDiff ( change . diff ) ? createPatchContentFromUnifiedDiff ( change ) : null ;
372372 }
373373
374374 const newContent = applyPatch ( oldContent , change . diff ) ;
375- if ( newContent === false ) {
376- return null ;
375+ if ( newContent !== false ) {
376+ return {
377+ type : "diff" ,
378+ oldText : change . kind . type === "add" ? null : oldContent ,
379+ newText : newContent ,
380+ path : change . path ,
381+ _meta : {
382+ kind : change . kind . type ,
383+ } ,
384+ } ;
377385 }
378- return {
379- type : "diff" ,
380- oldText : change . kind . type === "add" ? null : oldContent ,
381- newText : newContent ,
382- path : change . path ,
383- _meta : {
384- kind : change . kind . type ,
385- } ,
386- } ;
386+ return createPatchContentFromUnifiedDiff ( change ) ;
387387}
388388
389389function isUnifiedDiff ( content : string ) : boolean {
@@ -472,3 +472,60 @@ function patchToDeletedContent(unifiedDiff: string): string | null {
472472 return null ;
473473 }
474474}
475+
476+ function createPatchContentFromUnifiedDiff ( change : FileUpdateChange ) : ToolCallContent | null {
477+ const diffContent = patchToDiffContent ( change . diff ) ;
478+ if ( diffContent === null ) {
479+ return null ;
480+ }
481+
482+ return {
483+ type : "diff" ,
484+ oldText : change . kind . type === "add" ? null : diffContent . oldText ,
485+ newText : change . kind . type === "delete" ? "" : diffContent . newText ,
486+ path : change . path ,
487+ _meta : {
488+ kind : change . kind . type ,
489+ } ,
490+ } ;
491+ }
492+
493+ function patchToDiffContent ( unifiedDiff : string ) : { oldText : string ; newText : string } | null {
494+ try {
495+ const [ patch ] = parsePatch ( unifiedDiff ) ;
496+ if ( ! patch || patch . hunks . length === 0 ) {
497+ return null ;
498+ }
499+
500+ const oldLines : string [ ] = [ ] ;
501+ const newLines : string [ ] = [ ] ;
502+
503+ for ( const hunk of patch . hunks ) {
504+ for ( const line of hunk . lines ) {
505+ if ( line === "\\ No newline at end of file" ) {
506+ continue ;
507+ }
508+ if ( line . startsWith ( " " ) ) {
509+ const text = line . slice ( 1 ) ;
510+ oldLines . push ( text ) ;
511+ newLines . push ( text ) ;
512+ continue ;
513+ }
514+ if ( line . startsWith ( "-" ) ) {
515+ oldLines . push ( line . slice ( 1 ) ) ;
516+ continue ;
517+ }
518+ if ( line . startsWith ( "+" ) ) {
519+ newLines . push ( line . slice ( 1 ) ) ;
520+ }
521+ }
522+ }
523+
524+ return {
525+ oldText : oldLines . join ( "\n" ) ,
526+ newText : newLines . join ( "\n" ) ,
527+ } ;
528+ } catch {
529+ return null ;
530+ }
531+ }
0 commit comments