@greppleai/grip 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/core/extensions/types.d.ts +5 -1
  3. package/dist/core/extensions/types.d.ts.map +1 -1
  4. package/dist/core/extensions/types.js.map +1 -1
  5. package/dist/core/tools/find.d.ts.map +1 -1
  6. package/dist/core/tools/find.js +2 -3
  7. package/dist/core/tools/find.js.map +1 -1
  8. package/dist/core/tools/grep.d.ts.map +1 -1
  9. package/dist/core/tools/grep.js +2 -3
  10. package/dist/core/tools/grep.js.map +1 -1
  11. package/dist/core/tools/ls.d.ts.map +1 -1
  12. package/dist/core/tools/ls.js +2 -3
  13. package/dist/core/tools/ls.js.map +1 -1
  14. package/dist/core/tools/read.d.ts.map +1 -1
  15. package/dist/core/tools/read.js +3 -3
  16. package/dist/core/tools/read.js.map +1 -1
  17. package/dist/core/tools/render-utils.d.ts +1 -0
  18. package/dist/core/tools/render-utils.d.ts.map +1 -1
  19. package/dist/core/tools/render-utils.js +5 -0
  20. package/dist/core/tools/render-utils.js.map +1 -1
  21. package/dist/core/tools/write.d.ts.map +1 -1
  22. package/dist/core/tools/write.js +2 -3
  23. package/dist/core/tools/write.js.map +1 -1
  24. package/dist/modes/interactive/components/hook-execution.d.ts +3 -0
  25. package/dist/modes/interactive/components/hook-execution.d.ts.map +1 -1
  26. package/dist/modes/interactive/components/hook-execution.js +17 -0
  27. package/dist/modes/interactive/components/hook-execution.js.map +1 -1
  28. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  29. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  30. package/dist/modes/interactive/interactive-mode.js +51 -3
  31. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  32. package/docs/extensions.md +3 -0
  33. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  34. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  35. package/examples/extensions/sandbox/package.json +1 -1
  36. package/examples/extensions/with-deps/package.json +1 -1
  37. package/npm-shrinkwrap.json +12 -12
  38. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"interactive-mode.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-mode.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAaH,OAAO,EAGN,KAAK,YAAY,EAUjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EASX,QAAQ,EAER,OAAO,EACP,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEN,KAAK,SAAS,EAgBd,KAAK,GAAG,EACR,YAAY,EACZ,aAAa,EAGb,MAAM,qBAAqB,CAAC;AAuC7B,OAAO,EAEN,KAAK,oBAAoB,EAEzB,MAAM,0BAA0B,CAAC;AAqClC,OAAO,EAAE,KAAK,oBAAoB,EAA2B,MAAM,gCAAgC,CAAC;AAiBpG,OAAO,EAA0B,KAAK,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AA0I9F,wBAAgB,qBAAqB,CACpC,UAAU,EAAE,MAAM,EAClB,gBAAgB,EAAE,WAAW,CAAC,MAAM,CAAC,EACrC,kBAAkB,GAAE,WAAW,CAAC,MAAM,CAA4B,GAChE,OAAO,CAQT;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACtC,gEAAgE;IAChE,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC7B,4DAA4D;IAC5D,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,qEAAqE;IACrE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,8CAA8C;IAC9C,aAAa,CAAC,EAAE,YAAY,EAAE,CAAC;IAC/B,4DAA4D;IAC5D,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,6DAA6D;IAC7D,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,qGAAqG;IACrG,OAAO,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,UAAU,qBAAqB;IAC9B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,kBAAkB,EAAE,OAAO,CAAC;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,IAAI,CAAC;CAC/B;AAED,MAAM,MAAM,cAAc,GAAG,aAAa,GAAG,YAAY,CAAC;AA2H1D,MAAM,WAAW,uBAAuB;IACvC,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAKD,MAAM,WAAW,2BAA2B;IAC3C,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAWD,MAAM,WAAW,YAAY;IAC5B,SAAS,EAAE,SAAS,CAAC;IACrB,KAAK,EAAE,SAAS,CAAC;CACjB;AAED,MAAM,MAAM,eAAe,GAAG,CAAC,IAAI,EAAE,MAAM,IAAI,KAAK,YAAY,CAAC;AAMjE,MAAM,WAAW,kBAAkB;IAClC,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED,wEAAwE;AACxE,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,cAAc,CASnF;AAED,0FAA0F;AAC1F,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,GAAG,CA4BpE;AAED,qBAAa,eAAe;IAC3B,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAEhC;IACF,OAAO,CAAC,QAAQ,CAA+B;IAC/C,OAAO,CAAC,EAAE,CAAM;IAChB,OAAO,CAAC,qBAAqB,CAAuC;IACpE,OAAO,CAAC,wBAAwB,CAAY;IAC5C,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,iBAAiB,CAAY;IACrC,OAAO,CAAC,oBAAoB,CAAyB;IACrD,OAAO,CAAC,oBAAoB,CAAwB;IACpD,OAAO,CAAC,wBAAwB,CAAY;IAC5C,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,aAAa,CAAe;IACpC,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,sBAAsB,CAA4B;IAC1D,OAAO,CAAC,oBAAoB,CAAmC;IAC/D,OAAO,CAAC,4BAA4B,CAAqC;IACzE,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,kBAAkB,CAAqB;IAE/C,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,eAAe,CAAC,CAAyB;IACjD,OAAO,CAAC,iBAAiB,CAAgB;IACzC,OAAO,CAAC,gBAAgB,CAAiC;IACzD,OAAO,CAAC,cAAc,CAAiC;IACvD,OAAO,CAAC,0BAA0B,CAAS;IAC3C,OAAO,CAAC,8BAA8B,CAAS;IAC/C,OAAO,CAAC,cAAc,CAAQ;IAC9B,OAAO,CAAC,uBAAuB,CAAiD;IAChF,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAgB;IACtD,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAAiB;IAC5D,OAAO,CAAC,mBAAmB,CAAmC;IAE9D,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,iBAAiB,CAAiC;IAC1D,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,iCAAiC,CAAS;IAGlD,OAAO,CAAC,gBAAgB,CAAiC;IACzD,OAAO,CAAC,cAAc,CAA+B;IAGrD,OAAO,CAAC,kBAAkB,CAAoD;IAC9E,OAAO,CAAC,gBAAgB,CAA2C;IAGnE,OAAO,CAAC,YAAY,CAA6C;IAGjE,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,wBAAwB,CAAqB;IACrD,OAAO,CAAC,6BAA6B,CAAS;IAC9C,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAA0C;IAC/E,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAA0C;IAG/E,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,SAAS,CAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAAsB;IAEjE,OAAO,CAAC,aAAa,CAA6B;IAGlD,OAAO,CAAC,WAAW,CAAC,CAAa;IACjC,OAAO,CAAC,wBAAwB,CAAC,CAAa;IAC9C,OAAO,CAAC,gCAAgC,CAAC,CAAa;IACtD,OAAO,CAAC,0BAA0B,CAAK;IACvC,OAAO,CAAC,+BAA+B,CAAS;IAChD,OAAO,CAAC,oBAAoB,CAAC,CAAU;IACvC,OAAO,CAAC,oBAAoB,CAA+B;IAC3D,OAAO,CAAC,uBAAuB,CAAgC;IAC/D,OAAO,CAAC,6BAA6B,CAAmD;IACxF,OAAO,CAAC,uBAAuB,CAAS;IACxC,OAAO,CAAC,qBAAqB,CAAyB;IAGtD,OAAO,CAAC,UAAU,CAAS;IAG3B,OAAO,CAAC,aAAa,CAAiD;IAGtE,OAAO,CAAC,qBAAqB,CAAgC;IAG7D,OAAO,CAAC,oBAAoB,CAAiC;IAC7D,OAAO,CAAC,2BAA2B,CAAC,CAAa;IACjD,OAAO,CAAC,mBAAmB,CAAqB;IAChD,OAAO,CAAC,wBAAwB,CAAqB;IACrD,OAAO,CAAC,2BAA2B,CAA6B;IAGhE,OAAO,CAAC,WAAW,CAAiC;IACpD,OAAO,CAAC,cAAc,CAAyC;IAC/D,OAAO,CAAC,kBAAkB,CAAC,CAAa;IAGxC,OAAO,CAAC,wBAAwB,CAAiC;IAGjE,OAAO,CAAC,iBAAiB,CAAS;IAGlC,OAAO,CAAC,iBAAiB,CAAqD;IAC9E,OAAO,CAAC,cAAc,CAAkD;IACxE,OAAO,CAAC,eAAe,CAAmD;IAC1E,OAAO,CAAC,mCAAmC,CAAiD;IAE5F,OAAO,CAAC,qBAAqB,CAA0C;IACvE,OAAO,CAAC,qBAAqB,CAA0C;IACvE,OAAO,CAAC,oBAAoB,CAAa;IACzC,OAAO,CAAC,oBAAoB,CAAa;IAGzC,OAAO,CAAC,YAAY,CAA8C;IAGlE,OAAO,CAAC,eAAe,CAAY;IAGnC,OAAO,CAAC,aAAa,CAAoC;IAGzD,OAAO,CAAC,YAAY,CAA8C;IAGlE,OAAO,KAAK,OAAO,GAElB;IACD,OAAO,KAAK,KAAK,GAEhB;IACD,OAAO,KAAK,aAAa,GAExB;IACD,OAAO,KAAK,eAAe,GAE1B;IAED,YAAY,WAAW,EAAE,oBAAoB,EAAE,OAAO,GAAE,sBAA2B,EA2DlF;IAED,OAAO,CAAC,wBAAwB;IAyBhC,OAAO,CAAC,6BAA6B;IASrC,OAAO,CAAC,oCAAoC;IAkB5C,OAAO,CAAC,8BAA8B;IAgHtC,OAAO,CAAC,yBAAyB;IAajC,OAAO,CAAC,0BAA0B;IA8BlC,OAAO,CAAC,uBAAuB;IAwD/B,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,mBAAmB;IAoC3B,OAAO,CAAC,kBAAkB;IAS1B,OAAO,CAAC,aAAa;IAgDf,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CA8D1B;IAED;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAU3B;;;OAGG;IACG,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAMzB;IAED,OAAO,CAAC,qBAAqB;IAY7B,OAAO,CAAC,mBAAmB;YAWb,oBAAoB;YAQpB,sBAAsB;YAMtB,wBAAwB;YAMxB,sBAAsB;YAkBtB,sBAAsB;IA+CpC;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IA2B9B,OAAO,CAAC,sBAAsB;IAmB9B,OAAO,CAAC,4BAA4B;IAWpC,OAAO,CAAC,iBAAiB;IAYzB,OAAO,CAAC,0BAA0B;IAMlC,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,wBAAwB;IAIhC;;OAEG;IACH,OAAO,CAAC,YAAY;IA6BpB,OAAO,CAAC,mBAAmB;IAU3B,OAAO,CAAC,4BAA4B;IAcpC,OAAO,CAAC,wBAAwB;IAqBhC,OAAO,CAAC,6BAA6B;IAOrC,OAAO,CAAC,kCAAkC;IAwB1C,OAAO,CAAC,yBAAyB;IA0BjC,OAAO,CAAC,oBAAoB;IAY5B,OAAO,CAAC,aAAa;IASrB,OAAO,CAAC,eAAe;IAKvB,OAAO,CAAC,gBAAgB;IA0BxB,OAAO,CAAC,iBAAiB;IAwBzB,OAAO,CAAC,qBAAqB;IAc7B,OAAO,CAAC,oBAAoB;IAW5B,OAAO,CAAC,oBAAoB;IAyB5B,OAAO,CAAC,wBAAwB;IAUhC,OAAO,CAAC,iBAAiB;IAYzB,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,wBAAwB;IAchC,OAAO,CAAC,yBAAyB;IAuBjC,OAAO,CAAC,yBAAyB;IAwBjC,OAAO,CAAC,6BAA6B;IAuBrC,OAAO,CAAC,2BAA2B;IAuBnC,OAAO,CAAC,sBAAsB;IAc9B,OAAO,CAAC,kBAAkB;IAwB1B,OAAO,CAAC,2BAA2B;IASnC,OAAO,CAAC,4BAA4B;IAYpC,OAAO,CAAC,+BAA+B;IAWvC,OAAO,CAAC,+BAA+B;IAcvC,OAAO,CAAC,mBAAmB;YAcb,4BAA4B;IAuF1C,OAAO,CAAC,oBAAoB;YAmBd,oBAAoB;YA0BpB,uBAAuB;IAQrC,OAAO,CAAC,gCAAgC;IAWxC,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,sBAAsB;IAQ9B,OAAO,CAAC,uBAAuB;IAI/B;;OAEG;IACH,OAAO,CAAC,2BAA2B;IAInC;;OAEG;IACH,OAAO,CAAC,uBAAuB;IA4D/B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAK1B,OAAO,CAAC,uBAAuB;IAS/B,OAAO,CAAC,uBAAuB;IAI/B,OAAO,CAAC,uBAAuB;IAK/B,OAAO,CAAC,mBAAmB;IAU3B,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,0BAA0B;IASlC,OAAO,CAAC,2BAA2B;IAuBnC,OAAO,CAAC,iCAAiC;IAgBzC,OAAO,CAAC,kCAAkC;IAe1C,OAAO,CAAC,iBAAiB;IAmBzB,OAAO,CAAC,mBAAmB;IAM3B,OAAO,CAAC,sBAAsB;IAa9B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IA0C1B,OAAO,CAAC,qBAAqB;IAY7B,OAAO,CAAC,gBAAgB;IAgCxB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAM;IAE9C;;OAEG;IACH,OAAO,CAAC,aAAa;IAOrB,OAAO,CAAC,qBAAqB;IAuB7B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAoB1B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAyC1B,OAAO,CAAC,iCAAiC;IASzC,OAAO,CAAC,qCAAqC;IAO7C,OAAO,CAAC,oCAAoC;IAK5C;;OAEG;IACH,OAAO,CAAC,wBAAwB;IA2DhC;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAwC7B;;OAEG;IACH,OAAO,CAAC,qBAAqB;YAYf,oBAAoB;YASpB,0BAA0B;IAQxC;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAwC1B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAS1B;;OAEG;IACH,OAAO,CAAC,mBAAmB;IA0B3B;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAQ3B;;;OAGG;IACH,OAAO,CAAC,iCAAiC;IAQzC,OAAO,CAAC,wBAAwB;IAehC,OAAO,CAAC,2BAA2B;IAUnC,OAAO,CAAC,wBAAwB;IAehC;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAU3B,OAAO,CAAC,0BAA0B;IAWlC,OAAO,CAAC,6BAA6B;YAiBvB,mBAAmB;IA+CjC;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAqB1B,OAAO,CAAC,uBAAuB;IAa/B,OAAO,CAAC,kBAAkB;IAkB1B,OAAO,CAAC,gBAAgB;YA0CV,oBAAoB;YAyBpB,qBAAqB;IAcnC,OAAO,CAAC,oBAAoB;IAI5B,OAAO,CAAC,8BAA8B;IAsBtC,OAAO,CAAC,iCAAiC;IA2FzC,OAAO,CAAC,yBAAyB;YA4GnB,0BAA0B;YAO1B,0BAA0B;YAiB1B,gCAAgC;YAYhC,+BAA+B;IAU7C,OAAO,CAAC,iBAAiB;YAOX,kBAAkB;IAYhC,OAAO,CAAC,wBAAwB;IAIhC,OAAO,CAAC,sBAAsB;IAa9B,OAAO,CAAC,sCAAsC;IAW9C,OAAO,CAAC,0BAA0B;IAalC,OAAO,CAAC,wBAAwB;IAYhC,OAAO,CAAC,0BAA0B;IAKlC,OAAO,CAAC,gBAAgB;IAYxB,OAAO,CAAC,gBAAgB;IAmBxB,OAAO,CAAC,0BAA0B;IAmBlC,OAAO,CAAC,kBAAkB;IA2B1B,OAAO,CAAC,6BAA6B;IASrC,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,0BAA0B;IASlC,OAAO,CAAC,gBAAgB;IAUxB,OAAO,CAAC,4BAA4B;IAIpC,OAAO,CAAC,gBAAgB;IAiBxB,OAAO,CAAC,cAAc;IAatB,OAAO,CAAC,wBAAwB;IAOhC,OAAO,CAAC,qBAAqB;IAgB7B,OAAO,CAAC,sBAAsB;IAa9B,OAAO,CAAC,mBAAmB;IAS3B,OAAO,CAAC,mBAAmB;IAwB3B,OAAO,CAAC,oBAAoB;IA0B5B,OAAO,CAAC,kBAAkB;IAmB1B,OAAO,CAAC,iCAAiC;IA8BzC,OAAO,CAAC,oCAAoC;IA4B5C,OAAO,CAAC,gCAAgC;YAW1B,WAAW;IA2GzB,+CAA+C;IAC/C,OAAO,CAAC,kBAAkB;IAQ1B;;;;;OAKG;IACH,OAAO,CAAC,UAAU;IAoBlB,OAAO,CAAC,uBAAuB;IAY/B,OAAO,CAAC,gBAAgB;IAcxB,OAAO,CAAC,2BAA2B;IAOnC,OAAO,CAAC,uBAAuB;IAO/B,OAAO,CAAC,0BAA0B;IASlC,OAAO,CAAC,qBAAqB;IAc7B,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,mBAAmB;IAa3B,OAAO,CAAC,gBAAgB;IA4BxB,OAAO,CAAC,wBAAwB;IAkBhC,OAAO,CAAC,wBAAwB;IAQhC,OAAO,CAAC,gCAAgC;IAiBxC,OAAO,CAAC,yBAAyB;IAUjC,OAAO,CAAC,uBAAuB;IAgB/B;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;IAmB5B,qBAAqB,IAAI,IAAI,CAoB5B;IAEK,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC,CAYpC;IAED,OAAO,CAAC,uBAAuB;IAc/B,OAAO,CAAC,WAAW;IAUnB,OAAO,CAAC,WAAW;IAKnB;;;;OAIG;IACH,OAAO,CAAC,cAAc,CAAS;YAEjB,QAAQ;IAiCtB,OAAO,CAAC,qBAAqB;IAS7B;;;;;;;;;;OAUG;IACH,OAAO,CAAC,aAAa;YAsBP,sBAAsB;IAKpC,OAAO,CAAC,sBAAsB;IAwC9B,OAAO,CAAC,wBAAwB;IAOhC,OAAO,CAAC,WAAW;YAqCL,cAAc;IAgC5B,OAAO,CAAC,aAAa;IASrB,OAAO,CAAC,uBAAuB;IAU/B,OAAO,CAAC,kBAAkB;YAWZ,UAAU;IAmBxB,OAAO,CAAC,yBAAyB;IAIjC,OAAO,CAAC,gBAAgB;IAmBxB,OAAO,CAAC,6BAA6B;YAkBvB,kBAAkB;IA2DhC,WAAW,IAAI,IAAI,CAGlB;IAED,SAAS,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAKpC;IAED,WAAW,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAIxC;IAED,0BAA0B,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI,CA4B3D;IAED,6BAA6B,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAgBtD;IAED;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAa5B;;;OAGG;IACH,OAAO,CAAC,cAAc;IAetB,OAAO,CAAC,4BAA4B;IAmBpC,OAAO,CAAC,6BAA6B;IAqBrC,OAAO,CAAC,sBAAsB;IAQ9B,OAAO,CAAC,kBAAkB;YAUZ,2BAA2B;IAUzC,OAAO,CAAC,sBAAsB;YAWhB,uBAAuB;YAkBvB,oBAAoB;IAkBlC,6DAA6D;IAC7D,OAAO,CAAC,0BAA0B;IAYlC;;;OAGG;IACH,OAAO,CAAC,YAAY;IAYpB,OAAO,CAAC,eAAe;IAgBvB,OAAO,CAAC,oBAAoB;YA+Ld,kBAAkB;YAsBlB,sCAAsC;YAwCtC,mBAAmB;YAKnB,kBAAkB;YAclB,4BAA4B;YAM5B,uCAAuC;IAgCrD,OAAO,CAAC,iBAAiB;YA+BX,kBAAkB;IA6EhC,OAAO,CAAC,uBAAuB;YAuCjB,kBAAkB;YAsBlB,0BAA0B;YAsB1B,mBAAmB;YA8CnB,mBAAmB;IAgBjC,OAAO,CAAC,gBAAgB;IA2CxB,OAAO,CAAC,mBAAmB;YAwCb,mBAAmB;IAyCjC,OAAO,CAAC,uBAAuB;IA0B/B,OAAO,CAAC,wBAAwB;IAmBhC,OAAO,CAAC,yBAAyB;IAqBjC,OAAO,CAAC,yBAAyB;YAwCnB,iBAAiB;YAiDjB,6CAA6C;IAkC3D,OAAO,CAAC,mCAAmC;YAmB7B,8BAA8B;IAmB5C,OAAO,CAAC,sBAAsB;YA4BhB,qBAAqB;IA2CnC,OAAO,CAAC,oBAAoB;YA4Bd,eAAe;YAoGf,eAAe;YA4Cf,oBAAoB;YAoDpB,mBAAmB;YAuFnB,mBAAmB;IAgBjC,OAAO,CAAC,sBAAsB;YA6BhB,mBAAmB;YAkDnB,kBAAkB;YA8FlB,iBAAiB;IAmB/B,OAAO,CAAC,kBAAkB;IAW1B,OAAO,CAAC,iBAAiB;IAoBzB,OAAO,CAAC,2BAA2B;IAMnC,OAAO,CAAC,wBAAwB;YAOlB,uBAAuB;YAgBvB,4BAA4B;IAqB1C,OAAO,CAAC,4BAA4B;IAWpC,OAAO,CAAC,wBAAwB;YAQlB,mBAAmB;YAgBnB,oBAAoB;IAgBlC,OAAO,CAAC,wBAAwB;IAehC,OAAO,CAAC,wBAAwB;YAQlB,sBAAsB;YA2CtB,mBAAmB;IAgDjC,OAAO,CAAC,wBAAwB;IAIhC,OAAO,CAAC,+BAA+B;YAYzB,uBAAuB;YA6BvB,kBAAkB;YAuClB,qBAAqB;YAoCrB,oBAAoB;IAmBlC,OAAO,CAAC,oBAAoB;IAqC5B,OAAO,CAAC,sBAAsB;IAqB9B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAIxB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,oBAAoB;YAqHd,kBAAkB;IAoBhC,OAAO,CAAC,kBAAkB;IAiC1B,OAAO,CAAC,0BAA0B;YAgBpB,iBAAiB;YAuEjB,oBAAoB;IAsBlC,IAAI,CAAC,oBAAoB,uBAAiD,GAAG,IAAI,CA6BhF;CACD","sourcesContent":["/**\n * Interactive mode for the coding agent.\n * Handles TUI rendering and user interaction, delegating business logic to AgentSession.\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type {\n\tAgentMessage,\n\tBashExecutionMessage,\n\tBranchSummaryMessage,\n\tCompactionSummaryMessage,\n\tCustomMessage,\n} from \"@greppleai/grip-agent-core\";\nimport {\n\ttype AssistantMessage,\n\tgetProviders,\n\ttype ImageContent,\n\ttype Model,\n\ttype OAuthAuthInfo,\n\ttype OAuthPrompt,\n\ttype OAuthProviderId,\n\ttype OAuthSelectPrompt,\n\ttype TextContent,\n\ttype ToolCall,\n\ttype ToolResultMessage,\n\ttype UserMessage,\n} from \"@greppleai/grip-ai\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tEditorComponent,\n\tKeybinding,\n\tKeyId,\n\tMarkdownTheme,\n\tOverlayOptions,\n\tSlashCommand,\n\tTerminal,\n\tTuiMainScreenRenderState,\n\tTuiMode,\n} from \"@greppleai/grip-tui\";\nimport {\n\tCombinedAutocompleteProvider,\n\ttype Component,\n\tContainer,\n\tfuzzyFilter,\n\tgetCapabilities,\n\thyperlink,\n\tisViewportTUI,\n\tLoader,\n\ttype LoaderIndicatorOptions,\n\tMarkdown,\n\tmatchesKey,\n\tProcessTerminal,\n\tScrollView,\n\tSpacer,\n\tsetKeybindings,\n\tText,\n\tTruncatedText,\n\ttype TUI,\n\tTuiAltScreen,\n\tTuiMainScreen,\n\tVStack,\n\tvisibleWidth,\n} from \"@greppleai/grip-tui\";\nimport { spawn, spawnSync } from \"child_process\";\nimport {\n\tAPP_NAME,\n\tAPP_TITLE,\n\tgetAgentDir,\n\tgetAuthPath,\n\tgetChangelogPath,\n\tgetDebugLogPath,\n\tgetDocsPath,\n\tgetShareViewerUrl,\n\tPACKAGE_NAME,\n\tVERSION,\n} from \"../../config.ts\";\nimport {\n\ttype AgentSession,\n\ttype AgentSessionEvent,\n\ttype ModelCycleDirection,\n\ttype NavigateTreeOptions,\n\ttype PromptOptions,\n\tparseSkillBlock,\n\ttype QueuedMessages,\n} from \"../../core/agent-session.ts\";\nimport { executeBashWithOperations } from \"../../core/bash-executor.ts\";\nimport type { ExtensionRunner } from \"../../core/extensions/runner.ts\";\nimport type {\n\tAutocompleteProviderFactory,\n\tEditorFactory,\n\tExtensionContext,\n\tExtensionCustomOptions,\n\tExtensionSwitchSessionOptions,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tMarkdownTransformer,\n\tStreamingBehavior,\n\tTerminalInputHandler,\n} from \"../../core/extensions/types.ts\";\nimport { FooterDataProvider, type ReadonlyFooterDataProvider } from \"../../core/footer-data-provider.ts\";\nimport {\n\ttype GripAgentDiagnostic,\n\ttype GripAgentRuntimeHost,\n\tSessionImportFileNotFoundError,\n} from \"../../core/grip-agent.ts\";\nimport {\n\tHOOK_EXECUTION_CUSTOM_TYPE,\n\ttype HookExecutionNotice,\n\tparseHookExecutionNotice,\n} from \"../../core/hooks/types.ts\";\nimport { type AppKeybinding, KeybindingsManager } from \"../../core/keybindings.ts\";\nimport { createCompactionSummaryMessage } from \"../../core/messages.ts\";\nimport { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope } from \"../../core/model-resolver.ts\";\nimport { DefaultPackageManager } from \"../../core/package-manager.ts\";\nimport { BUILT_IN_PROVIDER_DISPLAY_NAMES } from \"../../core/provider-display-names.ts\";\nimport type {\n\tLoadPromptTemplatesResult,\n\tLoadThemesResult,\n\tResourceCollision,\n\tResourceDiagnostic,\n} from \"../../core/resource-loader.ts\";\nimport type { LoadRulesResult } from \"../../core/rules.ts\";\nimport {\n\tformatSandboxList,\n\tformatSandboxStartResult,\n\tformatSandboxStopResult,\n\tparseSandboxUserCommand,\n\ttype SandboxStartUserCommand,\n\ttype SandboxUserCommand,\n} from \"../../core/sandbox/command.ts\";\nimport {\n\tredactSecrets,\n\ttype SandboxService,\n\ttype SandboxStartResult,\n\ttype SandboxStopResult,\n} from \"../../core/sandbox/config.ts\";\nimport { LimaSandboxService, type ManagedLimaInstance } from \"../../core/sandbox/lima.ts\";\nimport { LocalSessionManager } from \"../../core/session/local-session-manager.ts\";\nimport type { Session } from \"../../core/session/session.ts\";\nimport type { SessionContext } from \"../../core/session/types.ts\";\nimport { formatMissingSessionCwdPrompt, MissingSessionCwdError } from \"../../core/session-cwd.ts\";\nimport { type FullscreenExitOutput, isValidModelProfileName } from \"../../core/settings-manager.ts\";\nimport type { LoadSkillsResult } from \"../../core/skills.ts\";\nimport { BUILTIN_SLASH_COMMANDS, HIDDEN_BUILTIN_SLASH_COMMAND_NAMES } from \"../../core/slash-commands.ts\";\nimport { getSourceBackendIcon, type SourceInfo } from \"../../core/source-info.ts\";\nimport { isInstallTelemetryEnabled } from \"../../core/telemetry.ts\";\nimport type { ToolBackendInfo } from \"../../core/tools/operations.ts\";\nimport type { TruncationResult } from \"../../core/tools/truncate.ts\";\nimport { getNewEntries, parseChangelog } from \"../../utils/changelog.ts\";\nimport { copyToClipboard, readClipboardText } from \"../../utils/clipboard.ts\";\nimport { extensionForImageMimeType, readClipboardImage } from \"../../utils/clipboard-image.ts\";\nimport { getDirectoryCompletions, resolveDirectoryPath } from \"../../utils/directory-completions.ts\";\nimport { parseGitUrl } from \"../../utils/git.ts\";\nimport { getGripUserAgent } from \"../../utils/grip-user-agent.ts\";\nimport { openBrowser } from \"../../utils/open-browser.ts\";\nimport { getCwdRelativePath } from \"../../utils/paths.ts\";\nimport { killTrackedDetachedChildren } from \"../../utils/shell.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport { checkForNewGripVersion, type LatestGripRelease } from \"../../utils/version-check.ts\";\nimport { AssistantMessageComponent } from \"./components/assistant-message.ts\";\nimport { BashExecutionComponent } from \"./components/bash-execution.ts\";\nimport { BorderedLoader } from \"./components/bordered-loader.ts\";\nimport { BranchSummaryMessageComponent } from \"./components/branch-summary-message.ts\";\nimport { CompactionSummaryMessageComponent } from \"./components/compaction-summary-message.ts\";\nimport { CountdownTimer } from \"./components/countdown-timer.ts\";\nimport { CustomEditor } from \"./components/custom-editor.ts\";\nimport { CustomMessageComponent } from \"./components/custom-message.ts\";\nimport { DynamicBorder } from \"./components/dynamic-border.ts\";\nimport { ExtensionEditorComponent } from \"./components/extension-editor.ts\";\nimport { ExtensionInputComponent } from \"./components/extension-input.ts\";\nimport { ExtensionSelectorComponent } from \"./components/extension-selector.ts\";\nimport { FooterComponent } from \"./components/footer.ts\";\nimport { HookExecutionComponent } from \"./components/hook-execution.ts\";\nimport { formatKeyText, keyDisplayText, keyHint, keyText, rawKeyHint } from \"./components/keybinding-hints.ts\";\nimport { LoginDialogComponent } from \"./components/login-dialog.ts\";\nimport { createMermaidMarkdownTransformer } from \"./components/mermaid.ts\";\nimport { ModelSelectorComponent } from \"./components/model-selector.ts\";\nimport { type AuthSelectorProvider, OAuthSelectorComponent } from \"./components/oauth-selector.ts\";\nimport { ScopedModelsSelectorComponent } from \"./components/scoped-models-selector.ts\";\nimport { SessionSelectorComponent } from \"./components/session-selector.ts\";\nimport { SettingsSelectorComponent } from \"./components/settings-selector.ts\";\nimport { SkillInvocationMessageComponent } from \"./components/skill-invocation-message.ts\";\nimport { ToolExecutionComponent } from \"./components/tool-execution.ts\";\nimport { TreeSelectorComponent } from \"./components/tree-selector.ts\";\nimport { UserMessageComponent } from \"./components/user-message.ts\";\nimport { UserMessageSelectorComponent } from \"./components/user-message-selector.ts\";\nimport {\n\tgetAvailableThemes,\n\tgetAvailableThemesWithPaths,\n\tgetEditorTheme,\n\tgetMarkdownTheme,\n\tgetThemeByName,\n\tinitTheme,\n\tonThemeChange,\n\tsetRegisteredThemes,\n\tsetTheme,\n\tsetThemeInstance,\n\tstopThemeWatcher,\n\tTheme,\n\ttype ThemeColor,\n\ttheme,\n} from \"./theme/theme.ts\";\n\n/** Interface for components that can be expanded/collapsed */\ninterface Expandable {\n\tsetExpanded(expanded: boolean): void;\n}\n\nfunction isExpandable(obj: unknown): obj is Expandable {\n\treturn typeof obj === \"object\" && obj !== null && \"setExpanded\" in obj && typeof obj.setExpanded === \"function\";\n}\n\nclass ExpandableText extends Text implements Expandable {\n\tprivate readonly getCollapsedText: () => string;\n\tprivate readonly getExpandedText: () => string;\n\n\tconstructor(\n\t\tgetCollapsedText: () => string,\n\t\tgetExpandedText: () => string,\n\t\texpanded = false,\n\t\tpaddingX = 0,\n\t\tpaddingY = 0,\n\t) {\n\t\tsuper(expanded ? getExpandedText() : getCollapsedText(), paddingX, paddingY);\n\t\tthis.getCollapsedText = getCollapsedText;\n\t\tthis.getExpandedText = getExpandedText;\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.setText(expanded ? this.getExpandedText() : this.getCollapsedText());\n\t}\n}\n\ntype ExtensionNotificationType = \"info\" | \"warning\" | \"error\";\ntype CompactionDisplayReason = \"manual\" | \"threshold\" | \"overflow\";\ntype ProviderAuthenticationType = \"oauth\" | \"api_key\";\ntype AuthenticationOperation = \"login\" | \"logout\";\ntype SessionPathCommand = \"/cd\" | \"/export\" | \"/import\";\n\ninterface ProviderAuthenticationModelSelection {\n\tselectedModel?: Model<any>;\n\tselectionError?: string;\n}\n\ntype CompactionQueuedMessage = {\n\ttext: string;\n\tmode: StreamingBehavior;\n};\n\ninterface SessionSandboxState {\n\ttype: \"daemon\";\n\turl: string;\n\ttoken: string;\n\texpectedCwd: string;\n\tcontainerId?: string;\n}\n\nfunction getSessionSandboxKey(session: Session): string {\n\treturn `${session.getCwd()}\\0${session.getSessionId()}`;\n}\n\nconst DEAD_TERMINAL_ERROR_CODES = new Set([\"EIO\", \"EPIPE\", \"ENOTCONN\"]);\n\nfunction isDeadTerminalError(error: unknown): boolean {\n\tif (!error || typeof error !== \"object\" || !(\"code\" in error)) {\n\t\treturn false;\n\t}\n\tconst code = (error as NodeJS.ErrnoException).code;\n\treturn code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code);\n}\n\nconst ANTHROPIC_SUBSCRIPTION_AUTH_WARNING =\n\t\"Anthropic subscription auth is active. Third-party harness usage draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage.\";\n\nfunction isAnthropicSubscriptionAuthKey(apiKey: string | undefined): boolean {\n\treturn typeof apiKey === \"string\" && apiKey.startsWith(\"sk-ant-oat\");\n}\n\nfunction isUnknownModel(model: Model<any> | undefined): boolean {\n\treturn !!model && model.provider === \"unknown\" && model.id === \"unknown\" && model.api === \"unknown\";\n}\n\nfunction hasDefaultModelProvider(providerId: string): providerId is keyof typeof defaultModelPerProvider {\n\treturn providerId in defaultModelPerProvider;\n}\n\nconst MAX_TUI_HOOK_EXECUTION_NOTICES = 200;\ntype ToolHookEvent = \"PreToolUse\" | \"PostToolUse\" | \"PostToolUseFailure\";\n\nfunction isToolHookEvent(event: string): event is ToolHookEvent {\n\treturn event === \"PreToolUse\" || event === \"PostToolUse\" || event === \"PostToolUseFailure\";\n}\nconst BEDROCK_PROVIDER_ID = \"amazon-bedrock\";\n\nconst BUILT_IN_MODEL_PROVIDERS = new Set<string>(getProviders());\n\nexport function isApiKeyLoginProvider(\n\tproviderId: string,\n\toauthProviderIds: ReadonlySet<string>,\n\tbuiltInProviderIds: ReadonlySet<string> = BUILT_IN_MODEL_PROVIDERS,\n): boolean {\n\tif (BUILT_IN_PROVIDER_DISPLAY_NAMES[providerId]) {\n\t\treturn true;\n\t}\n\tif (builtInProviderIds.has(providerId)) {\n\t\treturn false;\n\t}\n\treturn !oauthProviderIds.has(providerId);\n}\n\n/**\n * Options for InteractiveMode initialization.\n */\nexport interface InteractiveModeOptions {\n\t/** Providers that were migrated to auth.json (shows warning) */\n\tmigratedProviders?: string[];\n\t/** Warning message if session model couldn't be restored */\n\tmodelFallbackMessage?: string;\n\t/** Initial message to send on startup (can include @file content) */\n\tinitialMessage?: string;\n\t/** Images to attach to the initial message */\n\tinitialImages?: ImageContent[];\n\t/** Additional messages to send after the initial message */\n\tinitialMessages?: string[];\n\t/** Force verbose startup (overrides quietStartup setting) */\n\tverbose?: boolean;\n\t/** Initial renderer choice. Defaults to the persisted mode and can be changed during the session. */\n\ttuiMode?: TuiMode;\n}\n\ninterface InteractiveTuiOptions {\n\ttuiMode?: TuiMode;\n\tshowHardwareCursor: boolean;\n\tlogDirectory: string;\n\tterminal?: Terminal;\n\tonRightClickPaste?: () => void;\n}\n\nexport type InteractiveTui = TuiMainScreen | TuiAltScreen;\n\ntype DisposableComponent = Component & { dispose?(): void };\n\ninterface ExtensionTerminalInputSubscription {\n\thandler: TerminalInputHandler;\n\tunsubscribe: () => void;\n}\n\ntype ExtensionWidgetFactory = (tui: TUI, theme: Theme) => DisposableComponent;\ntype ExtensionFooterFactory = (tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => DisposableComponent;\ntype ExtensionHeaderFactory = (tui: TUI, theme: Theme) => DisposableComponent;\ntype ExtensionCustomFactory<T> = (\n\ttui: TUI,\n\ttheme: Theme,\n\tkeybindings: KeybindingsManager,\n\tdone: (result: T) => void,\n) => DisposableComponent | Promise<DisposableComponent>;\n\ninterface ResourceDisplayItem {\n\tpath: string;\n\tsourceInfo?: SourceInfo;\n}\n\ninterface CompactResourcePath {\n\tpath: string;\n\tsegments: string[];\n}\n\ntype ResourceScope = \"user\" | \"project\" | \"path\";\ntype ResourceSourceColor = \"accent\" | \"muted\";\n\ninterface ResourceSourceDisplayInfo {\n\tlabel: string;\n\tscopeLabel?: string;\n\tcolor: ResourceSourceColor;\n}\n\nconst LOCAL_SOURCE_DISPLAY_INFO: Record<SourceInfo[\"scope\"], Omit<ResourceSourceDisplayInfo, \"color\">> = {\n\tuser: { label: \"user\" },\n\tproject: { label: \"project\" },\n\ttemporary: { label: \"path\", scopeLabel: \"temp\" },\n};\n\nconst CLI_SOURCE_SCOPE_LABELS: Partial<Record<SourceInfo[\"scope\"], string>> = { temporary: \"temp\" };\nconst ACCENT_SOURCE_SCOPE_LABELS: Record<SourceInfo[\"scope\"], string> = {\n\tuser: \"user\",\n\tproject: \"project\",\n\ttemporary: \"temp\",\n};\n\ninterface GroupedResourceDiagnostics {\n\tcollisions: Map<string, ResourceCollision[]>;\n\totherDiagnostics: ResourceDiagnostic[];\n}\n\nfunction groupResourceDiagnostics(diagnostics: readonly ResourceDiagnostic[]): GroupedResourceDiagnostics {\n\tconst collisions = new Map<string, ResourceCollision[]>();\n\tconst otherDiagnostics: ResourceDiagnostic[] = [];\n\tfor (const diagnostic of diagnostics) {\n\t\tif (diagnostic.type !== \"collision\" || !diagnostic.collision) {\n\t\t\totherDiagnostics.push(diagnostic);\n\t\t\tcontinue;\n\t\t}\n\t\tconst collision = diagnostic.collision;\n\t\tconst list = collisions.get(collision.name) ?? [];\n\t\tlist.push(collision);\n\t\tcollisions.set(collision.name, list);\n\t}\n\treturn { collisions, otherDiagnostics };\n}\n\nfunction indexResourceSourceInfos(items: ResourceDisplayItem[]): Map<string, SourceInfo> {\n\tconst sourceInfos = new Map<string, SourceInfo>();\n\tfor (const item of items) {\n\t\tif (item.sourceInfo) sourceInfos.set(item.path, item.sourceInfo);\n\t}\n\treturn sourceInfos;\n}\n\ninterface ResourceScopeGroup {\n\tscope: ResourceScope;\n\tpaths: ResourceDisplayItem[];\n\tpackages: Map<string, ResourceDisplayItem[]>;\n}\n\ninterface ResourceScopeFormatOptions {\n\tformatPath: (item: ResourceDisplayItem) => string;\n\tformatPackagePath: (item: ResourceDisplayItem, source: string) => string;\n}\n\ninterface ShowLoadedResourcesOptions {\n\textensions?: ResourceDisplayItem[];\n\tforce?: boolean;\n\tshowDiagnosticsWhenQuiet?: boolean;\n}\n\ninterface LoadedResourceSnapshot {\n\tskillsResult: LoadSkillsResult;\n\trulesResult: LoadRulesResult;\n\tpromptsResult: LoadPromptTemplatesResult;\n\tthemesResult: LoadThemesResult;\n\textensions: ResourceDisplayItem[];\n\tsourceInfos: Map<string, SourceInfo>;\n}\n\ninterface LoadedResourceSectionOptions {\n\tname: string;\n\tcollapsedBody: string;\n\texpandedBody?: string;\n\tcolor?: ThemeColor;\n}\n\ninterface NamedInstructionResource {\n\tname: string;\n\tfilePath: string;\n\tsourceInfo?: SourceInfo;\n}\n\ninterface CompactListOptions {\n\tsort?: boolean;\n}\n\nexport interface AddMessageToChatOptions {\n\tpopulateHistory?: boolean;\n}\ninterface EditorCommandAction {\n\trun: () => void | Promise<void>;\n}\n\nexport interface RenderSessionContextOptions {\n\tupdateFooter?: boolean;\n\tpopulateHistory?: boolean;\n}\n\nexport interface ShutdownOptions {\n\tfromSignal?: boolean;\n}\n\ninterface RestoreQueuedMessagesOptions {\n\tabort?: boolean;\n\tcurrentText?: string;\n}\n\ninterface FlushCompactionQueueOptions {\n\twillRetry?: boolean;\n}\n\nexport interface SelectorView {\n\tcomponent: Component;\n\tfocus: Component;\n}\n\nexport type SelectorFactory = (done: () => void) => SelectorView;\n\ninterface SessionResumeResult {\n\tcancelled: boolean;\n}\n\nexport interface CopyCommandOptions {\n\tflashConfirmation?: boolean;\n}\n\n/** Composition root for selecting the interactive terminal renderer. */\nexport function createInteractiveTui(options: InteractiveTuiOptions): InteractiveTui {\n\tconst terminal = options.terminal ?? new ProcessTerminal();\n\tif (options.tuiMode === \"fullscreen\") {\n\t\treturn new TuiAltScreen(terminal, options.showHardwareCursor, options.logDirectory, {\n\t\t\topenUrl: openBrowser,\n\t\t\tonRightClickPaste: options.onRightClickPaste,\n\t\t});\n\t}\n\treturn new TuiMainScreen(terminal, options.showHardwareCursor, options.logDirectory);\n}\n\n/** Stable reference for components while InteractiveMode replaces the active renderer. */\nexport function createInteractiveTuiReference(getTui: () => TUI): TUI {\n\treturn new Proxy({} as TUI, {\n\t\tget: (_target, property) => {\n\t\t\tconst tui = getTui();\n\t\t\tconst value = Reflect.get(tui, property, tui);\n\t\t\tif (typeof value !== \"function\") return value;\n\t\t\tlet methodTui = tui;\n\t\t\tlet method = value;\n\t\t\treturn (...args: unknown[]) => {\n\t\t\t\tconst currentTui = getTui();\n\t\t\t\tif (currentTui !== methodTui) {\n\t\t\t\t\tconst currentMethod = Reflect.get(currentTui, property, currentTui);\n\t\t\t\t\tif (typeof currentMethod !== \"function\") {\n\t\t\t\t\t\tthrow new TypeError(`TUI property ${String(property)} is not callable`);\n\t\t\t\t\t}\n\t\t\t\t\tmethodTui = currentTui;\n\t\t\t\t\tmethod = currentMethod;\n\t\t\t\t}\n\t\t\t\treturn Reflect.apply(method, methodTui, args);\n\t\t\t};\n\t\t},\n\t\tset: (_target, property, value) => {\n\t\t\tconst tui = getTui();\n\t\t\treturn Reflect.set(tui, property, value, tui);\n\t\t},\n\t\thas: (_target, property) => Reflect.has(getTui(), property),\n\t\tgetPrototypeOf: () => Reflect.getPrototypeOf(getTui()),\n\t});\n}\n\nexport class InteractiveMode {\n\tprivate runtimeHost: GripAgentRuntimeHost;\n\tprivate options: InteractiveModeOptions;\n\tprivate readonly onRightClickPaste = (): void => {\n\t\tvoid this.handleRightClickPaste();\n\t};\n\tprivate renderer: TuiMainScreen | TuiAltScreen;\n\tprivate ui: TUI;\n\tprivate mainScreenRenderState: TuiMainScreenRenderState | undefined;\n\tprivate loadedResourcesContainer: Container;\n\tprivate chatContainer: Container;\n\tprivate documentContainer: Container;\n\tprivate transcriptScrollView: ScrollView | undefined;\n\tprivate fullscreenLayoutRoot: Component | undefined;\n\tprivate pendingMessagesContainer: Container;\n\tprivate statusContainer: Container;\n\tprivate defaultEditor: CustomEditor;\n\tprivate editor: EditorComponent;\n\tprivate editorComponentFactory: EditorFactory | undefined;\n\tprivate autocompleteProvider: AutocompleteProvider | undefined;\n\tprivate autocompleteProviderWrappers: AutocompleteProviderFactory[] = [];\n\tprivate fdPath: string | undefined;\n\tprivate editorContainer: Container;\n\tprivate footer: FooterComponent;\n\tprivate footerContainer: Container;\n\tprivate footerDataProvider: FooterDataProvider;\n\t// Stored so the same manager can be injected into custom editors, selectors, and extension UI.\n\tprivate keybindings: KeybindingsManager;\n\tprivate version: string;\n\tprivate isInitialized = false;\n\tprivate transcriptRendered = false;\n\tprivate onInputCallback?: (text: string) => void;\n\tprivate pendingUserInputs: string[] = [];\n\tprivate loadingAnimation: Loader | undefined = undefined;\n\tprivate workingMessage: string | undefined = undefined;\n\tprivate compressionDetectionActive = false;\n\tprivate compressionDetectionOwnsLoader = false;\n\tprivate workingVisible = true;\n\tprivate workingIndicatorOptions: LoaderIndicatorOptions | undefined = undefined;\n\tprivate readonly defaultWorkingMessage = \"Working...\";\n\tprivate readonly defaultHiddenThinkingLabel = \"Thinking...\";\n\tprivate hiddenThinkingLabel = this.defaultHiddenThinkingLabel;\n\n\tprivate lastSigintTime = 0;\n\tprivate lastEscapeTime = 0;\n\tprivate changelogMarkdown: string | undefined = undefined;\n\tprivate startupNoticesShown = false;\n\tprivate anthropicSubscriptionWarningShown = false;\n\n\t// Status line tracking (for mutating immediately-sequential status updates)\n\tprivate lastStatusSpacer: Spacer | undefined = undefined;\n\tprivate lastStatusText: Text | undefined = undefined;\n\n\t// Streaming message tracking\n\tprivate streamingComponent: AssistantMessageComponent | undefined = undefined;\n\tprivate streamingMessage: AssistantMessage | undefined = undefined;\n\n\t// Tool execution tracking: toolCallId -> component\n\tprivate pendingTools = new Map<string, ToolExecutionComponent>();\n\n\t// Tool output expansion state\n\tprivate toolOutputExpanded = false;\n\tprivate activeSandboxContainerId: string | undefined;\n\tprivate activeSandboxBackendConnected = false;\n\tprivate readonly sessionSandboxStates = new Map<string, SessionSandboxState>();\n\tprivate readonly managedLimaInstances = new Map<string, ManagedLimaInstance>();\n\n\t// Thinking block visibility state\n\tprivate hideThinkingBlock = false;\n\tprivate outputPad = 1;\n\tprivate readonly mermaidMarkdownTransformer: MarkdownTransformer;\n\t// Skill commands: command name -> skill file path\n\tprivate skillCommands = new Map<string, string>();\n\n\t// Agent subscription unsubscribe function\n\tprivate unsubscribe?: () => void;\n\tprivate hookExecutionUnsubscribe?: () => void;\n\tprivate hookExecutionActivityUnsubscribe?: () => void;\n\tprivate hookExecutionActivityDepth = 0;\n\tprivate hookExecutionActivityOwnsLoader = false;\n\tprivate hookExecutionSession?: Session;\n\tprivate hookExecutionNotices: HookExecutionNotice[][] = [];\n\tprivate hookExecutionComponents: HookExecutionComponent[] = [];\n\tprivate activeToolHookExecutionGroups = new Map<ToolHookEvent, HookExecutionNotice[]>();\n\tprivate hookExecutionTurnActive = false;\n\tprivate signalCleanupHandlers: Array<() => void> = [];\n\n\t// Track if editor is in bash mode (text starts with !)\n\tprivate isBashMode = false;\n\n\t// Track current bash execution component\n\tprivate bashComponent: BashExecutionComponent | undefined = undefined;\n\n\t// Track pending bash components (shown in pending area, moved to chat on submit)\n\tprivate pendingBashComponents: BashExecutionComponent[] = [];\n\n\t// Auto-compaction state\n\tprivate autoCompactionLoader: Loader | undefined = undefined;\n\tprivate autoCompactionEscapeHandler?: () => void;\n\tprivate branchSummaryLoader: Loader | undefined;\n\tprivate summarizationRetryLoader: Loader | undefined;\n\tprivate summarizationRetryCountdown: CountdownTimer | undefined;\n\n\t// Auto-retry state\n\tprivate retryLoader: Loader | undefined = undefined;\n\tprivate retryCountdown: CountdownTimer | undefined = undefined;\n\tprivate retryEscapeHandler?: () => void;\n\n\t// Messages queued while compaction is running\n\tprivate compactionQueuedMessages: CompactionQueuedMessage[] = [];\n\n\t// Shutdown state\n\tprivate shutdownRequested = false;\n\n\t// Extension UI state\n\tprivate extensionSelector: ExtensionSelectorComponent | undefined = undefined;\n\tprivate extensionInput: ExtensionInputComponent | undefined = undefined;\n\tprivate extensionEditor: ExtensionEditorComponent | undefined = undefined;\n\tprivate extensionTerminalInputSubscriptions = new Set<ExtensionTerminalInputSubscription>();\n\t// Extension widgets (components rendered above/below the editor)\n\tprivate extensionWidgetsAbove = new Map<string, DisposableComponent>();\n\tprivate extensionWidgetsBelow = new Map<string, DisposableComponent>();\n\tprivate widgetContainerAbove!: Container;\n\tprivate widgetContainerBelow!: Container;\n\n\t// Custom footer from extension (undefined = use built-in footer)\n\tprivate customFooter: DisposableComponent | undefined = undefined;\n\n\t// Header container that holds the built-in or custom header\n\tprivate headerContainer: Container;\n\n\t// Built-in header (logo + keybinding hints + changelog)\n\tprivate builtInHeader: Component | undefined = undefined;\n\n\t// Custom header from extension (undefined = use built-in header)\n\tprivate customHeader: DisposableComponent | undefined = undefined;\n\n\t// Convenience accessors\n\tprivate get session(): AgentSession {\n\t\treturn this.runtimeHost.session;\n\t}\n\tprivate get agent() {\n\t\treturn this.session.agent;\n\t}\n\tprivate get activeSession() {\n\t\treturn this.session.session;\n\t}\n\tprivate get settingsManager() {\n\t\treturn this.session.settingsManager;\n\t}\n\n\tconstructor(runtimeHost: GripAgentRuntimeHost, options: InteractiveModeOptions = {}) {\n\t\tthis.runtimeHost = runtimeHost;\n\t\tconst tuiMode = options.tuiMode ?? this.settingsManager.getTuiMode();\n\t\tthis.options = { ...options, tuiMode };\n\t\tthis.mermaidMarkdownTransformer = createMermaidMarkdownTransformer({\n\t\t\tgetMode: () => this.settingsManager.getMermaidRenderingMode(),\n\t\t\ttheme,\n\t\t});\n\t\tthis.runtimeHost.setBeforeSessionInvalidate(() => {\n\t\t\tthis.resetExtensionUI();\n\t\t});\n\t\tthis.runtimeHost.setRebindSession(async () => {\n\t\t\tawait this.restoreCurrentSessionSandbox();\n\t\t\tawait this.rebindCurrentSession();\n\t\t});\n\t\tthis.version = VERSION;\n\t\tthis.renderer = createInteractiveTui({\n\t\t\ttuiMode,\n\t\t\tshowHardwareCursor: this.settingsManager.getShowHardwareCursor(),\n\t\t\tlogDirectory: getAgentDir(),\n\t\t\tonRightClickPaste: this.onRightClickPaste,\n\t\t});\n\t\tthis.ui = createInteractiveTuiReference(() => this.renderer);\n\t\tthis.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());\n\t\tthis.headerContainer = new Container();\n\t\tthis.loadedResourcesContainer = new Container();\n\t\tthis.chatContainer = new Container();\n\t\tthis.documentContainer = new Container();\n\t\tthis.documentContainer.addChild(this.headerContainer);\n\t\tthis.documentContainer.addChild(this.loadedResourcesContainer);\n\t\tthis.documentContainer.addChild(this.chatContainer);\n\t\tthis.pendingMessagesContainer = new Container();\n\t\tthis.statusContainer = new Container();\n\t\tthis.widgetContainerAbove = new Container();\n\t\tthis.widgetContainerBelow = new Container();\n\t\tthis.keybindings = KeybindingsManager.create();\n\t\tsetKeybindings(this.keybindings);\n\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\tthis.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, {\n\t\t\tpaddingX: editorPaddingX,\n\t\t\tautocompleteMaxVisible,\n\t\t});\n\t\tthis.editor = this.defaultEditor;\n\t\tthis.editorContainer = new Container();\n\t\tthis.editorContainer.addChild(this.editor as Component);\n\t\tthis.footerDataProvider = new FooterDataProvider(this.activeSession.getCwd());\n\t\tthis.footer = new FooterComponent(this.session, this.footerDataProvider);\n\t\tthis.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);\n\t\tthis.footerContainer = new Container();\n\t\tthis.footerContainer.addChild(this.footer);\n\n\t\t// Load hide thinking block setting\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\n\t\t// Register themes from resource loader and initialize\n\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\tinitTheme(this.settingsManager.getTheme(), true);\n\t}\n\n\tprivate getAutocompleteSourceTag(sourceInfo?: SourceInfo): string | undefined {\n\t\tif (!sourceInfo) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst scopePrefix = sourceInfo.scope === \"user\" ? \"u\" : sourceInfo.scope === \"project\" ? \"p\" : \"t\";\n\t\tconst source = sourceInfo.source.trim();\n\n\t\tif (source === \"auto\" || source === \"local\" || source === \"cli\") {\n\t\t\treturn scopePrefix;\n\t\t}\n\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\treturn `${scopePrefix}:${source}`;\n\t\t}\n\n\t\tconst gitSource = parseGitUrl(source);\n\t\tif (gitSource) {\n\t\t\tconst ref = gitSource.ref ? `@${gitSource.ref}` : \"\";\n\t\t\treturn `${scopePrefix}:git:${gitSource.host}/${gitSource.path}${ref}`;\n\t\t}\n\n\t\treturn scopePrefix;\n\t}\n\n\tprivate prefixAutocompleteDescription(description: string | undefined, sourceInfo?: SourceInfo): string | undefined {\n\t\tconst sourceTag = this.getAutocompleteSourceTag(sourceInfo);\n\t\tif (!sourceTag) {\n\t\t\treturn description;\n\t\t}\n\t\tconst backendIcon = getSourceBackendIcon(sourceInfo);\n\t\treturn description ? `[${backendIcon} ${sourceTag}] ${description}` : `[${backendIcon} ${sourceTag}]`;\n\t}\n\n\tprivate getBuiltInCommandConflictDiagnostics(extensionRunner: ExtensionRunner): ResourceDiagnostic[] {\n\t\tconst builtinNames = new Set([\n\t\t\t...BUILTIN_SLASH_COMMANDS.map((command) => command.name),\n\t\t\t...HIDDEN_BUILTIN_SLASH_COMMAND_NAMES,\n\t\t]);\n\t\treturn extensionRunner\n\t\t\t.getRegisteredCommands()\n\t\t\t.filter((command) => builtinNames.has(command.name))\n\t\t\t.map((command) => ({\n\t\t\t\ttype: \"warning\" as const,\n\t\t\t\tmessage:\n\t\t\t\t\tcommand.invocationName === command.name\n\t\t\t\t\t\t? `Extension command '/${command.name}' conflicts with built-in interactive command. Skipping in autocomplete.`\n\t\t\t\t\t\t: `Extension command '/${command.name}' conflicts with built-in interactive command. Available as '/${command.invocationName}'.`,\n\t\t\t\tpath: command.sourceInfo.path,\n\t\t\t}));\n\t}\n\n\tprivate createBaseAutocompleteProvider(): AutocompleteProvider {\n\t\t// Define commands for autocomplete\n\t\tconst slashCommands: SlashCommand[] = BUILTIN_SLASH_COMMANDS.map((command) => ({\n\t\t\tname: command.name,\n\t\t\tdescription: command.description,\n\t\t}));\n\n\t\tconst cdCommand = slashCommands.find((command) => command.name === \"cd\");\n\t\tif (cdCommand) {\n\t\t\tcdCommand.argumentHint = \"<directory>\";\n\t\t\tcdCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] =>\n\t\t\t\tthis.session.supportsDirectoryChange() ? getDirectoryCompletions(prefix, this.activeSession.getCwd()) : [];\n\t\t}\n\n\t\tconst modelCommand = slashCommands.find((command) => command.name === \"model\");\n\t\tif (modelCommand) {\n\t\t\tmodelCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] | null => {\n\t\t\t\t// Get available models (scoped or from registry)\n\t\t\t\tconst models =\n\t\t\t\t\tthis.session.scopedModels.length > 0\n\t\t\t\t\t\t? this.session.scopedModels.map((s) => s.model)\n\t\t\t\t\t\t: this.session.modelRegistry.getAvailable();\n\n\t\t\t\tif (models.length === 0) return null;\n\n\t\t\t\t// Create items with provider/id format\n\t\t\t\tconst items = models.map((m) => ({\n\t\t\t\t\tid: m.id,\n\t\t\t\t\tprovider: m.provider,\n\t\t\t\t\tlabel: `${m.provider}/${m.id}`,\n\t\t\t\t}));\n\n\t\t\t\t// Fuzzy filter by model ID + provider (allows \"opus anthropic\" to match)\n\t\t\t\tconst filtered = fuzzyFilter(items, prefix, (item) => `${item.id} ${item.provider}`);\n\n\t\t\t\tif (filtered.length === 0) return null;\n\n\t\t\t\treturn filtered.map((item) => ({\n\t\t\t\t\tvalue: item.label,\n\t\t\t\t\tlabel: item.id,\n\t\t\t\t\tdescription: item.provider,\n\t\t\t\t}));\n\t\t\t};\n\t\t}\n\n\t\tconst profileCommand = slashCommands.find((command) => command.name === \"profile\");\n\t\tif (profileCommand) {\n\t\t\tprofileCommand.argumentHint = \"use <name> | create <name>\";\n\t\t\tprofileCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] | null => {\n\t\t\t\tif (!prefix.includes(\" \")) {\n\t\t\t\t\treturn fuzzyFilter([\"create\", \"use\"], prefix, (action) => action).map((action) => ({\n\t\t\t\t\t\tvalue: `${action} `,\n\t\t\t\t\t\tlabel: action,\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t\tconst useMatch = prefix.match(/^use\\s+(.*)$/);\n\t\t\t\tif (!useMatch) return null;\n\t\t\t\tconst profileNames = Object.keys(this.settingsManager.getModelProfiles());\n\t\t\t\tconst matches = fuzzyFilter(profileNames, useMatch[1] ?? \"\", (name) => name);\n\t\t\t\treturn matches.map((name) => ({ value: `use ${name}`, label: name }));\n\t\t\t};\n\t\t}\n\n\t\t// Convert prompt templates to SlashCommand format for autocomplete\n\t\tconst templateCommands: SlashCommand[] = this.session.promptTemplates.map((cmd) => ({\n\t\t\tname: cmd.name,\n\t\t\tdescription: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),\n\t\t\t...(cmd.argumentHint && { argumentHint: cmd.argumentHint }),\n\t\t}));\n\n\t\tconst builtinCommandNames = new Set([\n\t\t\t...slashCommands.map((command) => command.name),\n\t\t\t...HIDDEN_BUILTIN_SLASH_COMMAND_NAMES,\n\t\t]);\n\t\tconst extensionCommands: SlashCommand[] = this.session.extensionRunner\n\t\t\t.getRegisteredCommands()\n\t\t\t.filter((cmd) => !builtinCommandNames.has(cmd.name))\n\t\t\t.map((cmd) => ({\n\t\t\t\tname: cmd.invocationName,\n\t\t\t\tdescription: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),\n\t\t\t\tgetArgumentCompletions: cmd.getArgumentCompletions,\n\t\t\t}));\n\n\t\t// Build skill/rule commands from loaded resources (if enabled)\n\t\tthis.skillCommands.clear();\n\t\tconst skillCommandList: SlashCommand[] = [];\n\t\tconst ruleCommandList: SlashCommand[] = [];\n\t\tif (this.settingsManager.getEnableSkillCommands()) {\n\t\t\tfor (const skill of this.session.resourceLoader.getSkills().skills) {\n\t\t\t\tconst commandName = `skill:${skill.name}`;\n\t\t\t\tthis.skillCommands.set(commandName, skill.filePath);\n\t\t\t\tskillCommandList.push({\n\t\t\t\t\tname: commandName,\n\t\t\t\t\tdescription: this.prefixAutocompleteDescription(skill.description, skill.sourceInfo),\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const rule of this.session.resourceLoader.getRules().rules) {\n\t\t\t\tconst commandName = `rule:${rule.name}`;\n\t\t\t\truleCommandList.push({\n\t\t\t\t\tname: commandName,\n\t\t\t\t\tdescription: this.prefixAutocompleteDescription(rule.description, rule.sourceInfo),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn new CombinedAutocompleteProvider(\n\t\t\t[...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList, ...ruleCommandList],\n\t\t\tthis.activeSession.getCwd(),\n\t\t\tthis.fdPath,\n\t\t);\n\t}\n\n\tprivate setupAutocompleteProvider(): void {\n\t\tlet provider = this.createBaseAutocompleteProvider();\n\t\tfor (const wrapProvider of this.autocompleteProviderWrappers) {\n\t\t\tprovider = wrapProvider(provider);\n\t\t}\n\n\t\tthis.autocompleteProvider = provider;\n\t\tthis.defaultEditor.setAutocompleteProvider(provider);\n\t\tif (this.editor !== this.defaultEditor) {\n\t\t\tthis.editor.setAutocompleteProvider?.(provider);\n\t\t}\n\t}\n\n\tprivate showStartupNoticesIfNeeded(): void {\n\t\tif (this.startupNoticesShown) {\n\t\t\treturn;\n\t\t}\n\t\tthis.startupNoticesShown = true;\n\n\t\tif (!this.changelogMarkdown) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.chatContainer.children.length > 0) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tif (this.settingsManager.getCollapseChangelog()) {\n\t\t\tconst versionMatch = this.changelogMarkdown.match(/##\\s+\\[?(\\d+\\.\\d+\\.\\d+)\\]?/);\n\t\t\tconst latestVersion = versionMatch ? versionMatch[1] : this.version;\n\t\t\tconst condensedText = `Updated to v${latestVersion}. Use ${theme.bold(\"/changelog\")} to view full changelog.`;\n\t\t\tthis.chatContainer.addChild(new Text(condensedText, 1, 0));\n\t\t} else {\n\t\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings()),\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t}\n\n\tprivate initializeBuiltInHeader(): void {\n\t\tif (this.options.verbose || !this.settingsManager.getQuietStartup()) {\n\t\t\tconst logo = theme.bold(theme.fg(\"accent\", APP_NAME)) + theme.fg(\"dim\", ` v${this.version}`);\n\t\t\tconst hint = (keybinding: AppKeybinding, description: string) => keyHint(keybinding, description);\n\t\t\tconst expandedInstructions = [\n\t\t\t\thint(\"app.interrupt\", \"to interrupt\"),\n\t\t\t\thint(\"app.clear\", \"to clear\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.clear\")} twice`, \"to exit\"),\n\t\t\t\thint(\"app.exit\", \"to exit (empty)\"),\n\t\t\t\thint(\"app.suspend\", \"to suspend\"),\n\t\t\t\tkeyHint(\"tui.editor.deleteToLineEnd\", \"to delete to end\"),\n\t\t\t\thint(\"app.thinking.cycle\", \"to cycle thinking level\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.model.cycleForward\")}/${keyText(\"app.model.cycleBackward\")}`, \"to cycle models\"),\n\t\t\t\thint(\"app.model.select\", \"to select model\"),\n\t\t\t\thint(\"app.tools.expand\", \"to expand tools\"),\n\t\t\t\thint(\"app.thinking.toggle\", \"to expand thinking\"),\n\t\t\t\thint(\"app.editor.external\", \"for external editor\"),\n\t\t\t\trawKeyHint(\"/\", \"for commands\"),\n\t\t\t\trawKeyHint(\"!\", \"to run bash\"),\n\t\t\t\trawKeyHint(\"!!\", \"to run bash (no context)\"),\n\t\t\t\thint(\"app.message.followUp\", \"to queue follow-up\"),\n\t\t\t\thint(\"app.message.dequeue\", \"to edit all queued messages\"),\n\t\t\t\thint(\"app.clipboard.pasteImage\", \"to paste image\"),\n\t\t\t\trawKeyHint(\"drop files\", \"to attach\"),\n\t\t\t].join(\"\\n\");\n\t\t\tconst compactInstructions = [\n\t\t\t\thint(\"app.interrupt\", \"interrupt\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.clear\")}/${keyText(\"app.exit\")}`, \"clear/exit\"),\n\t\t\t\trawKeyHint(\"/\", \"commands\"),\n\t\t\t\trawKeyHint(\"!\", \"bash\"),\n\t\t\t\thint(\"app.tools.expand\", \"more\"),\n\t\t\t].join(theme.fg(\"muted\", \" · \"));\n\t\t\tconst compactOnboarding = theme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t`Press ${keyText(\"app.tools.expand\")} to show full startup help and loaded resources.`,\n\t\t\t);\n\t\t\tconst onboarding = theme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t\"Grip can explain its own features and look up its docs. Ask it how to use or extend Grip.\",\n\t\t\t);\n\t\t\tthis.builtInHeader = new ExpandableText(\n\t\t\t\t() => `${logo}\\n${compactInstructions}\\n${compactOnboarding}\\n\\n${onboarding}`,\n\t\t\t\t() => `${logo}\\n${expandedInstructions}\\n\\n${onboarding}`,\n\t\t\t\tthis.getStartupExpansionState(),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t);\n\t\t\tthis.headerContainer.addChild(new Spacer(1));\n\t\t\tthis.headerContainer.addChild(this.builtInHeader);\n\t\t\tthis.headerContainer.addChild(new Spacer(1));\n\t\t} else {\n\t\t\tthis.builtInHeader = new Text(\"\", 0, 0);\n\t\t\tthis.headerContainer.addChild(this.builtInHeader);\n\t\t}\n\t}\n\n\tprivate mountInteractiveTui(tui: TuiMainScreen | TuiAltScreen, components: readonly Component[]): void {\n\t\tfor (const component of components) tui.addChild(component);\n\t\tif (isViewportTUI(tui)) {\n\t\t\tif (!this.fullscreenLayoutRoot) throw new Error(\"Fullscreen layout is not initialized\");\n\t\t\ttui.setLayoutRoot(this.fullscreenLayoutRoot);\n\t\t}\n\t}\n\n\tprivate mountRootComponents(): void {\n\t\t// Build one stable component tree. Main-screen mode renders the flat child list;\n\t\t// fullscreen mode constrains the same instances into a transcript and fixed dock.\n\t\tthis.renderWidgets();\n\t\tthis.transcriptScrollView = new ScrollView(this.documentContainer, {\n\t\t\tfollow: \"end\",\n\t\t\tprimary: true,\n\t\t\toverscroll: \"chain\",\n\t\t\tscrollbar: this.settingsManager.getFullscreenScrollbar(),\n\t\t\tscrollbarStyle: (text) => theme.bg(\"selectedBg\", text),\n\t\t});\n\t\tconst dock = new VStack([\n\t\t\t{ component: this.pendingMessagesContainer, shrink: 1, minSize: 0 },\n\t\t\t{ component: this.statusContainer, shrink: 1, minSize: 0 },\n\t\t\t{ component: this.widgetContainerAbove, shrink: 1, minSize: 0 },\n\t\t\t{ component: this.editorContainer, shrink: 1, minSize: 3 },\n\t\t\t{ component: this.widgetContainerBelow, shrink: 1, minSize: 0 },\n\t\t\t{ component: this.footerContainer, shrink: 1, minSize: 1 },\n\t\t]);\n\t\tthis.fullscreenLayoutRoot = new VStack([\n\t\t\t{ component: this.transcriptScrollView, basis: 0, grow: 1, shrink: 1, minSize: 1 },\n\t\t\t{ component: dock, basis: \"auto\", grow: 0, shrink: 1, minSize: 1 },\n\t\t]);\n\n\t\tthis.mountInteractiveTui(this.renderer, [\n\t\t\tthis.documentContainer,\n\t\t\tthis.pendingMessagesContainer,\n\t\t\tthis.statusContainer,\n\t\t\tthis.widgetContainerAbove,\n\t\t\tthis.editorContainer,\n\t\t\tthis.widgetContainerBelow,\n\t\t\tthis.footerContainer,\n\t\t]);\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate stopInteractiveTui(fullscreenExitOutput: FullscreenExitOutput): void {\n\t\tif (this.renderer.mode === \"fullscreen\" && fullscreenExitOutput === \"transcript\") {\n\t\t\twhile (this.renderer.hasOverlayEntries) this.renderer.hideOverlay();\n\t\t\tthis.switchTuiMode(\"regular\", false, false);\n\t\t\tthis.renderer.renderNow();\n\t\t}\n\t\tthis.ui.stop({ preserveScreen: this.renderer.mode === \"fullscreen\" });\n\t}\n\n\tprivate switchTuiMode(mode: TuiMode, restoreProgress = true, startRenderer = true): boolean {\n\t\tconst previousUi = this.renderer;\n\t\tif (mode === previousUi.mode) return true;\n\t\tif (previousUi.hasOverlayEntries) return false;\n\n\t\tconst components = [...previousUi.children];\n\t\tconst focus = previousUi.getFocusedComponent();\n\t\tconst terminal = previousUi.terminal;\n\t\tconst showHardwareCursor = previousUi.getShowHardwareCursor();\n\t\tconst clearOnShrink = previousUi.getClearOnShrink();\n\t\tconst onDebug = previousUi.onDebug;\n\t\tif (previousUi instanceof TuiMainScreen) this.mainScreenRenderState = previousUi.captureRenderState();\n\n\t\tpreviousUi.stop({ preserveScreen: true });\n\t\tpreviousUi.setFocus(null);\n\t\tpreviousUi.clear();\n\t\tif (isViewportTUI(previousUi)) previousUi.setLayoutRoot(undefined);\n\n\t\tconst nextUi = createInteractiveTui({\n\t\t\ttuiMode: mode,\n\t\t\tshowHardwareCursor,\n\t\t\tlogDirectory: getAgentDir(),\n\t\t\tterminal,\n\t\t\tonRightClickPaste: this.onRightClickPaste,\n\t\t});\n\t\tnextUi.setClearOnShrink(clearOnShrink);\n\t\tnextUi.onDebug = onDebug;\n\t\tif (nextUi instanceof TuiMainScreen && this.mainScreenRenderState) {\n\t\t\tnextUi.restoreRenderState(this.mainScreenRenderState);\n\t\t}\n\t\tthis.renderer = nextUi;\n\t\tthis.options.tuiMode = mode;\n\t\tthis.mountInteractiveTui(nextUi, components);\n\t\tnextUi.invalidate();\n\t\tnextUi.setFocus(focus);\n\t\tif (!startRenderer) return true;\n\t\tnextUi.start();\n\t\tthis.rebindExtensionTerminalInputListeners();\n\t\tif (\n\t\t\trestoreProgress &&\n\t\t\tthis.settingsManager.getShowTerminalProgress() &&\n\t\t\t(this.session.isStreaming || this.session.isCompacting)\n\t\t) {\n\t\t\tterminal.setProgress(true);\n\t\t}\n\t\treturn true;\n\t}\n\n\tasync init(): Promise<void> {\n\t\tif (this.isInitialized) return;\n\n\t\tthis.registerSignalHandlers();\n\n\t\t// Load changelog (only show new entries, skip for resumed sessions)\n\t\tthis.changelogMarkdown = this.getChangelogForDisplay();\n\n\t\t// Ensure fd and rg are available (downloads if missing, adds to PATH via getBinDir)\n\t\t// Both are needed: fd for autocomplete, rg for grep tool and bash commands\n\t\tconst [fdPath] = await Promise.all([ensureTool(\"fd\"), ensureTool(\"rg\")]);\n\t\tthis.fdPath = fdPath;\n\n\t\tif (this.session.scopedModels.length > 0 && (this.options.verbose || !this.settingsManager.getQuietStartup())) {\n\t\t\tconst modelList = this.session.scopedModels\n\t\t\t\t.map((sm) => {\n\t\t\t\t\tconst thinkingStr = sm.thinkingLevel ? `:${sm.thinkingLevel}` : \"\";\n\t\t\t\t\treturn `${sm.model.id}${thinkingStr}`;\n\t\t\t\t})\n\t\t\t\t.join(\", \");\n\t\t\tconst cycleKeys = this.keybindings.getKeys(\"app.model.cycleForward\");\n\t\t\tconst cycleHint =\n\t\t\t\tcycleKeys.length > 0\n\t\t\t\t\t? theme.fg(\"muted\", ` (${formatKeyText(cycleKeys.join(\"/\"), { capitalize: true })} to cycle)`)\n\t\t\t\t\t: \"\";\n\t\t\tconsole.log(theme.fg(\"dim\", `Model scope: ${modelList}${cycleHint}`));\n\t\t}\n\n\t\tthis.initializeBuiltInHeader();\n\n\t\t// Mount the existing flat document in the same order for both renderers.\n\t\tthis.mountRootComponents();\n\t\tthis.ui.setFocus(this.editor);\n\n\t\tthis.setupKeyHandlers();\n\t\tthis.setupEditorSubmitHandler();\n\n\t\t// Start the UI before initializing extensions so session_start handlers can use interactive dialogs\n\t\tthis.ui.start();\n\t\tthis.isInitialized = true;\n\n\t\t// Initialize extensions first so resources are shown before messages\n\t\tawait this.rebindCurrentSession();\n\n\t\t// Render initial messages AFTER showing loaded resources\n\t\tthis.renderInitialMessages();\n\t\tthis.showRuntimeDiagnostics();\n\n\t\t// Set up theme file watcher\n\t\tonThemeChange(() => {\n\t\t\tthis.ui.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Set up git branch watcher (uses provider instead of footer)\n\t\tthis.footerDataProvider.onBranchChange(() => {\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Initialize available provider count for footer display\n\t\tawait this.updateAvailableProviderCount();\n\t}\n\n\t/**\n\t * Update terminal title with session name and cwd.\n\t */\n\tprivate updateTerminalTitle(): void {\n\t\tconst cwdBasename = path.basename(this.activeSession.getCwd());\n\t\tconst sessionName = this.activeSession.getSessionName();\n\t\tif (sessionName) {\n\t\t\tthis.ui.terminal.setTitle(`${APP_TITLE} - ${sessionName} - ${cwdBasename}`);\n\t\t} else {\n\t\t\tthis.ui.terminal.setTitle(`${APP_TITLE} - ${cwdBasename}`);\n\t\t}\n\t}\n\n\t/**\n\t * Run the interactive mode. This is the main entry point.\n\t * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop.\n\t */\n\tasync run(): Promise<void> {\n\t\tawait this.init();\n\t\tthis.startBackgroundChecks();\n\t\tthis.showStartupWarnings();\n\t\tawait this.processInitialMessages();\n\t\tawait this.runInteractivePromptLoop();\n\t}\n\n\tprivate startBackgroundChecks(): void {\n\t\tvoid checkForNewGripVersion(this.version).then((newRelease) => {\n\t\t\tif (newRelease) this.showNewVersionNotification(newRelease);\n\t\t});\n\t\tvoid this.checkForPackageUpdates().then((updates) => {\n\t\t\tif (updates.length > 0) this.showPackageUpdateNotification(updates);\n\t\t});\n\t\tvoid this.checkTmuxKeyboardSetup().then((warning) => {\n\t\t\tif (warning) this.showWarning(warning);\n\t\t});\n\t}\n\n\tprivate showStartupWarnings(): void {\n\t\tconst { migratedProviders, modelFallbackMessage } = this.options;\n\t\tif (migratedProviders && migratedProviders.length > 0) {\n\t\t\tthis.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(\", \")}`);\n\t\t}\n\t\tconst modelsJsonError = this.session.modelRegistry.getError();\n\t\tif (modelsJsonError) this.showError(`models.json error: ${modelsJsonError}`);\n\t\tif (modelFallbackMessage) this.showWarning(modelFallbackMessage);\n\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth();\n\t}\n\n\tprivate async promptAndReportError(message: string, options?: PromptOptions): Promise<void> {\n\t\ttry {\n\t\t\tawait this.session.prompt(message, options);\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(error instanceof Error ? error.message : \"Unknown error occurred\");\n\t\t}\n\t}\n\n\tprivate async processInitialMessages(): Promise<void> {\n\t\tconst { initialMessage, initialImages, initialMessages } = this.options;\n\t\tif (initialMessage) await this.promptAndReportError(initialMessage, { images: initialImages });\n\t\tfor (const message of initialMessages ?? []) await this.promptAndReportError(message);\n\t}\n\n\tprivate async runInteractivePromptLoop(): Promise<never> {\n\t\twhile (true) {\n\t\t\tawait this.promptAndReportError(await this.getUserInput());\n\t\t}\n\t}\n\n\tprivate async checkForPackageUpdates(): Promise<string[]> {\n\t\tif (process.env.GRIP_OFFLINE) {\n\t\t\treturn [];\n\t\t}\n\n\t\ttry {\n\t\t\tconst packageManager = new DefaultPackageManager({\n\t\t\t\tcwd: this.activeSession.getCwd(),\n\t\t\t\tagentDir: getAgentDir(),\n\t\t\t\tsettingsManager: this.settingsManager,\n\t\t\t});\n\t\t\tconst updates = await packageManager.checkForAvailableUpdates();\n\t\t\treturn updates.map((update) => update.displayName);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\tprivate async checkTmuxKeyboardSetup(): Promise<string | undefined> {\n\t\tif (!process.env.TMUX) return undefined;\n\n\t\tconst runTmuxShow = (option: string): Promise<string | undefined> => {\n\t\t\treturn new Promise((resolve) => {\n\t\t\t\tconst proc = spawn(\"tmux\", [\"show\", \"-gv\", option], {\n\t\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\t});\n\t\t\t\tlet stdout = \"\";\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\tproc.kill();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t}, 2000);\n\n\t\t\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\t\t\tstdout += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.on(\"error\", () => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t});\n\t\t\t\tproc.on(\"close\", (code) => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(code === 0 ? stdout.trim() : undefined);\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\n\t\tconst [extendedKeys, extendedKeysFormat] = await Promise.all([\n\t\t\trunTmuxShow(\"extended-keys\"),\n\t\t\trunTmuxShow(\"extended-keys-format\"),\n\t\t]);\n\n\t\t// If we couldn't query tmux (timeout, sandbox, etc.), don't warn\n\t\tif (extendedKeys === undefined) return undefined;\n\n\t\tif (extendedKeys !== \"on\" && extendedKeys !== \"always\") {\n\t\t\treturn \"tmux extended-keys is off. Modified Enter keys may not work. Add `set -g extended-keys on` to ~/.tmux.conf and restart tmux.\";\n\t\t}\n\n\t\tif (extendedKeysFormat === \"xterm\") {\n\t\t\treturn \"tmux extended-keys-format is xterm. Grip works best with csi-u. Add `set -g extended-keys-format csi-u` to ~/.tmux.conf and restart tmux.\";\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Get changelog entries to display on startup.\n\t * Only shows new entries since last seen version, skips for resumed sessions.\n\t */\n\tprivate getChangelogForDisplay(): string | undefined {\n\t\t// Skip changelog for resumed/continued sessions (already have messages)\n\t\tif (this.session.state.messages.length > 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst lastVersion = this.settingsManager.getLastChangelogVersion();\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst entries = parseChangelog(changelogPath);\n\n\t\tif (!lastVersion) {\n\t\t\t// Fresh install - record the version, send telemetry, don't show changelog\n\t\t\tthis.settingsManager.setLastChangelogVersion(VERSION);\n\t\t\tthis.reportInstallTelemetry(VERSION);\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst newEntries = getNewEntries(entries, lastVersion);\n\t\tif (newEntries.length > 0) {\n\t\t\tthis.settingsManager.setLastChangelogVersion(VERSION);\n\t\t\tthis.reportInstallTelemetry(VERSION);\n\t\t\treturn newEntries.map((e) => e.content).join(\"\\n\\n\");\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate reportInstallTelemetry(version: string): void {\n\t\tif (process.env.GRIP_OFFLINE) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!isInstallTelemetryEnabled(this.settingsManager)) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(version)}`, {\n\t\t\theaders: {\n\t\t\t\t\"User-Agent\": getGripUserAgent(version),\n\t\t\t},\n\t\t\tsignal: AbortSignal.timeout(5000),\n\t\t})\n\t\t\t.then(() => undefined)\n\t\t\t.catch(() => undefined);\n\t}\n\n\tprivate getMarkdownThemeWithSettings(): MarkdownTheme {\n\t\treturn {\n\t\t\t...getMarkdownTheme(),\n\t\t\tcodeBlockIndent: this.settingsManager.getCodeBlockIndent(),\n\t\t};\n\t}\n\n\t// =========================================================================\n\t// Extension System\n\t// =========================================================================\n\n\tprivate formatDisplayPath(p: string): string {\n\t\tconst home = os.homedir();\n\t\tlet result = p;\n\n\t\t// Replace home directory with ~\n\t\tif (result.startsWith(home)) {\n\t\t\tresult = `~${result.slice(home.length)}`;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate formatExtensionDisplayPath(path: string): string {\n\t\tlet result = this.formatDisplayPath(path);\n\t\tresult = result.replace(/\\/index\\.ts$/, \"\").replace(/\\/index\\.js$/, \"\");\n\t\treturn result;\n\t}\n\n\tprivate formatContextPath(p: string): string {\n\t\tconst cwd = path.resolve(this.activeSession.getCwd());\n\t\tconst absolutePath = path.isAbsolute(p) ? path.resolve(p) : path.resolve(cwd, p);\n\t\tconst relativePath = getCwdRelativePath(absolutePath, cwd);\n\t\tif (relativePath !== undefined) {\n\t\t\treturn relativePath;\n\t\t}\n\n\t\treturn this.formatDisplayPath(absolutePath);\n\t}\n\n\tprivate getStartupExpansionState(): boolean {\n\t\treturn this.options.verbose || this.toolOutputExpanded;\n\t}\n\n\t/**\n\t * Get a short path relative to the package root for display.\n\t */\n\tprivate getShortPath(fullPath: string, sourceInfo?: SourceInfo): string {\n\t\tconst baseDir = sourceInfo?.baseDir;\n\t\tif (baseDir && this.isPackageSource(sourceInfo)) {\n\t\t\tconst relativePath = path.relative(path.resolve(baseDir), path.resolve(fullPath));\n\t\t\tif (\n\t\t\t\trelativePath &&\n\t\t\t\trelativePath !== \".\" &&\n\t\t\t\t!relativePath.startsWith(\"..\") &&\n\t\t\t\t!relativePath.startsWith(`..${path.sep}`) &&\n\t\t\t\t!path.isAbsolute(relativePath)\n\t\t\t) {\n\t\t\t\treturn relativePath.replace(/\\\\/g, \"/\");\n\t\t\t}\n\t\t}\n\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\tconst npmMatch = fullPath.match(/node_modules\\/(@?[^/]+(?:\\/[^/]+)?)\\/(.*)/);\n\t\tif (npmMatch && source.startsWith(\"npm:\")) {\n\t\t\treturn npmMatch[2];\n\t\t}\n\n\t\tconst gitMatch = fullPath.match(/git\\/[^/]+\\/[^/]+\\/(.*)/);\n\t\tif (gitMatch && source.startsWith(\"git:\")) {\n\t\t\treturn gitMatch[1];\n\t\t}\n\n\t\treturn this.formatDisplayPath(fullPath);\n\t}\n\n\tprivate getCompactPathLabel(resourcePath: string, sourceInfo?: SourceInfo): string {\n\t\tconst shortPath = this.getShortPath(resourcePath, sourceInfo);\n\t\tconst normalizedPath = shortPath.replace(/\\\\/g, \"/\");\n\t\tconst segments = normalizedPath.split(\"/\").filter((segment) => segment.length > 0 && segment !== \"~\");\n\t\tif (segments.length > 0) {\n\t\t\treturn segments[segments.length - 1]!;\n\t\t}\n\t\treturn shortPath;\n\t}\n\n\tprivate getCompactPackageSourceLabel(sourceInfo?: SourceInfo): string {\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\treturn source.slice(\"npm:\".length) || source;\n\t\t}\n\n\t\tconst gitSource = parseGitUrl(source);\n\t\tif (gitSource) {\n\t\t\treturn gitSource.path || source;\n\t\t}\n\n\t\treturn source;\n\t}\n\n\tprivate getCompactExtensionLabel(resourcePath: string, sourceInfo?: SourceInfo): string {\n\t\tif (!this.isPackageSource(sourceInfo)) {\n\t\t\treturn this.getCompactPathLabel(resourcePath, sourceInfo);\n\t\t}\n\n\t\tconst sourceLabel = this.getCompactPackageSourceLabel(sourceInfo);\n\t\tif (!sourceLabel) {\n\t\t\treturn this.getCompactPathLabel(resourcePath, sourceInfo);\n\t\t}\n\n\t\tconst shortPath = this.getShortPath(resourcePath, sourceInfo).replace(/\\\\/g, \"/\");\n\t\tconst packagePath = shortPath.startsWith(\"extensions/\") ? shortPath.slice(\"extensions/\".length) : shortPath;\n\t\tconst parsedPath = path.posix.parse(packagePath);\n\n\t\tif (parsedPath.name === \"index\") {\n\t\t\treturn !parsedPath.dir || parsedPath.dir === \".\" ? sourceLabel : `${sourceLabel}:${parsedPath.dir}`;\n\t\t}\n\n\t\treturn `${sourceLabel}:${packagePath}`;\n\t}\n\n\tprivate getCompactDisplayPathSegments(resourcePath: string): string[] {\n\t\treturn this.formatDisplayPath(resourcePath)\n\t\t\t.replace(/\\\\/g, \"/\")\n\t\t\t.split(\"/\")\n\t\t\t.filter((segment) => segment.length > 0 && segment !== \"~\");\n\t}\n\n\tprivate getCompactNonPackageExtensionLabel(allPaths: CompactResourcePath[]): Map<string, string> {\n\t\tconst suffixCounts = new Map<string, number>();\n\t\tfor (const item of allPaths) {\n\t\t\tfor (let segmentCount = 1; segmentCount <= item.segments.length; segmentCount += 1) {\n\t\t\t\tconst suffix = item.segments.slice(-segmentCount).join(\"/\");\n\t\t\t\tsuffixCounts.set(suffix, (suffixCounts.get(suffix) ?? 0) + 1);\n\t\t\t}\n\t\t}\n\n\t\tconst labels = new Map<string, string>();\n\t\tfor (const item of allPaths) {\n\t\t\tif (labels.has(item.path)) continue;\n\t\t\tlet label = item.segments.join(\"/\");\n\t\t\tfor (let segmentCount = 1; segmentCount <= item.segments.length; segmentCount += 1) {\n\t\t\t\tconst suffix = item.segments.slice(-segmentCount).join(\"/\");\n\t\t\t\tif (suffixCounts.get(suffix) !== 1) continue;\n\t\t\t\tlabel = suffix;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlabels.set(item.path, label || this.getCompactPathLabel(item.path));\n\t\t}\n\t\treturn labels;\n\t}\n\n\tprivate getCompactExtensionLabels(extensions: ResourceDisplayItem[]): string[] {\n\t\tconst nonPackageExtensions = extensions\n\t\t\t.map((extension) => {\n\t\t\t\tconst segments = this.getCompactDisplayPathSegments(extension.path);\n\t\t\t\tconst lastSegment = segments[segments.length - 1];\n\t\t\t\tif (segments.length > 1 && (lastSegment === \"index.ts\" || lastSegment === \"index.ts\")) {\n\t\t\t\t\tsegments.pop();\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tpath: extension.path,\n\t\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t\tsegments,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter((extension) => !this.isPackageSource(extension.sourceInfo));\n\n\t\tconst nonPackageLabels = this.getCompactNonPackageExtensionLabel(nonPackageExtensions);\n\t\treturn extensions.map((extension) => {\n\t\t\tif (this.isPackageSource(extension.sourceInfo)) {\n\t\t\t\treturn this.getCompactExtensionLabel(extension.path, extension.sourceInfo);\n\t\t\t}\n\n\t\t\treturn nonPackageLabels.get(extension.path) ?? this.getCompactPathLabel(extension.path, extension.sourceInfo);\n\t\t});\n\t}\n\n\tprivate getDisplaySourceInfo(sourceInfo?: SourceInfo): ResourceSourceDisplayInfo {\n\t\tconst source = sourceInfo?.source ?? \"local\";\n\t\tconst scope = sourceInfo?.scope ?? \"project\";\n\t\tif (source === \"local\") {\n\t\t\treturn { ...(LOCAL_SOURCE_DISPLAY_INFO[scope] ?? { label: \"path\" }), color: \"muted\" };\n\t\t}\n\t\tif (source === \"cli\") {\n\t\t\treturn { label: \"path\", scopeLabel: CLI_SOURCE_SCOPE_LABELS[scope], color: \"muted\" };\n\t\t}\n\t\treturn { label: source, scopeLabel: ACCENT_SOURCE_SCOPE_LABELS[scope], color: \"accent\" };\n\t}\n\n\tprivate getScopeGroup(sourceInfo?: SourceInfo): ResourceScope {\n\t\tconst source = sourceInfo?.source ?? \"local\";\n\t\tconst scope = sourceInfo?.scope ?? \"project\";\n\t\tif (source === \"cli\" || scope === \"temporary\") return \"path\";\n\t\tif (scope === \"user\") return \"user\";\n\t\tif (scope === \"project\") return \"project\";\n\t\treturn \"path\";\n\t}\n\n\tprivate isPackageSource(sourceInfo?: SourceInfo): boolean {\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\treturn source.startsWith(\"npm:\") || source.startsWith(\"git:\");\n\t}\n\n\tprivate buildScopeGroups(items: ResourceDisplayItem[]): ResourceScopeGroup[] {\n\t\tconst groups: Record<ResourceScope, ResourceScopeGroup> = {\n\t\t\tuser: { scope: \"user\", paths: [], packages: new Map() },\n\t\t\tproject: { scope: \"project\", paths: [], packages: new Map() },\n\t\t\tpath: { scope: \"path\", paths: [], packages: new Map() },\n\t\t};\n\n\t\tfor (const item of items) {\n\t\t\tconst groupKey = this.getScopeGroup(item.sourceInfo);\n\t\t\tconst group = groups[groupKey];\n\t\t\tconst source = item.sourceInfo?.source ?? \"local\";\n\n\t\t\tif (this.isPackageSource(item.sourceInfo)) {\n\t\t\t\tconst list = group.packages.get(source) ?? [];\n\t\t\t\tlist.push(item);\n\t\t\t\tgroup.packages.set(source, list);\n\t\t\t} else {\n\t\t\t\tgroup.paths.push(item);\n\t\t\t}\n\t\t}\n\n\t\treturn [groups.project, groups.user, groups.path].filter(\n\t\t\t(group) => group.paths.length > 0 || group.packages.size > 0,\n\t\t);\n\t}\n\n\tprivate formatScopeGroups(groups: ResourceScopeGroup[], options: ResourceScopeFormatOptions): string {\n\t\tconst lines: string[] = [];\n\n\t\tfor (const group of groups) {\n\t\t\tlines.push(` ${theme.fg(\"accent\", group.scope)}`);\n\n\t\t\tconst sortedPaths = [...group.paths].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\tfor (const item of sortedPaths) {\n\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPath(item)}`));\n\t\t\t}\n\n\t\t\tconst sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b));\n\t\t\tfor (const [source, items] of sortedPackages) {\n\t\t\t\tlines.push(` ${theme.fg(\"mdLink\", source)}`);\n\t\t\t\tconst sortedPackagePaths = [...items].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\t\tfor (const item of sortedPackagePaths) {\n\t\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPackagePath(item, source)}`));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate findSourceInfoForPath(p: string, sourceInfos: Map<string, SourceInfo>): SourceInfo | undefined {\n\t\tconst exact = sourceInfos.get(p);\n\t\tif (exact) return exact;\n\n\t\tlet current = p;\n\t\twhile (current.includes(\"/\")) {\n\t\t\tcurrent = current.substring(0, current.lastIndexOf(\"/\"));\n\t\t\tconst parent = sourceInfos.get(current);\n\t\t\tif (parent) return parent;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate formatPathWithSource(p: string, sourceInfo?: SourceInfo): string {\n\t\tif (sourceInfo) {\n\t\t\tconst shortPath = this.getShortPath(p, sourceInfo);\n\t\t\tconst { label, scopeLabel } = this.getDisplaySourceInfo(sourceInfo);\n\t\t\tconst backendIcon = getSourceBackendIcon(sourceInfo);\n\t\t\tconst labelText = scopeLabel ? `${backendIcon} ${label} (${scopeLabel})` : `${backendIcon} ${label}`;\n\t\t\treturn `${labelText} ${shortPath}`;\n\t\t}\n\t\treturn this.formatDisplayPath(p);\n\t}\n\n\tprivate formatCollisionGroup(\n\t\tname: string,\n\t\tcollisions: ResourceCollision[],\n\t\tsourceInfos: Map<string, SourceInfo>,\n\t): string[] {\n\t\tconst winner = collisions[0];\n\t\tif (!winner) return [];\n\t\tconst lines = [\n\t\t\ttheme.fg(\"warning\", ` \"${name}\" collision:`),\n\t\t\ttheme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t` ${theme.fg(\"success\", \"✓\")} ${this.formatPathWithSource(winner.winnerPath, this.findSourceInfoForPath(winner.winnerPath, sourceInfos))}`,\n\t\t\t),\n\t\t];\n\t\tfor (const collision of collisions) {\n\t\t\tlines.push(\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"dim\",\n\t\t\t\t\t` ${theme.fg(\"warning\", \"✗\")} ${this.formatPathWithSource(collision.loserPath, this.findSourceInfoForPath(collision.loserPath, sourceInfos))} (skipped)`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn lines;\n\t}\n\n\tprivate formatResourceDiagnostic(diagnostic: ResourceDiagnostic, sourceInfos: Map<string, SourceInfo>): string[] {\n\t\tconst color = diagnostic.type === \"error\" ? \"error\" : \"warning\";\n\t\tif (!diagnostic.path) return [theme.fg(color, ` ${diagnostic.message}`)];\n\t\tconst formattedPath = this.formatPathWithSource(\n\t\t\tdiagnostic.path,\n\t\t\tthis.findSourceInfoForPath(diagnostic.path, sourceInfos),\n\t\t);\n\t\treturn [theme.fg(color, ` ${formattedPath}`), theme.fg(color, ` ${diagnostic.message}`)];\n\t}\n\n\tprivate formatDiagnostics(diagnostics: readonly ResourceDiagnostic[], sourceInfos: Map<string, SourceInfo>): string {\n\t\tconst { collisions, otherDiagnostics } = groupResourceDiagnostics(diagnostics);\n\t\tconst lines: string[] = [];\n\t\tfor (const [name, group] of collisions) {\n\t\t\tlines.push(...this.formatCollisionGroup(name, group, sourceInfos));\n\t\t}\n\t\tfor (const diagnostic of otherDiagnostics) {\n\t\t\tlines.push(...this.formatResourceDiagnostic(diagnostic, sourceInfos));\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate formatCompactResourceList(items: string[], options?: CompactListOptions): string {\n\t\tconst labels = items.map((item) => item.trim()).filter((item) => item.length > 0);\n\t\tif (options?.sort !== false) labels.sort((a, b) => a.localeCompare(b));\n\t\treturn theme.fg(\"dim\", ` ${labels.join(\", \")}`);\n\t}\n\n\tprivate addLoadedResourceSection(container: Container, options: LoadedResourceSectionOptions): void {\n\t\tconst color = options.color ?? \"mdHeading\";\n\t\tconst header = theme.fg(color, `[${options.name}]`);\n\t\tconst section = new ExpandableText(\n\t\t\t() => `${header}\\n${options.collapsedBody}`,\n\t\t\t() => `${header}\\n${options.expandedBody ?? options.collapsedBody}`,\n\t\t\tthis.getStartupExpansionState(),\n\t\t\t0,\n\t\t\t0,\n\t\t);\n\t\tcontainer.addChild(section);\n\t\tcontainer.addChild(new Spacer(1));\n\t}\n\n\tprivate getLoadedResourceSnapshot(options?: ShowLoadedResourcesOptions): LoadedResourceSnapshot {\n\t\tconst skillsResult = this.session.resourceLoader.getSkills();\n\t\tconst rulesResult = this.session.resourceLoader.getRules();\n\t\tconst promptsResult = this.session.resourceLoader.getPrompts();\n\t\tconst themesResult = this.session.resourceLoader.getThemes();\n\t\tconst extensions =\n\t\t\toptions?.extensions ??\n\t\t\tthis.session.resourceLoader.getExtensions().extensions.map((extension) => ({\n\t\t\t\tpath: extension.path,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t}));\n\t\tconst sourceInfos = indexResourceSourceInfos([\n\t\t\t...extensions,\n\t\t\t...skillsResult.skills.map((skill) => ({ path: skill.filePath, sourceInfo: skill.sourceInfo })),\n\t\t\t...rulesResult.rules.map((rule) => ({ path: rule.filePath, sourceInfo: rule.sourceInfo })),\n\t\t\t...promptsResult.prompts.map((prompt) => ({ path: prompt.filePath, sourceInfo: prompt.sourceInfo })),\n\t\t\t...themesResult.themes\n\t\t\t\t.filter((loadedTheme) => loadedTheme.sourcePath !== undefined)\n\t\t\t\t.map((loadedTheme) => ({ path: loadedTheme.sourcePath!, sourceInfo: loadedTheme.sourceInfo })),\n\t\t]);\n\t\treturn { skillsResult, rulesResult, promptsResult, themesResult, extensions, sourceInfos };\n\t}\n\n\tprivate renderContextFilesSection(container: Container): void {\n\t\tconst contextFiles = this.session.resourceLoader.getAgentsFiles().agentsFiles;\n\t\tif (contextFiles.length === 0) return;\n\t\tcontainer.addChild(new Spacer(1));\n\t\tconst backend = this.session.getToolBackendInfo?.();\n\t\tconst backendIcon = backend?.type === \"remote\" ? \"☁\" : \"🖥\";\n\t\tconst expandedBody = contextFiles\n\t\t\t.map((file) =>\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"dim\",\n\t\t\t\t\t` ${file.path.startsWith(getAgentDir()) ? \"🖥\" : backendIcon} ${this.formatDisplayPath(file.path)}`,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.join(\"\\n\");\n\t\tthis.addLoadedResourceSection(container, {\n\t\t\tname: \"Context\",\n\t\t\tcollapsedBody: this.formatCompactResourceList(\n\t\t\t\tcontextFiles.map((file) => this.formatContextPath(file.path)),\n\t\t\t\t{ sort: false },\n\t\t\t),\n\t\t\texpandedBody,\n\t\t});\n\t}\n\n\tprivate renderNamedInstructionSection(\n\t\tcontainer: Container,\n\t\tname: string,\n\t\tresources: NamedInstructionResource[],\n\t): void {\n\t\tif (resources.length === 0) return;\n\t\tconst groups = this.buildScopeGroups(\n\t\t\tresources.map((resource) => ({ path: resource.filePath, sourceInfo: resource.sourceInfo })),\n\t\t);\n\t\tconst expandedBody = this.formatScopeGroups(groups, {\n\t\t\tformatPath: (item) => `${getSourceBackendIcon(item.sourceInfo)} ${this.formatDisplayPath(item.path)}`,\n\t\t\tformatPackagePath: (item) =>\n\t\t\t\t`${getSourceBackendIcon(item.sourceInfo)} ${this.getShortPath(item.path, item.sourceInfo)}`,\n\t\t});\n\t\tthis.addLoadedResourceSection(container, {\n\t\t\tname,\n\t\t\tcollapsedBody: this.formatCompactResourceList(\n\t\t\t\tresources.map((resource) => `${getSourceBackendIcon(resource.sourceInfo)} ${resource.name}`),\n\t\t\t),\n\t\t\texpandedBody,\n\t\t});\n\t}\n\n\tprivate renderPromptTemplateSection(container: Container): void {\n\t\tconst templates = this.session.promptTemplates;\n\t\tif (templates.length === 0) return;\n\t\tconst groups = this.buildScopeGroups(\n\t\t\ttemplates.map((template) => ({ path: template.filePath, sourceInfo: template.sourceInfo })),\n\t\t);\n\t\tconst templateByPath = new Map(templates.map((template) => [template.filePath, template]));\n\t\tconst formatTemplate = (item: ResourceDisplayItem): string => {\n\t\t\tconst template = templateByPath.get(item.path);\n\t\t\treturn `${getSourceBackendIcon(item.sourceInfo)} ${template ? `/${template.name}` : this.formatDisplayPath(item.path)}`;\n\t\t};\n\t\tthis.addLoadedResourceSection(container, {\n\t\t\tname: \"Prompts\",\n\t\t\tcollapsedBody: this.formatCompactResourceList(\n\t\t\t\ttemplates.map((template) => `${getSourceBackendIcon(template.sourceInfo)} /${template.name}`),\n\t\t\t),\n\t\t\texpandedBody: this.formatScopeGroups(groups, {\n\t\t\t\tformatPath: formatTemplate,\n\t\t\t\tformatPackagePath: formatTemplate,\n\t\t\t}),\n\t\t});\n\t}\n\n\tprivate renderExtensionSection(container: Container, extensions: ResourceDisplayItem[]): void {\n\t\tif (extensions.length === 0) return;\n\t\tconst groups = this.buildScopeGroups(extensions);\n\t\tthis.addLoadedResourceSection(container, {\n\t\t\tname: \"Extensions\",\n\t\t\tcollapsedBody: this.formatCompactResourceList(this.getCompactExtensionLabels(extensions)),\n\t\t\texpandedBody: this.formatScopeGroups(groups, {\n\t\t\t\tformatPath: (item) => this.formatExtensionDisplayPath(item.path),\n\t\t\t\tformatPackagePath: (item) => this.formatExtensionDisplayPath(this.getShortPath(item.path, item.sourceInfo)),\n\t\t\t}),\n\t\t\tcolor: \"mdHeading\",\n\t\t});\n\t}\n\n\tprivate renderThemeSection(container: Container, themesResult: LoadThemesResult): void {\n\t\tconst customThemes = themesResult.themes.filter((loadedTheme) => loadedTheme.sourcePath);\n\t\tif (customThemes.length === 0) return;\n\t\tconst groups = this.buildScopeGroups(\n\t\t\tcustomThemes.map((loadedTheme) => ({\n\t\t\t\tpath: loadedTheme.sourcePath!,\n\t\t\t\tsourceInfo: loadedTheme.sourceInfo,\n\t\t\t})),\n\t\t);\n\t\tthis.addLoadedResourceSection(container, {\n\t\t\tname: \"Themes\",\n\t\t\tcollapsedBody: this.formatCompactResourceList(\n\t\t\t\tcustomThemes.map(\n\t\t\t\t\t(loadedTheme) =>\n\t\t\t\t\t\tloadedTheme.name ?? this.getCompactPathLabel(loadedTheme.sourcePath!, loadedTheme.sourceInfo),\n\t\t\t\t),\n\t\t\t),\n\t\t\texpandedBody: this.formatScopeGroups(groups, {\n\t\t\t\tformatPath: (item) => this.formatDisplayPath(item.path),\n\t\t\t\tformatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),\n\t\t\t}),\n\t\t});\n\t}\n\n\tprivate renderLoadedResourceListing(container: Container, snapshot: LoadedResourceSnapshot): void {\n\t\tthis.renderContextFilesSection(container);\n\t\tthis.renderNamedInstructionSection(container, \"Skills\", snapshot.skillsResult.skills);\n\t\tthis.renderNamedInstructionSection(container, \"Rules\", snapshot.rulesResult.rules);\n\t\tthis.renderPromptTemplateSection(container);\n\t\tthis.renderExtensionSection(container, snapshot.extensions);\n\t\tthis.renderThemeSection(container, snapshot.themesResult);\n\t}\n\n\tprivate addResourceDiagnosticSection(\n\t\tcontainer: Container,\n\t\ttitle: string,\n\t\tdiagnostics: readonly ResourceDiagnostic[],\n\t\tsourceInfos: Map<string, SourceInfo>,\n\t): void {\n\t\tif (diagnostics.length === 0) return;\n\t\tconst warningLines = this.formatDiagnostics(diagnostics, sourceInfos);\n\t\tcontainer.addChild(new Text(`${theme.fg(\"warning\", `[${title}]`)}\\n${warningLines}`, 0, 0));\n\t\tcontainer.addChild(new Spacer(1));\n\t}\n\n\tprivate getExtensionResourceDiagnostics(): ResourceDiagnostic[] {\n\t\tconst diagnostics: ResourceDiagnostic[] = this.session.resourceLoader\n\t\t\t.getExtensions()\n\t\t\t.errors.map((error) => ({ type: \"error\" as const, message: error.error, path: error.path }));\n\t\tconst extensionRunner = this.session.extensionRunner;\n\t\tdiagnostics.push(...extensionRunner.getCommandDiagnostics());\n\t\tdiagnostics.push(...this.getBuiltInCommandConflictDiagnostics(extensionRunner));\n\t\tdiagnostics.push(...extensionRunner.getShortcutDiagnostics());\n\t\treturn diagnostics;\n\t}\n\n\tprivate renderLoadedResourceDiagnostics(container: Container, snapshot: LoadedResourceSnapshot): void {\n\t\tconst sourceInfos = snapshot.sourceInfos;\n\t\tthis.addResourceDiagnosticSection(container, \"Skill conflicts\", snapshot.skillsResult.diagnostics, sourceInfos);\n\t\tthis.addResourceDiagnosticSection(container, \"Rule conflicts\", snapshot.rulesResult.diagnostics, sourceInfos);\n\t\tthis.addResourceDiagnosticSection(container, \"Prompt conflicts\", snapshot.promptsResult.diagnostics, sourceInfos);\n\t\tthis.addResourceDiagnosticSection(\n\t\t\tcontainer,\n\t\t\t\"Extension issues\",\n\t\t\tthis.getExtensionResourceDiagnostics(),\n\t\t\tsourceInfos,\n\t\t);\n\t\tthis.addResourceDiagnosticSection(container, \"Theme conflicts\", snapshot.themesResult.diagnostics, sourceInfos);\n\t}\n\n\tprivate showLoadedResources(options?: ShowLoadedResourcesOptions): void {\n\t\tconst container = this.loadedResourcesContainer ?? this.chatContainer;\n\t\tcontainer.clear();\n\t\tconst showListing = options?.force || this.options.verbose || !this.settingsManager.getQuietStartup();\n\t\tconst showDiagnostics = showListing || options?.showDiagnosticsWhenQuiet === true;\n\t\tif (!showListing && !showDiagnostics) return;\n\t\tconst snapshot = this.getLoadedResourceSnapshot(options);\n\t\tif (showListing) this.renderLoadedResourceListing(container, snapshot);\n\t\tif (showDiagnostics) this.renderLoadedResourceDiagnostics(container, snapshot);\n\t}\n\n\t/**\n\t * Initialize the extension system with TUI-based UI context.\n\t */\n\tprivate async bindCurrentSessionExtensions(): Promise<void> {\n\t\tconst uiContext = this.createExtensionUIContext();\n\t\tawait this.session.bindExtensions({\n\t\t\tuiContext,\n\t\t\tabortHandler: () => {\n\t\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\t},\n\t\t\tcommandContextActions: {\n\t\t\t\twaitForIdle: () => this.session.waitForIdle(),\n\t\t\t\tnewSession: async (options) => {\n\t\t\t\t\tif (this.loadingAnimation) {\n\t\t\t\t\t\tthis.loadingAnimation.stop();\n\t\t\t\t\t\tthis.loadingAnimation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tthis.statusContainer.clear();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.runtimeHost.newSession(options);\n\t\t\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\t\t\tthis.renderCurrentSessionState();\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\treturn this.handleFatalRuntimeError(\"Failed to create session\", error);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tfork: async (entryId, options) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.runtimeHost.fork(entryId, options);\n\t\t\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\t\t\tthis.renderCurrentSessionState();\n\t\t\t\t\t\t\tthis.editor.setText(result.selectedText ?? \"\");\n\t\t\t\t\t\t\tthis.showStatus(\"Forked to new session\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\treturn this.handleFatalRuntimeError(\"Failed to fork session\", error);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tnavigateTree: async (targetId, options) => {\n\t\t\t\t\tconst result = await this.session.navigateTree(targetId, {\n\t\t\t\t\t\tsummarize: options?.summarize,\n\t\t\t\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\t\t\t\treplaceInstructions: options?.replaceInstructions,\n\t\t\t\t\t\tlabel: options?.label,\n\t\t\t\t\t});\n\t\t\t\t\tif (result.cancelled) {\n\t\t\t\t\t\treturn { cancelled: true };\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\tthis.renderInitialMessages();\n\t\t\t\t\tif (result.editorText && !this.editor.getText().trim()) {\n\t\t\t\t\t\tthis.editor.setText(result.editorText);\n\t\t\t\t\t}\n\t\t\t\t\tthis.showStatus(\"Navigated to selected point\");\n\t\t\t\t\tvoid this.flushCompactionQueue({ willRetry: false });\n\t\t\t\t\treturn { cancelled: false };\n\t\t\t\t},\n\t\t\t\tswitchSession: async (sessionPath, options) => {\n\t\t\t\t\treturn this.handleResumeSession(sessionPath, options);\n\t\t\t\t},\n\t\t\t\treload: async () => {\n\t\t\t\t\tawait this.handleReloadCommand();\n\t\t\t\t},\n\t\t\t},\n\t\t\tshutdownHandler: () => {\n\t\t\t\tthis.shutdownRequested = true;\n\t\t\t\tif (this.session.isIdle) {\n\t\t\t\t\tvoid this.shutdown();\n\t\t\t\t}\n\t\t\t},\n\t\t\tonError: (error) => {\n\t\t\t\tthis.showExtensionError(error.extensionPath, error.error, error.stack);\n\t\t\t},\n\t\t});\n\n\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\tthis.setupAutocompleteProvider();\n\t\tthis.updateToolBackendStatus();\n\n\t\tconst extensionRunner = this.session.extensionRunner;\n\t\tthis.setupExtensionShortcuts(extensionRunner);\n\t\tthis.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });\n\t\tthis.showStartupNoticesIfNeeded();\n\t}\n\n\tprivate applyRuntimeSettings(): void {\n\t\tthis.transcriptScrollView?.setScrollbar(this.settingsManager.getFullscreenScrollbar());\n\t\tthis.footer.setSession(this.session);\n\t\tthis.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);\n\t\tthis.footerDataProvider.setCwd(this.activeSession.getCwd());\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\t\tthis.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());\n\t\tthis.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());\n\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\tthis.defaultEditor.setPaddingX(editorPaddingX);\n\t\tthis.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);\n\t\tif (this.editor !== this.defaultEditor) {\n\t\t\tthis.editor.setPaddingX?.(editorPaddingX);\n\t\t\tthis.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);\n\t\t}\n\t}\n\n\tprivate async rebindCurrentSession(): Promise<void> {\n\t\tthis.unsubscribe?.();\n\t\tthis.unsubscribe = undefined;\n\t\tthis.hookExecutionUnsubscribe?.();\n\t\tthis.hookExecutionUnsubscribe = undefined;\n\t\tthis.hookExecutionActivityUnsubscribe?.();\n\t\tthis.hookExecutionActivityUnsubscribe = undefined;\n\t\tthis.resetHookExecutionActivity();\n\t\tconst activeSession = this.activeSession;\n\t\tif (this.hookExecutionSession !== undefined && this.hookExecutionSession !== activeSession) {\n\t\t\tthis.hookExecutionNotices = [];\n\t\t\tthis.hookExecutionComponents = [];\n\t\t\tthis.resetHookExecutionGrouping();\n\t\t}\n\t\tthis.hookExecutionSession = activeSession;\n\t\tthis.applyRuntimeSettings();\n\t\tawait this.bindCurrentSessionExtensions();\n\t\tif (this.transcriptRendered) {\n\t\t\tthis.retireAndRenderCurrentTranscript();\n\t\t}\n\t\tthis.subscribeToAgent();\n\t\tawait this.updateAvailableProviderCount();\n\t\tthis.updateEditorBorderColor();\n\t\tthis.updateTerminalTitle();\n\t}\n\n\tprivate async handleFatalRuntimeError(prefix: string, error: unknown): Promise<never> {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis.showError(`${prefix}: ${message}`);\n\t\tstopThemeWatcher();\n\t\tthis.stop(\"transcript\");\n\t\tprocess.exit(1);\n\t}\n\n\tprivate retireAndRenderCurrentTranscript(): void {\n\t\tthis.transcriptScrollView?.scrollToEnd();\n\t\tthis.chatContainer.clear();\n\t\tthis.pendingMessagesContainer.clear();\n\t\tthis.compactionQueuedMessages = [];\n\t\tthis.streamingComponent = undefined;\n\t\tthis.streamingMessage = undefined;\n\t\tthis.pendingTools.clear();\n\t\tthis.renderInitialMessages();\n\t}\n\n\tprivate renderCurrentSessionState(): void {\n\t\t(this.loadedResourcesContainer ?? this.chatContainer).clear();\n\t\tthis.retireAndRenderCurrentTranscript();\n\t\tthis.showRuntimeDiagnostics();\n\t}\n\n\tprivate showRuntimeDiagnostics(diagnostics: readonly GripAgentDiagnostic[] = this.runtimeHost.diagnostics): void {\n\t\tfor (const diagnostic of diagnostics) {\n\t\t\tif (diagnostic.type === \"error\") this.showError(diagnostic.message);\n\t\t\telse if (diagnostic.type === \"warning\") this.showWarning(diagnostic.message);\n\t\t\telse this.showStatus(diagnostic.message);\n\t\t}\n\t}\n\n\tprivate getMarkdownTransformers(): MarkdownTransformer[] {\n\t\treturn [this.mermaidMarkdownTransformer, ...this.session.extensionRunner.getMarkdownTransformers()];\n\t}\n\n\t/**\n\t * Get a registered tool definition by name (for custom rendering).\n\t */\n\tprivate getRegisteredToolDefinition(toolName: string) {\n\t\treturn this.session.getToolDefinition(toolName);\n\t}\n\n\t/**\n\t * Set up keyboard shortcuts registered by extensions.\n\t */\n\tprivate setupExtensionShortcuts(extensionRunner: ExtensionRunner): void {\n\t\tconst shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());\n\t\tif (shortcuts.size === 0) return;\n\n\t\t// Create a context for shortcut handlers\n\t\tconst createContext = (): ExtensionContext => ({\n\t\t\tui: this.createExtensionUIContext(),\n\t\t\thasUI: true,\n\t\t\tcwd: this.activeSession.getCwd(),\n\t\t\ttoolOperations: this.session.getToolOperations(),\n\t\t\tgetToolBackendInfo: () => this.session.getToolBackendInfo(),\n\t\t\tgetLspStatus: () => this.session.getLspStatus(),\n\t\t\tconfigureLsp: (configuration) => this.session.configureLsp(configuration),\n\t\t\texecToolBackend: (command, options) => {\n\t\t\t\tconst operations = this.session.getToolOperations();\n\t\t\t\treturn executeBashWithOperations(command, options?.cwd ?? operations.cwd, operations, options);\n\t\t\t},\n\t\t\tsession: this.activeSession,\n\t\t\tmodelRegistry: this.session.modelRegistry,\n\t\t\tmodel: this.session.model,\n\t\t\tisIdle: () => this.session.isIdle,\n\t\t\tsignal: this.session.agent.signal,\n\t\t\tabort: () => {\n\t\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\t},\n\t\t\thasPendingMessages: () => this.session.pendingMessageCount > 0,\n\t\t\tshutdown: () => {\n\t\t\t\tthis.shutdownRequested = true;\n\t\t\t},\n\t\t\tgetContextUsage: () => this.session.getContextUsage(),\n\t\t\tcompact: (options) => {\n\t\t\t\tvoid (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.session.compact(options?.customInstructions);\n\t\t\t\t\t\toptions?.onComplete?.(result);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\t\toptions?.onError?.(err);\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t},\n\t\t\tgetSystemPrompt: () => this.session.systemPrompt,\n\t\t});\n\n\t\t// Set up the extension shortcut handler on the default editor\n\t\tthis.defaultEditor.onExtensionShortcut = (data: string) => {\n\t\t\tfor (const [shortcutStr, shortcut] of shortcuts) {\n\t\t\t\t// Cast to KeyId - extension shortcuts use the same format\n\t\t\t\tif (matchesKey(data, shortcutStr as KeyId)) {\n\t\t\t\t\t// Run handler async, don't block input\n\t\t\t\t\tPromise.resolve(shortcut.handler(createContext())).catch((err) => {\n\t\t\t\t\t\tthis.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t\t\t});\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t};\n\t}\n\n\t/**\n\t * Set extension status text in the footer.\n\t */\n\tprivate setExtensionStatus(key: string, text: string | undefined): void {\n\t\tthis.footerDataProvider.setExtensionStatus(key, text);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate formatToolBackendStatus(info: ToolBackendInfo): string {\n\t\tif (info.type === \"local\") {\n\t\t\treturn theme.fg(\"dim\", `tools: local ${info.cwd}`);\n\t\t}\n\t\treturn info.configured\n\t\t\t? theme.fg(\"accent\", `tools: remote ${info.url} ${info.cwd}`)\n\t\t\t: theme.fg(\"warning\", `tools: remote not configured ${info.cwd}`);\n\t}\n\n\tprivate updateToolBackendStatus(): void {\n\t\tthis.setExtensionStatus(\"toolBackend\", this.formatToolBackendStatus(this.session.getToolBackendInfo()));\n\t}\n\n\tprivate getWorkingLoaderMessage(): string {\n\t\tconst message = this.workingMessage ?? this.defaultWorkingMessage;\n\t\treturn this.compressionDetectionActive ? `${message} [Evaluating compression possibility]` : message;\n\t}\n\n\tprivate createWorkingLoader(): Loader {\n\t\treturn new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tthis.getWorkingLoaderMessage(),\n\t\t\tthis.workingIndicatorOptions,\n\t\t);\n\t}\n\n\tprivate stopWorkingLoader(): void {\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t}\n\t\tthis.compressionDetectionOwnsLoader = false;\n\t\tthis.statusContainer.clear();\n\t}\n\n\tprivate resetHookExecutionActivity(): void {\n\t\tif (this.hookExecutionActivityDepth === 0) return;\n\t\tthis.hookExecutionActivityDepth = 0;\n\t\tif (this.hookExecutionActivityOwnsLoader && !this.compressionDetectionActive) this.stopWorkingLoader();\n\t\telse this.loadingAnimation?.setMessage(this.getWorkingLoaderMessage());\n\t\tthis.hookExecutionActivityOwnsLoader = false;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleHookExecutionActivity(active: boolean): void {\n\t\tif (active) {\n\t\t\tthis.hookExecutionActivityDepth += 1;\n\t\t\tif (this.hookExecutionActivityDepth > 1) return;\n\t\t\tif (!this.loadingAnimation) {\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t\tthis.loadingAnimation = this.createWorkingLoader();\n\t\t\t\tthis.statusContainer.addChild(this.loadingAnimation);\n\t\t\t\tthis.hookExecutionActivityOwnsLoader = true;\n\t\t\t}\n\t\t\tthis.loadingAnimation.setMessage(\"Running hooks ...\");\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (this.hookExecutionActivityDepth === 0) return;\n\t\tthis.hookExecutionActivityDepth -= 1;\n\t\tif (this.hookExecutionActivityDepth > 0) return;\n\t\tif (this.hookExecutionActivityOwnsLoader && !this.session.isStreaming && !this.compressionDetectionActive)\n\t\t\tthis.stopWorkingLoader();\n\t\telse this.loadingAnimation?.setMessage(this.getWorkingLoaderMessage());\n\t\tthis.hookExecutionActivityOwnsLoader = false;\n\t\tthis.ui.requestRender();\n\t}\n\tprivate releaseCompressionDetectionLoader(): void {\n\t\tif (!this.compressionDetectionOwnsLoader) return;\n\t\tthis.compressionDetectionOwnsLoader = false;\n\t\tif (this.hookExecutionActivityDepth > 0) {\n\t\t\tthis.hookExecutionActivityOwnsLoader = true;\n\t\t\treturn;\n\t\t}\n\t\tif (this.session.isStreaming) return;\n\t\tif (this.loadingAnimation && !this.statusContainer.children.includes(this.loadingAnimation)) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t\treturn;\n\t\t}\n\t\tthis.stopWorkingLoader();\n\t}\n\n\tprivate handleCompressionDetectionActivity(active: boolean): void {\n\t\tthis.compressionDetectionActive = active;\n\t\tif (active && this.workingVisible && !this.loadingAnimation && this.statusContainer.children.length === 0) {\n\t\t\tthis.loadingAnimation = this.createWorkingLoader();\n\t\t\tthis.statusContainer.addChild(this.loadingAnimation);\n\t\t\tthis.compressionDetectionOwnsLoader = true;\n\t\t} else if (!active) {\n\t\t\tthis.releaseCompressionDetectionLoader();\n\t\t\tif (this.hookExecutionActivityDepth === 0) this.loadingAnimation?.setMessage(this.getWorkingLoaderMessage());\n\t\t} else if (this.hookExecutionActivityDepth === 0) {\n\t\t\tthis.loadingAnimation?.setMessage(this.getWorkingLoaderMessage());\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate setWorkingVisible(visible: boolean): void {\n\t\tthis.workingVisible = visible;\n\t\tif (!visible) {\n\t\t\tthis.stopWorkingLoader();\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\t(this.session.isStreaming || this.compressionDetectionActive) &&\n\t\t\t!this.loadingAnimation &&\n\t\t\tthis.statusContainer.children.length === 0\n\t\t) {\n\t\t\tthis.loadingAnimation = this.createWorkingLoader();\n\t\t\tif (this.compressionDetectionActive && !this.session.isStreaming) this.compressionDetectionOwnsLoader = true;\n\t\t\tthis.statusContainer.addChild(this.loadingAnimation);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate setWorkingIndicator(options?: LoaderIndicatorOptions): void {\n\t\tthis.workingIndicatorOptions = options;\n\t\tthis.loadingAnimation?.setIndicator(options);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate setHiddenThinkingLabel(label?: string): void {\n\t\tthis.hiddenThinkingLabel = label ?? this.defaultHiddenThinkingLabel;\n\t\tfor (const child of this.chatContainer.children) {\n\t\t\tif (child instanceof AssistantMessageComponent) {\n\t\t\t\tchild.setHiddenThinkingLabel(this.hiddenThinkingLabel);\n\t\t\t}\n\t\t}\n\t\tif (this.streamingComponent) {\n\t\t\tthis.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set an extension widget (string array or custom component).\n\t */\n\tprivate setExtensionWidget(\n\t\tkey: string,\n\t\tcontent: string[] | ExtensionWidgetFactory | undefined,\n\t\toptions?: ExtensionWidgetOptions,\n\t): void {\n\t\tconst placement = options?.placement ?? \"aboveEditor\";\n\t\tconst removeExisting = (map: Map<string, DisposableComponent>) => {\n\t\t\tconst existing = map.get(key);\n\t\t\tif (existing?.dispose) existing.dispose();\n\t\t\tmap.delete(key);\n\t\t};\n\n\t\tremoveExisting(this.extensionWidgetsAbove);\n\t\tremoveExisting(this.extensionWidgetsBelow);\n\n\t\tif (content === undefined) {\n\t\t\tthis.renderWidgets();\n\t\t\treturn;\n\t\t}\n\n\t\tlet component: DisposableComponent;\n\n\t\tif (Array.isArray(content)) {\n\t\t\t// Wrap string array in a Container with Text components\n\t\t\tconst container = new Container();\n\t\t\tfor (const line of content.slice(0, InteractiveMode.MAX_WIDGET_LINES)) {\n\t\t\t\tcontainer.addChild(new Text(line, 1, 0));\n\t\t\t}\n\t\t\tif (content.length > InteractiveMode.MAX_WIDGET_LINES) {\n\t\t\t\tcontainer.addChild(new Text(theme.fg(\"muted\", \"... (widget truncated)\"), 1, 0));\n\t\t\t}\n\t\t\tcomponent = container;\n\t\t} else {\n\t\t\t// Factory function - create component\n\t\t\tcomponent = content(this.ui, theme);\n\t\t}\n\n\t\tconst targetMap = placement === \"belowEditor\" ? this.extensionWidgetsBelow : this.extensionWidgetsAbove;\n\t\ttargetMap.set(key, component);\n\t\tthis.renderWidgets();\n\t}\n\n\tprivate clearExtensionWidgets(): void {\n\t\tfor (const widget of this.extensionWidgetsAbove.values()) {\n\t\t\twidget.dispose?.();\n\t\t}\n\t\tfor (const widget of this.extensionWidgetsBelow.values()) {\n\t\t\twidget.dispose?.();\n\t\t}\n\t\tthis.extensionWidgetsAbove.clear();\n\t\tthis.extensionWidgetsBelow.clear();\n\t\tthis.renderWidgets();\n\t}\n\n\tprivate resetExtensionUI(): void {\n\t\tif (this.extensionSelector) {\n\t\t\tthis.hideExtensionSelector();\n\t\t}\n\t\tif (this.extensionInput) {\n\t\t\tthis.hideExtensionInput();\n\t\t}\n\t\tif (this.extensionEditor) {\n\t\t\tthis.hideExtensionEditor();\n\t\t}\n\t\tthis.ui.hideOverlay();\n\t\tthis.clearExtensionTerminalInputListeners();\n\t\tthis.setExtensionFooter(undefined);\n\t\tthis.setExtensionHeader(undefined);\n\t\tthis.clearExtensionWidgets();\n\t\tthis.footerDataProvider.clearExtensionStatuses();\n\t\tthis.footer.invalidate();\n\t\tthis.autocompleteProviderWrappers = [];\n\t\tthis.setCustomEditorComponent(undefined);\n\t\tthis.setupAutocompleteProvider();\n\t\tthis.defaultEditor.onExtensionShortcut = undefined;\n\t\tthis.updateTerminalTitle();\n\t\tthis.workingMessage = undefined;\n\t\tthis.workingVisible = true;\n\t\tthis.setWorkingIndicator();\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${keyText(\"app.interrupt\")} to interrupt)`);\n\t\t}\n\t\tthis.setHiddenThinkingLabel();\n\t}\n\n\t// Maximum total widget lines to prevent viewport overflow\n\tprivate static readonly MAX_WIDGET_LINES = 10;\n\n\t/**\n\t * Render all extension widgets to the widget container.\n\t */\n\tprivate renderWidgets(): void {\n\t\tif (!this.widgetContainerAbove || !this.widgetContainerBelow) return;\n\t\tthis.renderWidgetContainer(this.widgetContainerAbove, this.extensionWidgetsAbove, true, true);\n\t\tthis.renderWidgetContainer(this.widgetContainerBelow, this.extensionWidgetsBelow, false, false);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate renderWidgetContainer(\n\t\tcontainer: Container,\n\t\twidgets: Map<string, DisposableComponent>,\n\t\tspacerWhenEmpty: boolean,\n\t\tleadingSpacer: boolean,\n\t): void {\n\t\tcontainer.clear();\n\n\t\tif (widgets.size === 0) {\n\t\t\tif (spacerWhenEmpty) {\n\t\t\t\tcontainer.addChild(new Spacer(1));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (leadingSpacer) {\n\t\t\tcontainer.addChild(new Spacer(1));\n\t\t}\n\t\tfor (const component of widgets.values()) {\n\t\t\tcontainer.addChild(component);\n\t\t}\n\t}\n\n\t/**\n\t * Set a custom footer component, or restore the built-in footer.\n\t */\n\tprivate setExtensionFooter(factory: ExtensionFooterFactory | undefined): void {\n\t\t// Dispose existing custom footer\n\t\tif (this.customFooter?.dispose) {\n\t\t\tthis.customFooter.dispose();\n\t\t}\n\n\t\tthis.footerContainer.clear();\n\t\tif (factory) {\n\t\t\t// Create and add custom footer, passing the data provider\n\t\t\tthis.customFooter = factory(this.ui, theme, this.footerDataProvider);\n\t\t\tthis.footerContainer.addChild(this.customFooter);\n\t\t} else {\n\t\t\t// Restore built-in footer\n\t\t\tthis.customFooter = undefined;\n\t\t\tthis.footerContainer.addChild(this.footer);\n\t\t}\n\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set a custom header component, or restore the built-in header.\n\t */\n\tprivate setExtensionHeader(factory: ExtensionHeaderFactory | undefined): void {\n\t\t// Header may not be initialized yet if called during early initialization\n\t\tif (!this.builtInHeader) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Dispose existing custom header\n\t\tif (this.customHeader?.dispose) {\n\t\t\tthis.customHeader.dispose();\n\t\t}\n\n\t\t// Find the index of the current header in the header container\n\t\tconst currentHeader = this.customHeader || this.builtInHeader;\n\t\tconst index = this.headerContainer.children.indexOf(currentHeader);\n\n\t\tif (factory) {\n\t\t\t// Create and add custom header\n\t\t\tthis.customHeader = factory(this.ui, theme);\n\t\t\tif (isExpandable(this.customHeader)) {\n\t\t\t\tthis.customHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.headerContainer.children[index] = this.customHeader;\n\t\t\t} else {\n\t\t\t\t// If not found (e.g. builtInHeader was never added), add at the top\n\t\t\t\tthis.headerContainer.children.unshift(this.customHeader);\n\t\t\t}\n\t\t} else {\n\t\t\t// Restore built-in header\n\t\t\tthis.customHeader = undefined;\n\t\t\tif (isExpandable(this.builtInHeader)) {\n\t\t\t\tthis.builtInHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.headerContainer.children[index] = this.builtInHeader;\n\t\t\t}\n\t\t}\n\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate addExtensionTerminalInputListener(handler: TerminalInputHandler): () => void {\n\t\tconst subscription = { handler, unsubscribe: this.ui.addInputListener(handler) };\n\t\tthis.extensionTerminalInputSubscriptions.add(subscription);\n\t\treturn () => {\n\t\t\tsubscription.unsubscribe();\n\t\t\tthis.extensionTerminalInputSubscriptions.delete(subscription);\n\t\t};\n\t}\n\n\tprivate rebindExtensionTerminalInputListeners(): void {\n\t\tfor (const subscription of this.extensionTerminalInputSubscriptions) {\n\t\t\tsubscription.unsubscribe();\n\t\t\tsubscription.unsubscribe = this.ui.addInputListener(subscription.handler);\n\t\t}\n\t}\n\n\tprivate clearExtensionTerminalInputListeners(): void {\n\t\tfor (const subscription of this.extensionTerminalInputSubscriptions) subscription.unsubscribe();\n\t\tthis.extensionTerminalInputSubscriptions.clear();\n\t}\n\n\t/**\n\t * Create the ExtensionUIContext for extensions.\n\t */\n\tprivate createExtensionUIContext(): ExtensionUIContext {\n\t\treturn {\n\t\t\tselect: (title, options, opts) => this.showExtensionSelector(title, options, opts),\n\t\t\tconfirm: (title, message, opts) => this.showExtensionConfirm(title, message, opts),\n\t\t\tinput: (title, placeholder, opts) => this.showExtensionInput(title, placeholder, opts),\n\t\t\tnotify: (message, type) => this.showExtensionNotify(message, type),\n\t\t\tonTerminalInput: (handler) => this.addExtensionTerminalInputListener(handler),\n\t\t\tsetStatus: (key, text) => this.setExtensionStatus(key, text),\n\t\t\tsetWorkingMessage: (message) => {\n\t\t\t\tthis.workingMessage = message;\n\t\t\t\tif (this.loadingAnimation && this.hookExecutionActivityDepth === 0) {\n\t\t\t\t\tthis.loadingAnimation.setMessage(this.getWorkingLoaderMessage());\n\t\t\t\t}\n\t\t\t},\n\t\t\tsetWorkingVisible: (visible) => this.setWorkingVisible(visible),\n\t\t\tsetWorkingIndicator: (options) => this.setWorkingIndicator(options),\n\t\t\tsetHiddenThinkingLabel: (label) => this.setHiddenThinkingLabel(label),\n\t\t\tsetWidget: (key, content, options) => this.setExtensionWidget(key, content, options),\n\t\t\tsetFooter: (factory) => this.setExtensionFooter(factory),\n\t\t\tsetHeader: (factory) => this.setExtensionHeader(factory),\n\t\t\tsetTitle: (title) => this.ui.terminal.setTitle(title),\n\t\t\tcustom: (factory, options) => this.showExtensionCustom(factory, options),\n\t\t\tpasteToEditor: (text) => this.editor.handleInput(`\\x1b[200~${text}\\x1b[201~`),\n\t\t\tsetEditorText: (text) => this.editor.setText(text),\n\t\t\tgetEditorText: () => this.editor.getExpandedText?.() ?? this.editor.getText(),\n\t\t\teditor: (title, prefill) => this.showExtensionEditor(title, prefill),\n\t\t\taddAutocompleteProvider: (factory) => {\n\t\t\t\tthis.autocompleteProviderWrappers.push(factory);\n\t\t\t\tthis.setupAutocompleteProvider();\n\t\t\t},\n\t\t\tsetEditorComponent: (factory) => this.setCustomEditorComponent(factory),\n\t\t\tgetEditorComponent: () => this.editorComponentFactory,\n\t\t\tget theme() {\n\t\t\t\treturn theme;\n\t\t\t},\n\t\t\tgetAllThemes: () => getAvailableThemesWithPaths(),\n\t\t\tgetTheme: (name) => getThemeByName(name),\n\t\t\tsetTheme: (themeOrName) => {\n\t\t\t\tif (themeOrName instanceof Theme) {\n\t\t\t\t\tsetThemeInstance(themeOrName);\n\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\treturn { success: true };\n\t\t\t\t}\n\t\t\t\tconst result = setTheme(themeOrName, true);\n\t\t\t\tif (result.success) {\n\t\t\t\t\tif (this.settingsManager.getTheme() !== themeOrName) {\n\t\t\t\t\t\tthis.settingsManager.setTheme(themeOrName);\n\t\t\t\t\t}\n\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tgetToolsExpanded: () => this.toolOutputExpanded,\n\t\t\tsetToolsExpanded: (expanded) => this.setToolsExpanded(expanded),\n\t\t};\n\t}\n\n\t/**\n\t * Show a selector for extensions.\n\t */\n\tprivate showExtensionSelector(\n\t\ttitle: string,\n\t\toptions: string[],\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tif (opts?.signal?.aborted) {\n\t\t\t\tresolve(undefined);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\tresolve(undefined);\n\t\t\t};\n\t\t\topts?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tthis.extensionSelector = new ExtensionSelectorComponent(\n\t\t\t\ttitle,\n\t\t\t\toptions,\n\t\t\t\t(option) => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\t\tresolve(option);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\t{ tui: this.ui, timeout: opts?.timeout, onToggleToolsExpanded: () => this.toggleToolOutputExpansion() },\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionSelector);\n\t\t\tthis.ui.setFocus(this.extensionSelector);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension selector.\n\t */\n\tprivate hideExtensionSelector(): void {\n\t\tthis.extensionSelector?.dispose();\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionSelector = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a confirmation dialog for extensions.\n\t */\n\tprivate async showExtensionConfirm(\n\t\ttitle: string,\n\t\tmessage: string,\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise<boolean> {\n\t\tconst result = await this.showExtensionSelector(`${title}\\n${message}`, [\"Yes\", \"No\"], opts);\n\t\treturn result === \"Yes\";\n\t}\n\n\tprivate async promptForMissingSessionCwd(error: MissingSessionCwdError): Promise<string | undefined> {\n\t\tconst confirmed = await this.showExtensionConfirm(\n\t\t\t\"Session cwd not found\",\n\t\t\tformatMissingSessionCwdPrompt(error.issue),\n\t\t);\n\t\treturn confirmed ? error.issue.fallbackCwd : undefined;\n\t}\n\n\t/**\n\t * Show a text input for extensions.\n\t */\n\tprivate showExtensionInput(\n\t\ttitle: string,\n\t\tplaceholder?: string,\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tif (opts?.signal?.aborted) {\n\t\t\t\tresolve(undefined);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tthis.hideExtensionInput();\n\t\t\t\tresolve(undefined);\n\t\t\t};\n\t\t\topts?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tthis.extensionInput = new ExtensionInputComponent(\n\t\t\t\ttitle,\n\t\t\t\tplaceholder,\n\t\t\t\t(value) => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionInput();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionInput();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\t{ tui: this.ui, timeout: opts?.timeout },\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionInput);\n\t\t\tthis.ui.setFocus(this.extensionInput);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension input.\n\t */\n\tprivate hideExtensionInput(): void {\n\t\tthis.extensionInput?.dispose();\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionInput = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a multi-line editor for extensions (with Ctrl+G support).\n\t */\n\tprivate showExtensionEditor(title: string, prefill?: string): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.extensionEditor = new ExtensionEditorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.keybindings,\n\t\t\t\ttitle,\n\t\t\t\tprefill,\n\t\t\t\t(value) => {\n\t\t\t\t\tthis.hideExtensionEditor();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tthis.hideExtensionEditor();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\tundefined,\n\t\t\t\tthis.settingsManager.getExternalEditorCommand(),\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionEditor);\n\t\t\tthis.ui.setFocus(this.extensionEditor);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension editor.\n\t */\n\tprivate hideExtensionEditor(): void {\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionEditor = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set a custom editor component from an extension.\n\t * Pass undefined to restore the default editor.\n\t */\n\tprivate configureCustomEditorPresentation(editor: EditorComponent): void {\n\t\tif (editor.borderColor !== undefined) editor.borderColor = this.defaultEditor.borderColor;\n\t\tif (editor.setPaddingX !== undefined) editor.setPaddingX(this.defaultEditor.getPaddingX());\n\t\tif (editor.setAutocompleteProvider && this.autocompleteProvider) {\n\t\t\teditor.setAutocompleteProvider(this.autocompleteProvider);\n\t\t}\n\t}\n\n\tprivate inheritAppEditorHandlers(editor: EditorComponent): void {\n\t\t// Use duck typing because instanceof fails across jiti module boundaries.\n\t\tconst customEditor = editor as unknown as Record<string, unknown>;\n\t\tif (!(\"actionHandlers\" in customEditor) || !(customEditor.actionHandlers instanceof Map)) return;\n\t\tif (!customEditor.onEscape) customEditor.onEscape = () => this.defaultEditor.onEscape?.();\n\t\tif (!customEditor.onCtrlD) customEditor.onCtrlD = () => this.defaultEditor.onCtrlD?.();\n\t\tif (!customEditor.onPasteImage) customEditor.onPasteImage = () => this.defaultEditor.onPasteImage?.();\n\t\tif (!customEditor.onExtensionShortcut) {\n\t\t\tcustomEditor.onExtensionShortcut = (data: string) => this.defaultEditor.onExtensionShortcut?.(data);\n\t\t}\n\t\tfor (const [action, handler] of this.defaultEditor.actionHandlers) {\n\t\t\t(customEditor.actionHandlers as Map<string, () => void>).set(action, handler);\n\t\t}\n\t}\n\n\tprivate createCustomEditorComponent(factory: EditorFactory, text: string): EditorComponent {\n\t\tconst editor = factory(this.ui, getEditorTheme(), this.keybindings);\n\t\teditor.onSubmit = this.defaultEditor.onSubmit;\n\t\teditor.onChange = this.defaultEditor.onChange;\n\t\teditor.setText(text);\n\t\tthis.configureCustomEditorPresentation(editor);\n\t\tthis.inheritAppEditorHandlers(editor);\n\t\treturn editor;\n\t}\n\n\tprivate setCustomEditorComponent(factory: EditorFactory | undefined): void {\n\t\tthis.editorComponentFactory = factory;\n\t\tconst currentText = this.editor.getText();\n\t\tthis.editorContainer.clear();\n\t\tif (factory) {\n\t\t\tthis.editor = this.createCustomEditorComponent(factory, currentText);\n\t\t} else {\n\t\t\tthis.defaultEditor.setText(currentText);\n\t\t\tthis.editor = this.defaultEditor;\n\t\t}\n\t\tthis.editorContainer.addChild(this.editor as Component);\n\t\tthis.ui.setFocus(this.editor as Component);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a notification for extensions.\n\t */\n\tprivate showExtensionNotify(message: string, type?: ExtensionNotificationType): void {\n\t\tif (type === \"error\") {\n\t\t\tthis.showError(message);\n\t\t} else if (type === \"warning\") {\n\t\t\tthis.showWarning(message);\n\t\t} else {\n\t\t\tthis.showStatus(message);\n\t\t}\n\t}\n\n\tprivate getExtensionOverlayOptions(\n\t\tcomponent: DisposableComponent,\n\t\toptions?: ExtensionCustomOptions,\n\t): OverlayOptions | undefined {\n\t\tif (options?.overlayOptions) {\n\t\t\treturn typeof options.overlayOptions === \"function\" ? options.overlayOptions() : options.overlayOptions;\n\t\t}\n\t\tconst width = (component as { width?: number }).width;\n\t\treturn width ? { width } : undefined;\n\t}\n\n\tprivate mountExtensionCustomComponent(\n\t\tcomponent: DisposableComponent,\n\t\tisOverlay: boolean,\n\t\toptions?: ExtensionCustomOptions,\n\t): void {\n\t\tif (isOverlay) {\n\t\t\tconst handle = this.ui.showOverlay(component, this.getExtensionOverlayOptions(component, options));\n\t\t\toptions?.onHandle?.(handle);\n\t\t\treturn;\n\t\t}\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(component);\n\t\tthis.ui.setFocus(component);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/** Show a custom component with keyboard focus. Overlay mode renders on top of existing content. */\n\tprivate async showExtensionCustom<T>(\n\t\tfactory: ExtensionCustomFactory<T>,\n\t\toptions?: ExtensionCustomOptions,\n\t): Promise<T> {\n\t\tconst savedText = this.editor.getText();\n\t\tconst isOverlay = options?.overlay ?? false;\n\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.editor.setText(savedText);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet component: DisposableComponent;\n\t\t\tlet closed = false;\n\n\t\t\tconst close = (result: T) => {\n\t\t\t\tif (closed) return;\n\t\t\t\tclosed = true;\n\t\t\t\tif (isOverlay) this.ui.hideOverlay();\n\t\t\t\telse restoreEditor();\n\t\t\t\t// Note: both branches above already call requestRender\n\t\t\t\tresolve(result);\n\t\t\t\ttry {\n\t\t\t\t\tcomponent?.dispose?.();\n\t\t\t\t} catch {\n\t\t\t\t\t/* ignore dispose errors */\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tPromise.resolve(factory(this.ui, theme, this.keybindings, close))\n\t\t\t\t.then((resolvedComponent) => {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tcomponent = resolvedComponent;\n\t\t\t\t\tthis.mountExtensionCustomComponent(component, isOverlay, options);\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tif (!isOverlay) restoreEditor();\n\t\t\t\t\treject(err);\n\t\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Show an extension error in the UI.\n\t */\n\tprivate showExtensionError(extensionPath: string, error: string, stack?: string): void {\n\t\tconst errorMsg = `Extension \"${extensionPath}\" error: ${error}`;\n\t\tconst errorText = new Text(theme.fg(\"error\", errorMsg), 1, 0);\n\t\tthis.chatContainer.addChild(errorText);\n\t\tif (stack) {\n\t\t\t// Show stack trace in dim color, indented\n\t\t\tconst stackLines = stack\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.slice(1) // Skip first line (duplicates error message)\n\t\t\t\t.map((line) => theme.fg(\"dim\", ` ${line.trim()}`))\n\t\t\t\t.join(\"\\n\");\n\t\t\tif (stackLines) {\n\t\t\t\tthis.chatContainer.addChild(new Text(stackLines, 1, 0));\n\t\t\t}\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\t// =========================================================================\n\t// Key Handlers\n\t// =========================================================================\n\tprivate handleEmptyEditorEscape(): void {\n\t\tconst action = this.settingsManager.getDoubleEscapeAction();\n\t\tif (action === \"none\") return;\n\t\tconst now = Date.now();\n\t\tif (now - this.lastEscapeTime >= 500) {\n\t\t\tthis.lastEscapeTime = now;\n\t\t\treturn;\n\t\t}\n\t\tif (action === \"tree\") this.showTreeSelector();\n\t\telse this.showUserMessageSelector();\n\t\tthis.lastEscapeTime = 0;\n\t}\n\n\tprivate handleEditorEscape(): void {\n\t\tif (this.session.isStreaming) {\n\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\treturn;\n\t\t}\n\t\tif (this.session.isBashRunning) {\n\t\t\tthis.session.abortBash();\n\t\t\treturn;\n\t\t}\n\t\tif (this.isBashMode) {\n\t\t\tthis.editor.setText(\"\");\n\t\t\tthis.isBashMode = false;\n\t\t\tthis.updateEditorBorderColor();\n\t\t\treturn;\n\t\t}\n\t\tif (!this.editor.getText().trim()) this.handleEmptyEditorEscape();\n\t}\n\n\tprivate setupKeyHandlers(): void {\n\t\t// Set up handlers on defaultEditor - they use this.editor for text access\n\t\t// so they work correctly regardless of which editor is active\n\t\tthis.defaultEditor.onEscape = () => this.handleEditorEscape();\n\n\t\t// Register app action handlers\n\t\tthis.defaultEditor.onAction(\"app.clear\", () => this.handleCtrlC());\n\t\tthis.defaultEditor.onCtrlD = () => this.handleCtrlD();\n\t\tthis.defaultEditor.onAction(\"app.suspend\", () => this.handleCtrlZ());\n\t\tthis.defaultEditor.onAction(\"app.thinking.cycle\", () => this.cycleThinkingLevel());\n\t\tthis.defaultEditor.onAction(\"app.model.cycleForward\", () => this.cycleModel(\"forward\"));\n\t\tthis.defaultEditor.onAction(\"app.model.cycleBackward\", () => this.cycleModel(\"backward\"));\n\n\t\t// Global debug handler on TUI (works regardless of focus)\n\t\tthis.ui.onDebug = () => this.handleDebugCommand();\n\t\tthis.defaultEditor.onAction(\"app.model.select\", () => this.showModelSelector());\n\t\tthis.defaultEditor.onAction(\"app.tools.expand\", () => this.toggleToolOutputExpansion());\n\t\tthis.defaultEditor.onAction(\"app.thinking.toggle\", () => this.toggleThinkingBlockVisibility());\n\t\tthis.defaultEditor.onAction(\"app.editor.external\", () => this.openExternalEditor());\n\t\tthis.defaultEditor.onAction(\"app.message.copy\", () => void this.handleCopyCommand({ flashConfirmation: true }));\n\t\tthis.defaultEditor.onAction(\"app.message.followUp\", () => this.handleFollowUp());\n\t\tthis.defaultEditor.onAction(\"app.message.dequeue\", () => this.handleDequeue());\n\t\tthis.defaultEditor.onAction(\"app.session.new\", () => this.handleClearCommand());\n\t\tthis.defaultEditor.onAction(\"app.session.tree\", () => this.showTreeSelector());\n\t\tthis.defaultEditor.onAction(\"app.session.fork\", () => this.showUserMessageSelector());\n\t\tthis.defaultEditor.onAction(\"app.session.resume\", () => this.showSessionSelector());\n\n\t\tthis.defaultEditor.onChange = (text: string) => {\n\t\t\tconst wasBashMode = this.isBashMode;\n\t\t\tthis.isBashMode = text.trimStart().startsWith(\"!\");\n\t\t\tif (wasBashMode !== this.isBashMode) {\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t}\n\t\t};\n\n\t\t// Handle clipboard paste (triggered on Ctrl+V). Images are attached by path;\n\t\t// otherwise, paste plain text from the system clipboard.\n\t\tthis.defaultEditor.onPasteImage = () => {\n\t\t\tvoid this.handleClipboardPaste();\n\t\t};\n\t}\n\n\tprivate async handleClipboardPaste(): Promise<void> {\n\t\ttry {\n\t\t\tconst image = await readClipboardImage();\n\t\t\tif (image) {\n\t\t\t\tconst tmpDir = os.tmpdir();\n\t\t\t\tconst ext = extensionForImageMimeType(image.mimeType) ?? \"png\";\n\t\t\t\tconst fileName = `grip-clipboard-${crypto.randomUUID()}.${ext}`;\n\t\t\t\tconst filePath = path.join(tmpDir, fileName);\n\t\t\t\tfs.writeFileSync(filePath, Buffer.from(image.bytes));\n\n\t\t\t\tthis.editor.insertTextAtCursor?.(filePath);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst text = await readClipboardText();\n\t\t\tif (text) {\n\t\t\t\tthis.editor.insertTextAtCursor?.(text);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t}\n\t\t} catch {\n\t\t\t// Silently ignore clipboard errors (may not have permission, etc.)\n\t\t}\n\t}\n\n\tprivate async handleRightClickPaste(): Promise<void> {\n\t\tconst target = this.renderer.getFocusedComponent();\n\t\tconst handleInput = target?.handleInput;\n\t\tif (!target || !handleInput) return;\n\t\ttry {\n\t\t\tconst text = await readClipboardText();\n\t\t\tif (!text || this.renderer.getFocusedComponent() !== target) return;\n\t\t\thandleInput.call(target, `\\x1b[200~${text}\\x1b[201~`);\n\t\t\tthis.ui.requestRender();\n\t\t} catch {\n\t\t\t// Silently ignore clipboard errors (may not have permission, etc.)\n\t\t}\n\t}\n\n\tprivate matchesEditorCommand(text: string, command: string): boolean {\n\t\treturn text === command || text.startsWith(`${command} `);\n\t}\n\n\tprivate handleCompressionToggleCommand(text: string, command: string): void {\n\t\tthis.editor.setText(\"\");\n\t\tconst action = text.slice(command.length).trim();\n\t\tconst detection = command === \"/compress-detection\";\n\t\tif (action && action !== \"on\" && action !== \"off\") {\n\t\t\tthis.showWarning(`Usage: ${command} [on|off]`);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tif (action) {\n\t\t\t\tif (detection) this.session.setCompressionDetectionEnabled(action === \"on\");\n\t\t\t\telse this.session.setContextCompressionEnabled(action === \"on\");\n\t\t\t}\n\t\t\tconst enabled = detection ? this.session.compressionDetectionEnabled : this.session.contextCompressionEnabled;\n\t\t\tthis.showStatus(\n\t\t\t\t`${detection ? \"Compression detection\" : \"Context compression\"} ${enabled ? \"enabled\" : \"disabled\"} for this session`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate resolveParameterizedEditorCommand(text: string): EditorCommandAction | undefined {\n\t\tif (this.matchesEditorCommand(text, \"/cd\")) {\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleCdCommand(text);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/profile\")) {\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleProfileCommand(text);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/model\")) {\n\t\t\tconst searchTerm = text.slice(\"/model\".length).trim() || undefined;\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleModelCommand(searchTerm);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconst compressionCommand = [\"/context-compression\", \"/compress-detection\"].find((command) =>\n\t\t\tthis.matchesEditorCommand(text, command),\n\t\t);\n\t\tif (compressionCommand) return { run: () => this.handleCompressionToggleCommand(text, compressionCommand) };\n\t\tif (this.matchesEditorCommand(text, \"/compress-detection-model\")) {\n\t\t\tconst searchTerm = text.slice(\"/compress-detection-model\".length).trim();\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleCompressionDetectionModelCommand(searchTerm);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/export\")) {\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tawait this.handleExportCommand(text);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/import\")) {\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tawait this.handleImportCommand(text);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/name\")) {\n\t\t\treturn {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleNameCommand(text);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/hooks\")) {\n\t\t\treturn {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleHooksCommand(text);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (text === \"/sandbox\" || /^\\/sandbox\\s/.test(text)) {\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleSandboxCommand(text);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/compact\")) {\n\t\t\tconst customInstructions = text.slice(\"/compact\".length).trim() || undefined;\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleCompactCommand(customInstructions);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate resolveExactEditorCommand(text: string): EditorCommandAction | undefined {\n\t\tconst commands: Partial<Record<string, EditorCommandAction>> = {\n\t\t\t\"/settings\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showSettingsSelector();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/scoped-models\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.showModelsSelector();\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/share\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tawait this.handleShareCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/copy\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tawait this.handleCopyCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/session\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleSessionCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/changelog\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleChangelogCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/hotkeys\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleHotkeysCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/fork\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showUserMessageSelector();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/clone\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleCloneCommand();\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/tree\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showTreeSelector();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/login\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showOAuthSelector(\"login\");\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/logout\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showOAuthSelector(\"logout\");\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/new\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleClearCommand();\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/reload\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleReloadCommand();\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/debug\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleDebugCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/resume\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showSessionSelector();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/quit\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.shutdown();\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t\treturn commands[text];\n\t}\n\n\tprivate async handleBuiltInEditorCommand(text: string): Promise<boolean> {\n\t\tconst action = this.resolveParameterizedEditorCommand(text) ?? this.resolveExactEditorCommand(text);\n\t\tif (!action) return false;\n\t\tawait action.run();\n\t\treturn true;\n\t}\n\n\tprivate async handleBashEditorSubmission(text: string): Promise<boolean> {\n\t\tif (!text.startsWith(\"!\")) return false;\n\t\tconst isExcluded = text.startsWith(\"!!\");\n\t\tconst command = isExcluded ? text.slice(2).trim() : text.slice(1).trim();\n\t\tif (!command) return false;\n\t\tif (this.session.isBashRunning) {\n\t\t\tthis.showWarning(\"A bash command is already running. Press Esc to cancel it first.\");\n\t\t\tthis.editor.setText(text);\n\t\t\treturn true;\n\t\t}\n\t\tthis.editor.addToHistory?.(text);\n\t\tawait this.handleBashCommand(command, isExcluded);\n\t\tthis.isBashMode = false;\n\t\tthis.updateEditorBorderColor();\n\t\treturn true;\n\t}\n\n\tprivate async handleCompactingEditorSubmission(text: string): Promise<boolean> {\n\t\tif (!this.session.isCompacting) return false;\n\t\tif (this.isExtensionCommand(text)) {\n\t\t\tthis.editor.addToHistory?.(text);\n\t\t\tthis.editor.setText(\"\");\n\t\t\tawait this.session.prompt(text);\n\t\t} else {\n\t\t\tthis.queueCompactionMessage(text, \"steer\");\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate async handleStreamingEditorSubmission(text: string): Promise<boolean> {\n\t\tif (!this.session.isStreaming) return false;\n\t\tthis.editor.addToHistory?.(text);\n\t\tthis.editor.setText(\"\");\n\t\tawait this.session.prompt(text, { streamingBehavior: \"steer\" });\n\t\tthis.updatePendingMessagesDisplay();\n\t\tthis.ui.requestRender();\n\t\treturn true;\n\t}\n\n\tprivate submitEditorInput(text: string): void {\n\t\tthis.flushPendingBashComponents();\n\t\tif (this.onInputCallback) this.onInputCallback(text);\n\t\telse this.pendingUserInputs.push(text);\n\t\tthis.editor.addToHistory?.(text);\n\t}\n\n\tprivate async handleEditorSubmit(text: string): Promise<void> {\n\t\tconst submittedText = text.trim();\n\t\tif (!submittedText) return;\n\t\t// Keep attempted commands as well as accepted prompts available through editor history.\n\t\tthis.editor.addToHistory?.(submittedText);\n\t\tif (await this.handleBuiltInEditorCommand(submittedText)) return;\n\t\tif (await this.handleBashEditorSubmission(submittedText)) return;\n\t\tif (await this.handleCompactingEditorSubmission(submittedText)) return;\n\t\tif (await this.handleStreamingEditorSubmission(submittedText)) return;\n\t\tthis.submitEditorInput(submittedText);\n\t}\n\n\tprivate setupEditorSubmitHandler(): void {\n\t\tthis.defaultEditor.onSubmit = (text: string) => this.handleEditorSubmit(text);\n\t}\n\n\tprivate addHookExecutionNotice(notice: HookExecutionNotice): void {\n\t\tconst activeSession = this.activeSession;\n\t\tif (this.hookExecutionSession !== activeSession) {\n\t\t\tthis.hookExecutionSession = activeSession;\n\t\t\tthis.hookExecutionNotices = [];\n\t\t\tfor (const component of this.hookExecutionComponents) this.chatContainer.removeChild(component);\n\t\t\tthis.hookExecutionComponents = [];\n\t\t\tthis.resetHookExecutionGrouping();\n\t\t}\n\t\tif (!this.appendHookExecutionNoticeToActiveGroup(notice)) this.addHookExecutionNoticeCard(notice);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate appendHookExecutionNoticeToActiveGroup(notice: HookExecutionNotice): boolean {\n\t\tif (!this.hookExecutionTurnActive || !isToolHookEvent(notice.event)) return false;\n\t\tconst activeGroup = this.activeToolHookExecutionGroups.get(notice.event);\n\t\tif (!activeGroup) return false;\n\t\tconst component = this.hookExecutionComponents[this.hookExecutionNotices.indexOf(activeGroup)];\n\t\tif (!component) return false;\n\t\tactiveGroup.push(notice);\n\t\tcomponent.appendNotice(notice);\n\t\treturn true;\n\t}\n\n\tprivate addHookExecutionNoticeCard(notice: HookExecutionNotice): void {\n\t\tconst group = [notice];\n\t\tthis.hookExecutionNotices.push(group);\n\t\tconst component = new HookExecutionComponent(notice, this.getMarkdownThemeWithSettings());\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.hookExecutionComponents.push(component);\n\t\tthis.chatContainer.addChild(component);\n\t\tif (this.hookExecutionTurnActive && isToolHookEvent(notice.event)) {\n\t\t\tthis.activeToolHookExecutionGroups.set(notice.event, group);\n\t\t}\n\t\tthis.trimHookExecutionNotices();\n\t}\n\n\tprivate trimHookExecutionNotices(): void {\n\t\tif (this.hookExecutionNotices.length <= MAX_TUI_HOOK_EXECUTION_NOTICES) return;\n\t\tconst oldestGroup = this.hookExecutionNotices.shift();\n\t\tif (oldestGroup) {\n\t\t\tfor (const [event, active] of this.activeToolHookExecutionGroups) {\n\t\t\t\tif (active === oldestGroup) this.activeToolHookExecutionGroups.delete(event);\n\t\t\t}\n\t\t}\n\t\tconst oldestComponent = this.hookExecutionComponents.shift();\n\t\tif (oldestComponent) this.chatContainer.removeChild(oldestComponent);\n\t}\n\n\tprivate resetHookExecutionGrouping(): void {\n\t\tthis.hookExecutionTurnActive = false;\n\t\tthis.activeToolHookExecutionGroups.clear();\n\t}\n\n\tprivate subscribeToAgent(): void {\n\t\tthis.unsubscribe = this.session.subscribe(async (event) => {\n\t\t\tawait this.handleEvent(event);\n\t\t});\n\t\tthis.hookExecutionUnsubscribe = this.session.subscribeToHookExecutions((notice) => {\n\t\t\tthis.addHookExecutionNotice(notice);\n\t\t});\n\t\tthis.hookExecutionActivityUnsubscribe = this.session.subscribeToHookExecutionActivity((active) => {\n\t\t\tthis.handleHookExecutionActivity(active);\n\t\t});\n\t}\n\n\tprivate handleAgentStart(): void {\n\t\tthis.pendingTools.clear();\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(true);\n\t\tif (this.retryEscapeHandler) {\n\t\t\tthis.defaultEditor.onEscape = this.retryEscapeHandler;\n\t\t\tthis.retryEscapeHandler = undefined;\n\t\t}\n\t\tthis.retryCountdown?.dispose();\n\t\tthis.retryCountdown = undefined;\n\t\tthis.retryLoader?.stop();\n\t\tthis.retryLoader = undefined;\n\t\tthis.stopWorkingLoader();\n\t\tif (this.workingVisible) {\n\t\t\tthis.loadingAnimation = this.createWorkingLoader();\n\t\t\tthis.statusContainer.addChild(this.loadingAnimation);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate createPendingToolComponent(toolName: string, toolCallId: string, args: unknown): ToolExecutionComponent {\n\t\tconst component = new ToolExecutionComponent(\n\t\t\ttoolName,\n\t\t\ttoolCallId,\n\t\t\targs,\n\t\t\t{\n\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t},\n\t\t\tthis.getRegisteredToolDefinition(toolName),\n\t\t\tthis.ui,\n\t\t\tthis.activeSession.getCwd(),\n\t\t);\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(component);\n\t\tthis.pendingTools.set(toolCallId, component);\n\t\treturn component;\n\t}\n\n\tprivate handleMessageStart(message: AgentMessage): void {\n\t\tif (message.role === \"custom\") {\n\t\t\tthis.addMessageToChat(message);\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (message.role === \"user\") {\n\t\t\tthis.addMessageToChat(message);\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (message.role !== \"assistant\") return;\n\t\tthis.streamingComponent = new AssistantMessageComponent(\n\t\t\tundefined,\n\t\t\tthis.hideThinkingBlock,\n\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\tthis.hiddenThinkingLabel,\n\t\t\tthis.outputPad,\n\t\t\tthis.getMarkdownTransformers(),\n\t\t);\n\t\tthis.streamingMessage = message;\n\t\tthis.chatContainer.addChild(this.streamingComponent);\n\t\tthis.streamingComponent.updateContent(message, true);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate updateStreamingToolComponents(message: AssistantMessage): void {\n\t\tfor (const content of message.content) {\n\t\t\tif (content.type !== \"toolCall\") continue;\n\t\t\tconst component = this.pendingTools.get(content.id);\n\t\t\tif (component) component.updateArgs(content.arguments);\n\t\t\telse this.createPendingToolComponent(content.name, content.id, content.arguments);\n\t\t}\n\t}\n\n\tprivate handleMessageUpdate(message: AgentMessage): void {\n\t\tif (!this.streamingComponent || message.role !== \"assistant\") return;\n\t\tthis.streamingMessage = message;\n\t\tthis.streamingComponent.updateContent(message, true);\n\t\tthis.updateStreamingToolComponents(message);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate getAbortedStreamingMessage(message: AssistantMessage): AssistantMessage {\n\t\tconst retryAttempt = this.session.retryAttempt;\n\t\tconst errorMessage =\n\t\t\tretryAttempt > 0\n\t\t\t\t? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? \"s\" : \"\"}`\n\t\t\t\t: \"Operation aborted\";\n\t\treturn { ...message, errorMessage };\n\t}\n\n\tprivate failPendingTools(errorMessage: string): void {\n\t\tfor (const component of this.pendingTools.values()) {\n\t\t\tcomponent.updateResult({\n\t\t\t\tcontent: [{ type: \"text\", text: errorMessage }],\n\t\t\t\tisError: true,\n\t\t\t});\n\t\t}\n\t\tthis.pendingTools.clear();\n\t}\n\n\tprivate completePendingToolArguments(): void {\n\t\tfor (const component of this.pendingTools.values()) component.setArgsComplete();\n\t}\n\n\tprivate handleMessageEnd(message: AgentMessage): void {\n\t\tif (message.role === \"user\") return;\n\t\tif (this.streamingComponent && message.role === \"assistant\") {\n\t\t\tthis.streamingMessage = message.stopReason === \"aborted\" ? this.getAbortedStreamingMessage(message) : message;\n\t\t\tthis.streamingComponent.updateContent(this.streamingMessage, false);\n\t\t\tif (message.stopReason === \"aborted\" || message.stopReason === \"error\") {\n\t\t\t\tthis.failPendingTools(this.streamingMessage.errorMessage || \"Error\");\n\t\t\t} else {\n\t\t\t\tthis.completePendingToolArguments();\n\t\t\t}\n\t\t\tthis.streamingComponent = undefined;\n\t\t\tthis.streamingMessage = undefined;\n\t\t\tthis.footer.invalidate();\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleAgentEnd(): void {\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(false);\n\t\tif (this.loadingAnimation) this.stopWorkingLoader();\n\t\tif (this.streamingComponent) {\n\t\t\tthis.chatContainer.removeChild(this.streamingComponent);\n\t\t\tthis.streamingComponent = undefined;\n\t\t\tthis.streamingMessage = undefined;\n\t\t}\n\t\tthis.pendingTools.clear();\n\t\tif (this.compressionDetectionActive) this.handleCompressionDetectionActivity(true);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate getCompactionLoaderLabel(reason: CompactionDisplayReason): string {\n\t\tconst cancelHint = `(${keyText(\"app.interrupt\")} to cancel)`;\n\t\tif (reason === \"manual\") return `Compacting context... ${cancelHint}`;\n\t\tconst prefix = reason === \"overflow\" ? \"Context overflow detected, \" : \"\";\n\t\treturn `${prefix}Auto-compacting... ${cancelHint}`;\n\t}\n\n\tprivate handleCompactionStart(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"compaction_start\") return;\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(true);\n\t\tthis.autoCompactionEscapeHandler = this.defaultEditor.onEscape;\n\t\tthis.defaultEditor.onEscape = () => this.session.abortCompaction();\n\t\tthis.statusContainer.clear();\n\t\tthis.autoCompactionLoader = new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tthis.getCompactionLoaderLabel(event.reason),\n\t\t);\n\t\tthis.statusContainer.addChild(this.autoCompactionLoader);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate restoreAfterCompaction(): void {\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(false);\n\t\tif (this.autoCompactionEscapeHandler) {\n\t\t\tthis.defaultEditor.onEscape = this.autoCompactionEscapeHandler;\n\t\t\tthis.autoCompactionEscapeHandler = undefined;\n\t\t}\n\t\tif (this.autoCompactionLoader) {\n\t\t\tthis.autoCompactionLoader.stop();\n\t\t\tthis.autoCompactionLoader = undefined;\n\t\t\tthis.statusContainer.clear();\n\t\t}\n\t}\n\n\tprivate showCompactionError(reason: CompactionDisplayReason, errorMessage: string): void {\n\t\tif (reason === \"manual\") {\n\t\t\tthis.showError(errorMessage);\n\t\t\treturn;\n\t\t}\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"error\", errorMessage), 1, 0));\n\t}\n\n\tprivate handleCompactionEnd(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"compaction_end\") return;\n\t\tthis.restoreAfterCompaction();\n\t\tif (event.aborted) {\n\t\t\tif (event.reason === \"manual\") this.showError(\"Compaction cancelled\");\n\t\t\telse this.showStatus(\"Auto-compaction cancelled\");\n\t\t} else if (event.result) {\n\t\t\tthis.chatContainer.clear();\n\t\t\tthis.hookExecutionNotices = [];\n\t\t\tthis.hookExecutionComponents = [];\n\t\t\tthis.resetHookExecutionGrouping();\n\t\t\tthis.rebuildChatFromMessages();\n\t\t\tthis.addMessageToChat(\n\t\t\t\tcreateCompactionSummaryMessage(event.result.summary, event.result.tokensBefore, new Date().toISOString()),\n\t\t\t);\n\t\t\tthis.footer.invalidate();\n\t\t} else if (event.errorMessage) {\n\t\t\tthis.showCompactionError(event.reason, event.errorMessage);\n\t\t}\n\t\tconst resumeViaCurrentRun = event.reason !== \"manual\" && event.result !== undefined;\n\t\tvoid this.flushCompactionQueue({ willRetry: event.willRetry || resumeViaCurrentRun });\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleAutoRetryStart(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"auto_retry_start\") return;\n\t\tthis.retryEscapeHandler = this.defaultEditor.onEscape;\n\t\tthis.defaultEditor.onEscape = () => this.session.abortRetry();\n\t\tthis.statusContainer.clear();\n\t\tthis.retryCountdown?.dispose();\n\t\tconst retryMessage = (seconds: number) =>\n\t\t\t`Retrying (${event.attempt}/${event.maxAttempts}) in ${seconds}s... (${keyText(\"app.interrupt\")} to cancel)`;\n\t\tthis.retryLoader = new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"warning\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tretryMessage(Math.ceil(event.delayMs / 1000)),\n\t\t);\n\t\tthis.retryCountdown = new CountdownTimer(\n\t\t\tevent.delayMs,\n\t\t\tthis.ui,\n\t\t\t(seconds) => this.retryLoader?.setMessage(retryMessage(seconds)),\n\t\t\t() => {\n\t\t\t\tthis.retryCountdown = undefined;\n\t\t\t},\n\t\t);\n\t\tthis.statusContainer.addChild(this.retryLoader);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleAutoRetryEnd(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"auto_retry_end\") return;\n\t\tif (this.retryEscapeHandler) {\n\t\t\tthis.defaultEditor.onEscape = this.retryEscapeHandler;\n\t\t\tthis.retryEscapeHandler = undefined;\n\t\t}\n\t\tthis.retryCountdown?.dispose();\n\t\tthis.retryCountdown = undefined;\n\t\tif (this.retryLoader) {\n\t\t\tthis.retryLoader.stop();\n\t\t\tthis.retryLoader = undefined;\n\t\t\tthis.statusContainer.clear();\n\t\t}\n\t\tif (!event.success) {\n\t\t\tthis.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || \"Unknown error\"}`);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleSummarizationRetryScheduled(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"summarization_retry_scheduled\") return;\n\t\tthis.showError(event.errorMessage);\n\t\tthis.autoCompactionLoader?.stop();\n\t\tthis.autoCompactionLoader = undefined;\n\t\tthis.branchSummaryLoader?.stop();\n\t\tthis.branchSummaryLoader = undefined;\n\t\tthis.summarizationRetryCountdown?.dispose();\n\t\tthis.summarizationRetryLoader?.stop();\n\t\tthis.statusContainer.clear();\n\t\tconst retryMessage = (seconds: number) =>\n\t\t\t`Retrying summary (${event.attempt}/${event.maxAttempts}) in ${seconds}s... (${keyText(\"app.interrupt\")} to cancel)`;\n\t\tthis.summarizationRetryLoader = new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"warning\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tretryMessage(Math.ceil(event.delayMs / 1000)),\n\t\t);\n\t\tthis.summarizationRetryCountdown = new CountdownTimer(\n\t\t\tevent.delayMs,\n\t\t\tthis.ui,\n\t\t\t(seconds) => this.summarizationRetryLoader?.setMessage(retryMessage(seconds)),\n\t\t\t() => {\n\t\t\t\tthis.summarizationRetryCountdown = undefined;\n\t\t\t},\n\t\t);\n\t\tthis.statusContainer.addChild(this.summarizationRetryLoader);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleSummarizationRetryAttemptStart(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"summarization_retry_attempt_start\") return;\n\t\tthis.summarizationRetryCountdown?.dispose();\n\t\tthis.summarizationRetryCountdown = undefined;\n\t\tthis.summarizationRetryLoader?.stop();\n\t\tthis.summarizationRetryLoader = undefined;\n\t\tthis.statusContainer.clear();\n\t\tconst cancelHint = `(${keyText(\"app.interrupt\")} to cancel)`;\n\t\tif (event.source === \"branchSummary\") {\n\t\t\tthis.branchSummaryLoader = new Loader(\n\t\t\t\tthis.ui,\n\t\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\t`Summarizing branch... ${cancelHint}`,\n\t\t\t);\n\t\t\tthis.statusContainer.addChild(this.branchSummaryLoader);\n\t\t} else {\n\t\t\tthis.autoCompactionLoader = new Loader(\n\t\t\t\tthis.ui,\n\t\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\tthis.getCompactionLoaderLabel(event.reason),\n\t\t\t);\n\t\t\tthis.statusContainer.addChild(this.autoCompactionLoader);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleSummarizationRetryFinished(): void {\n\t\tthis.summarizationRetryCountdown?.dispose();\n\t\tthis.summarizationRetryCountdown = undefined;\n\t\tif (this.summarizationRetryLoader) {\n\t\t\tthis.summarizationRetryLoader.stop();\n\t\t\tthis.summarizationRetryLoader = undefined;\n\t\t\tthis.statusContainer.clear();\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleEvent(event: AgentSessionEvent): Promise<void> {\n\t\tif (!this.isInitialized) await this.init();\n\t\tthis.footer.invalidate();\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\t\tthis.resetHookExecutionGrouping();\n\t\t\t\tthis.handleAgentStart();\n\t\t\t\tbreak;\n\t\t\tcase \"turn_start\":\n\t\t\t\tthis.hookExecutionTurnActive = true;\n\t\t\t\tthis.activeToolHookExecutionGroups.clear();\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\":\n\t\t\t\tthis.resetHookExecutionGrouping();\n\t\t\t\tbreak;\n\t\t\tcase \"queue_update\":\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\tcase \"compression_detection_activity\":\n\t\t\t\tthis.handleCompressionDetectionActivity(event.active);\n\t\t\t\tbreak;\n\t\t\tcase \"compression_detection_result\":\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\tcase \"state_compressed\":\n\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\tcase \"session_info_changed\":\n\t\t\t\tthis.updateTerminalTitle();\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\tcase \"thinking_level_changed\":\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\t\tthis.handleMessageStart(event.message);\n\t\t\t\tbreak;\n\t\t\tcase \"message_update\":\n\t\t\t\tthis.handleMessageUpdate(event.message);\n\t\t\t\tbreak;\n\t\t\tcase \"message_end\":\n\t\t\t\tthis.handleMessageEnd(event.message);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst component =\n\t\t\t\t\tthis.pendingTools.get(event.toolCallId) ??\n\t\t\t\t\tthis.createPendingToolComponent(event.toolName, event.toolCallId, event.args);\n\t\t\t\tcomponent.markExecutionStarted();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool_execution_update\": {\n\t\t\t\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult({ ...event.partialResult, isError: false }, true);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult({ ...event.result, isError: event.isError });\n\t\t\t\t\tthis.pendingTools.delete(event.toolCallId);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis.resetHookExecutionGrouping();\n\t\t\t\tthis.handleAgentEnd();\n\t\t\t\tbreak;\n\t\t\tcase \"agent_settled\":\n\t\t\t\tawait this.checkShutdownRequested();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\tcase \"compaction_start\":\n\t\t\t\tthis.resetHookExecutionGrouping();\n\t\t\t\tthis.handleCompactionStart(event);\n\t\t\t\tbreak;\n\t\t\tcase \"compaction_end\":\n\t\t\t\tthis.handleCompactionEnd(event);\n\t\t\t\tbreak;\n\t\t\tcase \"auto_retry_start\":\n\t\t\t\tthis.handleAutoRetryStart(event);\n\t\t\t\tbreak;\n\t\t\tcase \"auto_retry_end\":\n\t\t\t\tthis.handleAutoRetryEnd(event);\n\t\t\t\tbreak;\n\t\t\tcase \"summarization_retry_scheduled\":\n\t\t\t\tthis.handleSummarizationRetryScheduled(event);\n\t\t\t\tbreak;\n\t\t\tcase \"summarization_retry_attempt_start\":\n\t\t\t\tthis.handleSummarizationRetryAttemptStart(event);\n\t\t\t\tbreak;\n\t\t\tcase \"summarization_retry_finished\":\n\t\t\t\tthis.handleSummarizationRetryFinished();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/** Extract text content from a user message */\n\tprivate getUserMessageText(message: UserMessage): string {\n\t\tif (typeof message.content === \"string\") return message.content;\n\t\treturn message.content\n\t\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t\t.map((content) => content.text)\n\t\t\t.join(\"\");\n\t}\n\n\t/**\n\t * Show a status message in the chat.\n\t *\n\t * If multiple status messages are emitted back-to-back (without anything else being added to the chat),\n\t * we update the previous status line instead of appending new ones to avoid log spam.\n\t */\n\tprivate showStatus(message: string): void {\n\t\tconst children = this.chatContainer.children;\n\t\tconst last = children.length > 0 ? children[children.length - 1] : undefined;\n\t\tconst secondLast = children.length > 1 ? children[children.length - 2] : undefined;\n\n\t\tif (last && secondLast && last === this.lastStatusText && secondLast === this.lastStatusSpacer) {\n\t\t\tthis.lastStatusText.setText(theme.fg(\"dim\", message));\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tconst spacer = new Spacer(1);\n\t\tconst text = new Text(theme.fg(\"dim\", message), 1, 0);\n\t\tthis.chatContainer.addChild(spacer);\n\t\tthis.chatContainer.addChild(text);\n\t\tthis.lastStatusSpacer = spacer;\n\t\tthis.lastStatusText = text;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate addBashExecutionMessage(message: BashExecutionMessage): void {\n\t\tconst component = new BashExecutionComponent(message.command, this.ui, message.excludeFromContext);\n\t\tif (message.output) component.appendOutput(message.output);\n\t\tcomponent.setComplete(\n\t\t\tmessage.exitCode,\n\t\t\tmessage.cancelled,\n\t\t\tmessage.truncated ? ({ truncated: true } as TruncationResult) : undefined,\n\t\t\tmessage.fullOutputPath,\n\t\t);\n\t\tthis.chatContainer.addChild(component);\n\t}\n\n\tprivate addCustomMessage(message: CustomMessage): void {\n\t\tif (!message.display) return;\n\t\tif (message.customType === HOOK_EXECUTION_CUSTOM_TYPE) {\n\t\t\tconst notice = parseHookExecutionNotice(message.content);\n\t\t\tif (!notice) return;\n\t\t\tif (!this.appendHookExecutionNoticeToActiveGroup(notice)) this.addHookExecutionNoticeCard(notice);\n\t\t\treturn;\n\t\t}\n\t\tconst renderer = this.session.extensionRunner.getMessageRenderer(message.customType);\n\t\tconst component = new CustomMessageComponent(message, renderer, this.getMarkdownThemeWithSettings());\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(component);\n\t}\n\n\tprivate addCompactionSummaryMessage(message: CompactionSummaryMessage): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tconst component = new CompactionSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(component);\n\t}\n\n\tprivate addBranchSummaryMessage(message: BranchSummaryMessage): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tconst component = new BranchSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(component);\n\t}\n\n\tprivate createUserMessageComponent(text: string): UserMessageComponent {\n\t\treturn new UserMessageComponent(\n\t\t\ttext,\n\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\tthis.outputPad,\n\t\t\tthis.getMarkdownTransformers(),\n\t\t);\n\t}\n\n\tprivate addUserMessageContent(text: string): void {\n\t\tconst skillBlock = parseSkillBlock(text);\n\t\tif (!skillBlock) {\n\t\t\tthis.chatContainer.addChild(this.createUserMessageComponent(text));\n\t\t\treturn;\n\t\t}\n\t\tconst skillComponent = new SkillInvocationMessageComponent(skillBlock, this.getMarkdownThemeWithSettings());\n\t\tskillComponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(skillComponent);\n\t\tif (skillBlock.userMessage) {\n\t\t\tthis.chatContainer.addChild(this.createUserMessageComponent(skillBlock.userMessage));\n\t\t}\n\t}\n\n\tprivate addUserMessage(message: UserMessage, options?: AddMessageToChatOptions): void {\n\t\tconst textContent = this.getUserMessageText(message);\n\t\tif (!textContent) return;\n\t\tif (this.chatContainer.children.length > 0) this.chatContainer.addChild(new Spacer(1));\n\t\tthis.addUserMessageContent(textContent);\n\t\tif (options?.populateHistory) this.editor.addToHistory?.(textContent);\n\t}\n\n\tprivate addAssistantMessage(message: AssistantMessage): void {\n\t\tthis.chatContainer.addChild(\n\t\t\tnew AssistantMessageComponent(\n\t\t\t\tmessage,\n\t\t\t\tthis.hideThinkingBlock,\n\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\tthis.hiddenThinkingLabel,\n\t\t\t\tthis.outputPad,\n\t\t\t\tthis.getMarkdownTransformers(),\n\t\t\t),\n\t\t);\n\t}\n\n\tprivate addMessageToChat(message: AgentMessage, options?: AddMessageToChatOptions): void {\n\t\tswitch (message.role) {\n\t\t\tcase \"bashExecution\":\n\t\t\t\tthis.addBashExecutionMessage(message);\n\t\t\t\tbreak;\n\t\t\tcase \"custom\":\n\t\t\t\tthis.addCustomMessage(message);\n\t\t\t\tbreak;\n\t\t\tcase \"compactionSummary\":\n\t\t\t\tthis.addCompactionSummaryMessage(message);\n\t\t\t\tbreak;\n\t\t\tcase \"branchSummary\":\n\t\t\t\tthis.addBranchSummaryMessage(message);\n\t\t\t\tbreak;\n\t\t\tcase \"user\":\n\t\t\t\tthis.addUserMessage(message, options);\n\t\t\t\tbreak;\n\t\t\tcase \"assistant\":\n\t\t\t\tthis.addAssistantMessage(message);\n\t\t\t\tbreak;\n\t\t\tcase \"toolResult\":\n\t\t\t\tbreak;\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustive: never = message;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate renderTranscriptToolCall(toolCall: ToolCall): ToolExecutionComponent {\n\t\tconst component = new ToolExecutionComponent(\n\t\t\ttoolCall.name,\n\t\t\ttoolCall.id,\n\t\t\ttoolCall.arguments,\n\t\t\t{\n\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t},\n\t\t\tthis.getRegisteredToolDefinition(toolCall.name),\n\t\t\tthis.ui,\n\t\t\tthis.activeSession.getCwd(),\n\t\t);\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(component);\n\t\treturn component;\n\t}\n\n\tprivate getTranscriptToolFailure(message: AssistantMessage): string | undefined {\n\t\tif (message.stopReason === \"error\") return message.errorMessage || \"Error\";\n\t\tif (message.stopReason !== \"aborted\") return undefined;\n\t\tconst retryAttempt = this.session.retryAttempt;\n\t\tif (retryAttempt === 0) return \"Operation aborted\";\n\t\treturn `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? \"s\" : \"\"}`;\n\t}\n\n\tprivate renderAssistantTranscriptMessage(\n\t\tmessage: AssistantMessage,\n\t\tpendingTools: Map<string, ToolExecutionComponent>,\n\t): void {\n\t\tthis.addMessageToChat(message);\n\t\tconst failure = this.getTranscriptToolFailure(message);\n\t\tfor (const content of message.content) {\n\t\t\tif (content.type !== \"toolCall\") continue;\n\t\t\tconst component = this.renderTranscriptToolCall(content);\n\t\t\tif (failure !== undefined) {\n\t\t\t\tcomponent.updateResult({ content: [{ type: \"text\", text: failure }], isError: true });\n\t\t\t} else {\n\t\t\t\tpendingTools.set(content.id, component);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate applyTranscriptToolResult(\n\t\tmessage: ToolResultMessage,\n\t\tpendingTools: Map<string, ToolExecutionComponent>,\n\t): void {\n\t\tconst component = pendingTools.get(message.toolCallId);\n\t\tif (!component) return;\n\t\tcomponent.updateResult(message);\n\t\tpendingTools.delete(message.toolCallId);\n\t}\n\n\tprivate renderTranscriptMessage(\n\t\tmessage: AgentMessage,\n\t\tpendingTools: Map<string, ToolExecutionComponent>,\n\t\toptions: RenderSessionContextOptions,\n\t): void {\n\t\tif (message.role === \"assistant\") {\n\t\t\tthis.renderAssistantTranscriptMessage(message, pendingTools);\n\t\t\treturn;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tthis.applyTranscriptToolResult(message, pendingTools);\n\t\t\treturn;\n\t\t}\n\t\tthis.addMessageToChat(message, options);\n\t}\n\n\t/**\n\t * Render session context to chat. Used for initial load and rebuild after compaction.\n\t * @param sessionContext Session context to render\n\t * @param options.updateFooter Update footer state\n\t * @param options.populateHistory Add user messages to editor history\n\t */\n\tprivate renderSessionContext(sessionContext: SessionContext, options: RenderSessionContextOptions = {}): void {\n\t\tthis.pendingTools.clear();\n\t\tconst renderedPendingTools = new Map<string, ToolExecutionComponent>();\n\t\tif (options.updateFooter) {\n\t\t\tthis.footer.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t}\n\t\tfor (const message of sessionContext.messages) {\n\t\t\tif (message.role === \"user\" || message.role === \"assistant\") this.resetHookExecutionGrouping();\n\t\t\tthis.renderTranscriptMessage(message, renderedPendingTools, options);\n\t\t\tif (message.role === \"assistant\") this.hookExecutionTurnActive = true;\n\t\t}\n\t\tthis.resetHookExecutionGrouping();\n\t\tfor (const [toolCallId, component] of renderedPendingTools) {\n\t\t\tthis.pendingTools.set(toolCallId, component);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\trenderInitialMessages(): void {\n\t\tthis.transcriptRendered = true;\n\t\tthis.hookExecutionSession = this.activeSession;\n\t\tthis.hookExecutionNotices = [];\n\t\tthis.hookExecutionComponents = [];\n\t\tthis.resetHookExecutionGrouping();\n\t\t// Get aligned messages and entries from session context\n\t\tconst context = this.activeSession.buildSessionContext();\n\t\tthis.renderSessionContext(context, {\n\t\t\tupdateFooter: true,\n\t\t\tpopulateHistory: true,\n\t\t});\n\n\t\t// Show compaction info if session was compacted\n\t\tconst allEntries = this.activeSession.getEntries();\n\t\tconst compactionCount = allEntries.filter((e) => e.type === \"compaction\").length;\n\t\tif (compactionCount > 0) {\n\t\t\tconst times = compactionCount === 1 ? \"1 time\" : `${compactionCount} times`;\n\t\t\tthis.showStatus(`Session compacted ${times}`);\n\t\t}\n\t}\n\n\tasync getUserInput(): Promise<string> {\n\t\tconst queuedInput = this.pendingUserInputs.shift();\n\t\tif (queuedInput !== undefined) {\n\t\t\treturn queuedInput;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.onInputCallback = (text: string) => {\n\t\t\t\tthis.onInputCallback = undefined;\n\t\t\t\tresolve(text);\n\t\t\t};\n\t\t});\n\t}\n\n\tprivate rebuildChatFromMessages(): void {\n\t\tthis.chatContainer.clear();\n\t\tthis.hookExecutionSession = this.activeSession;\n\t\tthis.hookExecutionNotices = [];\n\t\tthis.hookExecutionComponents = [];\n\t\tthis.resetHookExecutionGrouping();\n\t\tconst context = this.activeSession.buildSessionContext();\n\t\tthis.renderSessionContext(context);\n\t}\n\n\t// =========================================================================\n\t// Key handlers\n\t// =========================================================================\n\n\tprivate handleCtrlC(): void {\n\t\tconst now = Date.now();\n\t\tif (now - this.lastSigintTime < 500) {\n\t\t\tvoid this.shutdown();\n\t\t} else {\n\t\t\tthis.clearEditor();\n\t\t\tthis.lastSigintTime = now;\n\t\t}\n\t}\n\n\tprivate handleCtrlD(): void {\n\t\t// Only called when editor is empty (enforced by CustomEditor)\n\t\tvoid this.shutdown();\n\t}\n\n\t/**\n\t * Gracefully shutdown the agent.\n\t * Stops the TUI before emitting shutdown events so extension UI cleanup cannot\n\t * repaint the final frame while the process is exiting.\n\t */\n\tprivate isShuttingDown = false;\n\n\tprivate async shutdown(options?: ShutdownOptions): Promise<void> {\n\t\tif (this.isShuttingDown) return;\n\t\tthis.isShuttingDown = true;\n\t\tthis.unregisterSignalHandlers();\n\n\t\tif (options?.fromSignal) {\n\t\t\t// Signal-triggered shutdown (SIGTERM/SIGHUP). Emit extension cleanup\n\t\t\t// (session_shutdown) BEFORE touching the terminal. Extension teardown\n\t\t\t// such as removing sockets does not write to the tty, so it must not be\n\t\t\t// skipped if a later terminal-restore write fails on a dead or stalled\n\t\t\t// terminal. If the terminal is gone, the restore writes below emit EIO,\n\t\t\t// which the stdout/stderr error handler turns into emergencyTerminalExit;\n\t\t\t// the render loop is already idle, so this cannot hot-spin (see #4144).\n\t\t\tconst shutdownErrors = await this.disposeRuntimeResources();\n\t\t\tawait this.ui.terminal.drainInput(1000);\n\t\t\tthis.stop(this.settingsManager.getFullscreenExitOutput());\n\t\t\tfor (const error of shutdownErrors) console.error(\"Grip shutdown cleanup failed:\", error);\n\t\t\tprocess.exit(0);\n\t\t}\n\n\t\t// Interactive quit (Ctrl+D, Ctrl+C, /quit, extension shutdown()). Stop the\n\t\t// TUI before emitting shutdown events so extension UI cleanup cannot repaint\n\t\t// the final frame while the process is exiting.\n\t\t// Drain any in-flight Kitty key release events before stopping.\n\t\t// This prevents escape sequences from leaking to the parent shell over slow SSH.\n\t\tawait this.ui.terminal.drainInput(1000);\n\n\t\tthis.stop(this.settingsManager.getFullscreenExitOutput());\n\t\tconst shutdownErrors = await this.disposeRuntimeResources();\n\t\tfor (const error of shutdownErrors) console.error(\"Grip shutdown cleanup failed:\", error);\n\t\tprocess.exit(0);\n\t}\n\n\tprivate emergencyTerminalExit(): never {\n\t\tthis.isShuttingDown = true;\n\t\tthis.unregisterSignalHandlers();\n\t\tkillTrackedDetachedChildren();\n\t\t// The terminal is gone. Do not run normal shutdown because TUI and\n\t\t// extension cleanup can write restore sequences and re-trigger EIO.\n\t\tprocess.exit(129);\n\t}\n\n\t/**\n\t * Last-resort handler for uncaught exceptions. The TUI puts stdin into raw\n\t * mode and hides the cursor; without this handler, an uncaught throw from\n\t * anywhere (e.g. an extension's async `ChildProcess.on(\"exit\")` callback)\n\t * tears down the process while leaving the terminal in raw mode with no\n\t * cursor, requiring `stty sane && reset` to recover.\n\t *\n\t * Unlike emergencyTerminalExit, the terminal is still alive here, so we\n\t * call ui.stop() to restore cooked mode, the cursor, and disable bracketed\n\t * paste / Kitty / modifyOtherKeys sequences.\n\t */\n\tprivate uncaughtCrash(error: Error): never {\n\t\tif (this.isShuttingDown) {\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tthis.isShuttingDown = true;\n\t\ttry {\n\t\t\tthis.unregisterSignalHandlers();\n\t\t} catch {}\n\t\ttry {\n\t\t\tkillTrackedDetachedChildren();\n\t\t} catch {}\n\t\ttry {\n\t\t\tthis.stopInteractiveTui(\"transcript\");\n\t\t} catch {}\n\t\tconsole.error(\"grip exiting due to uncaughtException:\");\n\t\tconsole.error(error);\n\t\tprocess.exit(1);\n\t}\n\n\t/**\n\t * Check if shutdown was requested and perform shutdown if so.\n\t */\n\tprivate async checkShutdownRequested(): Promise<void> {\n\t\tif (!this.shutdownRequested) return;\n\t\tawait this.shutdown();\n\t}\n\n\tprivate registerSignalHandlers(): void {\n\t\tthis.unregisterSignalHandlers();\n\n\t\tconst signals: NodeJS.Signals[] = [\"SIGTERM\"];\n\t\tif (process.platform !== \"win32\") {\n\t\t\tsignals.push(\"SIGHUP\");\n\t\t}\n\n\t\tfor (const signal of signals) {\n\t\t\tconst handler = () => {\n\t\t\t\t// SIGHUP no longer hard-exits: graceful shutdown emits session_shutdown\n\t\t\t\t// first, then attempts terminal restore. A genuinely dead terminal\n\t\t\t\t// surfaces as an EIO on the restore writes, which the stdout/stderr\n\t\t\t\t// error handler converts into emergencyTerminalExit (see #4144, #5080).\n\t\t\t\tkillTrackedDetachedChildren();\n\t\t\t\tvoid this.shutdown({ fromSignal: true });\n\t\t\t};\n\t\t\tprocess.prependListener(signal, handler);\n\t\t\tthis.signalCleanupHandlers.push(() => process.off(signal, handler));\n\t\t}\n\n\t\tconst terminalErrorHandler = (error: Error) => {\n\t\t\tif (isDeadTerminalError(error)) {\n\t\t\t\tthis.emergencyTerminalExit();\n\t\t\t}\n\t\t\tthrow error;\n\t\t};\n\t\tprocess.stdout.on(\"error\", terminalErrorHandler);\n\t\tprocess.stderr.on(\"error\", terminalErrorHandler);\n\t\tthis.signalCleanupHandlers.push(() => process.stdout.off(\"error\", terminalErrorHandler));\n\t\tthis.signalCleanupHandlers.push(() => process.stderr.off(\"error\", terminalErrorHandler));\n\n\t\t// Restore the terminal before the process dies on any uncaught throw.\n\t\t// Without this, an unhandled exception from extension code (or anywhere\n\t\t// in grip) leaves the terminal in raw mode with no cursor.\n\t\tconst uncaughtExceptionHandler = (error: Error) => this.uncaughtCrash(error);\n\t\tprocess.prependListener(\"uncaughtException\", uncaughtExceptionHandler);\n\t\tthis.signalCleanupHandlers.push(() => process.off(\"uncaughtException\", uncaughtExceptionHandler));\n\t}\n\n\tprivate unregisterSignalHandlers(): void {\n\t\tfor (const cleanup of this.signalCleanupHandlers) {\n\t\t\tcleanup();\n\t\t}\n\t\tthis.signalCleanupHandlers = [];\n\t}\n\n\tprivate handleCtrlZ(): void {\n\t\tif (process.platform === \"win32\") {\n\t\t\tthis.showStatus(\"Suspend to background is not supported on Windows\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Keep the event loop alive while suspended. Without this, stopping the TUI\n\t\t// can leave Node with no ref'ed handles, causing the process to exit on fg\n\t\t// before the SIGCONT handler gets a chance to restore the terminal.\n\t\tconst suspendKeepAlive = setInterval(() => {}, 2 ** 30);\n\n\t\t// Ignore SIGINT while suspended so Ctrl+C in the terminal does not\n\t\t// kill the backgrounded process. The handler is removed on resume.\n\t\tconst ignoreSigint = () => {};\n\t\tprocess.on(\"SIGINT\", ignoreSigint);\n\n\t\t// Set up handler to restore TUI when resumed\n\t\tprocess.once(\"SIGCONT\", () => {\n\t\t\tclearInterval(suspendKeepAlive);\n\t\t\tprocess.removeListener(\"SIGINT\", ignoreSigint);\n\t\t\tthis.ui.start();\n\t\t\tthis.ui.requestRender(true);\n\t\t});\n\n\t\ttry {\n\t\t\t// Stop the TUI (restore terminal to normal mode)\n\t\t\tthis.ui.stop({ preserveScreen: true });\n\n\t\t\t// Send SIGTSTP to process group (pid=0 means all processes in group)\n\t\t\tprocess.kill(0, \"SIGTSTP\");\n\t\t} catch (error) {\n\t\t\tclearInterval(suspendKeepAlive);\n\t\t\tprocess.removeListener(\"SIGINT\", ignoreSigint);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async handleFollowUp(): Promise<void> {\n\t\tconst text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();\n\t\tif (!text) return;\n\n\t\t// Queue input during compaction (extension commands execute immediately)\n\t\tif (this.session.isCompacting) {\n\t\t\tif (this.isExtensionCommand(text)) {\n\t\t\t\tthis.editor.addToHistory?.(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.session.prompt(text);\n\t\t\t} else {\n\t\t\t\tthis.queueCompactionMessage(text, \"followUp\");\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Alt+Enter queues a follow-up message (waits until agent finishes)\n\t\t// This handles extension commands (execute immediately), prompt template expansion, and queueing\n\t\tif (this.session.isStreaming) {\n\t\t\tthis.editor.addToHistory?.(text);\n\t\t\tthis.editor.setText(\"\");\n\t\t\tawait this.session.prompt(text, { streamingBehavior: \"followUp\" });\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tthis.ui.requestRender();\n\t\t}\n\t\t// If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)\n\t\telse if (this.editor.onSubmit) {\n\t\t\tthis.editor.setText(\"\");\n\t\t\tthis.editor.onSubmit(text);\n\t\t}\n\t}\n\n\tprivate handleDequeue(): void {\n\t\tconst restored = this.restoreQueuedMessagesToEditor();\n\t\tif (restored === 0) {\n\t\t\tthis.showStatus(\"No queued messages to restore\");\n\t\t} else {\n\t\t\tthis.showStatus(`Restored ${restored} queued message${restored > 1 ? \"s\" : \"\"} to editor`);\n\t\t}\n\t}\n\n\tprivate updateEditorBorderColor(): void {\n\t\tif (this.isBashMode) {\n\t\t\tthis.editor.borderColor = theme.getBashModeBorderColor();\n\t\t} else {\n\t\t\tconst level = this.session.thinkingLevel || \"off\";\n\t\t\tthis.editor.borderColor = theme.getThinkingBorderColor(level);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate cycleThinkingLevel(): void {\n\t\tconst newLevel = this.session.cycleThinkingLevel();\n\t\tif (newLevel === undefined) {\n\t\t\tthis.showStatus(\"Current model does not support thinking\");\n\t\t} else {\n\t\t\tthis.footer.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.showStatus(`Thinking level: ${newLevel}`);\n\t\t}\n\t}\n\n\tprivate async cycleModel(direction: ModelCycleDirection): Promise<void> {\n\t\ttry {\n\t\t\tconst result = await this.session.cycleModel(direction);\n\t\t\tif (result === undefined) {\n\t\t\t\tconst msg = this.session.scopedModels.length > 0 ? \"Only one model in scope\" : \"Only one model available\";\n\t\t\t\tthis.showStatus(msg);\n\t\t\t} else {\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tconst thinkingStr =\n\t\t\t\t\tresult.model.reasoning && result.thinkingLevel !== \"off\" ? ` (thinking: ${result.thinkingLevel})` : \"\";\n\t\t\t\tthis.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`);\n\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(result.model);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate toggleToolOutputExpansion(): void {\n\t\tthis.setToolsExpanded(!this.toolOutputExpanded);\n\t}\n\n\tprivate setToolsExpanded(expanded: boolean): void {\n\t\tthis.toolOutputExpanded = expanded;\n\t\tconst activeHeader = this.customHeader ?? this.builtInHeader;\n\t\tif (isExpandable(activeHeader)) {\n\t\t\tactiveHeader.setExpanded(expanded);\n\t\t}\n\t\tconst expandableContainers = this.loadedResourcesContainer\n\t\t\t? [this.loadedResourcesContainer, this.chatContainer]\n\t\t\t: [this.chatContainer];\n\t\tfor (const container of expandableContainers) {\n\t\t\tfor (const child of container.children) {\n\t\t\t\tif (isExpandable(child)) {\n\t\t\t\t\tchild.setExpanded(expanded);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate toggleThinkingBlockVisibility(): void {\n\t\tthis.hideThinkingBlock = !this.hideThinkingBlock;\n\t\tthis.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);\n\n\t\t// Rebuild chat from session messages\n\t\tthis.chatContainer.clear();\n\t\tthis.rebuildChatFromMessages();\n\n\t\t// If streaming, re-add the streaming component with updated visibility and re-render\n\t\tif (this.streamingComponent && this.streamingMessage) {\n\t\t\tthis.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);\n\t\t\tthis.streamingComponent.updateContent(this.streamingMessage);\n\t\t\tthis.chatContainer.addChild(this.streamingComponent);\n\t\t}\n\n\t\tthis.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? \"hidden\" : \"visible\"}`);\n\t}\n\n\tprivate async openExternalEditor(): Promise<void> {\n\t\tconst editorCmd = this.settingsManager.getExternalEditorCommand();\n\t\tif (!editorCmd) {\n\t\t\tthis.showWarning(\"No editor configured. Set externalEditor in settings.json or $VISUAL/$EDITOR.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst currentText = this.editor.getExpandedText?.() ?? this.editor.getText();\n\t\tconst tmpFile = path.join(os.tmpdir(), `grip-editor-${Date.now()}.grip.md`);\n\n\t\ttry {\n\t\t\t// Write current content to temp file\n\t\t\tfs.writeFileSync(tmpFile, currentText, \"utf-8\");\n\n\t\t\t// Stop TUI to release terminal\n\t\t\tthis.ui.stop({ preserveScreen: true });\n\n\t\t\t// Split by space to support editor arguments (e.g., \"code --wait\")\n\t\t\tconst [editor, ...editorArgs] = editorCmd.split(\" \");\n\n\t\t\tprocess.stdout.write(`Launching external editor: ${editorCmd}\\nGrip will resume when the editor exits.\\n`);\n\n\t\t\t// Do not use spawnSync here. On Windows, synchronous child_process calls can keep\n\t\t\t// Node/libuv's console input read active after ui.stop() pauses stdin, racing\n\t\t\t// vim/nvim for the console input buffer until Ctrl+C cancels the pending read.\n\t\t\tconst status = await new Promise<number | null>((resolve) => {\n\t\t\t\tconst child = spawn(editor, [...editorArgs, tmpFile], {\n\t\t\t\t\tstdio: \"inherit\",\n\t\t\t\t\tshell: process.platform === \"win32\",\n\t\t\t\t});\n\t\t\t\tchild.on(\"error\", () => resolve(null));\n\t\t\t\tchild.on(\"close\", (code) => resolve(code));\n\t\t\t});\n\n\t\t\t// On successful exit (status 0), replace editor content\n\t\t\tif (status === 0) {\n\t\t\t\tconst newContent = fs.readFileSync(tmpFile, \"utf-8\").replace(/\\n$/, \"\");\n\t\t\t\tthis.editor.setText(newContent);\n\t\t\t}\n\t\t\t// On non-zero exit, keep original text (no action needed)\n\t\t} finally {\n\t\t\t// Clean up temp file\n\t\t\ttry {\n\t\t\t\tfs.unlinkSync(tmpFile);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\n\t\t\t// Restart TUI\n\t\t\tthis.ui.start();\n\t\t\t// Force full re-render since external editor uses alternate screen\n\t\t\tthis.ui.requestRender(true);\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// UI helpers\n\t// =========================================================================\n\n\tclearEditor(): void {\n\t\tthis.editor.setText(\"\");\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowError(errorMessage: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"error\", `Error: ${errorMessage}`), 1, 0));\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowWarning(warningMessage: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"warning\", `Warning: ${warningMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowNewVersionNotification(release: LatestGripRelease): void {\n\t\tconst action = theme.fg(\"accent\", `${APP_NAME} update`);\n\t\tconst updateInstruction =\n\t\t\ttheme.fg(\"muted\", `New ${PACKAGE_NAME} version ${release.version} is available. Run `) + action;\n\t\tconst changelogUrl = \"https://github.com/greppleai/grip/blob/main/packages/coding-agent/CHANGELOG.md\";\n\t\tconst changelogLink = getCapabilities().hyperlinks\n\t\t\t? hyperlink(theme.fg(\"accent\", \"open changelog\"), changelogUrl)\n\t\t\t: theme.fg(\"accent\", changelogUrl);\n\t\tconst changelogLine = theme.fg(\"muted\", \"Changelog: \") + changelogLink;\n\t\tconst note = release.note?.trim();\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(`${theme.bold(theme.fg(\"warning\", \"Update Available\"))}\\n${updateInstruction}`, 1, 0),\n\t\t);\n\t\tif (note) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Markdown(note, 1, 0, this.getMarkdownThemeWithSettings(), {\n\t\t\t\t\tcolor: (text) => theme.fg(\"muted\", text),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new Text(changelogLine, 1, 0));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowPackageUpdateNotification(packages: string[]): void {\n\t\tconst action = theme.fg(\"accent\", `${APP_NAME} update`);\n\t\tconst updateInstruction = theme.fg(\"muted\", \"Package updates are available. Run \") + action;\n\t\tconst packageLines = packages.map((pkg) => `- ${pkg}`).join(\"\\n\");\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(\n\t\t\t\t`${theme.bold(theme.fg(\"warning\", \"Package Updates Available\"))}\\n${updateInstruction}\\n${theme.fg(\"muted\", \"Packages:\")}\\n${packageLines}`,\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Get all queued messages (read-only).\n\t * Combines session queue and compaction queue.\n\t */\n\tprivate getAllQueuedMessages(): QueuedMessages {\n\t\treturn {\n\t\t\tsteering: [\n\t\t\t\t...this.session.getSteeringMessages(),\n\t\t\t\t...this.compactionQueuedMessages.filter((msg) => msg.mode === \"steer\").map((msg) => msg.text),\n\t\t\t],\n\t\t\tfollowUp: [\n\t\t\t\t...this.session.getFollowUpMessages(),\n\t\t\t\t...this.compactionQueuedMessages.filter((msg) => msg.mode === \"followUp\").map((msg) => msg.text),\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Clear all queued messages and return their contents.\n\t * Clears both session queue and compaction queue.\n\t */\n\tprivate clearAllQueues(): QueuedMessages {\n\t\tconst { steering, followUp } = this.session.clearQueue();\n\t\tconst compactionSteering = this.compactionQueuedMessages\n\t\t\t.filter((msg) => msg.mode === \"steer\")\n\t\t\t.map((msg) => msg.text);\n\t\tconst compactionFollowUp = this.compactionQueuedMessages\n\t\t\t.filter((msg) => msg.mode === \"followUp\")\n\t\t\t.map((msg) => msg.text);\n\t\tthis.compactionQueuedMessages = [];\n\t\treturn {\n\t\t\tsteering: [...steering, ...compactionSteering],\n\t\t\tfollowUp: [...followUp, ...compactionFollowUp],\n\t\t};\n\t}\n\n\tprivate updatePendingMessagesDisplay(): void {\n\t\tthis.pendingMessagesContainer.clear();\n\t\tconst { steering: steeringMessages, followUp: followUpMessages } = this.getAllQueuedMessages();\n\t\tif (steeringMessages.length > 0 || followUpMessages.length > 0) {\n\t\t\tthis.pendingMessagesContainer.addChild(new Spacer(1));\n\t\t\tfor (const message of steeringMessages) {\n\t\t\t\tconst text = theme.fg(\"dim\", `Steering: ${message}`);\n\t\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));\n\t\t\t}\n\t\t\tfor (const message of followUpMessages) {\n\t\t\t\tconst text = theme.fg(\"dim\", `Follow-up: ${message}`);\n\t\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));\n\t\t\t}\n\t\t\tconst dequeueHint = this.getAppKeyDisplay(\"app.message.dequeue\");\n\t\t\tconst hintText = theme.fg(\"dim\", `↳ ${dequeueHint} to edit all queued messages`);\n\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));\n\t\t}\n\t}\n\n\tprivate restoreQueuedMessagesToEditor(options?: RestoreQueuedMessagesOptions): number {\n\t\tconst { steering, followUp } = this.clearAllQueues();\n\t\tconst allQueued = [...steering, ...followUp];\n\t\tif (allQueued.length === 0) {\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tif (options?.abort) {\n\t\t\t\tthis.agent.abort();\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tconst queuedText = allQueued.join(\"\\n\\n\");\n\t\tconst currentText = options?.currentText ?? this.editor.getText();\n\t\tconst combinedText = [queuedText, currentText].filter((t) => t.trim()).join(\"\\n\\n\");\n\t\tthis.editor.setText(combinedText);\n\t\tthis.updatePendingMessagesDisplay();\n\t\tif (options?.abort) {\n\t\t\tthis.agent.abort();\n\t\t}\n\t\treturn allQueued.length;\n\t}\n\n\tprivate queueCompactionMessage(text: string, mode: StreamingBehavior): void {\n\t\tthis.compactionQueuedMessages.push({ text, mode });\n\t\tthis.editor.addToHistory?.(text);\n\t\tthis.editor.setText(\"\");\n\t\tthis.updatePendingMessagesDisplay();\n\t\tthis.showStatus(\"Queued message for after compaction\");\n\t}\n\n\tprivate isExtensionCommand(text: string): boolean {\n\t\tif (!text.startsWith(\"/\")) return false;\n\n\t\tconst extensionRunner = this.session.extensionRunner;\n\n\t\tconst spaceIndex = text.indexOf(\" \");\n\t\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\t\treturn !!extensionRunner.getCommand(commandName);\n\t}\n\n\tprivate async sendQueuedCompactionMessage(message: CompactionQueuedMessage): Promise<void> {\n\t\tif (this.isExtensionCommand(message.text)) {\n\t\t\tawait this.session.prompt(message.text);\n\t\t} else if (message.mode === \"followUp\") {\n\t\t\tawait this.session.followUp(message.text);\n\t\t} else {\n\t\t\tawait this.session.steer(message.text);\n\t\t}\n\t}\n\n\tprivate restoreCompactionQueue(queuedMessages: CompactionQueuedMessage[], error: unknown): void {\n\t\tthis.session.clearQueue();\n\t\tthis.compactionQueuedMessages = queuedMessages;\n\t\tthis.updatePendingMessagesDisplay();\n\t\tthis.showError(\n\t\t\t`Failed to send queued message${queuedMessages.length > 1 ? \"s\" : \"\"}: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n\n\tprivate async flushNewCompactionQueue(queuedMessages: CompactionQueuedMessage[]): Promise<void> {\n\t\tconst firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text));\n\t\tif (firstPromptIndex === -1) {\n\t\t\tfor (const message of queuedMessages) await this.session.prompt(message.text);\n\t\t\treturn;\n\t\t}\n\t\tconst preCommands = queuedMessages.slice(0, firstPromptIndex);\n\t\tconst firstPrompt = queuedMessages[firstPromptIndex];\n\t\tconst rest = queuedMessages.slice(firstPromptIndex + 1);\n\t\tfor (const message of preCommands) await this.session.prompt(message.text);\n\t\tconst promptPromise = this.session.prompt(firstPrompt.text).catch((error) => {\n\t\t\tthis.restoreCompactionQueue(queuedMessages, error);\n\t\t});\n\t\tfor (const message of rest) await this.sendQueuedCompactionMessage(message);\n\t\tthis.updatePendingMessagesDisplay();\n\t\tvoid promptPromise;\n\t}\n\n\tprivate async flushCompactionQueue(options?: FlushCompactionQueueOptions): Promise<void> {\n\t\tif (this.compactionQueuedMessages.length === 0) return;\n\t\tconst queuedMessages = [...this.compactionQueuedMessages];\n\t\tthis.compactionQueuedMessages = [];\n\t\tthis.updatePendingMessagesDisplay();\n\t\ttry {\n\t\t\tif (options?.willRetry) {\n\t\t\t\t// When retry is pending, queue messages for the retry turn.\n\t\t\t\tfor (const message of queuedMessages) await this.sendQueuedCompactionMessage(message);\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.flushNewCompactionQueue(queuedMessages);\n\t\t} catch (error) {\n\t\t\tthis.restoreCompactionQueue(queuedMessages, error);\n\t\t}\n\t}\n\n\t/** Move pending bash components from pending area to chat */\n\tprivate flushPendingBashComponents(): void {\n\t\tfor (const component of this.pendingBashComponents) {\n\t\t\tthis.pendingMessagesContainer.removeChild(component);\n\t\t\tthis.chatContainer.addChild(component);\n\t\t}\n\t\tthis.pendingBashComponents = [];\n\t}\n\n\t// =========================================================================\n\t// Selectors\n\t// =========================================================================\n\n\t/**\n\t * Shows a selector component in place of the editor.\n\t * @param create Factory that receives a `done` callback and returns the component and focus target\n\t */\n\tprivate showSelector(create: SelectorFactory): void {\n\t\tconst done = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t};\n\t\tconst { component, focus } = create(done);\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(component);\n\t\tthis.ui.setFocus(focus);\n\t\tthis.ui.requestRender();\n\t}\n\tprivate updateOutputPad(padding: number): void {\n\t\tthis.settingsManager.setOutputPad(padding);\n\t\tthis.outputPad = padding;\n\t\tif (!this.streamingComponent && !this.session.isStreaming) {\n\t\t\tthis.rebuildChatFromMessages();\n\t\t\treturn;\n\t\t}\n\t\tfor (const child of this.chatContainer.children) {\n\t\t\tif (child instanceof AssistantMessageComponent || child instanceof UserMessageComponent) {\n\t\t\t\tchild.setOutputPad(padding);\n\t\t\t}\n\t\t}\n\t\tthis.streamingComponent?.setOutputPad(padding);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate showSettingsSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tlet selector: SettingsSelectorComponent | undefined;\n\t\t\tselector = new SettingsSelectorComponent(\n\t\t\t\t{\n\t\t\t\t\tautoCompact: this.session.autoCompactionEnabled,\n\t\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t\t\tautoResizeImages: this.settingsManager.getImageAutoResize(),\n\t\t\t\t\tblockImages: this.settingsManager.getBlockImages(),\n\t\t\t\t\tenableSkillCommands: this.settingsManager.getEnableSkillCommands(),\n\t\t\t\t\tenableSubagents: this.session.subagentsEnabled,\n\t\t\t\t\tsteeringMode: this.session.steeringMode,\n\t\t\t\t\tfollowUpMode: this.session.followUpMode,\n\t\t\t\t\ttransport: this.settingsManager.getTransport(),\n\t\t\t\t\tthinkingLevel: this.session.thinkingLevel,\n\t\t\t\t\tavailableThinkingLevels: this.session.getAvailableThinkingLevels(),\n\t\t\t\t\tcurrentTheme: this.settingsManager.getTheme() || \"dark\",\n\t\t\t\t\tavailableThemes: getAvailableThemes(),\n\t\t\t\t\thideThinkingBlock: this.hideThinkingBlock,\n\t\t\t\t\tmermaidRenderingMode: this.settingsManager.getMermaidRenderingMode(),\n\t\t\t\t\tcollapseChangelog: this.settingsManager.getCollapseChangelog(),\n\t\t\t\t\tenableInstallTelemetry: this.settingsManager.getEnableInstallTelemetry(),\n\t\t\t\t\tdoubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),\n\t\t\t\t\ttreeFilterMode: this.settingsManager.getTreeFilterMode(),\n\t\t\t\t\tshowHardwareCursor: this.settingsManager.getShowHardwareCursor(),\n\t\t\t\t\teditorPaddingX: this.settingsManager.getEditorPaddingX(),\n\t\t\t\t\toutputPad: this.settingsManager.getOutputPad(),\n\t\t\t\t\tautocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(),\n\t\t\t\t\tquietStartup: this.settingsManager.getQuietStartup(),\n\t\t\t\t\tclearOnShrink: this.settingsManager.getClearOnShrink(),\n\t\t\t\t\tshowTerminalProgress: this.settingsManager.getShowTerminalProgress(),\n\t\t\t\t\ttuiMode: this.ui.mode,\n\t\t\t\t\tfullscreenExitOutput: this.settingsManager.getFullscreenExitOutput(),\n\t\t\t\t\tfullscreenScrollbar: this.settingsManager.getFullscreenScrollbar(),\n\t\t\t\t\thttpIdleTimeoutMs: this.settingsManager.getHttpIdleTimeoutMs(),\n\t\t\t\t\twarnings: this.settingsManager.getWarnings(),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonAutoCompactChange: (enabled) => {\n\t\t\t\t\t\tthis.session.setAutoCompactionEnabled(enabled);\n\t\t\t\t\t\tthis.footer.setAutoCompactEnabled(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonShowImagesChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowImages(enabled);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof ToolExecutionComponent) {\n\t\t\t\t\t\t\t\tchild.setShowImages(enabled);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonImageWidthCellsChange: (width) => {\n\t\t\t\t\t\tthis.settingsManager.setImageWidthCells(width);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof ToolExecutionComponent) {\n\t\t\t\t\t\t\t\tchild.setImageWidthCells(width);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonAutoResizeImagesChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setImageAutoResize(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonBlockImagesChange: (blocked) => {\n\t\t\t\t\t\tthis.settingsManager.setBlockImages(blocked);\n\t\t\t\t\t},\n\t\t\t\t\tonEnableSkillCommandsChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setEnableSkillCommands(enabled);\n\t\t\t\t\t\tthis.setupAutocompleteProvider();\n\t\t\t\t\t},\n\t\t\t\t\tonEnableSubagentsChange: (enabled) => {\n\t\t\t\t\t\tthis.session.setSubagentsEnabled(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonSteeringModeChange: (mode) => {\n\t\t\t\t\t\tthis.session.setSteeringMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonFollowUpModeChange: (mode) => {\n\t\t\t\t\t\tthis.session.setFollowUpMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonTransportChange: (transport) => {\n\t\t\t\t\t\tthis.settingsManager.setTransport(transport);\n\t\t\t\t\t\tthis.session.agent.transport = transport;\n\t\t\t\t\t},\n\t\t\t\t\tonThinkingLevelChange: (level) => {\n\t\t\t\t\t\tthis.session.setThinkingLevel(level);\n\t\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\t},\n\t\t\t\t\tonThemeChange: (themeName) => {\n\t\t\t\t\t\tconst result = setTheme(themeName, true);\n\t\t\t\t\t\tthis.settingsManager.setTheme(themeName);\n\t\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\t\tthis.showError(`Failed to load theme \"${themeName}\": ${result.error}\\nFell back to dark theme.`);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonThemePreview: (themeName) => {\n\t\t\t\t\t\tconst result = setTheme(themeName, true);\n\t\t\t\t\t\tif (result.success) {\n\t\t\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonHideThinkingBlockChange: (hidden) => {\n\t\t\t\t\t\tthis.hideThinkingBlock = hidden;\n\t\t\t\t\t\tthis.settingsManager.setHideThinkingBlock(hidden);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof AssistantMessageComponent) {\n\t\t\t\t\t\t\t\tchild.setHideThinkingBlock(hidden);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\t},\n\t\t\t\t\tonMermaidRenderingModeChange: (mode) => {\n\t\t\t\t\t\tthis.settingsManager.setMermaidRenderingMode(mode);\n\t\t\t\t\t\tthis.chatContainer.invalidate();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t},\n\t\t\t\t\tonCollapseChangelogChange: (collapsed) => {\n\t\t\t\t\t\tthis.settingsManager.setCollapseChangelog(collapsed);\n\t\t\t\t\t},\n\t\t\t\t\tonEnableInstallTelemetryChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setEnableInstallTelemetry(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonQuietStartupChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setQuietStartup(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonDoubleEscapeActionChange: (action) => {\n\t\t\t\t\t\tthis.settingsManager.setDoubleEscapeAction(action);\n\t\t\t\t\t},\n\t\t\t\t\tonTreeFilterModeChange: (mode) => {\n\t\t\t\t\t\tthis.settingsManager.setTreeFilterMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonShowHardwareCursorChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowHardwareCursor(enabled);\n\t\t\t\t\t\tthis.ui.setShowHardwareCursor(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonEditorPaddingXChange: (padding) => {\n\t\t\t\t\t\tthis.settingsManager.setEditorPaddingX(padding);\n\t\t\t\t\t\tthis.defaultEditor.setPaddingX(padding);\n\t\t\t\t\t\tif (this.editor !== this.defaultEditor && this.editor.setPaddingX !== undefined) {\n\t\t\t\t\t\t\tthis.editor.setPaddingX(padding);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonOutputPadChange: (padding) => this.updateOutputPad(padding),\n\t\t\t\t\tonAutocompleteMaxVisibleChange: (maxVisible) => {\n\t\t\t\t\t\tthis.settingsManager.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\tthis.defaultEditor.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\tif (this.editor !== this.defaultEditor && this.editor.setAutocompleteMaxVisible !== undefined) {\n\t\t\t\t\t\t\tthis.editor.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonClearOnShrinkChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setClearOnShrink(enabled);\n\t\t\t\t\t\tthis.ui.setClearOnShrink(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonShowTerminalProgressChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowTerminalProgress(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonTuiModeChange: (mode) => {\n\t\t\t\t\t\tif (!this.switchTuiMode(mode)) {\n\t\t\t\t\t\t\tselector?.getSettingsList().updateValue(\"tui-mode\", this.ui.mode);\n\t\t\t\t\t\t\tthis.showStatus(\"Close active overlays before changing TUI mode\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.settingsManager.setTuiMode(mode);\n\t\t\t\t\t\tthis.showStatus(`TUI mode: ${mode}`);\n\t\t\t\t\t},\n\t\t\t\t\tonFullscreenExitOutputChange: (output) => {\n\t\t\t\t\t\tthis.settingsManager.setFullscreenExitOutput(output);\n\t\t\t\t\t},\n\t\t\t\t\tonFullscreenScrollbarChange: (mode) => {\n\t\t\t\t\t\tthis.settingsManager.setFullscreenScrollbar(mode);\n\t\t\t\t\t\tthis.transcriptScrollView?.setScrollbar(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonHttpIdleTimeoutMsChange: (timeoutMs) => {\n\t\t\t\t\t\tthis.settingsManager.setHttpIdleTimeoutMs(timeoutMs);\n\t\t\t\t\t},\n\t\t\t\t\tonWarningsChange: (warnings) => {\n\t\t\t\t\t\tthis.settingsManager.setWarnings(warnings);\n\t\t\t\t\t},\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSettingsList() };\n\t\t});\n\t}\n\n\tprivate async handleModelCommand(searchTerm?: string): Promise<void> {\n\t\tif (!searchTerm) {\n\t\t\tthis.showModelSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst model = await this.findExactModelMatch(searchTerm);\n\t\tif (model) {\n\t\t\ttry {\n\t\t\t\tawait this.session.setModel(model);\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tthis.showStatus(`Model: ${model.id}`);\n\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(model);\n\t\t\t} catch (error) {\n\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showModelSelector(searchTerm);\n\t}\n\tprivate async handleCompressionDetectionModelCommand(searchTerm: string): Promise<void> {\n\t\tif ([\"clear\", \"off\", \"none\"].includes(searchTerm.toLowerCase())) {\n\t\t\tthis.session.setCompressionDetectionModel(undefined);\n\t\t\tthis.showStatus(\"Background compression detection disabled\");\n\t\t\treturn;\n\t\t}\n\t\tif (searchTerm) {\n\t\t\tthis.session.modelRegistry.refresh();\n\t\t\tconst model = findExactModelReferenceMatch(searchTerm, this.session.modelRegistry.getAvailable());\n\t\t\tif (model) {\n\t\t\t\tthis.session.setCompressionDetectionModel(`${model.provider}/${model.id}`);\n\t\t\t\tthis.showStatus(`Compression detection model: ${model.provider}/${model.id}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tconst reference = this.settingsManager.getCompressionDetectionModel();\n\t\tconst [provider, ...idParts] = reference?.split(\"/\") ?? [];\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ModelSelectorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.session.modelRegistry.find(provider, idParts.join(\"/\")),\n\t\t\t\tthis.settingsManager,\n\t\t\t\tthis.session.modelRegistry,\n\t\t\t\t[],\n\t\t\t\t(model) => {\n\t\t\t\t\tthis.session.setCompressionDetectionModel(`${model.provider}/${model.id}`);\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(`Compression detection model: ${model.provider}/${model.id}`);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tsearchTerm || undefined,\n\t\t\t\tfalse,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async findExactModelMatch(searchTerm: string): Promise<Model<any> | undefined> {\n\t\tconst models = await this.getModelCandidates();\n\t\treturn findExactModelReferenceMatch(searchTerm, models);\n\t}\n\n\tprivate async getModelCandidates(): Promise<Model<any>[]> {\n\t\tif (this.session.scopedModels.length > 0) {\n\t\t\treturn this.session.scopedModels.map((scoped) => scoped.model);\n\t\t}\n\n\t\tthis.session.modelRegistry.refresh();\n\t\ttry {\n\t\t\treturn await this.session.modelRegistry.getAvailable();\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\t/** Update the footer's available provider count from current model candidates */\n\tprivate async updateAvailableProviderCount(): Promise<void> {\n\t\tconst models = await this.getModelCandidates();\n\t\tconst uniqueProviders = new Set(models.map((m) => m.provider));\n\t\tthis.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);\n\t}\n\n\tprivate async maybeWarnAboutAnthropicSubscriptionAuth(\n\t\tmodel: Model<any> | undefined = this.session.model,\n\t): Promise<void> {\n\t\tif (this.settingsManager.getWarnings().anthropicExtraUsage === false) {\n\t\t\treturn;\n\t\t}\n\t\tif (this.anthropicSubscriptionWarningShown) {\n\t\t\treturn;\n\t\t}\n\t\tif (model?.provider !== \"anthropic\") {\n\t\t\treturn;\n\t\t}\n\n\t\tconst storedCredential = this.session.modelRegistry.authStorage.get(\"anthropic\");\n\t\tif (storedCredential?.type === \"oauth\") {\n\t\t\tthis.anthropicSubscriptionWarningShown = true;\n\t\t\tthis.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst apiKey = await this.session.modelRegistry.getApiKeyForProvider(model.provider);\n\t\t\tif (!isAnthropicSubscriptionAuthKey(apiKey)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.anthropicSubscriptionWarningShown = true;\n\t\t\tthis.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);\n\t\t} catch {\n\t\t\t// Ignore auth lookup failures for warning-only checks.\n\t\t}\n\t}\n\n\tprivate showModelSelector(initialSearchInput?: string): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ModelSelectorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.session.model,\n\t\t\t\tthis.settingsManager,\n\t\t\t\tthis.session.modelRegistry,\n\t\t\t\tthis.session.scopedModels,\n\t\t\t\tasync (model) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.session.setModel(model);\n\t\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.showStatus(`Model: ${model.id}`);\n\t\t\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(model);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSearchInput,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async showModelsSelector(): Promise<void> {\n\t\t// Get all available models\n\t\tthis.session.modelRegistry.refresh();\n\t\tconst allModels = this.session.modelRegistry.getAvailable();\n\n\t\tif (allModels.length === 0) {\n\t\t\tthis.showStatus(\"No models available\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Check if session has scoped models (from previous session-only changes or CLI --models)\n\t\tconst sessionScopedModels = this.session.scopedModels;\n\t\tconst hasSessionScope = sessionScopedModels.length > 0;\n\n\t\t// Build enabled model IDs from session state or settings\n\t\tlet currentEnabledIds: string[] | null = null;\n\n\t\tif (hasSessionScope) {\n\t\t\t// Use current session's scoped models\n\t\t\tcurrentEnabledIds = sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);\n\t\t} else {\n\t\t\t// Fall back to settings\n\t\t\tconst patterns = this.settingsManager.getEnabledModels();\n\t\t\tif (patterns !== undefined && patterns.length > 0) {\n\t\t\t\tconst scopedModels = await resolveModelScope(patterns, this.session.modelRegistry);\n\t\t\t\tcurrentEnabledIds = scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);\n\t\t\t}\n\t\t}\n\n\t\t// Helper to update session's scoped models (session-only, no persist)\n\t\tconst updateSessionModels = async (enabledIds: string[] | null) => {\n\t\t\tcurrentEnabledIds = enabledIds === null ? null : [...enabledIds];\n\t\t\tif (enabledIds && enabledIds.length > 0 && enabledIds.length < allModels.length) {\n\t\t\t\tconst newScopedModels = await resolveModelScope(enabledIds, this.session.modelRegistry);\n\t\t\t\tthis.session.setScopedModels(\n\t\t\t\t\tnewScopedModels.map((sm) => ({\n\t\t\t\t\t\tmodel: sm.model,\n\t\t\t\t\t\tthinkingLevel: sm.thinkingLevel,\n\t\t\t\t\t})),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// All enabled or none enabled = no filter\n\t\t\t\tthis.session.setScopedModels([]);\n\t\t\t}\n\t\t\tawait this.updateAvailableProviderCount();\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ScopedModelsSelectorComponent(\n\t\t\t\t{\n\t\t\t\t\tallModels,\n\t\t\t\t\tenabledModelIds: currentEnabledIds,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonChange: async (enabledIds) => {\n\t\t\t\t\t\tawait updateSessionModels(enabledIds);\n\t\t\t\t\t},\n\t\t\t\t\tonPersist: (enabledIds) => {\n\t\t\t\t\t\t// Persist to settings\n\t\t\t\t\t\tconst newPatterns =\n\t\t\t\t\t\t\tenabledIds === null || enabledIds.length === allModels.length\n\t\t\t\t\t\t\t\t? undefined // All enabled = clear filter\n\t\t\t\t\t\t\t\t: enabledIds;\n\t\t\t\t\t\tthis.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined);\n\t\t\t\t\t\tthis.showStatus(\"Model selection saved to settings\");\n\t\t\t\t\t},\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showUserMessageSelector(): void {\n\t\tconst userMessages = this.session.getUserMessagesForForking();\n\n\t\tif (userMessages.length === 0) {\n\t\t\tthis.showStatus(\"No messages to fork from\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst initialSelectedId = userMessages[userMessages.length - 1]?.entryId;\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new UserMessageSelectorComponent(\n\t\t\t\tuserMessages.map((m) => ({ id: m.entryId, text: m.text })),\n\t\t\t\tasync (entryId) => {\n\t\t\t\t\tdone();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.runtimeHost.fork(entryId);\n\t\t\t\t\t\tif (result.cancelled) {\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.renderCurrentSessionState();\n\t\t\t\t\t\tthis.editor.setText(result.selectedText ?? \"\");\n\t\t\t\t\t\tthis.showStatus(\"Forked to new session\");\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSelectedId,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getMessageList() };\n\t\t});\n\t}\n\n\tprivate async handleCloneCommand(): Promise<void> {\n\t\tconst leafId = this.activeSession.getLeafId();\n\t\tif (!leafId) {\n\t\t\tthis.showStatus(\"Nothing to clone yet\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.fork(leafId, { position: \"at\" });\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.editor.setText(\"\");\n\t\t\tthis.showStatus(\"Cloned to new session\");\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate async selectBranchSummaryOptions(entryId: string): Promise<NavigateTreeOptions | undefined> {\n\t\tif (this.settingsManager.getBranchSummarySkipPrompt()) return { summarize: false };\n\n\t\twhile (true) {\n\t\t\tconst summaryChoice = await this.showExtensionSelector(\"Summarize branch?\", [\n\t\t\t\t\"No summary\",\n\t\t\t\t\"Summarize\",\n\t\t\t\t\"Summarize with custom prompt\",\n\t\t\t]);\n\t\t\tif (summaryChoice === undefined) {\n\t\t\t\tthis.showTreeSelector(entryId);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (summaryChoice !== \"Summarize with custom prompt\") {\n\t\t\t\treturn { summarize: summaryChoice !== \"No summary\" };\n\t\t\t}\n\n\t\t\tconst customInstructions = await this.showExtensionEditor(\"Custom summarization instructions\");\n\t\t\tif (customInstructions !== undefined) return { summarize: true, customInstructions };\n\t\t}\n\t}\n\n\tprivate async navigateToTreeEntry(entryId: string, options: NavigateTreeOptions): Promise<void> {\n\t\tconst originalOnEscape = this.defaultEditor.onEscape;\n\t\tif (options.summarize) {\n\t\t\tthis.defaultEditor.onEscape = () => {\n\t\t\t\tthis.session.abortBranchSummary();\n\t\t\t};\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.branchSummaryLoader = new Loader(\n\t\t\t\tthis.ui,\n\t\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\t`Summarizing branch... (${keyText(\"app.interrupt\")} to cancel)`,\n\t\t\t);\n\t\t\tthis.statusContainer.addChild(this.branchSummaryLoader);\n\t\t\tthis.ui.requestRender();\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await this.session.navigateTree(entryId, options);\n\t\t\tif (result.aborted) {\n\t\t\t\tthis.showStatus(\"Branch summarization cancelled\");\n\t\t\t\tthis.showTreeSelector(entryId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.showStatus(\"Navigation cancelled\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.chatContainer.clear();\n\t\t\tthis.renderInitialMessages();\n\t\t\tif (result.editorText && !this.editor.getText().trim()) this.editor.setText(result.editorText);\n\t\t\tthis.showStatus(\"Navigated to selected point\");\n\t\t\tvoid this.flushCompactionQueue({ willRetry: false });\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t} finally {\n\t\t\tif (this.branchSummaryLoader) {\n\t\t\t\tthis.branchSummaryLoader.stop();\n\t\t\t\tthis.branchSummaryLoader = undefined;\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t}\n\t\t\tthis.defaultEditor.onEscape = originalOnEscape;\n\t\t}\n\t}\n\n\tprivate async handleTreeSelection(\n\t\tentryId: string,\n\t\tcurrentLeafId: string | null,\n\t\tcloseSelector: () => void,\n\t): Promise<void> {\n\t\tif (entryId === currentLeafId) {\n\t\t\tcloseSelector();\n\t\t\tthis.showStatus(\"Already at this point\");\n\t\t\treturn;\n\t\t}\n\n\t\tcloseSelector();\n\t\tconst options = await this.selectBranchSummaryOptions(entryId);\n\t\tif (options) await this.navigateToTreeEntry(entryId, options);\n\t}\n\n\tprivate showTreeSelector(initialSelectedId?: string): void {\n\t\tconst tree = this.activeSession.getTree();\n\t\tconst realLeafId = this.activeSession.getLeafId();\n\t\tconst initialFilterMode = this.settingsManager.getTreeFilterMode();\n\n\t\tif (tree.length === 0) {\n\t\t\tthis.showStatus(\"No entries in session\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new TreeSelectorComponent(\n\t\t\t\ttree,\n\t\t\t\trealLeafId,\n\t\t\t\tthis.ui.terminal.rows,\n\t\t\t\t(entryId) => this.handleTreeSelection(entryId, realLeafId, done),\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\t(entryId, label) => {\n\t\t\t\t\tthis.activeSession.appendLabelChange(entryId, label);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSelectedId,\n\t\t\t\tinitialFilterMode,\n\t\t\t);\n\t\t\tselector.onCopy = async (text) => {\n\t\t\t\tif (!text) {\n\t\t\t\t\tthis.showError(\"Selected entry has no text to copy\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait copyToClipboard(text);\n\t\t\t\t\tthis.showStatus(\"Copied selected message to clipboard\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showSessionSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst activeSessionReference = this.activeSession.getSessionReference();\n\t\t\tconst isRemoteSession = activeSessionReference?.startsWith(\"remote:\") ?? false;\n\t\t\tconst renameSession = isRemoteSession\n\t\t\t\t? undefined\n\t\t\t\t: async (sessionFilePath: string, nextName: string | undefined) => {\n\t\t\t\t\t\tconst next = (nextName ?? \"\").trim();\n\t\t\t\t\t\tif (!next) return;\n\t\t\t\t\t\tconst mgr = new LocalSessionManager({ cwd: process.cwd() }).openReference(sessionFilePath);\n\t\t\t\t\t\tmgr.appendSessionInfo(next);\n\t\t\t\t\t};\n\t\t\tconst selector = new SessionSelectorComponent(\n\t\t\t\t(onProgress) => this.runtimeHost.listSessions(onProgress),\n\t\t\t\t(onProgress) => this.runtimeHost.listAllSessions(onProgress),\n\n\t\t\t\tasync (sessionPath) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tawait this.handleResumeSession(sessionPath);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tvoid this.shutdown();\n\t\t\t\t},\n\t\t\t\t() => this.ui.requestRender(),\n\t\t\t\t{\n\t\t\t\t\trenameSession,\n\t\t\t\t\tshowRenameHint: !isRemoteSession,\n\t\t\t\t\tkeybindings: this.keybindings,\n\t\t\t\t},\n\n\t\t\t\tactiveSessionReference,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async handleResumeSession(\n\t\tsessionPath: string,\n\t\toptions?: ExtensionSwitchSessionOptions,\n\t): Promise<SessionResumeResult> {\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t}\n\t\tthis.statusContainer.clear();\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.switchSession(sessionPath, {\n\t\t\t\twithSession: options?.withSession,\n\t\t\t});\n\t\t\tif (result.cancelled) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.showStatus(\"Resumed session\");\n\t\t\treturn result;\n\t\t} catch (error: unknown) {\n\t\t\tif (error instanceof MissingSessionCwdError) {\n\t\t\t\tconst selectedCwd = await this.promptForMissingSessionCwd(error);\n\t\t\t\tif (!selectedCwd) {\n\t\t\t\t\tthis.showStatus(\"Resume cancelled\");\n\t\t\t\t\treturn { cancelled: true };\n\t\t\t\t}\n\t\t\t\tconst result = await this.runtimeHost.switchSession(sessionPath, {\n\t\t\t\t\tcwdOverride: selectedCwd,\n\t\t\t\t\twithSession: options?.withSession,\n\t\t\t\t});\n\t\t\t\tif (result.cancelled) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tthis.renderCurrentSessionState();\n\t\t\t\tthis.showStatus(\"Resumed session in current cwd\");\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\treturn this.handleFatalRuntimeError(\"Failed to resume session\", error);\n\t\t}\n\t}\n\n\tprivate getLoginProviderOptions(authType?: ProviderAuthenticationType): AuthSelectorProvider[] {\n\t\tconst authStorage = this.session.modelRegistry.authStorage;\n\t\tconst oauthProviders = authStorage.getOAuthProviders();\n\t\tconst oauthProviderIds = new Set(oauthProviders.map((provider) => provider.id));\n\t\tconst options: AuthSelectorProvider[] = oauthProviders.map((provider) => ({\n\t\t\tid: provider.id,\n\t\t\tname: provider.name,\n\t\t\tauthType: \"oauth\",\n\t\t}));\n\n\t\tconst modelProviders = new Set(this.session.modelRegistry.getAll().map((model) => model.provider));\n\t\tfor (const providerId of modelProviders) {\n\t\t\tif (!isApiKeyLoginProvider(providerId, oauthProviderIds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toptions.push({\n\t\t\t\tid: providerId,\n\t\t\t\tname: this.session.modelRegistry.getProviderDisplayName(providerId),\n\t\t\t\tauthType: \"api_key\",\n\t\t\t});\n\t\t}\n\n\t\tconst filteredOptions = authType ? options.filter((option) => option.authType === authType) : options;\n\t\treturn filteredOptions.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate getLogoutProviderOptions(): AuthSelectorProvider[] {\n\t\tconst authStorage = this.session.modelRegistry.authStorage;\n\t\tconst options: AuthSelectorProvider[] = [];\n\n\t\tfor (const providerId of authStorage.list()) {\n\t\t\tconst credential = authStorage.get(providerId);\n\t\t\tif (!credential) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toptions.push({\n\t\t\t\tid: providerId,\n\t\t\t\tname: this.session.modelRegistry.getProviderDisplayName(providerId),\n\t\t\t\tauthType: credential.type,\n\t\t\t});\n\t\t}\n\n\t\treturn options.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate showLoginAuthTypeSelector(): void {\n\t\tconst subscriptionLabel = \"Use a subscription\";\n\t\tconst apiKeyLabel = \"Use an API key\";\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\t\"Select authentication method:\",\n\t\t\t\t[subscriptionLabel, apiKeyLabel],\n\t\t\t\t(option) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tconst authType = option === subscriptionLabel ? \"oauth\" : \"api_key\";\n\t\t\t\t\tthis.showLoginProviderSelector(authType);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showLoginProviderSelector(authType: ProviderAuthenticationType): void {\n\t\tconst providerOptions = this.getLoginProviderOptions(authType);\n\t\tif (providerOptions.length === 0) {\n\t\t\tthis.showStatus(\n\t\t\t\tauthType === \"oauth\" ? \"No subscription providers available.\" : \"No API key providers available.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\t\"login\",\n\t\t\t\tthis.session.modelRegistry.authStorage,\n\t\t\t\tproviderOptions,\n\t\t\t\tasync (providerId: string) => {\n\t\t\t\t\tdone();\n\n\t\t\t\t\tconst providerOption = providerOptions.find((provider) => provider.id === providerId);\n\t\t\t\t\tif (!providerOption) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (providerOption.authType === \"oauth\") {\n\t\t\t\t\t\tawait this.showLoginDialog(providerOption.id, providerOption.name);\n\t\t\t\t\t} else if (providerOption.id === BEDROCK_PROVIDER_ID) {\n\t\t\t\t\t\tthis.showBedrockSetupDialog(providerOption.id, providerOption.name);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.showApiKeyLoginDialog(providerOption.id, providerOption.name);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\t\t},\n\t\t\t\t(providerId) => this.session.modelRegistry.getProviderAuthStatus(providerId),\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async showOAuthSelector(mode: AuthenticationOperation): Promise<void> {\n\t\tif (mode === \"login\") {\n\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst providerOptions = this.getLogoutProviderOptions();\n\t\tif (providerOptions.length === 0) {\n\t\t\tthis.showStatus(\n\t\t\t\t\"No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\tmode,\n\t\t\t\tthis.session.modelRegistry.authStorage,\n\t\t\t\tproviderOptions,\n\t\t\t\tasync (providerId: string) => {\n\t\t\t\t\tdone();\n\n\t\t\t\t\tconst providerOption = providerOptions.find((provider) => provider.id === providerId);\n\t\t\t\t\tif (!providerOption) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.session.modelRegistry.authStorage.logout(providerOption.id);\n\t\t\t\t\t\tthis.session.modelRegistry.refresh();\n\t\t\t\t\t\tawait this.updateAvailableProviderCount();\n\t\t\t\t\t\tconst message =\n\t\t\t\t\t\t\tproviderOption.authType === \"oauth\"\n\t\t\t\t\t\t\t\t? `Logged out of ${providerOption.name}`\n\t\t\t\t\t\t\t\t: `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;\n\t\t\t\t\t\tthis.showStatus(message);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tthis.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async selectProviderDefaultModelAfterAuthentication(\n\t\tproviderId: string,\n\t\tactionLabel: string,\n\t): Promise<ProviderAuthenticationModelSelection> {\n\t\tconst availableModels = this.session.modelRegistry.getAvailable();\n\t\tconst providerModels = availableModels.filter((model) => model.provider === providerId);\n\t\tif (!hasDefaultModelProvider(providerId)) {\n\t\t\treturn {\n\t\t\t\tselectionError: `${actionLabel}, but no default model is configured for provider \"${providerId}\". Use /model to select a model.`,\n\t\t\t};\n\t\t}\n\t\tif (providerModels.length === 0) {\n\t\t\treturn {\n\t\t\t\tselectionError: `${actionLabel}, but no models are available for that provider. Use /model to select a model.`,\n\t\t\t};\n\t\t}\n\t\tconst defaultModelId = defaultModelPerProvider[providerId];\n\t\tconst selectedModel = providerModels.find((model) => model.id === defaultModelId);\n\t\tif (!selectedModel) {\n\t\t\treturn {\n\t\t\t\tselectionError: `${actionLabel}, but its default model \"${defaultModelId}\" is not available. Use /model to select a model.`,\n\t\t\t};\n\t\t}\n\t\ttry {\n\t\t\tawait this.session.setModel(selectedModel);\n\t\t\treturn { selectedModel };\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\treturn {\n\t\t\t\tselectionError: `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`,\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate showCompletedProviderAuthentication(\n\t\tactionLabel: string,\n\t\tselection: ProviderAuthenticationModelSelection,\n\t): void {\n\t\tif (selection.selectedModel) {\n\t\t\tthis.showStatus(\n\t\t\t\t`${actionLabel}. Selected ${selection.selectedModel.id}. Credentials saved to ${getAuthPath()}`,\n\t\t\t);\n\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(selection.selectedModel);\n\t\t\treturn;\n\t\t}\n\t\tthis.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);\n\t\tif (selection.selectionError) {\n\t\t\tthis.showError(selection.selectionError);\n\t\t} else {\n\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth();\n\t\t}\n\t}\n\n\tprivate async completeProviderAuthentication(\n\t\tproviderId: string,\n\t\tproviderName: string,\n\t\tauthType: ProviderAuthenticationType,\n\t\tpreviousModel: Model<any> | undefined,\n\t): Promise<void> {\n\t\tthis.session.modelRegistry.refresh();\n\t\tconst actionLabel = authType === \"oauth\" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;\n\t\tlet selection: ProviderAuthenticationModelSelection = {};\n\t\tif (isUnknownModel(previousModel)) {\n\t\t\tselection = await this.selectProviderDefaultModelAfterAuthentication(providerId, actionLabel);\n\t\t}\n\n\t\tawait this.updateAvailableProviderCount();\n\t\tthis.footer.invalidate();\n\t\tthis.updateEditorBorderColor();\n\t\tthis.showCompletedProviderAuthentication(actionLabel, selection);\n\t}\n\n\tprivate showBedrockSetupDialog(providerId: string, providerName: string): void {\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui,\n\t\t\tproviderId,\n\t\t\t() => restoreEditor(),\n\t\t\tproviderName,\n\t\t\t\"Amazon Bedrock setup\",\n\t\t);\n\t\tdialog.showInfo([\n\t\t\ttheme.fg(\"text\", \"Amazon Bedrock uses AWS credentials instead of a single API key.\"),\n\t\t\ttheme.fg(\"text\", \"Configure an AWS profile, IAM keys, bearer token, or role-based credentials.\"),\n\t\t\ttheme.fg(\"muted\", \"See:\"),\n\t\t\ttheme.fg(\"accent\", ` ${path.join(getDocsPath(), \"providers.md\")}`),\n\t\t]);\n\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async showApiKeyLoginDialog(providerId: string, providerName: string): Promise<void> {\n\t\tconst previousModel = this.session.model;\n\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui,\n\t\t\tproviderId,\n\t\t\t(_success, _message) => {\n\t\t\t\t// Completion handled below\n\t\t\t},\n\t\t\tproviderName,\n\t\t);\n\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tconst apiKey = (await dialog.showPrompt(\"Enter API key:\")).trim();\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(\"API key cannot be empty.\");\n\t\t\t}\n\n\t\t\tthis.session.modelRegistry.authStorage.set(providerId, { type: \"api_key\", key: apiKey });\n\n\t\t\trestoreEditor();\n\t\t\tawait this.completeProviderAuthentication(providerId, providerName, \"api_key\", previousModel);\n\t\t} catch (error: unknown) {\n\t\t\trestoreEditor();\n\t\t\tconst errorMsg = error instanceof Error ? error.message : String(error);\n\t\t\tif (errorMsg !== \"Login cancelled\") {\n\t\t\t\tthis.showError(`Failed to save API key for ${providerName}: ${errorMsg}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate showOAuthLoginSelect(dialog: LoginDialogComponent, prompt: OAuthSelectPrompt): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst restoreDialog = () => {\n\t\t\t\tthis.editorContainer.clear();\n\t\t\t\tthis.editorContainer.addChild(dialog);\n\t\t\t\tthis.ui.setFocus(dialog);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t};\n\t\t\tconst labels = prompt.options.map((option) => option.label);\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\tprompt.message,\n\t\t\t\tlabels,\n\t\t\t\t(optionLabel) => {\n\t\t\t\t\trestoreDialog();\n\t\t\t\t\tresolve(prompt.options.find((option) => option.label === optionLabel)?.id);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\trestoreDialog();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(selector);\n\t\t\tthis.ui.setFocus(selector);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\tprivate async showLoginDialog(providerId: string, providerName: string): Promise<void> {\n\t\tconst providerInfo = this.session.modelRegistry.authStorage\n\t\t\t.getOAuthProviders()\n\t\t\t.find((provider) => provider.id === providerId);\n\t\tconst previousModel = this.session.model;\n\n\t\t// Providers that use callback servers (can paste redirect URL)\n\t\tconst usesCallbackServer = providerInfo?.usesCallbackServer ?? false;\n\n\t\t// Create login dialog component\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui,\n\t\t\tproviderId,\n\t\t\t(_success, _message) => {\n\t\t\t\t// Completion handled below\n\t\t\t},\n\t\t\tproviderName,\n\t\t);\n\n\t\t// Show dialog in editor container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\n\t\t// Promise for manual code input (racing with callback server)\n\t\tlet manualCodeResolve: ((code: string) => void) | undefined;\n\t\tlet manualCodeReject: ((err: Error) => void) | undefined;\n\t\tconst manualCodePromise = new Promise<string>((resolve, reject) => {\n\t\t\tmanualCodeResolve = resolve;\n\t\t\tmanualCodeReject = reject;\n\t\t});\n\n\t\t// Restore editor helper\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tawait this.session.modelRegistry.authStorage.login(providerId as OAuthProviderId, {\n\t\t\t\tonAuth: (info: OAuthAuthInfo) => {\n\t\t\t\t\tdialog.showAuth(info.url, info.instructions);\n\n\t\t\t\t\tif (usesCallbackServer) {\n\t\t\t\t\t\t// Show input for manual paste, racing with callback\n\t\t\t\t\t\tdialog\n\t\t\t\t\t\t\t.showManualInput(\"Paste redirect URL below, or complete login in browser:\")\n\t\t\t\t\t\t\t.then((value) => {\n\t\t\t\t\t\t\t\tif (value && manualCodeResolve) {\n\t\t\t\t\t\t\t\t\tmanualCodeResolve(value);\n\t\t\t\t\t\t\t\t\tmanualCodeResolve = undefined;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\t\t\tif (manualCodeReject) {\n\t\t\t\t\t\t\t\t\tmanualCodeReject(new Error(\"Login cancelled\"));\n\t\t\t\t\t\t\t\t\tmanualCodeReject = undefined;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\t// For Anthropic: onPrompt is called immediately after\n\t\t\t\t},\n\n\t\t\t\tonDeviceCode: (info) => {\n\t\t\t\t\tdialog.showDeviceCode(info);\n\t\t\t\t\tdialog.showWaiting(\"Waiting for authentication...\");\n\t\t\t\t},\n\n\t\t\t\tonPrompt: async (prompt: OAuthPrompt) => {\n\t\t\t\t\treturn dialog.showPrompt(prompt.message, prompt.placeholder);\n\t\t\t\t},\n\n\t\t\t\tonProgress: (message: string) => {\n\t\t\t\t\tdialog.showProgress(message);\n\t\t\t\t},\n\n\t\t\t\tonSelect: (prompt: OAuthSelectPrompt) => this.showOAuthLoginSelect(dialog, prompt),\n\n\t\t\t\tonManualCodeInput: () => manualCodePromise,\n\n\t\t\t\tsignal: dialog.signal,\n\t\t\t});\n\n\t\t\t// Success\n\t\t\trestoreEditor();\n\t\t\tawait this.completeProviderAuthentication(providerId, providerName, \"oauth\", previousModel);\n\t\t} catch (error: unknown) {\n\t\t\trestoreEditor();\n\t\t\tconst errorMsg = error instanceof Error ? error.message : String(error);\n\t\t\tif (errorMsg !== \"Login cancelled\") {\n\t\t\t\tthis.showError(`Failed to login to ${providerName}: ${errorMsg}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Command handlers\n\tprivate async handleCdCommand(text: string): Promise<void> {\n\t\tif (!this.session.isIdle || this.session.isBashRunning) {\n\t\t\tthis.showWarning(\"Wait for the current operation to finish before changing directories.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.session.supportsDirectoryChange()) {\n\t\t\tthis.showWarning(\"Changing directories is not supported with the active workspace backend.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst argument = this.getPathCommandArgument(text, \"/cd\");\n\t\tif (text !== \"/cd\" && !argument) {\n\t\t\tthis.showError(\"Usage: /cd [directory]\");\n\t\t\treturn;\n\t\t}\n\t\tconst requestedPath = argument ?? os.homedir();\n\t\tconst targetDirectory = resolveDirectoryPath(requestedPath, this.activeSession.getCwd());\n\t\tif (!targetDirectory) {\n\t\t\tthis.showError(`Directory not found: ${requestedPath}`);\n\t\t\treturn;\n\t\t}\n\n\t\tif (targetDirectory === resolveDirectoryPath(this.activeSession.getCwd(), this.activeSession.getCwd())) {\n\t\t\tthis.showStatus(`Working directory: ${targetDirectory}`);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.changeDirectory(targetDirectory);\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.showStatus(\"Directory change cancelled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.showStatus(`Working directory: ${targetDirectory}`);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.showError(\n\t\t\t\tthis.activeSession.getCwd() === targetDirectory\n\t\t\t\t\t? `Working directory changed, but the runtime failed to rebind: ${message}`\n\t\t\t\t\t: `Failed to change directory: ${message}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async handleProfileCommand(text: string): Promise<void> {\n\t\tconst match = text.match(/^\\/profile\\s+(create|use)\\s+(\\S+)$/);\n\t\tif (!match) {\n\t\t\tthis.showError(\"Usage: /profile create <name> | /profile use <name>\");\n\t\t\treturn;\n\t\t}\n\t\tconst action = match[1];\n\t\tconst name = match[2]!;\n\t\tif (!isValidModelProfileName(name)) {\n\t\t\tthis.showError(\"Profile names must be 1-64 letters, numbers, dots, underscores, or hyphens.\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (action === \"create\") {\n\t\t\tconst currentScope = this.session.scopedModels;\n\t\t\tconst patterns =\n\t\t\t\tcurrentScope.length > 0\n\t\t\t\t\t? currentScope.map(\n\t\t\t\t\t\t\t(scoped) =>\n\t\t\t\t\t\t\t\t`${scoped.model.provider}/${scoped.model.id}${scoped.thinkingLevel ? `:${scoped.thinkingLevel}` : \"\"}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t: this.session.modelRegistry.getAvailable().map((model) => `${model.provider}/${model.id}`);\n\t\t\tif (patterns.length === 0) {\n\t\t\t\tthis.showError(\"Cannot create a profile because no models are available.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst exists = Object.hasOwn(this.settingsManager.getModelProfiles(), name);\n\t\t\tthis.settingsManager.setModelProfile(name, patterns);\n\t\t\tthis.showStatus(`${exists ? \"Updated\" : \"Created\"} profile \"${name}\" with ${patterns.length} models`);\n\t\t\treturn;\n\t\t}\n\n\t\tconst profiles = this.settingsManager.getModelProfiles();\n\t\tif (!Object.hasOwn(profiles, name)) {\n\t\t\tthis.showError(`Unknown profile: ${name}`);\n\t\t\treturn;\n\t\t}\n\t\tconst patterns = profiles[name]!;\n\t\tconst scopedModels = await resolveModelScope(patterns, this.session.modelRegistry);\n\t\tif (scopedModels.length === 0) {\n\t\t\tthis.showError(`Profile \"${name}\" has no available models`);\n\t\t\treturn;\n\t\t}\n\t\tthis.session.setScopedModels(scopedModels);\n\t\tthis.settingsManager.setEnabledModels([...patterns]);\n\t\tawait this.updateAvailableProviderCount();\n\t\tthis.ui.requestRender();\n\t\tthis.showStatus(`Using profile \"${name}\" with ${scopedModels.length} models`);\n\t}\n\n\t// =========================================================================\n\n\tprivate async handleReloadCommand(): Promise<void> {\n\t\tif (this.session.isStreaming) {\n\t\t\tthis.showWarning(\"Wait for the current response to finish before reloading.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.session.isCompacting) {\n\t\t\tthis.showWarning(\"Wait for compaction to finish before reloading.\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.resetExtensionUI();\n\n\t\tconst reloadBox = new Container();\n\t\tconst borderColor = (s: string) => theme.fg(\"border\", s);\n\t\treloadBox.addChild(new DynamicBorder(borderColor));\n\t\treloadBox.addChild(new Spacer(1));\n\t\treloadBox.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\"muted\", \"Reloading keybindings, hooks, extensions, skills, rules, prompts, themes...\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\treloadBox.addChild(new Spacer(1));\n\t\treloadBox.addChild(new DynamicBorder(borderColor));\n\n\t\tconst previousEditor = this.editor;\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(reloadBox);\n\t\tthis.ui.setFocus(reloadBox);\n\t\tthis.ui.requestRender(true);\n\t\tawait new Promise((resolve) => process.nextTick(resolve));\n\n\t\tconst dismissReloadBox = (editor: Component) => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(editor);\n\t\t\tthis.ui.setFocus(editor);\n\t\t\tthis.updateToolBackendStatus();\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tawait this.session.reload();\n\t\t\tthis.keybindings.reload();\n\t\t\tconst activeHeader = this.customHeader ?? this.builtInHeader;\n\t\t\tif (isExpandable(activeHeader)) {\n\t\t\t\tactiveHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\t\t\tconst themeName = this.settingsManager.getTheme();\n\t\t\tconst themeResult = themeName ? setTheme(themeName, true) : { success: true };\n\t\t\tif (!themeResult.success) {\n\t\t\t\tthis.showError(`Failed to load theme \"${themeName}\": ${themeResult.error}\\nFell back to dark theme.`);\n\t\t\t}\n\t\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\t\tthis.defaultEditor.setPaddingX(editorPaddingX);\n\t\t\tthis.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);\n\t\t\tif (this.editor !== this.defaultEditor) {\n\t\t\t\tthis.editor.setPaddingX?.(editorPaddingX);\n\t\t\t\tthis.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);\n\t\t\t}\n\t\t\tthis.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());\n\t\t\tthis.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());\n\t\t\tthis.setupAutocompleteProvider();\n\t\t\tconst runner = this.session.extensionRunner;\n\t\t\tthis.setupExtensionShortcuts(runner);\n\t\t\tthis.rebuildChatFromMessages();\n\t\t\tdismissReloadBox(this.editor as Component);\n\t\t\tthis.showLoadedResources({\n\t\t\t\tforce: false,\n\t\t\t\tshowDiagnosticsWhenQuiet: true,\n\t\t\t});\n\t\t\tthis.showRuntimeDiagnostics();\n\t\t\tconst modelsJsonError = this.session.modelRegistry.getError();\n\t\t\tif (modelsJsonError) {\n\t\t\t\tthis.showError(`models.json error: ${modelsJsonError}`);\n\t\t\t}\n\t\t\tthis.showStatus(\"Reloaded keybindings, hooks, extensions, skills, rules, prompts, themes\");\n\t\t} catch (error) {\n\t\t\tdismissReloadBox(previousEditor as Component);\n\t\t\tthis.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\n\tprivate async handleExportCommand(text: string): Promise<void> {\n\t\tconst outputPath = this.getPathCommandArgument(text, \"/export\");\n\n\t\ttry {\n\t\t\tif (outputPath?.endsWith(\".jsonl\")) {\n\t\t\t\tconst filePath = this.session.exportToJsonl(outputPath);\n\t\t\t\tthis.showStatus(`Session exported to: ${filePath}`);\n\t\t\t} else {\n\t\t\t\tconst filePath = await this.session.exportToHtml(outputPath);\n\t\t\t\tthis.showStatus(`Session exported to: ${filePath}`);\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(`Failed to export session: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\t}\n\n\tprivate getPathCommandArgument(text: string, command: SessionPathCommand): string | undefined {\n\t\tif (text === command) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!text.startsWith(`${command} `)) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst argsString = text.slice(command.length + 1).trimStart();\n\t\tif (!argsString) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst firstChar = argsString[0];\n\t\tif (firstChar === '\"' || firstChar === \"'\") {\n\t\t\tconst closingQuoteIndex = argsString.indexOf(firstChar, 1);\n\t\t\tif (closingQuoteIndex < 0) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn argsString.slice(1, closingQuoteIndex);\n\t\t}\n\n\t\tconst firstWhitespaceIndex = argsString.search(/\\s/);\n\t\tif (firstWhitespaceIndex < 0) {\n\t\t\treturn argsString;\n\t\t}\n\t\treturn argsString.slice(0, firstWhitespaceIndex);\n\t}\n\n\tprivate async handleImportCommand(text: string): Promise<void> {\n\t\tconst inputPath = this.getPathCommandArgument(text, \"/import\");\n\t\tif (!inputPath) {\n\t\t\tthis.showError(\"Usage: /import <path.jsonl>\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst confirmed = await this.showExtensionConfirm(\"Import session\", `Replace current session with ${inputPath}?`);\n\t\tif (!confirmed) {\n\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tif (this.loadingAnimation) {\n\t\t\t\tthis.loadingAnimation.stop();\n\t\t\t\tthis.loadingAnimation = undefined;\n\t\t\t}\n\t\t\tthis.statusContainer.clear();\n\t\t\tconst result = await this.runtimeHost.importFromJsonl(inputPath);\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.showStatus(`Session imported from: ${inputPath}`);\n\t\t} catch (error: unknown) {\n\t\t\tif (error instanceof MissingSessionCwdError) {\n\t\t\t\tconst selectedCwd = await this.promptForMissingSessionCwd(error);\n\t\t\t\tif (!selectedCwd) {\n\t\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst result = await this.runtimeHost.importFromJsonl(inputPath, selectedCwd);\n\t\t\t\tif (result.cancelled) {\n\t\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.renderCurrentSessionState();\n\t\t\t\tthis.showStatus(`Session imported from: ${inputPath}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (error instanceof SessionImportFileNotFoundError) {\n\t\t\t\tthis.showError(`Failed to import session: ${error.message}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.handleFatalRuntimeError(\"Failed to import session\", error);\n\t\t}\n\t}\n\n\tprivate async handleShareCommand(): Promise<void> {\n\t\t// Check if gh is available and logged in\n\t\ttry {\n\t\t\tconst authResult = spawnSync(\"gh\", [\"auth\", \"status\"], { encoding: \"utf-8\" });\n\t\t\tif (authResult.status !== 0) {\n\t\t\t\tthis.showError(\"GitHub CLI is not logged in. Run 'gh auth login' first.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.showError(\"GitHub CLI (gh) is not installed. Install it from https://cli.github.com/\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Export to a temp file\n\t\tconst tmpFile = path.join(os.tmpdir(), \"session.html\");\n\t\ttry {\n\t\t\tawait this.session.exportToHtml(tmpFile);\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(`Failed to export session: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Show cancellable loader, replacing the editor\n\t\tconst loader = new BorderedLoader(this.ui, theme, \"Creating gist...\");\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(loader);\n\t\tthis.ui.setFocus(loader);\n\t\tthis.ui.requestRender();\n\n\t\tconst restoreEditor = () => {\n\t\t\tloader.dispose();\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\ttry {\n\t\t\t\tfs.unlinkSync(tmpFile);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\t\t};\n\n\t\t// Create a secret gist asynchronously\n\t\tlet proc: ReturnType<typeof spawn> | null = null;\n\n\t\tloader.onAbort = () => {\n\t\t\tproc?.kill();\n\t\t\trestoreEditor();\n\t\t\tthis.showStatus(\"Share cancelled\");\n\t\t};\n\n\t\ttry {\n\t\t\tconst result = await new Promise<{ stdout: string; stderr: string; code: number | null }>((resolve) => {\n\t\t\t\tproc = spawn(\"gh\", [\"gist\", \"create\", \"--public=false\", tmpFile]);\n\t\t\t\tlet stdout = \"\";\n\t\t\t\tlet stderr = \"\";\n\t\t\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\t\t\tstdout += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.stderr?.on(\"data\", (data) => {\n\t\t\t\t\tstderr += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.on(\"close\", (code) => resolve({ stdout, stderr, code }));\n\t\t\t});\n\n\t\t\tif (loader.signal.aborted) return;\n\n\t\t\trestoreEditor();\n\n\t\t\tif (result.code !== 0) {\n\t\t\t\tconst errorMsg = result.stderr?.trim() || \"Unknown error\";\n\t\t\t\tthis.showError(`Failed to create gist: ${errorMsg}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Extract gist ID from the URL returned by gh\n\t\t\t// gh returns something like: https://gist.github.com/username/GIST_ID\n\t\t\tconst gistUrl = result.stdout?.trim();\n\t\t\tconst gistId = gistUrl?.split(\"/\").pop();\n\t\t\tif (!gistId) {\n\t\t\t\tthis.showError(\"Failed to parse gist ID from gh output\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Create the preview URL\n\t\t\tconst previewUrl = getShareViewerUrl(gistId);\n\t\t\tthis.showStatus(`Share URL: ${previewUrl}\\nGist: ${gistUrl}`);\n\t\t} catch (error: unknown) {\n\t\t\tif (!loader.signal.aborted) {\n\t\t\t\trestoreEditor();\n\t\t\t\tthis.showError(`Failed to create gist: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async handleCopyCommand(options: CopyCommandOptions = {}): Promise<void> {\n\t\tconst text = this.session.getLastAssistantText();\n\t\tif (!text) {\n\t\t\tthis.showError(\"No agent messages to copy yet.\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tawait copyToClipboard(text);\n\t\t\tif (options.flashConfirmation && this.ui instanceof TuiAltScreen) {\n\t\t\t\tthis.ui.flash(\"Copied!\");\n\t\t\t} else {\n\t\t\t\tthis.showStatus(\"Copied last agent message to clipboard\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate handleHooksCommand(text: string): void {\n\t\tconst action = text.slice(\"/hooks\".length).trim();\n\t\tif (action !== \"enable\" && action !== \"disable\") {\n\t\t\tthis.showWarning(\"Usage: /hooks <enable|disable>\");\n\t\t\treturn;\n\t\t}\n\t\tconst enabled = action === \"enable\";\n\t\tthis.session.setHooksEnabled(enabled);\n\t\tthis.showStatus(`Hooks ${enabled ? \"enabled\" : \"disabled\"} for this session`);\n\t}\n\n\tprivate handleNameCommand(text: string): void {\n\t\tconst name = text.replace(/^\\/name\\s*/, \"\").trim();\n\t\tif (!name) {\n\t\t\tconst currentName = this.activeSession.getSessionName();\n\t\t\tif (currentName) {\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", `Session name: ${currentName}`), 1, 0));\n\t\t\t} else {\n\t\t\t\tthis.showWarning(\"Usage: /name <name>\");\n\t\t\t}\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.session.setSessionName(name);\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", `Session name set: ${name}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate refreshUiAfterBackendChange(): void {\n\t\tthis.rebuildChatFromMessages();\n\t\tthis.showRuntimeDiagnostics();\n\t\tthis.setupAutocompleteProvider();\n\t\tthis.showLoadedResources({ force: true, showDiagnosticsWhenQuiet: true });\n\t}\n\tprivate createLimaSandboxService(): LimaSandboxService {\n\t\treturn new LimaSandboxService({\n\t\t\tsettingsManager: this.settingsManager,\n\t\t\tmanagedInstances: this.managedLimaInstances,\n\t\t});\n\t}\n\n\tprivate async disposeRuntimeResources(): Promise<Error[]> {\n\t\tconst limaSandboxService = this.createLimaSandboxService();\n\t\tconst errors: Error[] = [];\n\t\ttry {\n\t\t\tawait this.runtimeHost.dispose();\n\t\t} catch (error) {\n\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t\ttry {\n\t\t\tawait limaSandboxService.stopManagedInstances();\n\t\t} catch (error) {\n\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t\treturn errors;\n\t}\n\n\tprivate async restoreCurrentSessionSandbox(): Promise<void> {\n\t\tthis.activeSandboxContainerId = undefined;\n\t\tthis.activeSandboxBackendConnected = false;\n\t\tconst state = this.sessionSandboxStates.get(getSessionSandboxKey(this.activeSession));\n\t\tif (!state) return;\n\t\tthis.activeSandboxContainerId = state.containerId;\n\t\ttry {\n\t\t\tawait this.session.activateSandboxDaemon({\n\t\t\t\turl: state.url,\n\t\t\t\ttoken: state.token,\n\t\t\t\texpectedCwd: state.expectedCwd,\n\t\t\t});\n\t\t\tthis.activeSandboxBackendConnected = true;\n\t\t} catch (error) {\n\t\t\tif (!state.containerId) this.sessionSandboxStates.delete(getSessionSandboxKey(this.activeSession));\n\t\t\tthis.showWarning(\n\t\t\t\t`Could not restore this session's sandbox: ${redactSecrets(error instanceof Error ? error.message : String(error))}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate hasSandboxActivationConflict(sessionKey: string): boolean {\n\t\treturn (\n\t\t\tthis.activeSandboxBackendConnected ||\n\t\t\tthis.activeSandboxContainerId !== undefined ||\n\t\t\t[...(this.managedLimaInstances?.values() ?? [])].some(\n\t\t\t\t(instance) => instance.ownerId === this.activeSession.getSessionId(),\n\t\t\t) ||\n\t\t\tthis.sessionSandboxStates.has(sessionKey)\n\t\t);\n\t}\n\n\tprivate ensureSandboxCanActivate(sessionKey: string): boolean {\n\t\tif (!this.hasSandboxActivationConflict(sessionKey)) return true;\n\t\tthis.showWarning(\n\t\t\t\"A sandbox backend is already active or awaiting cleanup. Run /sandbox stop before starting or attaching another.\",\n\t\t);\n\t\treturn false;\n\t}\n\n\tprivate async clearSandboxBackend(sessionKey: string): Promise<void> {\n\t\tif (!this.activeSandboxBackendConnected && this.sessionSandboxStates.has(sessionKey)) {\n\t\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.showStatus(\"Stale sandbox state cleared\");\n\t\t\treturn;\n\t\t}\n\t\tawait this.session.clearRemoteSandbox();\n\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\tthis.activeSandboxContainerId = undefined;\n\t\tthis.activeSandboxBackendConnected = false;\n\t\tthis.refreshUiAfterBackendChange();\n\t\tthis.updateToolBackendStatus();\n\t\tthis.showStatus(\"Sandbox backend cleared\");\n\t}\n\n\tprivate async attachSandboxBackend(url: string, service: SandboxService, sessionKey: string): Promise<void> {\n\t\tconst currentBackend = this.session.getToolBackendInfo();\n\t\tconst expectedCwd =\n\t\t\tcurrentBackend.type === \"remote\" && !currentBackend.configured\n\t\t\t\t? currentBackend.cwd\n\t\t\t\t: service.resolveConfig().workspaceMountPath;\n\t\tconst token = process.env.GRIP_REMOTE_TOKEN ?? \"\";\n\t\tconst info = await this.session.activateSandboxDaemon({ url, token, expectedCwd });\n\t\tthis.activeSandboxContainerId = undefined;\n\t\tthis.activeSandboxBackendConnected = true;\n\t\tthis.sessionSandboxStates.set(sessionKey, { type: \"daemon\", url, token, expectedCwd });\n\t\tthis.refreshUiAfterBackendChange();\n\t\tthis.updateToolBackendStatus();\n\t\tthis.showStatus([`Sandbox attached: ${redactSecrets(url)}`, this.formatToolBackendStatus(info)].join(\"\\n\"));\n\t}\n\n\tprivate showSandboxStartupLoader(): Loader | undefined {\n\t\tif (!this.statusContainer || !this.ui) return undefined;\n\t\tconst loader = new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\"Starting sandbox...\",\n\t\t);\n\t\tthis.statusContainer.clear();\n\t\tthis.statusContainer.addChild(loader);\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(true);\n\t\tthis.ui.requestRender();\n\t\treturn loader;\n\t}\n\n\tprivate hideSandboxStartupLoader(loader: Loader | undefined): void {\n\t\tloader?.stop();\n\t\tif (!loader) return;\n\t\tthis.statusContainer.clear();\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(false);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async activateStartedSandbox(\n\t\tservice: SandboxService,\n\t\tworkspaceRoot: string,\n\t\tresult: SandboxStartResult,\n\t): Promise<ToolBackendInfo> {\n\t\tlet info: ToolBackendInfo | undefined;\n\t\tlet lastActivationError: unknown;\n\t\tfor (let attempt = 0; attempt < 10; attempt++) {\n\t\t\ttry {\n\t\t\t\tinfo = await this.session.activateSandboxDaemon({\n\t\t\t\t\turl: result.daemonUrl,\n\t\t\t\t\ttoken: result.token,\n\t\t\t\t\texpectedCwd: result.workspaceMountPath,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t} catch (error) {\n\t\t\t\tlastActivationError = error;\n\t\t\t\tif (attempt < 9) await new Promise((resolve) => setTimeout(resolve, 500));\n\t\t\t}\n\t\t}\n\t\tif (info) return info;\n\n\t\tconst activationError =\n\t\t\tlastActivationError instanceof Error ? lastActivationError : new Error(String(lastActivationError));\n\t\tif (result.daemonUrl.startsWith(\"grip+ws:\")) {\n\t\t\t// A shared-VM attach owns only its channel, never the VM or guest daemon.\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\tthrow activationError;\n\t\t}\n\t\ttry {\n\t\t\tawait service.stop({ workspaceRoot, currentContainerId: result.containerId });\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t} catch (cleanupError) {\n\t\t\tthis.activeSandboxContainerId = result.containerId;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\tconst cleanupMessage = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);\n\t\t\tthrow new Error(`${activationError.message}; failed to stop started sandbox: ${cleanupMessage}`);\n\t\t}\n\t\tthrow activationError;\n\t}\n\n\tprivate async startSandboxBackend(\n\t\tcommand: SandboxStartUserCommand,\n\t\tservice: SandboxService,\n\t\tworkspaceRoot: string,\n\t\tsessionKey: string,\n\t\tupdatingAttached = false,\n\t): Promise<void> {\n\t\tconst loader = this.showSandboxStartupLoader();\n\t\ttry {\n\t\t\tconst result = await service.start({\n\t\t\t\tworkspaceRoot,\n\t\t\t\t...(command.name ? { name: command.name } : {}),\n\t\t\t\t...(command.template ? { limaTemplate: command.template } : {}),\n\t\t\t\t...(command.update ? { update: true } : {}),\n\t\t\t\tsessionId: this.activeSession.getSessionId(),\n\t\t\t});\n\t\t\tif (updatingAttached) {\n\t\t\t\tawait this.session.abort();\n\t\t\t\tawait this.session.clearRemoteSandbox();\n\t\t\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\t}\n\t\t\tthis.activeSandboxContainerId = result.containerId;\n\t\t\tconst info = await this.activateStartedSandbox(service, workspaceRoot, result);\n\t\t\tthis.activeSandboxBackendConnected = true;\n\t\t\tthis.sessionSandboxStates.set(sessionKey, {\n\t\t\t\ttype: \"daemon\",\n\t\t\t\turl: result.daemonUrl,\n\t\t\t\ttoken: result.token,\n\t\t\t\texpectedCwd: result.workspaceMountPath,\n\t\t\t\tcontainerId: result.containerId,\n\t\t\t});\n\t\t\tthis.refreshUiAfterBackendChange();\n\t\t\tthis.updateToolBackendStatus();\n\t\t\tthis.showStatus(\n\t\t\t\t[\n\t\t\t\t\tcommand.update\n\t\t\t\t\t\t? formatSandboxStartResult(result).replace(\"Sandbox started:\", \"Sandbox updated:\")\n\t\t\t\t\t\t: formatSandboxStartResult(result),\n\t\t\t\t\tthis.formatToolBackendStatus(info),\n\t\t\t\t].join(\"\\n\"),\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.hideSandboxStartupLoader(loader);\n\t\t}\n\t}\n\n\tprivate sandboxContainerIdsMatch(left: string, right: string): boolean {\n\t\treturn left === right || left.startsWith(right) || right.startsWith(left);\n\t}\n\n\tprivate removeSandboxStatesForContainer(containerId: string): void {\n\t\tfor (const [key, state] of this.sessionSandboxStates) {\n\t\t\tif (\n\t\t\t\tstate.type === \"daemon\" &&\n\t\t\t\tstate.containerId &&\n\t\t\t\tthis.sandboxContainerIdsMatch(containerId, state.containerId)\n\t\t\t) {\n\t\t\t\tthis.sessionSandboxStates.delete(key);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async reconcileStoppedSandbox(result: SandboxStopResult, sessionKey: string): Promise<void> {\n\t\tif (result.status === \"not-found\") {\n\t\t\tif (!this.activeSandboxContainerId) return;\n\t\t\tif (this.activeSandboxBackendConnected) {\n\t\t\t\tawait this.session.clearRemoteSandbox();\n\t\t\t\tthis.refreshUiAfterBackendChange();\n\t\t\t\tthis.updateToolBackendStatus();\n\t\t\t}\n\t\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.removeSandboxStatesForContainer(result.container.id);\n\t\tconst activeContainerId = this.activeSandboxContainerId;\n\t\tconst stoppedActiveSandbox =\n\t\t\tactiveContainerId !== undefined && this.sandboxContainerIdsMatch(result.container.id, activeContainerId);\n\t\tif (stoppedActiveSandbox && this.activeSandboxBackendConnected) {\n\t\t\tawait this.session.clearRemoteSandbox();\n\t\t\tthis.refreshUiAfterBackendChange();\n\t\t\tthis.updateToolBackendStatus();\n\t\t}\n\t\tif (stoppedActiveSandbox) {\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t}\n\t}\n\n\tprivate async stopSandboxBackend(\n\t\ttarget: string | undefined,\n\t\tservice: SandboxService,\n\t\tworkspaceRoot: string,\n\t\tsessionKey: string,\n\t): Promise<void> {\n\t\tif (this.activeSandboxBackendConnected && !this.activeSandboxContainerId) {\n\t\t\tawait this.session.clearRemoteSandbox();\n\t\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\tthis.refreshUiAfterBackendChange();\n\t\t\tthis.updateToolBackendStatus();\n\t\t\tthis.showStatus(\"Sandbox detached\");\n\t\t\treturn;\n\t\t}\n\t\tconst attached = this.sessionSandboxStates.get(sessionKey);\n\t\tif (\n\t\t\tattached?.url?.startsWith(\"grip+ws:\") &&\n\t\t\tattached.containerId === this.activeSandboxContainerId &&\n\t\t\t(!target || target === attached.containerId)\n\t\t) {\n\t\t\tif (this.activeSandboxBackendConnected) await this.session.clearRemoteSandbox();\n\t\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\tthis.refreshUiAfterBackendChange();\n\t\t\tthis.updateToolBackendStatus();\n\t\t\tthis.showStatus(\"Shared sandbox detached; VM and guest daemon remain running\");\n\t\t\treturn;\n\t\t}\n\t\tconst result = await service.stop({\n\t\t\tworkspaceRoot,\n\t\t\ttarget,\n\t\t\tcurrentContainerId: this.activeSandboxContainerId,\n\t\t});\n\t\tawait this.reconcileStoppedSandbox(result, sessionKey);\n\t\tthis.showStatus(formatSandboxStopResult(result));\n\t}\n\n\tprivate async executeSandboxCommand(\n\t\tcommand: SandboxUserCommand,\n\t\tservice: LimaSandboxService,\n\t\tworkspaceRoot: string,\n\t\tsessionKey: string,\n\t): Promise<void> {\n\t\tswitch (command.subcommand) {\n\t\t\tcase \"status\":\n\t\t\t\tthis.showStatus(this.formatToolBackendStatus(this.session.getToolBackendInfo()));\n\t\t\t\treturn;\n\t\t\tcase \"clear\":\n\t\t\t\tawait this.clearSandboxBackend(sessionKey);\n\t\t\t\treturn;\n\t\t\tcase \"attach\":\n\t\t\t\tif (!this.ensureSandboxCanActivate(sessionKey)) return;\n\t\t\t\tawait this.attachSandboxBackend(command.url, service, sessionKey);\n\t\t\t\treturn;\n\t\t\tcase \"start\": {\n\t\t\t\tconst attached = this.sessionSandboxStates.get(sessionKey);\n\t\t\t\tconst updatingAttached =\n\t\t\t\t\tcommand.update === true &&\n\t\t\t\t\tattached?.url.startsWith(\"grip+ws:\") === true &&\n\t\t\t\t\tattached.containerId === command.name &&\n\t\t\t\t\tthis.activeSandboxBackendConnected;\n\t\t\t\tif (!updatingAttached && !this.ensureSandboxCanActivate(sessionKey)) return;\n\t\t\t\tawait this.startSandboxBackend(command, service, workspaceRoot, sessionKey, updatingAttached);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"list\":\n\t\t\t\tthis.showStatus(formatSandboxList(await service.list({ workspaceRoot })));\n\t\t\t\treturn;\n\t\t\tcase \"stop\":\n\t\t\t\tawait this.stopSandboxBackend(command.target, service, workspaceRoot, sessionKey);\n\t\t}\n\t}\n\n\tprivate async handleSandboxCommand(text: string): Promise<void> {\n\t\tlet command: SandboxUserCommand;\n\t\ttry {\n\t\t\tcommand = parseSandboxUserCommand(text);\n\t\t} catch (error) {\n\t\t\tthis.showWarning(error instanceof Error ? error.message : String(error));\n\t\t\treturn;\n\t\t}\n\n\t\tconst service = this.createLimaSandboxService();\n\t\tconst workspaceRoot = this.activeSession.getCwd();\n\t\tconst sessionKey = getSessionSandboxKey(this.activeSession);\n\t\ttry {\n\t\t\tawait this.executeSandboxCommand(command, service, workspaceRoot, sessionKey);\n\t\t} catch (error) {\n\t\t\tthis.showError(redactSecrets(error instanceof Error ? error.message : String(error)));\n\t\t}\n\t}\n\n\tprivate handleSessionCommand(): void {\n\t\tconst stats = this.session.getSessionStats();\n\t\tconst sessionName = this.activeSession.getSessionName();\n\n\t\tlet info = `${theme.bold(\"Session Info\")}\\n\\n`;\n\t\tif (sessionName) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Name:\")} ${sessionName}\\n`;\n\t\t}\n\t\tinfo += `${theme.fg(\"dim\", \"File:\")} ${stats.sessionFile ?? \"In-memory\"}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"ID:\")} ${stats.sessionId}\\n\\n`;\n\t\tinfo += `${theme.bold(\"Messages\")}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"User:\")} ${stats.userMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Assistant:\")} ${stats.assistantMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Tool Calls:\")} ${stats.toolCalls}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Tool Results:\")} ${stats.toolResults}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.totalMessages}\\n\\n`;\n\t\tinfo += `${theme.bold(\"Tokens\")}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Input:\")} ${stats.tokens.input.toLocaleString()}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Output:\")} ${stats.tokens.output.toLocaleString()}\\n`;\n\t\tif (stats.tokens.cacheRead > 0) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Cache Read:\")} ${stats.tokens.cacheRead.toLocaleString()}\\n`;\n\t\t}\n\t\tif (stats.tokens.cacheWrite > 0) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Cache Write:\")} ${stats.tokens.cacheWrite.toLocaleString()}\\n`;\n\t\t}\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.tokens.total.toLocaleString()}\\n`;\n\n\t\tif (stats.cost > 0) {\n\t\t\tinfo += `\\n${theme.bold(\"Cost\")}\\n`;\n\t\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.cost.toFixed(4)}`;\n\t\t}\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(info, 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleChangelogCommand(): void {\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst allEntries = parseChangelog(changelogPath);\n\n\t\tconst changelogMarkdown =\n\t\t\tallEntries.length > 0\n\t\t\t\t? allEntries\n\t\t\t\t\t\t.reverse()\n\t\t\t\t\t\t.map((e) => e.content)\n\t\t\t\t\t\t.join(\"\\n\\n\")\n\t\t\t\t: \"No changelog entries found.\";\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Get capitalized display string for an app keybinding action.\n\t */\n\tprivate getAppKeyDisplay(action: AppKeybinding): string {\n\t\treturn keyDisplayText(action);\n\t}\n\n\t/**\n\t * Get capitalized display string for an editor keybinding action.\n\t */\n\tprivate getEditorKeyDisplay(action: Keybinding): string {\n\t\treturn keyDisplayText(action);\n\t}\n\n\tprivate handleHotkeysCommand(): void {\n\t\t// Navigation keybindings\n\t\tconst cursorUp = this.getEditorKeyDisplay(\"tui.editor.cursorUp\");\n\t\tconst cursorDown = this.getEditorKeyDisplay(\"tui.editor.cursorDown\");\n\t\tconst cursorLeft = this.getEditorKeyDisplay(\"tui.editor.cursorLeft\");\n\t\tconst cursorRight = this.getEditorKeyDisplay(\"tui.editor.cursorRight\");\n\t\tconst cursorWordLeft = this.getEditorKeyDisplay(\"tui.editor.cursorWordLeft\");\n\t\tconst cursorWordRight = this.getEditorKeyDisplay(\"tui.editor.cursorWordRight\");\n\t\tconst cursorLineStart = this.getEditorKeyDisplay(\"tui.editor.cursorLineStart\");\n\t\tconst cursorLineEnd = this.getEditorKeyDisplay(\"tui.editor.cursorLineEnd\");\n\t\tconst jumpForward = this.getEditorKeyDisplay(\"tui.editor.jumpForward\");\n\t\tconst jumpBackward = this.getEditorKeyDisplay(\"tui.editor.jumpBackward\");\n\t\tconst pageUp = this.getEditorKeyDisplay(\"tui.editor.pageUp\");\n\t\tconst pageDown = this.getEditorKeyDisplay(\"tui.editor.pageDown\");\n\n\t\t// Editing keybindings\n\t\tconst submit = this.getEditorKeyDisplay(\"tui.input.submit\");\n\t\tconst newLine = this.getEditorKeyDisplay(\"tui.input.newLine\");\n\t\tconst deleteWordBackward = this.getEditorKeyDisplay(\"tui.editor.deleteWordBackward\");\n\t\tconst deleteWordForward = this.getEditorKeyDisplay(\"tui.editor.deleteWordForward\");\n\t\tconst deleteToLineStart = this.getEditorKeyDisplay(\"tui.editor.deleteToLineStart\");\n\t\tconst deleteToLineEnd = this.getEditorKeyDisplay(\"tui.editor.deleteToLineEnd\");\n\t\tconst yank = this.getEditorKeyDisplay(\"tui.editor.yank\");\n\t\tconst yankPop = this.getEditorKeyDisplay(\"tui.editor.yankPop\");\n\t\tconst undo = this.getEditorKeyDisplay(\"tui.editor.undo\");\n\t\tconst tab = this.getEditorKeyDisplay(\"tui.input.tab\");\n\n\t\t// App keybindings\n\t\tconst interrupt = this.getAppKeyDisplay(\"app.interrupt\");\n\t\tconst clear = this.getAppKeyDisplay(\"app.clear\");\n\t\tconst exit = this.getAppKeyDisplay(\"app.exit\");\n\t\tconst suspend = this.getAppKeyDisplay(\"app.suspend\");\n\t\tconst cycleThinkingLevel = this.getAppKeyDisplay(\"app.thinking.cycle\");\n\t\tconst cycleModelForward = this.getAppKeyDisplay(\"app.model.cycleForward\");\n\t\tconst selectModel = this.getAppKeyDisplay(\"app.model.select\");\n\t\tconst expandTools = this.getAppKeyDisplay(\"app.tools.expand\");\n\t\tconst toggleThinking = this.getAppKeyDisplay(\"app.thinking.toggle\");\n\t\tconst externalEditor = this.getAppKeyDisplay(\"app.editor.external\");\n\t\tconst cycleModelBackward = this.getAppKeyDisplay(\"app.model.cycleBackward\");\n\t\tconst copyMessage = this.getAppKeyDisplay(\"app.message.copy\");\n\t\tconst followUp = this.getAppKeyDisplay(\"app.message.followUp\");\n\t\tconst dequeue = this.getAppKeyDisplay(\"app.message.dequeue\");\n\t\tconst pasteImage = this.getAppKeyDisplay(\"app.clipboard.pasteImage\");\n\n\t\tlet hotkeys = `\n**Navigation**\n| Key | Action |\n|-----|--------|\n| \\`${cursorUp}\\` / \\`${cursorDown}\\` / \\`${cursorLeft}\\` / \\`${cursorRight}\\` | Move cursor / browse history (Up when empty) |\n| \\`${cursorWordLeft}\\` / \\`${cursorWordRight}\\` | Move by word |\n| \\`${cursorLineStart}\\` | Start of line |\n| \\`${cursorLineEnd}\\` | End of line |\n| \\`${jumpForward}\\` | Jump forward to character |\n| \\`${jumpBackward}\\` | Jump backward to character |\n| \\`${pageUp}\\` / \\`${pageDown}\\` | Scroll by page |\n\n**Editing**\n| Key | Action |\n|-----|--------|\n| \\`${submit}\\` | Send message |\n| \\`${newLine}\\` | New line${process.platform === \"win32\" ? \" (Ctrl+Enter on Windows Terminal)\" : \"\"} |\n| \\`${deleteWordBackward}\\` | Delete word backwards |\n| \\`${deleteWordForward}\\` | Delete word forwards |\n| \\`${deleteToLineStart}\\` | Delete to start of line |\n| \\`${deleteToLineEnd}\\` | Delete to end of line |\n| \\`${yank}\\` | Paste the most-recently-deleted text |\n| \\`${yankPop}\\` | Cycle through the deleted text after pasting |\n| \\`${undo}\\` | Undo |\n\n**Other**\n| Key | Action |\n|-----|--------|\n| \\`${tab}\\` | Path completion / accept autocomplete |\n| \\`${interrupt}\\` | Cancel autocomplete / abort streaming |\n| \\`${clear}\\` | Clear editor (first) / exit (second) |\n| \\`${exit}\\` | Exit (when editor is empty) |\n| \\`${suspend}\\` | Suspend to background |\n| \\`${cycleThinkingLevel}\\` | Cycle thinking level |\n| \\`${cycleModelForward}\\` / \\`${cycleModelBackward}\\` | Cycle models |\n| \\`${selectModel}\\` | Open model selector |\n| \\`${expandTools}\\` | Toggle tool output expansion |\n| \\`${toggleThinking}\\` | Toggle thinking block visibility |\n| \\`${externalEditor}\\` | Edit message in external editor |\n| \\`${copyMessage}\\` | Copy last assistant message |\n| \\`${followUp}\\` | Queue follow-up message |\n| \\`${dequeue}\\` | Restore queued messages |\n| \\`${pasteImage}\\` | Paste image or text from clipboard |\n| \\`/\\` | Slash commands |\n| \\`!\\` | Run bash command |\n| \\`!!\\` | Run bash command (excluded from context) |\n`;\n\n\t\t// Add extension-registered shortcuts\n\t\tconst extensionRunner = this.session.extensionRunner;\n\t\tconst shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());\n\t\tif (shortcuts.size > 0) {\n\t\t\thotkeys += `\n**Extensions**\n| Key | Action |\n|-----|--------|\n`;\n\t\t\tfor (const [key, shortcut] of shortcuts) {\n\t\t\t\tconst description = shortcut.description ?? shortcut.extensionPath;\n\t\t\t\tconst keyDisplay = formatKeyText(key, { capitalize: true });\n\t\t\t\thotkeys += `| \\`${keyDisplay}\\` | ${description} |\\n`;\n\t\t\t}\n\t\t}\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"Keyboard Shortcuts\")), 1, 0));\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings()));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleClearCommand(): Promise<void> {\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t}\n\t\tthis.statusContainer.clear();\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.newSession();\n\t\t\tif (result.cancelled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(`${theme.fg(\"accent\", \"✓ New session started\")}`, 1, 1));\n\t\t\tthis.ui.requestRender();\n\t\t} catch (error: unknown) {\n\t\t\tawait this.handleFatalRuntimeError(\"Failed to create session\", error);\n\t\t}\n\t}\n\n\tprivate handleDebugCommand(): void {\n\t\tconst width = this.ui.terminal.columns;\n\t\tconst height = this.ui.terminal.rows;\n\t\tconst allLines = this.ui.render(width);\n\n\t\tconst debugLogPath = getDebugLogPath();\n\t\tconst debugData = [\n\t\t\t`Debug output at ${new Date().toISOString()}`,\n\t\t\t`Terminal: ${width}x${height}`,\n\t\t\t`Total lines: ${allLines.length}`,\n\t\t\t\"\",\n\t\t\t\"=== All rendered lines with visible widths ===\",\n\t\t\t...allLines.map((line, idx) => {\n\t\t\t\tconst vw = visibleWidth(line);\n\t\t\t\tconst escaped = JSON.stringify(line);\n\t\t\t\treturn `[${idx}] (w=${vw}) ${escaped}`;\n\t\t\t}),\n\t\t\t\"\",\n\t\t\t\"=== Agent messages (JSONL) ===\",\n\t\t\t...this.session.messages.map((msg) => JSON.stringify(msg)),\n\t\t\t\"\",\n\t\t].join(\"\\n\");\n\n\t\tfs.mkdirSync(path.dirname(debugLogPath), { recursive: true });\n\t\tfs.writeFileSync(debugLogPath, debugData);\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(`${theme.fg(\"accent\", \"✓ Debug log written\")}\\n${theme.fg(\"muted\", debugLogPath)}`, 1, 1),\n\t\t);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate createBashExecutionDisplay(\n\t\tcommand: string,\n\t\texcludeFromContext: boolean,\n\t\tisDeferred: boolean,\n\t): BashExecutionComponent {\n\t\tconst component = new BashExecutionComponent(command, this.ui, excludeFromContext);\n\t\tthis.bashComponent = component;\n\t\tif (isDeferred) {\n\t\t\tthis.pendingMessagesContainer.addChild(component);\n\t\t\tthis.pendingBashComponents.push(component);\n\t\t} else {\n\t\t\tthis.chatContainer.addChild(component);\n\t\t}\n\t\treturn component;\n\t}\n\n\tprivate async handleBashCommand(command: string, excludeFromContext = false): Promise<void> {\n\t\tconst extensionRunner = this.session.extensionRunner;\n\n\t\t// Emit user_bash event to let extensions intercept\n\t\tconst eventResult = await extensionRunner.emitUserBash({\n\t\t\ttype: \"user_bash\",\n\t\t\tcommand,\n\t\t\texcludeFromContext,\n\t\t\tcwd: this.activeSession.getCwd(),\n\t\t});\n\n\t\t// If extension returned a full result, use it directly\n\t\tif (eventResult?.result) {\n\t\t\tconst result = eventResult.result;\n\n\t\t\tconst component = this.createBashExecutionDisplay(command, excludeFromContext, this.session.isStreaming);\n\n\t\t\t// Show output and complete\n\t\t\tif (result.output) {\n\t\t\t\tcomponent.appendOutput(result.output);\n\t\t\t}\n\t\t\tcomponent.setComplete(\n\t\t\t\tresult.exitCode,\n\t\t\t\tresult.cancelled,\n\t\t\t\tresult.truncated ? ({ truncated: true, content: result.output } as TruncationResult) : undefined,\n\t\t\t\tresult.fullOutputPath,\n\t\t\t);\n\n\t\t\t// Record the result in session\n\t\t\tthis.session.recordBashResult(command, result, { excludeFromContext });\n\t\t\tthis.bashComponent = undefined;\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\t// Normal execution path (possibly with custom operations)\n\t\tconst isDeferred = this.session.isStreaming;\n\t\tthis.createBashExecutionDisplay(command, excludeFromContext, isDeferred);\n\t\tthis.ui.requestRender();\n\n\t\ttry {\n\t\t\tconst result = await this.session.executeBash(\n\t\t\t\tcommand,\n\t\t\t\t(chunk) => {\n\t\t\t\t\tif (this.bashComponent) {\n\t\t\t\t\t\tthis.bashComponent.appendOutput(chunk);\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ excludeFromContext, operations: eventResult?.operations },\n\t\t\t);\n\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(\n\t\t\t\t\tresult.exitCode,\n\t\t\t\t\tresult.cancelled,\n\t\t\t\t\tresult.truncated ? ({ truncated: true, content: result.output } as TruncationResult) : undefined,\n\t\t\t\t\tresult.fullOutputPath,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(undefined, false);\n\t\t\t}\n\t\t\tthis.showError(`Bash command failed: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\n\t\tthis.bashComponent = undefined;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleCompactCommand(customInstructions?: string): Promise<void> {\n\t\tconst entries = this.activeSession.getEntries();\n\t\tconst messageCount = entries.filter((e) => e.type === \"message\").length;\n\n\t\tif (messageCount < 2) {\n\t\t\tthis.showWarning(\"Nothing to compact (no messages yet)\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t}\n\t\tthis.statusContainer.clear();\n\n\t\ttry {\n\t\t\tawait this.session.compact(customInstructions);\n\t\t} catch {\n\t\t\t// Ignore, will be emitted as an event\n\t\t}\n\t}\n\n\tstop(fullscreenExitOutput = this.settingsManager.getFullscreenExitOutput()): void {\n\t\tthis.unregisterSignalHandlers();\n\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\tthis.ui.terminal.setProgress(false);\n\t\t}\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t}\n\t\tthis.summarizationRetryCountdown?.dispose();\n\t\tthis.summarizationRetryCountdown = undefined;\n\t\tthis.summarizationRetryLoader?.stop();\n\t\tthis.summarizationRetryLoader = undefined;\n\t\tthis.branchSummaryLoader?.stop();\n\t\tthis.branchSummaryLoader = undefined;\n\t\tthis.clearExtensionTerminalInputListeners();\n\t\tthis.footer.dispose();\n\t\tthis.footerDataProvider.dispose();\n\t\tif (this.unsubscribe) {\n\t\t\tthis.unsubscribe();\n\t\t}\n\t\tthis.hookExecutionUnsubscribe?.();\n\t\tthis.hookExecutionUnsubscribe = undefined;\n\t\tthis.hookExecutionActivityUnsubscribe?.();\n\t\tthis.hookExecutionActivityUnsubscribe = undefined;\n\t\tif (this.isInitialized) {\n\t\t\tthis.stopInteractiveTui(fullscreenExitOutput);\n\t\t\tthis.isInitialized = false;\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"interactive-mode.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/interactive-mode.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAaH,OAAO,EAGN,KAAK,YAAY,EAUjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EASX,QAAQ,EAER,OAAO,EACP,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEN,KAAK,SAAS,EAgBd,KAAK,GAAG,EACR,YAAY,EACZ,aAAa,EAGb,MAAM,qBAAqB,CAAC;AAwC7B,OAAO,EAEN,KAAK,oBAAoB,EAEzB,MAAM,0BAA0B,CAAC;AAqClC,OAAO,EAAE,KAAK,oBAAoB,EAA2B,MAAM,gCAAgC,CAAC;AAiBpG,OAAO,EAA0B,KAAK,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AA8I9F,wBAAgB,qBAAqB,CACpC,UAAU,EAAE,MAAM,EAClB,gBAAgB,EAAE,WAAW,CAAC,MAAM,CAAC,EACrC,kBAAkB,GAAE,WAAW,CAAC,MAAM,CAA4B,GAChE,OAAO,CAQT;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB;IACtC,gEAAgE;IAChE,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC7B,4DAA4D;IAC5D,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,qEAAqE;IACrE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,8CAA8C;IAC9C,aAAa,CAAC,EAAE,YAAY,EAAE,CAAC;IAC/B,4DAA4D;IAC5D,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,6DAA6D;IAC7D,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,qGAAqG;IACrG,OAAO,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,UAAU,qBAAqB;IAC9B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,kBAAkB,EAAE,OAAO,CAAC;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,iBAAiB,CAAC,EAAE,MAAM,IAAI,CAAC;CAC/B;AAED,MAAM,MAAM,cAAc,GAAG,aAAa,GAAG,YAAY,CAAC;AA2H1D,MAAM,WAAW,uBAAuB;IACvC,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAKD,MAAM,WAAW,2BAA2B;IAC3C,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAWD,MAAM,WAAW,YAAY;IAC5B,SAAS,EAAE,SAAS,CAAC;IACrB,KAAK,EAAE,SAAS,CAAC;CACjB;AAED,MAAM,MAAM,eAAe,GAAG,CAAC,IAAI,EAAE,MAAM,IAAI,KAAK,YAAY,CAAC;AAMjE,MAAM,WAAW,kBAAkB;IAClC,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED,wEAAwE;AACxE,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,cAAc,CASnF;AAED,0FAA0F;AAC1F,wBAAgB,6BAA6B,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,GAAG,CA4BpE;AAED,qBAAa,eAAe;IAC3B,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,OAAO,CAAyB;IACxC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAEhC;IACF,OAAO,CAAC,QAAQ,CAA+B;IAC/C,OAAO,CAAC,EAAE,CAAM;IAChB,OAAO,CAAC,qBAAqB,CAAuC;IACpE,OAAO,CAAC,wBAAwB,CAAY;IAC5C,OAAO,CAAC,aAAa,CAAY;IACjC,OAAO,CAAC,iBAAiB,CAAY;IACrC,OAAO,CAAC,oBAAoB,CAAyB;IACrD,OAAO,CAAC,oBAAoB,CAAwB;IACpD,OAAO,CAAC,wBAAwB,CAAY;IAC5C,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,aAAa,CAAe;IACpC,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,sBAAsB,CAA4B;IAC1D,OAAO,CAAC,oBAAoB,CAAmC;IAC/D,OAAO,CAAC,4BAA4B,CAAqC;IACzE,OAAO,CAAC,MAAM,CAAqB;IACnC,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,eAAe,CAAY;IACnC,OAAO,CAAC,kBAAkB,CAAqB;IAE/C,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,eAAe,CAAC,CAAyB;IACjD,OAAO,CAAC,iBAAiB,CAAgB;IACzC,OAAO,CAAC,gBAAgB,CAAiC;IACzD,OAAO,CAAC,cAAc,CAAiC;IACvD,OAAO,CAAC,0BAA0B,CAAS;IAC3C,OAAO,CAAC,8BAA8B,CAAS;IAC/C,OAAO,CAAC,cAAc,CAAQ;IAC9B,OAAO,CAAC,uBAAuB,CAAiD;IAChF,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAgB;IACtD,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAAiB;IAC5D,OAAO,CAAC,mBAAmB,CAAmC;IAE9D,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,iBAAiB,CAAiC;IAC1D,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,iCAAiC,CAAS;IAGlD,OAAO,CAAC,gBAAgB,CAAiC;IACzD,OAAO,CAAC,cAAc,CAA+B;IAGrD,OAAO,CAAC,kBAAkB,CAAoD;IAC9E,OAAO,CAAC,gBAAgB,CAA2C;IAGnE,OAAO,CAAC,YAAY,CAA6C;IAGjE,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,wBAAwB,CAAqB;IACrD,OAAO,CAAC,6BAA6B,CAAS;IAC9C,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAA0C;IAC/E,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAA0C;IAG/E,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,SAAS,CAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAAsB;IAEjE,OAAO,CAAC,aAAa,CAA6B;IAGlD,OAAO,CAAC,WAAW,CAAC,CAAa;IACjC,OAAO,CAAC,wBAAwB,CAAC,CAAa;IAC9C,OAAO,CAAC,gCAAgC,CAAC,CAAa;IACtD,OAAO,CAAC,0BAA0B,CAAK;IACvC,OAAO,CAAC,+BAA+B,CAAS;IAChD,OAAO,CAAC,oBAAoB,CAAC,CAAU;IACvC,OAAO,CAAC,oBAAoB,CAA+B;IAC3D,OAAO,CAAC,uBAAuB,CAAgC;IAC/D,OAAO,CAAC,4BAA4B,CAAqC;IACzE,OAAO,CAAC,6BAA6B,CAAmD;IACxF,OAAO,CAAC,uBAAuB,CAAS;IACxC,OAAO,CAAC,qBAAqB,CAAyB;IAGtD,OAAO,CAAC,UAAU,CAAS;IAG3B,OAAO,CAAC,aAAa,CAAiD;IAGtE,OAAO,CAAC,qBAAqB,CAAgC;IAG7D,OAAO,CAAC,oBAAoB,CAAiC;IAC7D,OAAO,CAAC,2BAA2B,CAAC,CAAa;IACjD,OAAO,CAAC,mBAAmB,CAAqB;IAChD,OAAO,CAAC,wBAAwB,CAAqB;IACrD,OAAO,CAAC,2BAA2B,CAA6B;IAGhE,OAAO,CAAC,WAAW,CAAiC;IACpD,OAAO,CAAC,cAAc,CAAyC;IAC/D,OAAO,CAAC,kBAAkB,CAAC,CAAa;IAGxC,OAAO,CAAC,wBAAwB,CAAiC;IAGjE,OAAO,CAAC,iBAAiB,CAAS;IAGlC,OAAO,CAAC,iBAAiB,CAAqD;IAC9E,OAAO,CAAC,cAAc,CAAkD;IACxE,OAAO,CAAC,eAAe,CAAmD;IAC1E,OAAO,CAAC,mCAAmC,CAAiD;IAE5F,OAAO,CAAC,qBAAqB,CAA0C;IACvE,OAAO,CAAC,qBAAqB,CAA0C;IACvE,OAAO,CAAC,oBAAoB,CAAa;IACzC,OAAO,CAAC,oBAAoB,CAAa;IAGzC,OAAO,CAAC,YAAY,CAA8C;IAGlE,OAAO,CAAC,eAAe,CAAY;IAGnC,OAAO,CAAC,aAAa,CAAoC;IAGzD,OAAO,CAAC,YAAY,CAA8C;IAGlE,OAAO,KAAK,OAAO,GAElB;IACD,OAAO,KAAK,KAAK,GAEhB;IACD,OAAO,KAAK,aAAa,GAExB;IACD,OAAO,KAAK,eAAe,GAE1B;IAED,YAAY,WAAW,EAAE,oBAAoB,EAAE,OAAO,GAAE,sBAA2B,EA2DlF;IAED,OAAO,CAAC,wBAAwB;IAyBhC,OAAO,CAAC,6BAA6B;IASrC,OAAO,CAAC,oCAAoC;IAkB5C,OAAO,CAAC,8BAA8B;IAgJtC,OAAO,CAAC,yBAAyB;IAajC,OAAO,CAAC,0BAA0B;IA8BlC,OAAO,CAAC,uBAAuB;IAwD/B,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,mBAAmB;IAoC3B,OAAO,CAAC,kBAAkB;IAS1B,OAAO,CAAC,aAAa;IAgDf,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CA8D1B;IAED;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAU3B;;;OAGG;IACG,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAMzB;IAED,OAAO,CAAC,qBAAqB;IAY7B,OAAO,CAAC,mBAAmB;YAWb,oBAAoB;YAQpB,sBAAsB;YAMtB,wBAAwB;YAMxB,sBAAsB;YAkBtB,sBAAsB;IA+CpC;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IA2B9B,OAAO,CAAC,sBAAsB;IAmB9B,OAAO,CAAC,4BAA4B;IAWpC,OAAO,CAAC,iBAAiB;IAYzB,OAAO,CAAC,0BAA0B;IAMlC,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,wBAAwB;IAIhC;;OAEG;IACH,OAAO,CAAC,YAAY;IA6BpB,OAAO,CAAC,mBAAmB;IAU3B,OAAO,CAAC,4BAA4B;IAcpC,OAAO,CAAC,wBAAwB;IAqBhC,OAAO,CAAC,6BAA6B;IAOrC,OAAO,CAAC,kCAAkC;IAwB1C,OAAO,CAAC,yBAAyB;IA0BjC,OAAO,CAAC,oBAAoB;IAY5B,OAAO,CAAC,aAAa;IASrB,OAAO,CAAC,eAAe;IAKvB,OAAO,CAAC,gBAAgB;IA0BxB,OAAO,CAAC,iBAAiB;IAwBzB,OAAO,CAAC,qBAAqB;IAc7B,OAAO,CAAC,oBAAoB;IAW5B,OAAO,CAAC,oBAAoB;IAyB5B,OAAO,CAAC,wBAAwB;IAUhC,OAAO,CAAC,iBAAiB;IAYzB,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,wBAAwB;IAchC,OAAO,CAAC,yBAAyB;IAuBjC,OAAO,CAAC,yBAAyB;IAwBjC,OAAO,CAAC,6BAA6B;IAuBrC,OAAO,CAAC,2BAA2B;IAuBnC,OAAO,CAAC,sBAAsB;IAc9B,OAAO,CAAC,kBAAkB;IAwB1B,OAAO,CAAC,2BAA2B;IASnC,OAAO,CAAC,4BAA4B;IAYpC,OAAO,CAAC,+BAA+B;IAWvC,OAAO,CAAC,+BAA+B;IAcvC,OAAO,CAAC,mBAAmB;YAcb,4BAA4B;IAuF1C,OAAO,CAAC,oBAAoB;YAmBd,oBAAoB;YA0BpB,uBAAuB;IAQrC,OAAO,CAAC,gCAAgC;IAWxC,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,sBAAsB;IAQ9B,OAAO,CAAC,uBAAuB;IAI/B;;OAEG;IACH,OAAO,CAAC,2BAA2B;IAInC;;OAEG;IACH,OAAO,CAAC,uBAAuB;IA4D/B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAK1B,OAAO,CAAC,uBAAuB;IAS/B,OAAO,CAAC,uBAAuB;IAI/B,OAAO,CAAC,uBAAuB;IAK/B,OAAO,CAAC,mBAAmB;IAU3B,OAAO,CAAC,iBAAiB;IASzB,OAAO,CAAC,0BAA0B;IASlC,OAAO,CAAC,2BAA2B;IAuBnC,OAAO,CAAC,iCAAiC;IAgBzC,OAAO,CAAC,kCAAkC;IAe1C,OAAO,CAAC,iBAAiB;IAmBzB,OAAO,CAAC,mBAAmB;IAM3B,OAAO,CAAC,sBAAsB;IAa9B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IA0C1B,OAAO,CAAC,qBAAqB;IAY7B,OAAO,CAAC,gBAAgB;IAgCxB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAM;IAE9C;;OAEG;IACH,OAAO,CAAC,aAAa;IAOrB,OAAO,CAAC,qBAAqB;IAuB7B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAoB1B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAyC1B,OAAO,CAAC,iCAAiC;IASzC,OAAO,CAAC,qCAAqC;IAO7C,OAAO,CAAC,oCAAoC;IAK5C;;OAEG;IACH,OAAO,CAAC,wBAAwB;IA2DhC;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAwC7B;;OAEG;IACH,OAAO,CAAC,qBAAqB;YAYf,oBAAoB;YASpB,0BAA0B;IAQxC;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAwC1B;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAS1B;;OAEG;IACH,OAAO,CAAC,mBAAmB;IA0B3B;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAQ3B;;;OAGG;IACH,OAAO,CAAC,iCAAiC;IAQzC,OAAO,CAAC,wBAAwB;IAehC,OAAO,CAAC,2BAA2B;IAUnC,OAAO,CAAC,wBAAwB;IAehC;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAkB3B,OAAO,CAAC,0BAA0B;IAWlC,OAAO,CAAC,6BAA6B;YAiBvB,mBAAmB;IA+CjC;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAqB1B,OAAO,CAAC,uBAAuB;IAa/B,OAAO,CAAC,kBAAkB;IAkB1B,OAAO,CAAC,gBAAgB;YA0CV,oBAAoB;YAyBpB,qBAAqB;IAcnC,OAAO,CAAC,oBAAoB;IAI5B,OAAO,CAAC,8BAA8B;IAsBtC,OAAO,CAAC,iCAAiC;IA2FzC,OAAO,CAAC,yBAAyB;YA4GnB,0BAA0B;YAO1B,0BAA0B;YAiB1B,gCAAgC;YAYhC,+BAA+B;IAU7C,OAAO,CAAC,iBAAiB;YAOX,kBAAkB;IAYhC,OAAO,CAAC,wBAAwB;IAIhC,OAAO,CAAC,sBAAsB;IAa9B,OAAO,CAAC,sCAAsC;IAW9C,OAAO,CAAC,0BAA0B;IAiBlC,OAAO,CAAC,wBAAwB;IAYhC,OAAO,CAAC,0BAA0B;IAKlC,OAAO,CAAC,gBAAgB;IAYxB,OAAO,CAAC,gBAAgB;IAmBxB,OAAO,CAAC,0BAA0B;IAmBlC,OAAO,CAAC,kBAAkB;IA2B1B,OAAO,CAAC,6BAA6B;IASrC,OAAO,CAAC,mBAAmB;IAQ3B,OAAO,CAAC,0BAA0B;IASlC,OAAO,CAAC,gBAAgB;IAUxB,OAAO,CAAC,4BAA4B;IAIpC,OAAO,CAAC,gBAAgB;IAiBxB,OAAO,CAAC,cAAc;IAatB,OAAO,CAAC,wBAAwB;IAOhC,OAAO,CAAC,qBAAqB;IAgB7B,OAAO,CAAC,sBAAsB;IAa9B,OAAO,CAAC,mBAAmB;IAS3B,OAAO,CAAC,mBAAmB;IAwB3B,OAAO,CAAC,oBAAoB;IA0B5B,OAAO,CAAC,kBAAkB;IAmB1B,OAAO,CAAC,iCAAiC;IA8BzC,OAAO,CAAC,oCAAoC;IA4B5C,OAAO,CAAC,gCAAgC;YAW1B,WAAW;IA+GzB,+CAA+C;IAC/C,OAAO,CAAC,kBAAkB;IAQ1B;;;;;OAKG;IACH,OAAO,CAAC,UAAU;IAoBlB,OAAO,CAAC,uBAAuB;IAY/B,OAAO,CAAC,gBAAgB;IAcxB,OAAO,CAAC,2BAA2B;IAOnC,OAAO,CAAC,uBAAuB;IAO/B,OAAO,CAAC,0BAA0B;IASlC,OAAO,CAAC,qBAAqB;IAc7B,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,mBAAmB;IAa3B,OAAO,CAAC,gBAAgB;IA4BxB,OAAO,CAAC,wBAAwB;IAkBhC,OAAO,CAAC,wBAAwB;IAQhC,OAAO,CAAC,gCAAgC;IAiBxC,OAAO,CAAC,yBAAyB;IAUjC,OAAO,CAAC,uBAAuB;IAgB/B;;;;;OAKG;IACH,OAAO,CAAC,oBAAoB;IAmB5B,qBAAqB,IAAI,IAAI,CAoB5B;IAEK,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC,CAYpC;IAED,OAAO,CAAC,uBAAuB;IAc/B,OAAO,CAAC,WAAW;IAUnB,OAAO,CAAC,WAAW;IAKnB;;;;OAIG;IACH,OAAO,CAAC,cAAc,CAAS;YAEjB,QAAQ;IAiCtB,OAAO,CAAC,qBAAqB;IAS7B;;;;;;;;;;OAUG;IACH,OAAO,CAAC,aAAa;YAsBP,sBAAsB;IAKpC,OAAO,CAAC,sBAAsB;IAwC9B,OAAO,CAAC,wBAAwB;IAOhC,OAAO,CAAC,WAAW;YAqCL,cAAc;IAgC5B,OAAO,CAAC,aAAa;IASrB,OAAO,CAAC,uBAAuB;IAU/B,OAAO,CAAC,kBAAkB;YAWZ,UAAU;IAmBxB,OAAO,CAAC,yBAAyB;IAIjC,OAAO,CAAC,gBAAgB;IAmBxB,OAAO,CAAC,6BAA6B;YAkBvB,kBAAkB;IA2DhC,WAAW,IAAI,IAAI,CAGlB;IAED,SAAS,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAKpC;IAED,WAAW,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAIxC;IAED,0BAA0B,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI,CA4B3D;IAED,6BAA6B,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAgBtD;IAED;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAa5B;;;OAGG;IACH,OAAO,CAAC,cAAc;IAetB,OAAO,CAAC,4BAA4B;IAmBpC,OAAO,CAAC,6BAA6B;IAqBrC,OAAO,CAAC,sBAAsB;IAQ9B,OAAO,CAAC,kBAAkB;YAUZ,2BAA2B;IAUzC,OAAO,CAAC,sBAAsB;YAWhB,uBAAuB;YAkBvB,oBAAoB;IAkBlC,6DAA6D;IAC7D,OAAO,CAAC,0BAA0B;IAYlC;;;OAGG;IACH,OAAO,CAAC,YAAY;IAYpB,OAAO,CAAC,eAAe;IAgBvB,OAAO,CAAC,oBAAoB;YA+Ld,kBAAkB;YAsBlB,sCAAsC;YAwCtC,mBAAmB;YAKnB,kBAAkB;YAclB,4BAA4B;YAM5B,uCAAuC;IAgCrD,OAAO,CAAC,iBAAiB;YA+BX,kBAAkB;IA6EhC,OAAO,CAAC,uBAAuB;YAuCjB,kBAAkB;YAsBlB,0BAA0B;YAsB1B,mBAAmB;YA8CnB,mBAAmB;IAgBjC,OAAO,CAAC,gBAAgB;IA2CxB,OAAO,CAAC,mBAAmB;YAwCb,mBAAmB;IAyCjC,OAAO,CAAC,uBAAuB;IA0B/B,OAAO,CAAC,wBAAwB;IAmBhC,OAAO,CAAC,yBAAyB;IAqBjC,OAAO,CAAC,yBAAyB;YAwCnB,iBAAiB;YAiDjB,6CAA6C;IAkC3D,OAAO,CAAC,mCAAmC;YAmB7B,8BAA8B;IAmB5C,OAAO,CAAC,sBAAsB;YA4BhB,qBAAqB;IA2CnC,OAAO,CAAC,oBAAoB;YA4Bd,eAAe;YAoGf,eAAe;YA4Cf,oBAAoB;YAoDpB,mBAAmB;YAuFnB,mBAAmB;IAgBjC,OAAO,CAAC,sBAAsB;YA6BhB,mBAAmB;YAkDnB,kBAAkB;YA8FlB,iBAAiB;IAmB/B,OAAO,CAAC,kBAAkB;IAW1B,OAAO,CAAC,iBAAiB;IAoBzB,OAAO,CAAC,2BAA2B;IAMnC,OAAO,CAAC,wBAAwB;YAOlB,uBAAuB;YAgBvB,4BAA4B;IAqB1C,OAAO,CAAC,4BAA4B;IAWpC,OAAO,CAAC,wBAAwB;YAQlB,mBAAmB;YAgBnB,oBAAoB;IAgBlC,OAAO,CAAC,wBAAwB;IAehC,OAAO,CAAC,wBAAwB;YAQlB,sBAAsB;YA2CtB,mBAAmB;IAgDjC,OAAO,CAAC,wBAAwB;IAIhC,OAAO,CAAC,+BAA+B;YAYzB,uBAAuB;YA6BvB,kBAAkB;YAuClB,qBAAqB;YAoCrB,oBAAoB;IAmBlC,OAAO,CAAC,oBAAoB;IAqC5B,OAAO,CAAC,sBAAsB;IAqB9B;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAIxB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAI3B,OAAO,CAAC,oBAAoB;YAqHd,kBAAkB;IAoBhC,OAAO,CAAC,kBAAkB;IAiC1B,OAAO,CAAC,0BAA0B;YAgBpB,iBAAiB;YAuEjB,oBAAoB;IAsBlC,IAAI,CAAC,oBAAoB,uBAAiD,GAAG,IAAI,CA6BhF;CACD","sourcesContent":["/**\n * Interactive mode for the coding agent.\n * Handles TUI rendering and user interaction, delegating business logic to AgentSession.\n */\n\nimport * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type {\n\tAgentMessage,\n\tBashExecutionMessage,\n\tBranchSummaryMessage,\n\tCompactionSummaryMessage,\n\tCustomMessage,\n} from \"@greppleai/grip-agent-core\";\nimport {\n\ttype AssistantMessage,\n\tgetProviders,\n\ttype ImageContent,\n\ttype Model,\n\ttype OAuthAuthInfo,\n\ttype OAuthPrompt,\n\ttype OAuthProviderId,\n\ttype OAuthSelectPrompt,\n\ttype TextContent,\n\ttype ToolCall,\n\ttype ToolResultMessage,\n\ttype UserMessage,\n} from \"@greppleai/grip-ai\";\nimport type {\n\tAutocompleteItem,\n\tAutocompleteProvider,\n\tEditorComponent,\n\tKeybinding,\n\tKeyId,\n\tMarkdownTheme,\n\tOverlayOptions,\n\tSlashCommand,\n\tTerminal,\n\tTuiMainScreenRenderState,\n\tTuiMode,\n} from \"@greppleai/grip-tui\";\nimport {\n\tCombinedAutocompleteProvider,\n\ttype Component,\n\tContainer,\n\tfuzzyFilter,\n\tgetCapabilities,\n\thyperlink,\n\tisViewportTUI,\n\tLoader,\n\ttype LoaderIndicatorOptions,\n\tMarkdown,\n\tmatchesKey,\n\tProcessTerminal,\n\tScrollView,\n\tSpacer,\n\tsetKeybindings,\n\tText,\n\tTruncatedText,\n\ttype TUI,\n\tTuiAltScreen,\n\tTuiMainScreen,\n\tVStack,\n\tvisibleWidth,\n} from \"@greppleai/grip-tui\";\nimport { spawn, spawnSync } from \"child_process\";\nimport {\n\tAPP_NAME,\n\tAPP_TITLE,\n\tgetAgentDir,\n\tgetAuthPath,\n\tgetChangelogPath,\n\tgetDebugLogPath,\n\tgetDocsPath,\n\tgetShareViewerUrl,\n\tPACKAGE_NAME,\n\tVERSION,\n} from \"../../config.ts\";\nimport {\n\ttype AgentSession,\n\ttype AgentSessionEvent,\n\ttype ModelCycleDirection,\n\ttype NavigateTreeOptions,\n\ttype PromptOptions,\n\tparseSkillBlock,\n\ttype QueuedMessages,\n} from \"../../core/agent-session.ts\";\nimport { executeBashWithOperations } from \"../../core/bash-executor.ts\";\nimport type { ExtensionRunner } from \"../../core/extensions/runner.ts\";\nimport type {\n\tAutocompleteProviderFactory,\n\tEditorFactory,\n\tExtensionContext,\n\tExtensionCustomOptions,\n\tExtensionNotificationOptions,\n\tExtensionSwitchSessionOptions,\n\tExtensionUIContext,\n\tExtensionUIDialogOptions,\n\tExtensionWidgetOptions,\n\tMarkdownTransformer,\n\tStreamingBehavior,\n\tTerminalInputHandler,\n} from \"../../core/extensions/types.ts\";\nimport { FooterDataProvider, type ReadonlyFooterDataProvider } from \"../../core/footer-data-provider.ts\";\nimport {\n\ttype GripAgentDiagnostic,\n\ttype GripAgentRuntimeHost,\n\tSessionImportFileNotFoundError,\n} from \"../../core/grip-agent.ts\";\nimport {\n\tHOOK_EXECUTION_CUSTOM_TYPE,\n\ttype HookExecutionNotice,\n\tparseHookExecutionNotice,\n} from \"../../core/hooks/types.ts\";\nimport { type AppKeybinding, KeybindingsManager } from \"../../core/keybindings.ts\";\nimport { createCompactionSummaryMessage } from \"../../core/messages.ts\";\nimport { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope } from \"../../core/model-resolver.ts\";\nimport { DefaultPackageManager } from \"../../core/package-manager.ts\";\nimport { BUILT_IN_PROVIDER_DISPLAY_NAMES } from \"../../core/provider-display-names.ts\";\nimport type {\n\tLoadPromptTemplatesResult,\n\tLoadThemesResult,\n\tResourceCollision,\n\tResourceDiagnostic,\n} from \"../../core/resource-loader.ts\";\nimport type { LoadRulesResult } from \"../../core/rules.ts\";\nimport {\n\tformatSandboxList,\n\tformatSandboxStartResult,\n\tformatSandboxStopResult,\n\tparseSandboxUserCommand,\n\ttype SandboxStartUserCommand,\n\ttype SandboxUserCommand,\n} from \"../../core/sandbox/command.ts\";\nimport {\n\tredactSecrets,\n\ttype SandboxService,\n\ttype SandboxStartResult,\n\ttype SandboxStopResult,\n} from \"../../core/sandbox/config.ts\";\nimport { LimaSandboxService, type ManagedLimaInstance } from \"../../core/sandbox/lima.ts\";\nimport { LocalSessionManager } from \"../../core/session/local-session-manager.ts\";\nimport type { Session } from \"../../core/session/session.ts\";\nimport type { SessionContext } from \"../../core/session/types.ts\";\nimport { formatMissingSessionCwdPrompt, MissingSessionCwdError } from \"../../core/session-cwd.ts\";\nimport { type FullscreenExitOutput, isValidModelProfileName } from \"../../core/settings-manager.ts\";\nimport type { LoadSkillsResult } from \"../../core/skills.ts\";\nimport { BUILTIN_SLASH_COMMANDS, HIDDEN_BUILTIN_SLASH_COMMAND_NAMES } from \"../../core/slash-commands.ts\";\nimport { getSourceBackendIcon, type SourceInfo } from \"../../core/source-info.ts\";\nimport { isInstallTelemetryEnabled } from \"../../core/telemetry.ts\";\nimport type { ToolBackendInfo } from \"../../core/tools/operations.ts\";\nimport type { TruncationResult } from \"../../core/tools/truncate.ts\";\nimport { getNewEntries, parseChangelog } from \"../../utils/changelog.ts\";\nimport { copyToClipboard, readClipboardText } from \"../../utils/clipboard.ts\";\nimport { extensionForImageMimeType, readClipboardImage } from \"../../utils/clipboard-image.ts\";\nimport { getDirectoryCompletions, resolveDirectoryPath } from \"../../utils/directory-completions.ts\";\nimport { parseGitUrl } from \"../../utils/git.ts\";\nimport { getGripUserAgent } from \"../../utils/grip-user-agent.ts\";\nimport { openBrowser } from \"../../utils/open-browser.ts\";\nimport { getCwdRelativePath } from \"../../utils/paths.ts\";\nimport { killTrackedDetachedChildren } from \"../../utils/shell.ts\";\nimport { ensureTool } from \"../../utils/tools-manager.ts\";\nimport { checkForNewGripVersion, type LatestGripRelease } from \"../../utils/version-check.ts\";\nimport { AssistantMessageComponent } from \"./components/assistant-message.ts\";\nimport { BashExecutionComponent } from \"./components/bash-execution.ts\";\nimport { BorderedLoader } from \"./components/bordered-loader.ts\";\nimport { BranchSummaryMessageComponent } from \"./components/branch-summary-message.ts\";\nimport { CompactionSummaryMessageComponent } from \"./components/compaction-summary-message.ts\";\nimport { CountdownTimer } from \"./components/countdown-timer.ts\";\nimport { CustomEditor } from \"./components/custom-editor.ts\";\nimport { CustomMessageComponent } from \"./components/custom-message.ts\";\nimport { DynamicBorder } from \"./components/dynamic-border.ts\";\nimport { ExtensionEditorComponent } from \"./components/extension-editor.ts\";\nimport { ExtensionInputComponent } from \"./components/extension-input.ts\";\nimport { ExtensionSelectorComponent } from \"./components/extension-selector.ts\";\nimport { FooterComponent } from \"./components/footer.ts\";\nimport { HookExecutionComponent } from \"./components/hook-execution.ts\";\nimport { formatKeyText, keyDisplayText, keyHint, keyText, rawKeyHint } from \"./components/keybinding-hints.ts\";\nimport { LoginDialogComponent } from \"./components/login-dialog.ts\";\nimport { createMermaidMarkdownTransformer } from \"./components/mermaid.ts\";\nimport { ModelSelectorComponent } from \"./components/model-selector.ts\";\nimport { type AuthSelectorProvider, OAuthSelectorComponent } from \"./components/oauth-selector.ts\";\nimport { ScopedModelsSelectorComponent } from \"./components/scoped-models-selector.ts\";\nimport { SessionSelectorComponent } from \"./components/session-selector.ts\";\nimport { SettingsSelectorComponent } from \"./components/settings-selector.ts\";\nimport { SkillInvocationMessageComponent } from \"./components/skill-invocation-message.ts\";\nimport { ToolExecutionComponent } from \"./components/tool-execution.ts\";\nimport { TreeSelectorComponent } from \"./components/tree-selector.ts\";\nimport { UserMessageComponent } from \"./components/user-message.ts\";\nimport { UserMessageSelectorComponent } from \"./components/user-message-selector.ts\";\nimport {\n\tgetAvailableThemes,\n\tgetAvailableThemesWithPaths,\n\tgetEditorTheme,\n\tgetMarkdownTheme,\n\tgetThemeByName,\n\tinitTheme,\n\tonThemeChange,\n\tsetRegisteredThemes,\n\tsetTheme,\n\tsetThemeInstance,\n\tstopThemeWatcher,\n\tTheme,\n\ttype ThemeColor,\n\ttheme,\n} from \"./theme/theme.ts\";\n\n/** Interface for components that can be expanded/collapsed */\ninterface Expandable {\n\tsetExpanded(expanded: boolean): void;\n}\n\nfunction isExpandable(obj: unknown): obj is Expandable {\n\treturn typeof obj === \"object\" && obj !== null && \"setExpanded\" in obj && typeof obj.setExpanded === \"function\";\n}\n\nclass ExpandableText extends Text implements Expandable {\n\tprivate readonly getCollapsedText: () => string;\n\tprivate readonly getExpandedText: () => string;\n\n\tconstructor(\n\t\tgetCollapsedText: () => string,\n\t\tgetExpandedText: () => string,\n\t\texpanded = false,\n\t\tpaddingX = 0,\n\t\tpaddingY = 0,\n\t) {\n\t\tsuper(expanded ? getExpandedText() : getCollapsedText(), paddingX, paddingY);\n\t\tthis.getCollapsedText = getCollapsedText;\n\t\tthis.getExpandedText = getExpandedText;\n\t}\n\n\tsetExpanded(expanded: boolean): void {\n\t\tthis.setText(expanded ? this.getExpandedText() : this.getCollapsedText());\n\t}\n}\n\ntype ExtensionNotificationType = \"info\" | \"warning\" | \"error\";\ninterface PendingStopHookNotification {\n\tmessage: string;\n\ttype: ExtensionNotificationType | undefined;\n}\ntype CompactionDisplayReason = \"manual\" | \"threshold\" | \"overflow\";\ntype ProviderAuthenticationType = \"oauth\" | \"api_key\";\ntype AuthenticationOperation = \"login\" | \"logout\";\ntype SessionPathCommand = \"/cd\" | \"/export\" | \"/import\";\n\ninterface ProviderAuthenticationModelSelection {\n\tselectedModel?: Model<any>;\n\tselectionError?: string;\n}\n\ntype CompactionQueuedMessage = {\n\ttext: string;\n\tmode: StreamingBehavior;\n};\n\ninterface SessionSandboxState {\n\ttype: \"daemon\";\n\turl: string;\n\ttoken: string;\n\texpectedCwd: string;\n\tcontainerId?: string;\n}\n\nfunction getSessionSandboxKey(session: Session): string {\n\treturn `${session.getCwd()}\\0${session.getSessionId()}`;\n}\n\nconst DEAD_TERMINAL_ERROR_CODES = new Set([\"EIO\", \"EPIPE\", \"ENOTCONN\"]);\n\nfunction isDeadTerminalError(error: unknown): boolean {\n\tif (!error || typeof error !== \"object\" || !(\"code\" in error)) {\n\t\treturn false;\n\t}\n\tconst code = (error as NodeJS.ErrnoException).code;\n\treturn code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code);\n}\n\nconst ANTHROPIC_SUBSCRIPTION_AUTH_WARNING =\n\t\"Anthropic subscription auth is active. Third-party harness usage draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage.\";\n\nfunction isAnthropicSubscriptionAuthKey(apiKey: string | undefined): boolean {\n\treturn typeof apiKey === \"string\" && apiKey.startsWith(\"sk-ant-oat\");\n}\n\nfunction isUnknownModel(model: Model<any> | undefined): boolean {\n\treturn !!model && model.provider === \"unknown\" && model.id === \"unknown\" && model.api === \"unknown\";\n}\n\nfunction hasDefaultModelProvider(providerId: string): providerId is keyof typeof defaultModelPerProvider {\n\treturn providerId in defaultModelPerProvider;\n}\n\nconst MAX_TUI_HOOK_EXECUTION_NOTICES = 200;\ntype ToolHookEvent = \"PreToolUse\" | \"PostToolUse\" | \"PostToolUseFailure\";\n\nfunction isToolHookEvent(event: string): event is ToolHookEvent {\n\treturn event === \"PreToolUse\" || event === \"PostToolUse\" || event === \"PostToolUseFailure\";\n}\nconst BEDROCK_PROVIDER_ID = \"amazon-bedrock\";\n\nconst BUILT_IN_MODEL_PROVIDERS = new Set<string>(getProviders());\n\nexport function isApiKeyLoginProvider(\n\tproviderId: string,\n\toauthProviderIds: ReadonlySet<string>,\n\tbuiltInProviderIds: ReadonlySet<string> = BUILT_IN_MODEL_PROVIDERS,\n): boolean {\n\tif (BUILT_IN_PROVIDER_DISPLAY_NAMES[providerId]) {\n\t\treturn true;\n\t}\n\tif (builtInProviderIds.has(providerId)) {\n\t\treturn false;\n\t}\n\treturn !oauthProviderIds.has(providerId);\n}\n\n/**\n * Options for InteractiveMode initialization.\n */\nexport interface InteractiveModeOptions {\n\t/** Providers that were migrated to auth.json (shows warning) */\n\tmigratedProviders?: string[];\n\t/** Warning message if session model couldn't be restored */\n\tmodelFallbackMessage?: string;\n\t/** Initial message to send on startup (can include @file content) */\n\tinitialMessage?: string;\n\t/** Images to attach to the initial message */\n\tinitialImages?: ImageContent[];\n\t/** Additional messages to send after the initial message */\n\tinitialMessages?: string[];\n\t/** Force verbose startup (overrides quietStartup setting) */\n\tverbose?: boolean;\n\t/** Initial renderer choice. Defaults to the persisted mode and can be changed during the session. */\n\ttuiMode?: TuiMode;\n}\n\ninterface InteractiveTuiOptions {\n\ttuiMode?: TuiMode;\n\tshowHardwareCursor: boolean;\n\tlogDirectory: string;\n\tterminal?: Terminal;\n\tonRightClickPaste?: () => void;\n}\n\nexport type InteractiveTui = TuiMainScreen | TuiAltScreen;\n\ntype DisposableComponent = Component & { dispose?(): void };\n\ninterface ExtensionTerminalInputSubscription {\n\thandler: TerminalInputHandler;\n\tunsubscribe: () => void;\n}\n\ntype ExtensionWidgetFactory = (tui: TUI, theme: Theme) => DisposableComponent;\ntype ExtensionFooterFactory = (tui: TUI, theme: Theme, footerData: ReadonlyFooterDataProvider) => DisposableComponent;\ntype ExtensionHeaderFactory = (tui: TUI, theme: Theme) => DisposableComponent;\ntype ExtensionCustomFactory<T> = (\n\ttui: TUI,\n\ttheme: Theme,\n\tkeybindings: KeybindingsManager,\n\tdone: (result: T) => void,\n) => DisposableComponent | Promise<DisposableComponent>;\n\ninterface ResourceDisplayItem {\n\tpath: string;\n\tsourceInfo?: SourceInfo;\n}\n\ninterface CompactResourcePath {\n\tpath: string;\n\tsegments: string[];\n}\n\ntype ResourceScope = \"user\" | \"project\" | \"path\";\ntype ResourceSourceColor = \"accent\" | \"muted\";\n\ninterface ResourceSourceDisplayInfo {\n\tlabel: string;\n\tscopeLabel?: string;\n\tcolor: ResourceSourceColor;\n}\n\nconst LOCAL_SOURCE_DISPLAY_INFO: Record<SourceInfo[\"scope\"], Omit<ResourceSourceDisplayInfo, \"color\">> = {\n\tuser: { label: \"user\" },\n\tproject: { label: \"project\" },\n\ttemporary: { label: \"path\", scopeLabel: \"temp\" },\n};\n\nconst CLI_SOURCE_SCOPE_LABELS: Partial<Record<SourceInfo[\"scope\"], string>> = { temporary: \"temp\" };\nconst ACCENT_SOURCE_SCOPE_LABELS: Record<SourceInfo[\"scope\"], string> = {\n\tuser: \"user\",\n\tproject: \"project\",\n\ttemporary: \"temp\",\n};\n\ninterface GroupedResourceDiagnostics {\n\tcollisions: Map<string, ResourceCollision[]>;\n\totherDiagnostics: ResourceDiagnostic[];\n}\n\nfunction groupResourceDiagnostics(diagnostics: readonly ResourceDiagnostic[]): GroupedResourceDiagnostics {\n\tconst collisions = new Map<string, ResourceCollision[]>();\n\tconst otherDiagnostics: ResourceDiagnostic[] = [];\n\tfor (const diagnostic of diagnostics) {\n\t\tif (diagnostic.type !== \"collision\" || !diagnostic.collision) {\n\t\t\totherDiagnostics.push(diagnostic);\n\t\t\tcontinue;\n\t\t}\n\t\tconst collision = diagnostic.collision;\n\t\tconst list = collisions.get(collision.name) ?? [];\n\t\tlist.push(collision);\n\t\tcollisions.set(collision.name, list);\n\t}\n\treturn { collisions, otherDiagnostics };\n}\n\nfunction indexResourceSourceInfos(items: ResourceDisplayItem[]): Map<string, SourceInfo> {\n\tconst sourceInfos = new Map<string, SourceInfo>();\n\tfor (const item of items) {\n\t\tif (item.sourceInfo) sourceInfos.set(item.path, item.sourceInfo);\n\t}\n\treturn sourceInfos;\n}\n\ninterface ResourceScopeGroup {\n\tscope: ResourceScope;\n\tpaths: ResourceDisplayItem[];\n\tpackages: Map<string, ResourceDisplayItem[]>;\n}\n\ninterface ResourceScopeFormatOptions {\n\tformatPath: (item: ResourceDisplayItem) => string;\n\tformatPackagePath: (item: ResourceDisplayItem, source: string) => string;\n}\n\ninterface ShowLoadedResourcesOptions {\n\textensions?: ResourceDisplayItem[];\n\tforce?: boolean;\n\tshowDiagnosticsWhenQuiet?: boolean;\n}\n\ninterface LoadedResourceSnapshot {\n\tskillsResult: LoadSkillsResult;\n\trulesResult: LoadRulesResult;\n\tpromptsResult: LoadPromptTemplatesResult;\n\tthemesResult: LoadThemesResult;\n\textensions: ResourceDisplayItem[];\n\tsourceInfos: Map<string, SourceInfo>;\n}\n\ninterface LoadedResourceSectionOptions {\n\tname: string;\n\tcollapsedBody: string;\n\texpandedBody?: string;\n\tcolor?: ThemeColor;\n}\n\ninterface NamedInstructionResource {\n\tname: string;\n\tfilePath: string;\n\tsourceInfo?: SourceInfo;\n}\n\ninterface CompactListOptions {\n\tsort?: boolean;\n}\n\nexport interface AddMessageToChatOptions {\n\tpopulateHistory?: boolean;\n}\ninterface EditorCommandAction {\n\trun: () => void | Promise<void>;\n}\n\nexport interface RenderSessionContextOptions {\n\tupdateFooter?: boolean;\n\tpopulateHistory?: boolean;\n}\n\nexport interface ShutdownOptions {\n\tfromSignal?: boolean;\n}\n\ninterface RestoreQueuedMessagesOptions {\n\tabort?: boolean;\n\tcurrentText?: string;\n}\n\ninterface FlushCompactionQueueOptions {\n\twillRetry?: boolean;\n}\n\nexport interface SelectorView {\n\tcomponent: Component;\n\tfocus: Component;\n}\n\nexport type SelectorFactory = (done: () => void) => SelectorView;\n\ninterface SessionResumeResult {\n\tcancelled: boolean;\n}\n\nexport interface CopyCommandOptions {\n\tflashConfirmation?: boolean;\n}\n\n/** Composition root for selecting the interactive terminal renderer. */\nexport function createInteractiveTui(options: InteractiveTuiOptions): InteractiveTui {\n\tconst terminal = options.terminal ?? new ProcessTerminal();\n\tif (options.tuiMode === \"fullscreen\") {\n\t\treturn new TuiAltScreen(terminal, options.showHardwareCursor, options.logDirectory, {\n\t\t\topenUrl: openBrowser,\n\t\t\tonRightClickPaste: options.onRightClickPaste,\n\t\t});\n\t}\n\treturn new TuiMainScreen(terminal, options.showHardwareCursor, options.logDirectory);\n}\n\n/** Stable reference for components while InteractiveMode replaces the active renderer. */\nexport function createInteractiveTuiReference(getTui: () => TUI): TUI {\n\treturn new Proxy({} as TUI, {\n\t\tget: (_target, property) => {\n\t\t\tconst tui = getTui();\n\t\t\tconst value = Reflect.get(tui, property, tui);\n\t\t\tif (typeof value !== \"function\") return value;\n\t\t\tlet methodTui = tui;\n\t\t\tlet method = value;\n\t\t\treturn (...args: unknown[]) => {\n\t\t\t\tconst currentTui = getTui();\n\t\t\t\tif (currentTui !== methodTui) {\n\t\t\t\t\tconst currentMethod = Reflect.get(currentTui, property, currentTui);\n\t\t\t\t\tif (typeof currentMethod !== \"function\") {\n\t\t\t\t\t\tthrow new TypeError(`TUI property ${String(property)} is not callable`);\n\t\t\t\t\t}\n\t\t\t\t\tmethodTui = currentTui;\n\t\t\t\t\tmethod = currentMethod;\n\t\t\t\t}\n\t\t\t\treturn Reflect.apply(method, methodTui, args);\n\t\t\t};\n\t\t},\n\t\tset: (_target, property, value) => {\n\t\t\tconst tui = getTui();\n\t\t\treturn Reflect.set(tui, property, value, tui);\n\t\t},\n\t\thas: (_target, property) => Reflect.has(getTui(), property),\n\t\tgetPrototypeOf: () => Reflect.getPrototypeOf(getTui()),\n\t});\n}\n\nexport class InteractiveMode {\n\tprivate runtimeHost: GripAgentRuntimeHost;\n\tprivate options: InteractiveModeOptions;\n\tprivate readonly onRightClickPaste = (): void => {\n\t\tvoid this.handleRightClickPaste();\n\t};\n\tprivate renderer: TuiMainScreen | TuiAltScreen;\n\tprivate ui: TUI;\n\tprivate mainScreenRenderState: TuiMainScreenRenderState | undefined;\n\tprivate loadedResourcesContainer: Container;\n\tprivate chatContainer: Container;\n\tprivate documentContainer: Container;\n\tprivate transcriptScrollView: ScrollView | undefined;\n\tprivate fullscreenLayoutRoot: Component | undefined;\n\tprivate pendingMessagesContainer: Container;\n\tprivate statusContainer: Container;\n\tprivate defaultEditor: CustomEditor;\n\tprivate editor: EditorComponent;\n\tprivate editorComponentFactory: EditorFactory | undefined;\n\tprivate autocompleteProvider: AutocompleteProvider | undefined;\n\tprivate autocompleteProviderWrappers: AutocompleteProviderFactory[] = [];\n\tprivate fdPath: string | undefined;\n\tprivate editorContainer: Container;\n\tprivate footer: FooterComponent;\n\tprivate footerContainer: Container;\n\tprivate footerDataProvider: FooterDataProvider;\n\t// Stored so the same manager can be injected into custom editors, selectors, and extension UI.\n\tprivate keybindings: KeybindingsManager;\n\tprivate version: string;\n\tprivate isInitialized = false;\n\tprivate transcriptRendered = false;\n\tprivate onInputCallback?: (text: string) => void;\n\tprivate pendingUserInputs: string[] = [];\n\tprivate loadingAnimation: Loader | undefined = undefined;\n\tprivate workingMessage: string | undefined = undefined;\n\tprivate compressionDetectionActive = false;\n\tprivate compressionDetectionOwnsLoader = false;\n\tprivate workingVisible = true;\n\tprivate workingIndicatorOptions: LoaderIndicatorOptions | undefined = undefined;\n\tprivate readonly defaultWorkingMessage = \"Working...\";\n\tprivate readonly defaultHiddenThinkingLabel = \"Thinking...\";\n\tprivate hiddenThinkingLabel = this.defaultHiddenThinkingLabel;\n\n\tprivate lastSigintTime = 0;\n\tprivate lastEscapeTime = 0;\n\tprivate changelogMarkdown: string | undefined = undefined;\n\tprivate startupNoticesShown = false;\n\tprivate anthropicSubscriptionWarningShown = false;\n\n\t// Status line tracking (for mutating immediately-sequential status updates)\n\tprivate lastStatusSpacer: Spacer | undefined = undefined;\n\tprivate lastStatusText: Text | undefined = undefined;\n\n\t// Streaming message tracking\n\tprivate streamingComponent: AssistantMessageComponent | undefined = undefined;\n\tprivate streamingMessage: AssistantMessage | undefined = undefined;\n\n\t// Tool execution tracking: toolCallId -> component\n\tprivate pendingTools = new Map<string, ToolExecutionComponent>();\n\n\t// Tool output expansion state\n\tprivate toolOutputExpanded = false;\n\tprivate activeSandboxContainerId: string | undefined;\n\tprivate activeSandboxBackendConnected = false;\n\tprivate readonly sessionSandboxStates = new Map<string, SessionSandboxState>();\n\tprivate readonly managedLimaInstances = new Map<string, ManagedLimaInstance>();\n\n\t// Thinking block visibility state\n\tprivate hideThinkingBlock = false;\n\tprivate outputPad = 1;\n\tprivate readonly mermaidMarkdownTransformer: MarkdownTransformer;\n\t// Skill commands: command name -> skill file path\n\tprivate skillCommands = new Map<string, string>();\n\n\t// Agent subscription unsubscribe function\n\tprivate unsubscribe?: () => void;\n\tprivate hookExecutionUnsubscribe?: () => void;\n\tprivate hookExecutionActivityUnsubscribe?: () => void;\n\tprivate hookExecutionActivityDepth = 0;\n\tprivate hookExecutionActivityOwnsLoader = false;\n\tprivate hookExecutionSession?: Session;\n\tprivate hookExecutionNotices: HookExecutionNotice[][] = [];\n\tprivate hookExecutionComponents: HookExecutionComponent[] = [];\n\tprivate pendingStopHookNotifications: PendingStopHookNotification[] = [];\n\tprivate activeToolHookExecutionGroups = new Map<ToolHookEvent, HookExecutionNotice[]>();\n\tprivate hookExecutionTurnActive = false;\n\tprivate signalCleanupHandlers: Array<() => void> = [];\n\n\t// Track if editor is in bash mode (text starts with !)\n\tprivate isBashMode = false;\n\n\t// Track current bash execution component\n\tprivate bashComponent: BashExecutionComponent | undefined = undefined;\n\n\t// Track pending bash components (shown in pending area, moved to chat on submit)\n\tprivate pendingBashComponents: BashExecutionComponent[] = [];\n\n\t// Auto-compaction state\n\tprivate autoCompactionLoader: Loader | undefined = undefined;\n\tprivate autoCompactionEscapeHandler?: () => void;\n\tprivate branchSummaryLoader: Loader | undefined;\n\tprivate summarizationRetryLoader: Loader | undefined;\n\tprivate summarizationRetryCountdown: CountdownTimer | undefined;\n\n\t// Auto-retry state\n\tprivate retryLoader: Loader | undefined = undefined;\n\tprivate retryCountdown: CountdownTimer | undefined = undefined;\n\tprivate retryEscapeHandler?: () => void;\n\n\t// Messages queued while compaction is running\n\tprivate compactionQueuedMessages: CompactionQueuedMessage[] = [];\n\n\t// Shutdown state\n\tprivate shutdownRequested = false;\n\n\t// Extension UI state\n\tprivate extensionSelector: ExtensionSelectorComponent | undefined = undefined;\n\tprivate extensionInput: ExtensionInputComponent | undefined = undefined;\n\tprivate extensionEditor: ExtensionEditorComponent | undefined = undefined;\n\tprivate extensionTerminalInputSubscriptions = new Set<ExtensionTerminalInputSubscription>();\n\t// Extension widgets (components rendered above/below the editor)\n\tprivate extensionWidgetsAbove = new Map<string, DisposableComponent>();\n\tprivate extensionWidgetsBelow = new Map<string, DisposableComponent>();\n\tprivate widgetContainerAbove!: Container;\n\tprivate widgetContainerBelow!: Container;\n\n\t// Custom footer from extension (undefined = use built-in footer)\n\tprivate customFooter: DisposableComponent | undefined = undefined;\n\n\t// Header container that holds the built-in or custom header\n\tprivate headerContainer: Container;\n\n\t// Built-in header (logo + keybinding hints + changelog)\n\tprivate builtInHeader: Component | undefined = undefined;\n\n\t// Custom header from extension (undefined = use built-in header)\n\tprivate customHeader: DisposableComponent | undefined = undefined;\n\n\t// Convenience accessors\n\tprivate get session(): AgentSession {\n\t\treturn this.runtimeHost.session;\n\t}\n\tprivate get agent() {\n\t\treturn this.session.agent;\n\t}\n\tprivate get activeSession() {\n\t\treturn this.session.session;\n\t}\n\tprivate get settingsManager() {\n\t\treturn this.session.settingsManager;\n\t}\n\n\tconstructor(runtimeHost: GripAgentRuntimeHost, options: InteractiveModeOptions = {}) {\n\t\tthis.runtimeHost = runtimeHost;\n\t\tconst tuiMode = options.tuiMode ?? this.settingsManager.getTuiMode();\n\t\tthis.options = { ...options, tuiMode };\n\t\tthis.mermaidMarkdownTransformer = createMermaidMarkdownTransformer({\n\t\t\tgetMode: () => this.settingsManager.getMermaidRenderingMode(),\n\t\t\ttheme,\n\t\t});\n\t\tthis.runtimeHost.setBeforeSessionInvalidate(() => {\n\t\t\tthis.resetExtensionUI();\n\t\t});\n\t\tthis.runtimeHost.setRebindSession(async () => {\n\t\t\tawait this.restoreCurrentSessionSandbox();\n\t\t\tawait this.rebindCurrentSession();\n\t\t});\n\t\tthis.version = VERSION;\n\t\tthis.renderer = createInteractiveTui({\n\t\t\ttuiMode,\n\t\t\tshowHardwareCursor: this.settingsManager.getShowHardwareCursor(),\n\t\t\tlogDirectory: getAgentDir(),\n\t\t\tonRightClickPaste: this.onRightClickPaste,\n\t\t});\n\t\tthis.ui = createInteractiveTuiReference(() => this.renderer);\n\t\tthis.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());\n\t\tthis.headerContainer = new Container();\n\t\tthis.loadedResourcesContainer = new Container();\n\t\tthis.chatContainer = new Container();\n\t\tthis.documentContainer = new Container();\n\t\tthis.documentContainer.addChild(this.headerContainer);\n\t\tthis.documentContainer.addChild(this.loadedResourcesContainer);\n\t\tthis.documentContainer.addChild(this.chatContainer);\n\t\tthis.pendingMessagesContainer = new Container();\n\t\tthis.statusContainer = new Container();\n\t\tthis.widgetContainerAbove = new Container();\n\t\tthis.widgetContainerBelow = new Container();\n\t\tthis.keybindings = KeybindingsManager.create();\n\t\tsetKeybindings(this.keybindings);\n\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\tthis.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, {\n\t\t\tpaddingX: editorPaddingX,\n\t\t\tautocompleteMaxVisible,\n\t\t});\n\t\tthis.editor = this.defaultEditor;\n\t\tthis.editorContainer = new Container();\n\t\tthis.editorContainer.addChild(this.editor as Component);\n\t\tthis.footerDataProvider = new FooterDataProvider(this.activeSession.getCwd());\n\t\tthis.footer = new FooterComponent(this.session, this.footerDataProvider);\n\t\tthis.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);\n\t\tthis.footerContainer = new Container();\n\t\tthis.footerContainer.addChild(this.footer);\n\n\t\t// Load hide thinking block setting\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\n\t\t// Register themes from resource loader and initialize\n\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\tinitTheme(this.settingsManager.getTheme(), true);\n\t}\n\n\tprivate getAutocompleteSourceTag(sourceInfo?: SourceInfo): string | undefined {\n\t\tif (!sourceInfo) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst scopePrefix = sourceInfo.scope === \"user\" ? \"u\" : sourceInfo.scope === \"project\" ? \"p\" : \"t\";\n\t\tconst source = sourceInfo.source.trim();\n\n\t\tif (source === \"auto\" || source === \"local\" || source === \"cli\") {\n\t\t\treturn scopePrefix;\n\t\t}\n\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\treturn `${scopePrefix}:${source}`;\n\t\t}\n\n\t\tconst gitSource = parseGitUrl(source);\n\t\tif (gitSource) {\n\t\t\tconst ref = gitSource.ref ? `@${gitSource.ref}` : \"\";\n\t\t\treturn `${scopePrefix}:git:${gitSource.host}/${gitSource.path}${ref}`;\n\t\t}\n\n\t\treturn scopePrefix;\n\t}\n\n\tprivate prefixAutocompleteDescription(description: string | undefined, sourceInfo?: SourceInfo): string | undefined {\n\t\tconst sourceTag = this.getAutocompleteSourceTag(sourceInfo);\n\t\tif (!sourceTag) {\n\t\t\treturn description;\n\t\t}\n\t\tconst backendIcon = getSourceBackendIcon(sourceInfo);\n\t\treturn description ? `[${backendIcon} ${sourceTag}] ${description}` : `[${backendIcon} ${sourceTag}]`;\n\t}\n\n\tprivate getBuiltInCommandConflictDiagnostics(extensionRunner: ExtensionRunner): ResourceDiagnostic[] {\n\t\tconst builtinNames = new Set([\n\t\t\t...BUILTIN_SLASH_COMMANDS.map((command) => command.name),\n\t\t\t...HIDDEN_BUILTIN_SLASH_COMMAND_NAMES,\n\t\t]);\n\t\treturn extensionRunner\n\t\t\t.getRegisteredCommands()\n\t\t\t.filter((command) => builtinNames.has(command.name))\n\t\t\t.map((command) => ({\n\t\t\t\ttype: \"warning\" as const,\n\t\t\t\tmessage:\n\t\t\t\t\tcommand.invocationName === command.name\n\t\t\t\t\t\t? `Extension command '/${command.name}' conflicts with built-in interactive command. Skipping in autocomplete.`\n\t\t\t\t\t\t: `Extension command '/${command.name}' conflicts with built-in interactive command. Available as '/${command.invocationName}'.`,\n\t\t\t\tpath: command.sourceInfo.path,\n\t\t\t}));\n\t}\n\n\tprivate createBaseAutocompleteProvider(): AutocompleteProvider {\n\t\t// Define commands for autocomplete\n\t\tconst slashCommands: SlashCommand[] = BUILTIN_SLASH_COMMANDS.map((command) => ({\n\t\t\tname: command.name,\n\t\t\tdescription: command.description,\n\t\t}));\n\n\t\tconst cdCommand = slashCommands.find((command) => command.name === \"cd\");\n\t\tif (cdCommand) {\n\t\t\tcdCommand.argumentHint = \"<directory>\";\n\t\t\tcdCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] =>\n\t\t\t\tthis.session.supportsDirectoryChange() ? getDirectoryCompletions(prefix, this.activeSession.getCwd()) : [];\n\t\t}\n\n\t\tconst modelCommand = slashCommands.find((command) => command.name === \"model\");\n\t\tif (modelCommand) {\n\t\t\tmodelCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] | null => {\n\t\t\t\t// Get available models (scoped or from registry)\n\t\t\t\tconst models =\n\t\t\t\t\tthis.session.scopedModels.length > 0\n\t\t\t\t\t\t? this.session.scopedModels.map((s) => s.model)\n\t\t\t\t\t\t: this.session.modelRegistry.getAvailable();\n\n\t\t\t\tif (models.length === 0) return null;\n\n\t\t\t\t// Create items with provider/id format\n\t\t\t\tconst items = models.map((m) => ({\n\t\t\t\t\tid: m.id,\n\t\t\t\t\tprovider: m.provider,\n\t\t\t\t\tlabel: `${m.provider}/${m.id}`,\n\t\t\t\t}));\n\n\t\t\t\t// Fuzzy filter by model ID + provider (allows \"opus anthropic\" to match)\n\t\t\t\tconst filtered = fuzzyFilter(items, prefix, (item) => `${item.id} ${item.provider}`);\n\n\t\t\t\tif (filtered.length === 0) return null;\n\n\t\t\t\treturn filtered.map((item) => ({\n\t\t\t\t\tvalue: item.label,\n\t\t\t\t\tlabel: item.id,\n\t\t\t\t\tdescription: item.provider,\n\t\t\t\t}));\n\t\t\t};\n\t\t}\n\n\t\tconst profileCommand = slashCommands.find((command) => command.name === \"profile\");\n\t\tif (profileCommand) {\n\t\t\tprofileCommand.argumentHint = \"use <name> | create <name>\";\n\t\t\tprofileCommand.getArgumentCompletions = (prefix: string): AutocompleteItem[] | null => {\n\t\t\t\tif (!prefix.includes(\" \")) {\n\t\t\t\t\treturn fuzzyFilter([\"create\", \"use\"], prefix, (action) => action).map((action) => ({\n\t\t\t\t\t\tvalue: `${action} `,\n\t\t\t\t\t\tlabel: action,\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t\tconst useMatch = prefix.match(/^use\\s+(.*)$/);\n\t\t\t\tif (!useMatch) return null;\n\t\t\t\tconst profileNames = Object.keys(this.settingsManager.getModelProfiles());\n\t\t\t\tconst matches = fuzzyFilter(profileNames, useMatch[1] ?? \"\", (name) => name);\n\t\t\t\treturn matches.map((name) => ({ value: `use ${name}`, label: name }));\n\t\t\t};\n\t\t}\n\n\t\t// Convert prompt templates to SlashCommand format for autocomplete\n\t\tconst templateCommands: SlashCommand[] = this.session.promptTemplates.map((cmd) => ({\n\t\t\tname: cmd.name,\n\t\t\tdescription: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),\n\t\t\t...(cmd.argumentHint && { argumentHint: cmd.argumentHint }),\n\t\t}));\n\n\t\tconst builtinCommandNames = new Set([\n\t\t\t...slashCommands.map((command) => command.name),\n\t\t\t...HIDDEN_BUILTIN_SLASH_COMMAND_NAMES,\n\t\t]);\n\t\tconst extensionCommands: SlashCommand[] = this.session.extensionRunner\n\t\t\t.getRegisteredCommands()\n\t\t\t.filter((cmd) => !builtinCommandNames.has(cmd.name))\n\t\t\t.map((cmd) => ({\n\t\t\t\tname: cmd.invocationName,\n\t\t\t\tdescription: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),\n\t\t\t\tgetArgumentCompletions: cmd.getArgumentCompletions,\n\t\t\t}));\n\n\t\t// Build skill/rule commands from loaded resources (if enabled)\n\t\tthis.skillCommands.clear();\n\t\tconst skillCommandList: SlashCommand[] = [];\n\t\tconst ruleCommandList: SlashCommand[] = [];\n\t\tif (this.settingsManager.getEnableSkillCommands()) {\n\t\t\tfor (const skill of this.session.resourceLoader.getSkills().skills) {\n\t\t\t\tconst commandName = `skill:${skill.name}`;\n\t\t\t\tthis.skillCommands.set(commandName, skill.filePath);\n\t\t\t\tskillCommandList.push({\n\t\t\t\t\tname: commandName,\n\t\t\t\t\tdescription: this.prefixAutocompleteDescription(skill.description, skill.sourceInfo),\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const rule of this.session.resourceLoader.getRules().rules) {\n\t\t\t\tconst commandName = `rule:${rule.name}`;\n\t\t\t\truleCommandList.push({\n\t\t\t\t\tname: commandName,\n\t\t\t\t\tdescription: this.prefixAutocompleteDescription(rule.description, rule.sourceInfo),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst base = new CombinedAutocompleteProvider(\n\t\t\t[...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList, ...ruleCommandList],\n\t\t\tthis.activeSession.getCwd(),\n\t\t\tthis.fdPath,\n\t\t);\n\t\tconst provider: AutocompleteProvider = {\n\t\t\tgetSuggestions: async (lines, cursorLine, cursorCol, options) => {\n\t\t\t\tconst beforeCursor = (lines[cursorLine] ?? \"\").slice(0, cursorCol);\n\t\t\t\tconst nameMatch = beforeCursor.match(/^\\/sandbox[ \\t]+(start[ \\t]+--name(?:[ \\t]+([^\\s]*))?)$/);\n\t\t\t\tif (!options.force || !nameMatch) return base.getSuggestions(lines, cursorLine, cursorCol, options);\n\t\t\t\tif (options.signal.aborted) return null;\n\t\t\t\ttry {\n\t\t\t\t\tconst instances = await this.createLimaSandboxService().list({\n\t\t\t\t\t\tworkspaceRoot: this.activeSession.getCwd(),\n\t\t\t\t\t\tallWorkspaces: true,\n\t\t\t\t\t});\n\t\t\t\t\tif (options.signal.aborted) return null;\n\t\t\t\t\tconst prefix = nameMatch[2] ?? \"\";\n\t\t\t\t\tconst items = instances\n\t\t\t\t\t\t.filter((instance) => /^[a-z0-9][a-z0-9-]*$/.test(instance.name) && instance.name.startsWith(prefix))\n\t\t\t\t\t\t.map((instance) => ({\n\t\t\t\t\t\t\tvalue: `start --name ${instance.name}`,\n\t\t\t\t\t\t\tlabel: instance.name,\n\t\t\t\t\t\t\tdescription: instance.status,\n\t\t\t\t\t\t}));\n\t\t\t\t\treturn items.length > 0 ? { items, prefix: nameMatch[1]! } : null;\n\t\t\t\t} catch {\n\t\t\t\t\t// A failed Lima lookup must not fall back to directory suggestions.\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t},\n\t\t\tapplyCompletion: (lines, cursorLine, cursorCol, item, prefix) =>\n\t\t\t\tbase.applyCompletion(lines, cursorLine, cursorCol, item, prefix),\n\t\t\tshouldTriggerFileCompletion: (lines, cursorLine, cursorCol) =>\n\t\t\t\tbase.shouldTriggerFileCompletion(lines, cursorLine, cursorCol),\n\t\t};\n\t\treturn provider;\n\t}\n\n\tprivate setupAutocompleteProvider(): void {\n\t\tlet provider = this.createBaseAutocompleteProvider();\n\t\tfor (const wrapProvider of this.autocompleteProviderWrappers) {\n\t\t\tprovider = wrapProvider(provider);\n\t\t}\n\n\t\tthis.autocompleteProvider = provider;\n\t\tthis.defaultEditor.setAutocompleteProvider(provider);\n\t\tif (this.editor !== this.defaultEditor) {\n\t\t\tthis.editor.setAutocompleteProvider?.(provider);\n\t\t}\n\t}\n\n\tprivate showStartupNoticesIfNeeded(): void {\n\t\tif (this.startupNoticesShown) {\n\t\t\treturn;\n\t\t}\n\t\tthis.startupNoticesShown = true;\n\n\t\tif (!this.changelogMarkdown) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.chatContainer.children.length > 0) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tif (this.settingsManager.getCollapseChangelog()) {\n\t\t\tconst versionMatch = this.changelogMarkdown.match(/##\\s+\\[?(\\d+\\.\\d+\\.\\d+)\\]?/);\n\t\t\tconst latestVersion = versionMatch ? versionMatch[1] : this.version;\n\t\t\tconst condensedText = `Updated to v${latestVersion}. Use ${theme.bold(\"/changelog\")} to view full changelog.`;\n\t\t\tthis.chatContainer.addChild(new Text(condensedText, 1, 0));\n\t\t} else {\n\t\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings()),\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t}\n\n\tprivate initializeBuiltInHeader(): void {\n\t\tif (this.options.verbose || !this.settingsManager.getQuietStartup()) {\n\t\t\tconst logo = theme.bold(theme.fg(\"accent\", APP_NAME)) + theme.fg(\"dim\", ` v${this.version}`);\n\t\t\tconst hint = (keybinding: AppKeybinding, description: string) => keyHint(keybinding, description);\n\t\t\tconst expandedInstructions = [\n\t\t\t\thint(\"app.interrupt\", \"to interrupt\"),\n\t\t\t\thint(\"app.clear\", \"to clear\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.clear\")} twice`, \"to exit\"),\n\t\t\t\thint(\"app.exit\", \"to exit (empty)\"),\n\t\t\t\thint(\"app.suspend\", \"to suspend\"),\n\t\t\t\tkeyHint(\"tui.editor.deleteToLineEnd\", \"to delete to end\"),\n\t\t\t\thint(\"app.thinking.cycle\", \"to cycle thinking level\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.model.cycleForward\")}/${keyText(\"app.model.cycleBackward\")}`, \"to cycle models\"),\n\t\t\t\thint(\"app.model.select\", \"to select model\"),\n\t\t\t\thint(\"app.tools.expand\", \"to expand tools\"),\n\t\t\t\thint(\"app.thinking.toggle\", \"to expand thinking\"),\n\t\t\t\thint(\"app.editor.external\", \"for external editor\"),\n\t\t\t\trawKeyHint(\"/\", \"for commands\"),\n\t\t\t\trawKeyHint(\"!\", \"to run bash\"),\n\t\t\t\trawKeyHint(\"!!\", \"to run bash (no context)\"),\n\t\t\t\thint(\"app.message.followUp\", \"to queue follow-up\"),\n\t\t\t\thint(\"app.message.dequeue\", \"to edit all queued messages\"),\n\t\t\t\thint(\"app.clipboard.pasteImage\", \"to paste image\"),\n\t\t\t\trawKeyHint(\"drop files\", \"to attach\"),\n\t\t\t].join(\"\\n\");\n\t\t\tconst compactInstructions = [\n\t\t\t\thint(\"app.interrupt\", \"interrupt\"),\n\t\t\t\trawKeyHint(`${keyText(\"app.clear\")}/${keyText(\"app.exit\")}`, \"clear/exit\"),\n\t\t\t\trawKeyHint(\"/\", \"commands\"),\n\t\t\t\trawKeyHint(\"!\", \"bash\"),\n\t\t\t\thint(\"app.tools.expand\", \"more\"),\n\t\t\t].join(theme.fg(\"muted\", \" · \"));\n\t\t\tconst compactOnboarding = theme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t`Press ${keyText(\"app.tools.expand\")} to show full startup help and loaded resources.`,\n\t\t\t);\n\t\t\tconst onboarding = theme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t\"Grip can explain its own features and look up its docs. Ask it how to use or extend Grip.\",\n\t\t\t);\n\t\t\tthis.builtInHeader = new ExpandableText(\n\t\t\t\t() => `${logo}\\n${compactInstructions}\\n${compactOnboarding}\\n\\n${onboarding}`,\n\t\t\t\t() => `${logo}\\n${expandedInstructions}\\n\\n${onboarding}`,\n\t\t\t\tthis.getStartupExpansionState(),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t);\n\t\t\tthis.headerContainer.addChild(new Spacer(1));\n\t\t\tthis.headerContainer.addChild(this.builtInHeader);\n\t\t\tthis.headerContainer.addChild(new Spacer(1));\n\t\t} else {\n\t\t\tthis.builtInHeader = new Text(\"\", 0, 0);\n\t\t\tthis.headerContainer.addChild(this.builtInHeader);\n\t\t}\n\t}\n\n\tprivate mountInteractiveTui(tui: TuiMainScreen | TuiAltScreen, components: readonly Component[]): void {\n\t\tfor (const component of components) tui.addChild(component);\n\t\tif (isViewportTUI(tui)) {\n\t\t\tif (!this.fullscreenLayoutRoot) throw new Error(\"Fullscreen layout is not initialized\");\n\t\t\ttui.setLayoutRoot(this.fullscreenLayoutRoot);\n\t\t}\n\t}\n\n\tprivate mountRootComponents(): void {\n\t\t// Build one stable component tree. Main-screen mode renders the flat child list;\n\t\t// fullscreen mode constrains the same instances into a transcript and fixed dock.\n\t\tthis.renderWidgets();\n\t\tthis.transcriptScrollView = new ScrollView(this.documentContainer, {\n\t\t\tfollow: \"end\",\n\t\t\tprimary: true,\n\t\t\toverscroll: \"chain\",\n\t\t\tscrollbar: this.settingsManager.getFullscreenScrollbar(),\n\t\t\tscrollbarStyle: (text) => theme.bg(\"selectedBg\", text),\n\t\t});\n\t\tconst dock = new VStack([\n\t\t\t{ component: this.pendingMessagesContainer, shrink: 1, minSize: 0 },\n\t\t\t{ component: this.statusContainer, shrink: 1, minSize: 0 },\n\t\t\t{ component: this.widgetContainerAbove, shrink: 1, minSize: 0 },\n\t\t\t{ component: this.editorContainer, shrink: 1, minSize: 3 },\n\t\t\t{ component: this.widgetContainerBelow, shrink: 1, minSize: 0 },\n\t\t\t{ component: this.footerContainer, shrink: 1, minSize: 1 },\n\t\t]);\n\t\tthis.fullscreenLayoutRoot = new VStack([\n\t\t\t{ component: this.transcriptScrollView, basis: 0, grow: 1, shrink: 1, minSize: 1 },\n\t\t\t{ component: dock, basis: \"auto\", grow: 0, shrink: 1, minSize: 1 },\n\t\t]);\n\n\t\tthis.mountInteractiveTui(this.renderer, [\n\t\t\tthis.documentContainer,\n\t\t\tthis.pendingMessagesContainer,\n\t\t\tthis.statusContainer,\n\t\t\tthis.widgetContainerAbove,\n\t\t\tthis.editorContainer,\n\t\t\tthis.widgetContainerBelow,\n\t\t\tthis.footerContainer,\n\t\t]);\n\t\tthis.ui.setFocus(this.editor);\n\t}\n\n\tprivate stopInteractiveTui(fullscreenExitOutput: FullscreenExitOutput): void {\n\t\tif (this.renderer.mode === \"fullscreen\" && fullscreenExitOutput === \"transcript\") {\n\t\t\twhile (this.renderer.hasOverlayEntries) this.renderer.hideOverlay();\n\t\t\tthis.switchTuiMode(\"regular\", false, false);\n\t\t\tthis.renderer.renderNow();\n\t\t}\n\t\tthis.ui.stop({ preserveScreen: this.renderer.mode === \"fullscreen\" });\n\t}\n\n\tprivate switchTuiMode(mode: TuiMode, restoreProgress = true, startRenderer = true): boolean {\n\t\tconst previousUi = this.renderer;\n\t\tif (mode === previousUi.mode) return true;\n\t\tif (previousUi.hasOverlayEntries) return false;\n\n\t\tconst components = [...previousUi.children];\n\t\tconst focus = previousUi.getFocusedComponent();\n\t\tconst terminal = previousUi.terminal;\n\t\tconst showHardwareCursor = previousUi.getShowHardwareCursor();\n\t\tconst clearOnShrink = previousUi.getClearOnShrink();\n\t\tconst onDebug = previousUi.onDebug;\n\t\tif (previousUi instanceof TuiMainScreen) this.mainScreenRenderState = previousUi.captureRenderState();\n\n\t\tpreviousUi.stop({ preserveScreen: true });\n\t\tpreviousUi.setFocus(null);\n\t\tpreviousUi.clear();\n\t\tif (isViewportTUI(previousUi)) previousUi.setLayoutRoot(undefined);\n\n\t\tconst nextUi = createInteractiveTui({\n\t\t\ttuiMode: mode,\n\t\t\tshowHardwareCursor,\n\t\t\tlogDirectory: getAgentDir(),\n\t\t\tterminal,\n\t\t\tonRightClickPaste: this.onRightClickPaste,\n\t\t});\n\t\tnextUi.setClearOnShrink(clearOnShrink);\n\t\tnextUi.onDebug = onDebug;\n\t\tif (nextUi instanceof TuiMainScreen && this.mainScreenRenderState) {\n\t\t\tnextUi.restoreRenderState(this.mainScreenRenderState);\n\t\t}\n\t\tthis.renderer = nextUi;\n\t\tthis.options.tuiMode = mode;\n\t\tthis.mountInteractiveTui(nextUi, components);\n\t\tnextUi.invalidate();\n\t\tnextUi.setFocus(focus);\n\t\tif (!startRenderer) return true;\n\t\tnextUi.start();\n\t\tthis.rebindExtensionTerminalInputListeners();\n\t\tif (\n\t\t\trestoreProgress &&\n\t\t\tthis.settingsManager.getShowTerminalProgress() &&\n\t\t\t(this.session.isStreaming || this.session.isCompacting)\n\t\t) {\n\t\t\tterminal.setProgress(true);\n\t\t}\n\t\treturn true;\n\t}\n\n\tasync init(): Promise<void> {\n\t\tif (this.isInitialized) return;\n\n\t\tthis.registerSignalHandlers();\n\n\t\t// Load changelog (only show new entries, skip for resumed sessions)\n\t\tthis.changelogMarkdown = this.getChangelogForDisplay();\n\n\t\t// Ensure fd and rg are available (downloads if missing, adds to PATH via getBinDir)\n\t\t// Both are needed: fd for autocomplete, rg for grep tool and bash commands\n\t\tconst [fdPath] = await Promise.all([ensureTool(\"fd\"), ensureTool(\"rg\")]);\n\t\tthis.fdPath = fdPath;\n\n\t\tif (this.session.scopedModels.length > 0 && (this.options.verbose || !this.settingsManager.getQuietStartup())) {\n\t\t\tconst modelList = this.session.scopedModels\n\t\t\t\t.map((sm) => {\n\t\t\t\t\tconst thinkingStr = sm.thinkingLevel ? `:${sm.thinkingLevel}` : \"\";\n\t\t\t\t\treturn `${sm.model.id}${thinkingStr}`;\n\t\t\t\t})\n\t\t\t\t.join(\", \");\n\t\t\tconst cycleKeys = this.keybindings.getKeys(\"app.model.cycleForward\");\n\t\t\tconst cycleHint =\n\t\t\t\tcycleKeys.length > 0\n\t\t\t\t\t? theme.fg(\"muted\", ` (${formatKeyText(cycleKeys.join(\"/\"), { capitalize: true })} to cycle)`)\n\t\t\t\t\t: \"\";\n\t\t\tconsole.log(theme.fg(\"dim\", `Model scope: ${modelList}${cycleHint}`));\n\t\t}\n\n\t\tthis.initializeBuiltInHeader();\n\n\t\t// Mount the existing flat document in the same order for both renderers.\n\t\tthis.mountRootComponents();\n\t\tthis.ui.setFocus(this.editor);\n\n\t\tthis.setupKeyHandlers();\n\t\tthis.setupEditorSubmitHandler();\n\n\t\t// Start the UI before initializing extensions so session_start handlers can use interactive dialogs\n\t\tthis.ui.start();\n\t\tthis.isInitialized = true;\n\n\t\t// Initialize extensions first so resources are shown before messages\n\t\tawait this.rebindCurrentSession();\n\n\t\t// Render initial messages AFTER showing loaded resources\n\t\tthis.renderInitialMessages();\n\t\tthis.showRuntimeDiagnostics();\n\n\t\t// Set up theme file watcher\n\t\tonThemeChange(() => {\n\t\t\tthis.ui.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Set up git branch watcher (uses provider instead of footer)\n\t\tthis.footerDataProvider.onBranchChange(() => {\n\t\t\tthis.ui.requestRender();\n\t\t});\n\n\t\t// Initialize available provider count for footer display\n\t\tawait this.updateAvailableProviderCount();\n\t}\n\n\t/**\n\t * Update terminal title with session name and cwd.\n\t */\n\tprivate updateTerminalTitle(): void {\n\t\tconst cwdBasename = path.basename(this.activeSession.getCwd());\n\t\tconst sessionName = this.activeSession.getSessionName();\n\t\tif (sessionName) {\n\t\t\tthis.ui.terminal.setTitle(`${APP_TITLE} - ${sessionName} - ${cwdBasename}`);\n\t\t} else {\n\t\t\tthis.ui.terminal.setTitle(`${APP_TITLE} - ${cwdBasename}`);\n\t\t}\n\t}\n\n\t/**\n\t * Run the interactive mode. This is the main entry point.\n\t * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop.\n\t */\n\tasync run(): Promise<void> {\n\t\tawait this.init();\n\t\tthis.startBackgroundChecks();\n\t\tthis.showStartupWarnings();\n\t\tawait this.processInitialMessages();\n\t\tawait this.runInteractivePromptLoop();\n\t}\n\n\tprivate startBackgroundChecks(): void {\n\t\tvoid checkForNewGripVersion(this.version).then((newRelease) => {\n\t\t\tif (newRelease) this.showNewVersionNotification(newRelease);\n\t\t});\n\t\tvoid this.checkForPackageUpdates().then((updates) => {\n\t\t\tif (updates.length > 0) this.showPackageUpdateNotification(updates);\n\t\t});\n\t\tvoid this.checkTmuxKeyboardSetup().then((warning) => {\n\t\t\tif (warning) this.showWarning(warning);\n\t\t});\n\t}\n\n\tprivate showStartupWarnings(): void {\n\t\tconst { migratedProviders, modelFallbackMessage } = this.options;\n\t\tif (migratedProviders && migratedProviders.length > 0) {\n\t\t\tthis.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(\", \")}`);\n\t\t}\n\t\tconst modelsJsonError = this.session.modelRegistry.getError();\n\t\tif (modelsJsonError) this.showError(`models.json error: ${modelsJsonError}`);\n\t\tif (modelFallbackMessage) this.showWarning(modelFallbackMessage);\n\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth();\n\t}\n\n\tprivate async promptAndReportError(message: string, options?: PromptOptions): Promise<void> {\n\t\ttry {\n\t\t\tawait this.session.prompt(message, options);\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(error instanceof Error ? error.message : \"Unknown error occurred\");\n\t\t}\n\t}\n\n\tprivate async processInitialMessages(): Promise<void> {\n\t\tconst { initialMessage, initialImages, initialMessages } = this.options;\n\t\tif (initialMessage) await this.promptAndReportError(initialMessage, { images: initialImages });\n\t\tfor (const message of initialMessages ?? []) await this.promptAndReportError(message);\n\t}\n\n\tprivate async runInteractivePromptLoop(): Promise<never> {\n\t\twhile (true) {\n\t\t\tawait this.promptAndReportError(await this.getUserInput());\n\t\t}\n\t}\n\n\tprivate async checkForPackageUpdates(): Promise<string[]> {\n\t\tif (process.env.GRIP_OFFLINE) {\n\t\t\treturn [];\n\t\t}\n\n\t\ttry {\n\t\t\tconst packageManager = new DefaultPackageManager({\n\t\t\t\tcwd: this.activeSession.getCwd(),\n\t\t\t\tagentDir: getAgentDir(),\n\t\t\t\tsettingsManager: this.settingsManager,\n\t\t\t});\n\t\t\tconst updates = await packageManager.checkForAvailableUpdates();\n\t\t\treturn updates.map((update) => update.displayName);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\tprivate async checkTmuxKeyboardSetup(): Promise<string | undefined> {\n\t\tif (!process.env.TMUX) return undefined;\n\n\t\tconst runTmuxShow = (option: string): Promise<string | undefined> => {\n\t\t\treturn new Promise((resolve) => {\n\t\t\t\tconst proc = spawn(\"tmux\", [\"show\", \"-gv\", option], {\n\t\t\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\t\t});\n\t\t\t\tlet stdout = \"\";\n\t\t\t\tconst timer = setTimeout(() => {\n\t\t\t\t\tproc.kill();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t}, 2000);\n\n\t\t\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\t\t\tstdout += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.on(\"error\", () => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t});\n\t\t\t\tproc.on(\"close\", (code) => {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolve(code === 0 ? stdout.trim() : undefined);\n\t\t\t\t});\n\t\t\t});\n\t\t};\n\n\t\tconst [extendedKeys, extendedKeysFormat] = await Promise.all([\n\t\t\trunTmuxShow(\"extended-keys\"),\n\t\t\trunTmuxShow(\"extended-keys-format\"),\n\t\t]);\n\n\t\t// If we couldn't query tmux (timeout, sandbox, etc.), don't warn\n\t\tif (extendedKeys === undefined) return undefined;\n\n\t\tif (extendedKeys !== \"on\" && extendedKeys !== \"always\") {\n\t\t\treturn \"tmux extended-keys is off. Modified Enter keys may not work. Add `set -g extended-keys on` to ~/.tmux.conf and restart tmux.\";\n\t\t}\n\n\t\tif (extendedKeysFormat === \"xterm\") {\n\t\t\treturn \"tmux extended-keys-format is xterm. Grip works best with csi-u. Add `set -g extended-keys-format csi-u` to ~/.tmux.conf and restart tmux.\";\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Get changelog entries to display on startup.\n\t * Only shows new entries since last seen version, skips for resumed sessions.\n\t */\n\tprivate getChangelogForDisplay(): string | undefined {\n\t\t// Skip changelog for resumed/continued sessions (already have messages)\n\t\tif (this.session.state.messages.length > 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst lastVersion = this.settingsManager.getLastChangelogVersion();\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst entries = parseChangelog(changelogPath);\n\n\t\tif (!lastVersion) {\n\t\t\t// Fresh install - record the version, send telemetry, don't show changelog\n\t\t\tthis.settingsManager.setLastChangelogVersion(VERSION);\n\t\t\tthis.reportInstallTelemetry(VERSION);\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst newEntries = getNewEntries(entries, lastVersion);\n\t\tif (newEntries.length > 0) {\n\t\t\tthis.settingsManager.setLastChangelogVersion(VERSION);\n\t\t\tthis.reportInstallTelemetry(VERSION);\n\t\t\treturn newEntries.map((e) => e.content).join(\"\\n\\n\");\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate reportInstallTelemetry(version: string): void {\n\t\tif (process.env.GRIP_OFFLINE) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (!isInstallTelemetryEnabled(this.settingsManager)) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(version)}`, {\n\t\t\theaders: {\n\t\t\t\t\"User-Agent\": getGripUserAgent(version),\n\t\t\t},\n\t\t\tsignal: AbortSignal.timeout(5000),\n\t\t})\n\t\t\t.then(() => undefined)\n\t\t\t.catch(() => undefined);\n\t}\n\n\tprivate getMarkdownThemeWithSettings(): MarkdownTheme {\n\t\treturn {\n\t\t\t...getMarkdownTheme(),\n\t\t\tcodeBlockIndent: this.settingsManager.getCodeBlockIndent(),\n\t\t};\n\t}\n\n\t// =========================================================================\n\t// Extension System\n\t// =========================================================================\n\n\tprivate formatDisplayPath(p: string): string {\n\t\tconst home = os.homedir();\n\t\tlet result = p;\n\n\t\t// Replace home directory with ~\n\t\tif (result.startsWith(home)) {\n\t\t\tresult = `~${result.slice(home.length)}`;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate formatExtensionDisplayPath(path: string): string {\n\t\tlet result = this.formatDisplayPath(path);\n\t\tresult = result.replace(/\\/index\\.ts$/, \"\").replace(/\\/index\\.js$/, \"\");\n\t\treturn result;\n\t}\n\n\tprivate formatContextPath(p: string): string {\n\t\tconst cwd = path.resolve(this.activeSession.getCwd());\n\t\tconst absolutePath = path.isAbsolute(p) ? path.resolve(p) : path.resolve(cwd, p);\n\t\tconst relativePath = getCwdRelativePath(absolutePath, cwd);\n\t\tif (relativePath !== undefined) {\n\t\t\treturn relativePath;\n\t\t}\n\n\t\treturn this.formatDisplayPath(absolutePath);\n\t}\n\n\tprivate getStartupExpansionState(): boolean {\n\t\treturn this.options.verbose || this.toolOutputExpanded;\n\t}\n\n\t/**\n\t * Get a short path relative to the package root for display.\n\t */\n\tprivate getShortPath(fullPath: string, sourceInfo?: SourceInfo): string {\n\t\tconst baseDir = sourceInfo?.baseDir;\n\t\tif (baseDir && this.isPackageSource(sourceInfo)) {\n\t\t\tconst relativePath = path.relative(path.resolve(baseDir), path.resolve(fullPath));\n\t\t\tif (\n\t\t\t\trelativePath &&\n\t\t\t\trelativePath !== \".\" &&\n\t\t\t\t!relativePath.startsWith(\"..\") &&\n\t\t\t\t!relativePath.startsWith(`..${path.sep}`) &&\n\t\t\t\t!path.isAbsolute(relativePath)\n\t\t\t) {\n\t\t\t\treturn relativePath.replace(/\\\\/g, \"/\");\n\t\t\t}\n\t\t}\n\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\tconst npmMatch = fullPath.match(/node_modules\\/(@?[^/]+(?:\\/[^/]+)?)\\/(.*)/);\n\t\tif (npmMatch && source.startsWith(\"npm:\")) {\n\t\t\treturn npmMatch[2];\n\t\t}\n\n\t\tconst gitMatch = fullPath.match(/git\\/[^/]+\\/[^/]+\\/(.*)/);\n\t\tif (gitMatch && source.startsWith(\"git:\")) {\n\t\t\treturn gitMatch[1];\n\t\t}\n\n\t\treturn this.formatDisplayPath(fullPath);\n\t}\n\n\tprivate getCompactPathLabel(resourcePath: string, sourceInfo?: SourceInfo): string {\n\t\tconst shortPath = this.getShortPath(resourcePath, sourceInfo);\n\t\tconst normalizedPath = shortPath.replace(/\\\\/g, \"/\");\n\t\tconst segments = normalizedPath.split(\"/\").filter((segment) => segment.length > 0 && segment !== \"~\");\n\t\tif (segments.length > 0) {\n\t\t\treturn segments[segments.length - 1]!;\n\t\t}\n\t\treturn shortPath;\n\t}\n\n\tprivate getCompactPackageSourceLabel(sourceInfo?: SourceInfo): string {\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\tif (source.startsWith(\"npm:\")) {\n\t\t\treturn source.slice(\"npm:\".length) || source;\n\t\t}\n\n\t\tconst gitSource = parseGitUrl(source);\n\t\tif (gitSource) {\n\t\t\treturn gitSource.path || source;\n\t\t}\n\n\t\treturn source;\n\t}\n\n\tprivate getCompactExtensionLabel(resourcePath: string, sourceInfo?: SourceInfo): string {\n\t\tif (!this.isPackageSource(sourceInfo)) {\n\t\t\treturn this.getCompactPathLabel(resourcePath, sourceInfo);\n\t\t}\n\n\t\tconst sourceLabel = this.getCompactPackageSourceLabel(sourceInfo);\n\t\tif (!sourceLabel) {\n\t\t\treturn this.getCompactPathLabel(resourcePath, sourceInfo);\n\t\t}\n\n\t\tconst shortPath = this.getShortPath(resourcePath, sourceInfo).replace(/\\\\/g, \"/\");\n\t\tconst packagePath = shortPath.startsWith(\"extensions/\") ? shortPath.slice(\"extensions/\".length) : shortPath;\n\t\tconst parsedPath = path.posix.parse(packagePath);\n\n\t\tif (parsedPath.name === \"index\") {\n\t\t\treturn !parsedPath.dir || parsedPath.dir === \".\" ? sourceLabel : `${sourceLabel}:${parsedPath.dir}`;\n\t\t}\n\n\t\treturn `${sourceLabel}:${packagePath}`;\n\t}\n\n\tprivate getCompactDisplayPathSegments(resourcePath: string): string[] {\n\t\treturn this.formatDisplayPath(resourcePath)\n\t\t\t.replace(/\\\\/g, \"/\")\n\t\t\t.split(\"/\")\n\t\t\t.filter((segment) => segment.length > 0 && segment !== \"~\");\n\t}\n\n\tprivate getCompactNonPackageExtensionLabel(allPaths: CompactResourcePath[]): Map<string, string> {\n\t\tconst suffixCounts = new Map<string, number>();\n\t\tfor (const item of allPaths) {\n\t\t\tfor (let segmentCount = 1; segmentCount <= item.segments.length; segmentCount += 1) {\n\t\t\t\tconst suffix = item.segments.slice(-segmentCount).join(\"/\");\n\t\t\t\tsuffixCounts.set(suffix, (suffixCounts.get(suffix) ?? 0) + 1);\n\t\t\t}\n\t\t}\n\n\t\tconst labels = new Map<string, string>();\n\t\tfor (const item of allPaths) {\n\t\t\tif (labels.has(item.path)) continue;\n\t\t\tlet label = item.segments.join(\"/\");\n\t\t\tfor (let segmentCount = 1; segmentCount <= item.segments.length; segmentCount += 1) {\n\t\t\t\tconst suffix = item.segments.slice(-segmentCount).join(\"/\");\n\t\t\t\tif (suffixCounts.get(suffix) !== 1) continue;\n\t\t\t\tlabel = suffix;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tlabels.set(item.path, label || this.getCompactPathLabel(item.path));\n\t\t}\n\t\treturn labels;\n\t}\n\n\tprivate getCompactExtensionLabels(extensions: ResourceDisplayItem[]): string[] {\n\t\tconst nonPackageExtensions = extensions\n\t\t\t.map((extension) => {\n\t\t\t\tconst segments = this.getCompactDisplayPathSegments(extension.path);\n\t\t\t\tconst lastSegment = segments[segments.length - 1];\n\t\t\t\tif (segments.length > 1 && (lastSegment === \"index.ts\" || lastSegment === \"index.ts\")) {\n\t\t\t\t\tsegments.pop();\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tpath: extension.path,\n\t\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t\t\tsegments,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter((extension) => !this.isPackageSource(extension.sourceInfo));\n\n\t\tconst nonPackageLabels = this.getCompactNonPackageExtensionLabel(nonPackageExtensions);\n\t\treturn extensions.map((extension) => {\n\t\t\tif (this.isPackageSource(extension.sourceInfo)) {\n\t\t\t\treturn this.getCompactExtensionLabel(extension.path, extension.sourceInfo);\n\t\t\t}\n\n\t\t\treturn nonPackageLabels.get(extension.path) ?? this.getCompactPathLabel(extension.path, extension.sourceInfo);\n\t\t});\n\t}\n\n\tprivate getDisplaySourceInfo(sourceInfo?: SourceInfo): ResourceSourceDisplayInfo {\n\t\tconst source = sourceInfo?.source ?? \"local\";\n\t\tconst scope = sourceInfo?.scope ?? \"project\";\n\t\tif (source === \"local\") {\n\t\t\treturn { ...(LOCAL_SOURCE_DISPLAY_INFO[scope] ?? { label: \"path\" }), color: \"muted\" };\n\t\t}\n\t\tif (source === \"cli\") {\n\t\t\treturn { label: \"path\", scopeLabel: CLI_SOURCE_SCOPE_LABELS[scope], color: \"muted\" };\n\t\t}\n\t\treturn { label: source, scopeLabel: ACCENT_SOURCE_SCOPE_LABELS[scope], color: \"accent\" };\n\t}\n\n\tprivate getScopeGroup(sourceInfo?: SourceInfo): ResourceScope {\n\t\tconst source = sourceInfo?.source ?? \"local\";\n\t\tconst scope = sourceInfo?.scope ?? \"project\";\n\t\tif (source === \"cli\" || scope === \"temporary\") return \"path\";\n\t\tif (scope === \"user\") return \"user\";\n\t\tif (scope === \"project\") return \"project\";\n\t\treturn \"path\";\n\t}\n\n\tprivate isPackageSource(sourceInfo?: SourceInfo): boolean {\n\t\tconst source = sourceInfo?.source ?? \"\";\n\t\treturn source.startsWith(\"npm:\") || source.startsWith(\"git:\");\n\t}\n\n\tprivate buildScopeGroups(items: ResourceDisplayItem[]): ResourceScopeGroup[] {\n\t\tconst groups: Record<ResourceScope, ResourceScopeGroup> = {\n\t\t\tuser: { scope: \"user\", paths: [], packages: new Map() },\n\t\t\tproject: { scope: \"project\", paths: [], packages: new Map() },\n\t\t\tpath: { scope: \"path\", paths: [], packages: new Map() },\n\t\t};\n\n\t\tfor (const item of items) {\n\t\t\tconst groupKey = this.getScopeGroup(item.sourceInfo);\n\t\t\tconst group = groups[groupKey];\n\t\t\tconst source = item.sourceInfo?.source ?? \"local\";\n\n\t\t\tif (this.isPackageSource(item.sourceInfo)) {\n\t\t\t\tconst list = group.packages.get(source) ?? [];\n\t\t\t\tlist.push(item);\n\t\t\t\tgroup.packages.set(source, list);\n\t\t\t} else {\n\t\t\t\tgroup.paths.push(item);\n\t\t\t}\n\t\t}\n\n\t\treturn [groups.project, groups.user, groups.path].filter(\n\t\t\t(group) => group.paths.length > 0 || group.packages.size > 0,\n\t\t);\n\t}\n\n\tprivate formatScopeGroups(groups: ResourceScopeGroup[], options: ResourceScopeFormatOptions): string {\n\t\tconst lines: string[] = [];\n\n\t\tfor (const group of groups) {\n\t\t\tlines.push(` ${theme.fg(\"accent\", group.scope)}`);\n\n\t\t\tconst sortedPaths = [...group.paths].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\tfor (const item of sortedPaths) {\n\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPath(item)}`));\n\t\t\t}\n\n\t\t\tconst sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b));\n\t\t\tfor (const [source, items] of sortedPackages) {\n\t\t\t\tlines.push(` ${theme.fg(\"mdLink\", source)}`);\n\t\t\t\tconst sortedPackagePaths = [...items].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\t\tfor (const item of sortedPackagePaths) {\n\t\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPackagePath(item, source)}`));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate findSourceInfoForPath(p: string, sourceInfos: Map<string, SourceInfo>): SourceInfo | undefined {\n\t\tconst exact = sourceInfos.get(p);\n\t\tif (exact) return exact;\n\n\t\tlet current = p;\n\t\twhile (current.includes(\"/\")) {\n\t\t\tcurrent = current.substring(0, current.lastIndexOf(\"/\"));\n\t\t\tconst parent = sourceInfos.get(current);\n\t\t\tif (parent) return parent;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tprivate formatPathWithSource(p: string, sourceInfo?: SourceInfo): string {\n\t\tif (sourceInfo) {\n\t\t\tconst shortPath = this.getShortPath(p, sourceInfo);\n\t\t\tconst { label, scopeLabel } = this.getDisplaySourceInfo(sourceInfo);\n\t\t\tconst backendIcon = getSourceBackendIcon(sourceInfo);\n\t\t\tconst labelText = scopeLabel ? `${backendIcon} ${label} (${scopeLabel})` : `${backendIcon} ${label}`;\n\t\t\treturn `${labelText} ${shortPath}`;\n\t\t}\n\t\treturn this.formatDisplayPath(p);\n\t}\n\n\tprivate formatCollisionGroup(\n\t\tname: string,\n\t\tcollisions: ResourceCollision[],\n\t\tsourceInfos: Map<string, SourceInfo>,\n\t): string[] {\n\t\tconst winner = collisions[0];\n\t\tif (!winner) return [];\n\t\tconst lines = [\n\t\t\ttheme.fg(\"warning\", ` \"${name}\" collision:`),\n\t\t\ttheme.fg(\n\t\t\t\t\"dim\",\n\t\t\t\t` ${theme.fg(\"success\", \"✓\")} ${this.formatPathWithSource(winner.winnerPath, this.findSourceInfoForPath(winner.winnerPath, sourceInfos))}`,\n\t\t\t),\n\t\t];\n\t\tfor (const collision of collisions) {\n\t\t\tlines.push(\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"dim\",\n\t\t\t\t\t` ${theme.fg(\"warning\", \"✗\")} ${this.formatPathWithSource(collision.loserPath, this.findSourceInfoForPath(collision.loserPath, sourceInfos))} (skipped)`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn lines;\n\t}\n\n\tprivate formatResourceDiagnostic(diagnostic: ResourceDiagnostic, sourceInfos: Map<string, SourceInfo>): string[] {\n\t\tconst color = diagnostic.type === \"error\" ? \"error\" : \"warning\";\n\t\tif (!diagnostic.path) return [theme.fg(color, ` ${diagnostic.message}`)];\n\t\tconst formattedPath = this.formatPathWithSource(\n\t\t\tdiagnostic.path,\n\t\t\tthis.findSourceInfoForPath(diagnostic.path, sourceInfos),\n\t\t);\n\t\treturn [theme.fg(color, ` ${formattedPath}`), theme.fg(color, ` ${diagnostic.message}`)];\n\t}\n\n\tprivate formatDiagnostics(diagnostics: readonly ResourceDiagnostic[], sourceInfos: Map<string, SourceInfo>): string {\n\t\tconst { collisions, otherDiagnostics } = groupResourceDiagnostics(diagnostics);\n\t\tconst lines: string[] = [];\n\t\tfor (const [name, group] of collisions) {\n\t\t\tlines.push(...this.formatCollisionGroup(name, group, sourceInfos));\n\t\t}\n\t\tfor (const diagnostic of otherDiagnostics) {\n\t\t\tlines.push(...this.formatResourceDiagnostic(diagnostic, sourceInfos));\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tprivate formatCompactResourceList(items: string[], options?: CompactListOptions): string {\n\t\tconst labels = items.map((item) => item.trim()).filter((item) => item.length > 0);\n\t\tif (options?.sort !== false) labels.sort((a, b) => a.localeCompare(b));\n\t\treturn theme.fg(\"dim\", ` ${labels.join(\", \")}`);\n\t}\n\n\tprivate addLoadedResourceSection(container: Container, options: LoadedResourceSectionOptions): void {\n\t\tconst color = options.color ?? \"mdHeading\";\n\t\tconst header = theme.fg(color, `[${options.name}]`);\n\t\tconst section = new ExpandableText(\n\t\t\t() => `${header}\\n${options.collapsedBody}`,\n\t\t\t() => `${header}\\n${options.expandedBody ?? options.collapsedBody}`,\n\t\t\tthis.getStartupExpansionState(),\n\t\t\t0,\n\t\t\t0,\n\t\t);\n\t\tcontainer.addChild(section);\n\t\tcontainer.addChild(new Spacer(1));\n\t}\n\n\tprivate getLoadedResourceSnapshot(options?: ShowLoadedResourcesOptions): LoadedResourceSnapshot {\n\t\tconst skillsResult = this.session.resourceLoader.getSkills();\n\t\tconst rulesResult = this.session.resourceLoader.getRules();\n\t\tconst promptsResult = this.session.resourceLoader.getPrompts();\n\t\tconst themesResult = this.session.resourceLoader.getThemes();\n\t\tconst extensions =\n\t\t\toptions?.extensions ??\n\t\t\tthis.session.resourceLoader.getExtensions().extensions.map((extension) => ({\n\t\t\t\tpath: extension.path,\n\t\t\t\tsourceInfo: extension.sourceInfo,\n\t\t\t}));\n\t\tconst sourceInfos = indexResourceSourceInfos([\n\t\t\t...extensions,\n\t\t\t...skillsResult.skills.map((skill) => ({ path: skill.filePath, sourceInfo: skill.sourceInfo })),\n\t\t\t...rulesResult.rules.map((rule) => ({ path: rule.filePath, sourceInfo: rule.sourceInfo })),\n\t\t\t...promptsResult.prompts.map((prompt) => ({ path: prompt.filePath, sourceInfo: prompt.sourceInfo })),\n\t\t\t...themesResult.themes\n\t\t\t\t.filter((loadedTheme) => loadedTheme.sourcePath !== undefined)\n\t\t\t\t.map((loadedTheme) => ({ path: loadedTheme.sourcePath!, sourceInfo: loadedTheme.sourceInfo })),\n\t\t]);\n\t\treturn { skillsResult, rulesResult, promptsResult, themesResult, extensions, sourceInfos };\n\t}\n\n\tprivate renderContextFilesSection(container: Container): void {\n\t\tconst contextFiles = this.session.resourceLoader.getAgentsFiles().agentsFiles;\n\t\tif (contextFiles.length === 0) return;\n\t\tcontainer.addChild(new Spacer(1));\n\t\tconst backend = this.session.getToolBackendInfo?.();\n\t\tconst backendIcon = backend?.type === \"remote\" ? \"☁\" : \"🖥\";\n\t\tconst expandedBody = contextFiles\n\t\t\t.map((file) =>\n\t\t\t\ttheme.fg(\n\t\t\t\t\t\"dim\",\n\t\t\t\t\t` ${file.path.startsWith(getAgentDir()) ? \"🖥\" : backendIcon} ${this.formatDisplayPath(file.path)}`,\n\t\t\t\t),\n\t\t\t)\n\t\t\t.join(\"\\n\");\n\t\tthis.addLoadedResourceSection(container, {\n\t\t\tname: \"Context\",\n\t\t\tcollapsedBody: this.formatCompactResourceList(\n\t\t\t\tcontextFiles.map((file) => this.formatContextPath(file.path)),\n\t\t\t\t{ sort: false },\n\t\t\t),\n\t\t\texpandedBody,\n\t\t});\n\t}\n\n\tprivate renderNamedInstructionSection(\n\t\tcontainer: Container,\n\t\tname: string,\n\t\tresources: NamedInstructionResource[],\n\t): void {\n\t\tif (resources.length === 0) return;\n\t\tconst groups = this.buildScopeGroups(\n\t\t\tresources.map((resource) => ({ path: resource.filePath, sourceInfo: resource.sourceInfo })),\n\t\t);\n\t\tconst expandedBody = this.formatScopeGroups(groups, {\n\t\t\tformatPath: (item) => `${getSourceBackendIcon(item.sourceInfo)} ${this.formatDisplayPath(item.path)}`,\n\t\t\tformatPackagePath: (item) =>\n\t\t\t\t`${getSourceBackendIcon(item.sourceInfo)} ${this.getShortPath(item.path, item.sourceInfo)}`,\n\t\t});\n\t\tthis.addLoadedResourceSection(container, {\n\t\t\tname,\n\t\t\tcollapsedBody: this.formatCompactResourceList(\n\t\t\t\tresources.map((resource) => `${getSourceBackendIcon(resource.sourceInfo)} ${resource.name}`),\n\t\t\t),\n\t\t\texpandedBody,\n\t\t});\n\t}\n\n\tprivate renderPromptTemplateSection(container: Container): void {\n\t\tconst templates = this.session.promptTemplates;\n\t\tif (templates.length === 0) return;\n\t\tconst groups = this.buildScopeGroups(\n\t\t\ttemplates.map((template) => ({ path: template.filePath, sourceInfo: template.sourceInfo })),\n\t\t);\n\t\tconst templateByPath = new Map(templates.map((template) => [template.filePath, template]));\n\t\tconst formatTemplate = (item: ResourceDisplayItem): string => {\n\t\t\tconst template = templateByPath.get(item.path);\n\t\t\treturn `${getSourceBackendIcon(item.sourceInfo)} ${template ? `/${template.name}` : this.formatDisplayPath(item.path)}`;\n\t\t};\n\t\tthis.addLoadedResourceSection(container, {\n\t\t\tname: \"Prompts\",\n\t\t\tcollapsedBody: this.formatCompactResourceList(\n\t\t\t\ttemplates.map((template) => `${getSourceBackendIcon(template.sourceInfo)} /${template.name}`),\n\t\t\t),\n\t\t\texpandedBody: this.formatScopeGroups(groups, {\n\t\t\t\tformatPath: formatTemplate,\n\t\t\t\tformatPackagePath: formatTemplate,\n\t\t\t}),\n\t\t});\n\t}\n\n\tprivate renderExtensionSection(container: Container, extensions: ResourceDisplayItem[]): void {\n\t\tif (extensions.length === 0) return;\n\t\tconst groups = this.buildScopeGroups(extensions);\n\t\tthis.addLoadedResourceSection(container, {\n\t\t\tname: \"Extensions\",\n\t\t\tcollapsedBody: this.formatCompactResourceList(this.getCompactExtensionLabels(extensions)),\n\t\t\texpandedBody: this.formatScopeGroups(groups, {\n\t\t\t\tformatPath: (item) => this.formatExtensionDisplayPath(item.path),\n\t\t\t\tformatPackagePath: (item) => this.formatExtensionDisplayPath(this.getShortPath(item.path, item.sourceInfo)),\n\t\t\t}),\n\t\t\tcolor: \"mdHeading\",\n\t\t});\n\t}\n\n\tprivate renderThemeSection(container: Container, themesResult: LoadThemesResult): void {\n\t\tconst customThemes = themesResult.themes.filter((loadedTheme) => loadedTheme.sourcePath);\n\t\tif (customThemes.length === 0) return;\n\t\tconst groups = this.buildScopeGroups(\n\t\t\tcustomThemes.map((loadedTheme) => ({\n\t\t\t\tpath: loadedTheme.sourcePath!,\n\t\t\t\tsourceInfo: loadedTheme.sourceInfo,\n\t\t\t})),\n\t\t);\n\t\tthis.addLoadedResourceSection(container, {\n\t\t\tname: \"Themes\",\n\t\t\tcollapsedBody: this.formatCompactResourceList(\n\t\t\t\tcustomThemes.map(\n\t\t\t\t\t(loadedTheme) =>\n\t\t\t\t\t\tloadedTheme.name ?? this.getCompactPathLabel(loadedTheme.sourcePath!, loadedTheme.sourceInfo),\n\t\t\t\t),\n\t\t\t),\n\t\t\texpandedBody: this.formatScopeGroups(groups, {\n\t\t\t\tformatPath: (item) => this.formatDisplayPath(item.path),\n\t\t\t\tformatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),\n\t\t\t}),\n\t\t});\n\t}\n\n\tprivate renderLoadedResourceListing(container: Container, snapshot: LoadedResourceSnapshot): void {\n\t\tthis.renderContextFilesSection(container);\n\t\tthis.renderNamedInstructionSection(container, \"Skills\", snapshot.skillsResult.skills);\n\t\tthis.renderNamedInstructionSection(container, \"Rules\", snapshot.rulesResult.rules);\n\t\tthis.renderPromptTemplateSection(container);\n\t\tthis.renderExtensionSection(container, snapshot.extensions);\n\t\tthis.renderThemeSection(container, snapshot.themesResult);\n\t}\n\n\tprivate addResourceDiagnosticSection(\n\t\tcontainer: Container,\n\t\ttitle: string,\n\t\tdiagnostics: readonly ResourceDiagnostic[],\n\t\tsourceInfos: Map<string, SourceInfo>,\n\t): void {\n\t\tif (diagnostics.length === 0) return;\n\t\tconst warningLines = this.formatDiagnostics(diagnostics, sourceInfos);\n\t\tcontainer.addChild(new Text(`${theme.fg(\"warning\", `[${title}]`)}\\n${warningLines}`, 0, 0));\n\t\tcontainer.addChild(new Spacer(1));\n\t}\n\n\tprivate getExtensionResourceDiagnostics(): ResourceDiagnostic[] {\n\t\tconst diagnostics: ResourceDiagnostic[] = this.session.resourceLoader\n\t\t\t.getExtensions()\n\t\t\t.errors.map((error) => ({ type: \"error\" as const, message: error.error, path: error.path }));\n\t\tconst extensionRunner = this.session.extensionRunner;\n\t\tdiagnostics.push(...extensionRunner.getCommandDiagnostics());\n\t\tdiagnostics.push(...this.getBuiltInCommandConflictDiagnostics(extensionRunner));\n\t\tdiagnostics.push(...extensionRunner.getShortcutDiagnostics());\n\t\treturn diagnostics;\n\t}\n\n\tprivate renderLoadedResourceDiagnostics(container: Container, snapshot: LoadedResourceSnapshot): void {\n\t\tconst sourceInfos = snapshot.sourceInfos;\n\t\tthis.addResourceDiagnosticSection(container, \"Skill conflicts\", snapshot.skillsResult.diagnostics, sourceInfos);\n\t\tthis.addResourceDiagnosticSection(container, \"Rule conflicts\", snapshot.rulesResult.diagnostics, sourceInfos);\n\t\tthis.addResourceDiagnosticSection(container, \"Prompt conflicts\", snapshot.promptsResult.diagnostics, sourceInfos);\n\t\tthis.addResourceDiagnosticSection(\n\t\t\tcontainer,\n\t\t\t\"Extension issues\",\n\t\t\tthis.getExtensionResourceDiagnostics(),\n\t\t\tsourceInfos,\n\t\t);\n\t\tthis.addResourceDiagnosticSection(container, \"Theme conflicts\", snapshot.themesResult.diagnostics, sourceInfos);\n\t}\n\n\tprivate showLoadedResources(options?: ShowLoadedResourcesOptions): void {\n\t\tconst container = this.loadedResourcesContainer ?? this.chatContainer;\n\t\tcontainer.clear();\n\t\tconst showListing = options?.force || this.options.verbose || !this.settingsManager.getQuietStartup();\n\t\tconst showDiagnostics = showListing || options?.showDiagnosticsWhenQuiet === true;\n\t\tif (!showListing && !showDiagnostics) return;\n\t\tconst snapshot = this.getLoadedResourceSnapshot(options);\n\t\tif (showListing) this.renderLoadedResourceListing(container, snapshot);\n\t\tif (showDiagnostics) this.renderLoadedResourceDiagnostics(container, snapshot);\n\t}\n\n\t/**\n\t * Initialize the extension system with TUI-based UI context.\n\t */\n\tprivate async bindCurrentSessionExtensions(): Promise<void> {\n\t\tconst uiContext = this.createExtensionUIContext();\n\t\tawait this.session.bindExtensions({\n\t\t\tuiContext,\n\t\t\tabortHandler: () => {\n\t\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\t},\n\t\t\tcommandContextActions: {\n\t\t\t\twaitForIdle: () => this.session.waitForIdle(),\n\t\t\t\tnewSession: async (options) => {\n\t\t\t\t\tif (this.loadingAnimation) {\n\t\t\t\t\t\tthis.loadingAnimation.stop();\n\t\t\t\t\t\tthis.loadingAnimation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tthis.statusContainer.clear();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.runtimeHost.newSession(options);\n\t\t\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\t\t\tthis.renderCurrentSessionState();\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\treturn this.handleFatalRuntimeError(\"Failed to create session\", error);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tfork: async (entryId, options) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.runtimeHost.fork(entryId, options);\n\t\t\t\t\t\tif (!result.cancelled) {\n\t\t\t\t\t\t\tthis.renderCurrentSessionState();\n\t\t\t\t\t\t\tthis.editor.setText(result.selectedText ?? \"\");\n\t\t\t\t\t\t\tthis.showStatus(\"Forked to new session\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { cancelled: result.cancelled };\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\treturn this.handleFatalRuntimeError(\"Failed to fork session\", error);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tnavigateTree: async (targetId, options) => {\n\t\t\t\t\tconst result = await this.session.navigateTree(targetId, {\n\t\t\t\t\t\tsummarize: options?.summarize,\n\t\t\t\t\t\tcustomInstructions: options?.customInstructions,\n\t\t\t\t\t\treplaceInstructions: options?.replaceInstructions,\n\t\t\t\t\t\tlabel: options?.label,\n\t\t\t\t\t});\n\t\t\t\t\tif (result.cancelled) {\n\t\t\t\t\t\treturn { cancelled: true };\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\tthis.renderInitialMessages();\n\t\t\t\t\tif (result.editorText && !this.editor.getText().trim()) {\n\t\t\t\t\t\tthis.editor.setText(result.editorText);\n\t\t\t\t\t}\n\t\t\t\t\tthis.showStatus(\"Navigated to selected point\");\n\t\t\t\t\tvoid this.flushCompactionQueue({ willRetry: false });\n\t\t\t\t\treturn { cancelled: false };\n\t\t\t\t},\n\t\t\t\tswitchSession: async (sessionPath, options) => {\n\t\t\t\t\treturn this.handleResumeSession(sessionPath, options);\n\t\t\t\t},\n\t\t\t\treload: async () => {\n\t\t\t\t\tawait this.handleReloadCommand();\n\t\t\t\t},\n\t\t\t},\n\t\t\tshutdownHandler: () => {\n\t\t\t\tthis.shutdownRequested = true;\n\t\t\t\tif (this.session.isIdle) {\n\t\t\t\t\tvoid this.shutdown();\n\t\t\t\t}\n\t\t\t},\n\t\t\tonError: (error) => {\n\t\t\t\tthis.showExtensionError(error.extensionPath, error.error, error.stack);\n\t\t\t},\n\t\t});\n\n\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\tthis.setupAutocompleteProvider();\n\t\tthis.updateToolBackendStatus();\n\n\t\tconst extensionRunner = this.session.extensionRunner;\n\t\tthis.setupExtensionShortcuts(extensionRunner);\n\t\tthis.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });\n\t\tthis.showStartupNoticesIfNeeded();\n\t}\n\n\tprivate applyRuntimeSettings(): void {\n\t\tthis.transcriptScrollView?.setScrollbar(this.settingsManager.getFullscreenScrollbar());\n\t\tthis.footer.setSession(this.session);\n\t\tthis.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);\n\t\tthis.footerDataProvider.setCwd(this.activeSession.getCwd());\n\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\t\tthis.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());\n\t\tthis.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());\n\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\tthis.defaultEditor.setPaddingX(editorPaddingX);\n\t\tthis.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);\n\t\tif (this.editor !== this.defaultEditor) {\n\t\t\tthis.editor.setPaddingX?.(editorPaddingX);\n\t\t\tthis.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);\n\t\t}\n\t}\n\n\tprivate async rebindCurrentSession(): Promise<void> {\n\t\tthis.unsubscribe?.();\n\t\tthis.unsubscribe = undefined;\n\t\tthis.hookExecutionUnsubscribe?.();\n\t\tthis.hookExecutionUnsubscribe = undefined;\n\t\tthis.hookExecutionActivityUnsubscribe?.();\n\t\tthis.hookExecutionActivityUnsubscribe = undefined;\n\t\tthis.resetHookExecutionActivity();\n\t\tconst activeSession = this.activeSession;\n\t\tif (this.hookExecutionSession !== undefined && this.hookExecutionSession !== activeSession) {\n\t\t\tthis.hookExecutionNotices = [];\n\t\t\tthis.hookExecutionComponents = [];\n\t\t\tthis.resetHookExecutionGrouping();\n\t\t}\n\t\tthis.hookExecutionSession = activeSession;\n\t\tthis.applyRuntimeSettings();\n\t\tawait this.bindCurrentSessionExtensions();\n\t\tif (this.transcriptRendered) {\n\t\t\tthis.retireAndRenderCurrentTranscript();\n\t\t}\n\t\tthis.subscribeToAgent();\n\t\tawait this.updateAvailableProviderCount();\n\t\tthis.updateEditorBorderColor();\n\t\tthis.updateTerminalTitle();\n\t}\n\n\tprivate async handleFatalRuntimeError(prefix: string, error: unknown): Promise<never> {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis.showError(`${prefix}: ${message}`);\n\t\tstopThemeWatcher();\n\t\tthis.stop(\"transcript\");\n\t\tprocess.exit(1);\n\t}\n\n\tprivate retireAndRenderCurrentTranscript(): void {\n\t\tthis.transcriptScrollView?.scrollToEnd();\n\t\tthis.chatContainer.clear();\n\t\tthis.pendingMessagesContainer.clear();\n\t\tthis.compactionQueuedMessages = [];\n\t\tthis.streamingComponent = undefined;\n\t\tthis.streamingMessage = undefined;\n\t\tthis.pendingTools.clear();\n\t\tthis.renderInitialMessages();\n\t}\n\n\tprivate renderCurrentSessionState(): void {\n\t\t(this.loadedResourcesContainer ?? this.chatContainer).clear();\n\t\tthis.retireAndRenderCurrentTranscript();\n\t\tthis.showRuntimeDiagnostics();\n\t}\n\n\tprivate showRuntimeDiagnostics(diagnostics: readonly GripAgentDiagnostic[] = this.runtimeHost.diagnostics): void {\n\t\tfor (const diagnostic of diagnostics) {\n\t\t\tif (diagnostic.type === \"error\") this.showError(diagnostic.message);\n\t\t\telse if (diagnostic.type === \"warning\") this.showWarning(diagnostic.message);\n\t\t\telse this.showStatus(diagnostic.message);\n\t\t}\n\t}\n\n\tprivate getMarkdownTransformers(): MarkdownTransformer[] {\n\t\treturn [this.mermaidMarkdownTransformer, ...this.session.extensionRunner.getMarkdownTransformers()];\n\t}\n\n\t/**\n\t * Get a registered tool definition by name (for custom rendering).\n\t */\n\tprivate getRegisteredToolDefinition(toolName: string) {\n\t\treturn this.session.getToolDefinition(toolName);\n\t}\n\n\t/**\n\t * Set up keyboard shortcuts registered by extensions.\n\t */\n\tprivate setupExtensionShortcuts(extensionRunner: ExtensionRunner): void {\n\t\tconst shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());\n\t\tif (shortcuts.size === 0) return;\n\n\t\t// Create a context for shortcut handlers\n\t\tconst createContext = (): ExtensionContext => ({\n\t\t\tui: this.createExtensionUIContext(),\n\t\t\thasUI: true,\n\t\t\tcwd: this.activeSession.getCwd(),\n\t\t\ttoolOperations: this.session.getToolOperations(),\n\t\t\tgetToolBackendInfo: () => this.session.getToolBackendInfo(),\n\t\t\tgetLspStatus: () => this.session.getLspStatus(),\n\t\t\tconfigureLsp: (configuration) => this.session.configureLsp(configuration),\n\t\t\texecToolBackend: (command, options) => {\n\t\t\t\tconst operations = this.session.getToolOperations();\n\t\t\t\treturn executeBashWithOperations(command, options?.cwd ?? operations.cwd, operations, options);\n\t\t\t},\n\t\t\tsession: this.activeSession,\n\t\t\tmodelRegistry: this.session.modelRegistry,\n\t\t\tmodel: this.session.model,\n\t\t\tisIdle: () => this.session.isIdle,\n\t\t\tsignal: this.session.agent.signal,\n\t\t\tabort: () => {\n\t\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\t},\n\t\t\thasPendingMessages: () => this.session.pendingMessageCount > 0,\n\t\t\tshutdown: () => {\n\t\t\t\tthis.shutdownRequested = true;\n\t\t\t},\n\t\t\tgetContextUsage: () => this.session.getContextUsage(),\n\t\t\tcompact: (options) => {\n\t\t\t\tvoid (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.session.compact(options?.customInstructions);\n\t\t\t\t\t\toptions?.onComplete?.(result);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst err = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\t\toptions?.onError?.(err);\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t},\n\t\t\tgetSystemPrompt: () => this.session.systemPrompt,\n\t\t});\n\n\t\t// Set up the extension shortcut handler on the default editor\n\t\tthis.defaultEditor.onExtensionShortcut = (data: string) => {\n\t\t\tfor (const [shortcutStr, shortcut] of shortcuts) {\n\t\t\t\t// Cast to KeyId - extension shortcuts use the same format\n\t\t\t\tif (matchesKey(data, shortcutStr as KeyId)) {\n\t\t\t\t\t// Run handler async, don't block input\n\t\t\t\t\tPromise.resolve(shortcut.handler(createContext())).catch((err) => {\n\t\t\t\t\t\tthis.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`);\n\t\t\t\t\t});\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t};\n\t}\n\n\t/**\n\t * Set extension status text in the footer.\n\t */\n\tprivate setExtensionStatus(key: string, text: string | undefined): void {\n\t\tthis.footerDataProvider.setExtensionStatus(key, text);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate formatToolBackendStatus(info: ToolBackendInfo): string {\n\t\tif (info.type === \"local\") {\n\t\t\treturn theme.fg(\"dim\", `tools: local ${info.cwd}`);\n\t\t}\n\t\treturn info.configured\n\t\t\t? theme.fg(\"accent\", `tools: remote ${info.url} ${info.cwd}`)\n\t\t\t: theme.fg(\"warning\", `tools: remote not configured ${info.cwd}`);\n\t}\n\n\tprivate updateToolBackendStatus(): void {\n\t\tthis.setExtensionStatus(\"toolBackend\", this.formatToolBackendStatus(this.session.getToolBackendInfo()));\n\t}\n\n\tprivate getWorkingLoaderMessage(): string {\n\t\tconst message = this.workingMessage ?? this.defaultWorkingMessage;\n\t\treturn this.compressionDetectionActive ? `${message} [Evaluating compression possibility]` : message;\n\t}\n\n\tprivate createWorkingLoader(): Loader {\n\t\treturn new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tthis.getWorkingLoaderMessage(),\n\t\t\tthis.workingIndicatorOptions,\n\t\t);\n\t}\n\n\tprivate stopWorkingLoader(): void {\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t}\n\t\tthis.compressionDetectionOwnsLoader = false;\n\t\tthis.statusContainer.clear();\n\t}\n\n\tprivate resetHookExecutionActivity(): void {\n\t\tif (this.hookExecutionActivityDepth === 0) return;\n\t\tthis.hookExecutionActivityDepth = 0;\n\t\tif (this.hookExecutionActivityOwnsLoader && !this.compressionDetectionActive) this.stopWorkingLoader();\n\t\telse this.loadingAnimation?.setMessage(this.getWorkingLoaderMessage());\n\t\tthis.hookExecutionActivityOwnsLoader = false;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleHookExecutionActivity(active: boolean): void {\n\t\tif (active) {\n\t\t\tthis.hookExecutionActivityDepth += 1;\n\t\t\tif (this.hookExecutionActivityDepth > 1) return;\n\t\t\tif (!this.loadingAnimation) {\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t\tthis.loadingAnimation = this.createWorkingLoader();\n\t\t\t\tthis.statusContainer.addChild(this.loadingAnimation);\n\t\t\t\tthis.hookExecutionActivityOwnsLoader = true;\n\t\t\t}\n\t\t\tthis.loadingAnimation.setMessage(\"Running hooks ...\");\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (this.hookExecutionActivityDepth === 0) return;\n\t\tthis.hookExecutionActivityDepth -= 1;\n\t\tif (this.hookExecutionActivityDepth > 0) return;\n\t\tif (this.hookExecutionActivityOwnsLoader && !this.session.isStreaming && !this.compressionDetectionActive)\n\t\t\tthis.stopWorkingLoader();\n\t\telse this.loadingAnimation?.setMessage(this.getWorkingLoaderMessage());\n\t\tthis.hookExecutionActivityOwnsLoader = false;\n\t\tthis.ui.requestRender();\n\t}\n\tprivate releaseCompressionDetectionLoader(): void {\n\t\tif (!this.compressionDetectionOwnsLoader) return;\n\t\tthis.compressionDetectionOwnsLoader = false;\n\t\tif (this.hookExecutionActivityDepth > 0) {\n\t\t\tthis.hookExecutionActivityOwnsLoader = true;\n\t\t\treturn;\n\t\t}\n\t\tif (this.session.isStreaming) return;\n\t\tif (this.loadingAnimation && !this.statusContainer.children.includes(this.loadingAnimation)) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t\treturn;\n\t\t}\n\t\tthis.stopWorkingLoader();\n\t}\n\n\tprivate handleCompressionDetectionActivity(active: boolean): void {\n\t\tthis.compressionDetectionActive = active;\n\t\tif (active && this.workingVisible && !this.loadingAnimation && this.statusContainer.children.length === 0) {\n\t\t\tthis.loadingAnimation = this.createWorkingLoader();\n\t\t\tthis.statusContainer.addChild(this.loadingAnimation);\n\t\t\tthis.compressionDetectionOwnsLoader = true;\n\t\t} else if (!active) {\n\t\t\tthis.releaseCompressionDetectionLoader();\n\t\t\tif (this.hookExecutionActivityDepth === 0) this.loadingAnimation?.setMessage(this.getWorkingLoaderMessage());\n\t\t} else if (this.hookExecutionActivityDepth === 0) {\n\t\t\tthis.loadingAnimation?.setMessage(this.getWorkingLoaderMessage());\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate setWorkingVisible(visible: boolean): void {\n\t\tthis.workingVisible = visible;\n\t\tif (!visible) {\n\t\t\tthis.stopWorkingLoader();\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\t(this.session.isStreaming || this.compressionDetectionActive) &&\n\t\t\t!this.loadingAnimation &&\n\t\t\tthis.statusContainer.children.length === 0\n\t\t) {\n\t\t\tthis.loadingAnimation = this.createWorkingLoader();\n\t\t\tif (this.compressionDetectionActive && !this.session.isStreaming) this.compressionDetectionOwnsLoader = true;\n\t\t\tthis.statusContainer.addChild(this.loadingAnimation);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate setWorkingIndicator(options?: LoaderIndicatorOptions): void {\n\t\tthis.workingIndicatorOptions = options;\n\t\tthis.loadingAnimation?.setIndicator(options);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate setHiddenThinkingLabel(label?: string): void {\n\t\tthis.hiddenThinkingLabel = label ?? this.defaultHiddenThinkingLabel;\n\t\tfor (const child of this.chatContainer.children) {\n\t\t\tif (child instanceof AssistantMessageComponent) {\n\t\t\t\tchild.setHiddenThinkingLabel(this.hiddenThinkingLabel);\n\t\t\t}\n\t\t}\n\t\tif (this.streamingComponent) {\n\t\t\tthis.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set an extension widget (string array or custom component).\n\t */\n\tprivate setExtensionWidget(\n\t\tkey: string,\n\t\tcontent: string[] | ExtensionWidgetFactory | undefined,\n\t\toptions?: ExtensionWidgetOptions,\n\t): void {\n\t\tconst placement = options?.placement ?? \"aboveEditor\";\n\t\tconst removeExisting = (map: Map<string, DisposableComponent>) => {\n\t\t\tconst existing = map.get(key);\n\t\t\tif (existing?.dispose) existing.dispose();\n\t\t\tmap.delete(key);\n\t\t};\n\n\t\tremoveExisting(this.extensionWidgetsAbove);\n\t\tremoveExisting(this.extensionWidgetsBelow);\n\n\t\tif (content === undefined) {\n\t\t\tthis.renderWidgets();\n\t\t\treturn;\n\t\t}\n\n\t\tlet component: DisposableComponent;\n\n\t\tif (Array.isArray(content)) {\n\t\t\t// Wrap string array in a Container with Text components\n\t\t\tconst container = new Container();\n\t\t\tfor (const line of content.slice(0, InteractiveMode.MAX_WIDGET_LINES)) {\n\t\t\t\tcontainer.addChild(new Text(line, 1, 0));\n\t\t\t}\n\t\t\tif (content.length > InteractiveMode.MAX_WIDGET_LINES) {\n\t\t\t\tcontainer.addChild(new Text(theme.fg(\"muted\", \"... (widget truncated)\"), 1, 0));\n\t\t\t}\n\t\t\tcomponent = container;\n\t\t} else {\n\t\t\t// Factory function - create component\n\t\t\tcomponent = content(this.ui, theme);\n\t\t}\n\n\t\tconst targetMap = placement === \"belowEditor\" ? this.extensionWidgetsBelow : this.extensionWidgetsAbove;\n\t\ttargetMap.set(key, component);\n\t\tthis.renderWidgets();\n\t}\n\n\tprivate clearExtensionWidgets(): void {\n\t\tfor (const widget of this.extensionWidgetsAbove.values()) {\n\t\t\twidget.dispose?.();\n\t\t}\n\t\tfor (const widget of this.extensionWidgetsBelow.values()) {\n\t\t\twidget.dispose?.();\n\t\t}\n\t\tthis.extensionWidgetsAbove.clear();\n\t\tthis.extensionWidgetsBelow.clear();\n\t\tthis.renderWidgets();\n\t}\n\n\tprivate resetExtensionUI(): void {\n\t\tif (this.extensionSelector) {\n\t\t\tthis.hideExtensionSelector();\n\t\t}\n\t\tif (this.extensionInput) {\n\t\t\tthis.hideExtensionInput();\n\t\t}\n\t\tif (this.extensionEditor) {\n\t\t\tthis.hideExtensionEditor();\n\t\t}\n\t\tthis.ui.hideOverlay();\n\t\tthis.clearExtensionTerminalInputListeners();\n\t\tthis.setExtensionFooter(undefined);\n\t\tthis.setExtensionHeader(undefined);\n\t\tthis.clearExtensionWidgets();\n\t\tthis.footerDataProvider.clearExtensionStatuses();\n\t\tthis.footer.invalidate();\n\t\tthis.autocompleteProviderWrappers = [];\n\t\tthis.setCustomEditorComponent(undefined);\n\t\tthis.setupAutocompleteProvider();\n\t\tthis.defaultEditor.onExtensionShortcut = undefined;\n\t\tthis.updateTerminalTitle();\n\t\tthis.workingMessage = undefined;\n\t\tthis.workingVisible = true;\n\t\tthis.setWorkingIndicator();\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${keyText(\"app.interrupt\")} to interrupt)`);\n\t\t}\n\t\tthis.setHiddenThinkingLabel();\n\t}\n\n\t// Maximum total widget lines to prevent viewport overflow\n\tprivate static readonly MAX_WIDGET_LINES = 10;\n\n\t/**\n\t * Render all extension widgets to the widget container.\n\t */\n\tprivate renderWidgets(): void {\n\t\tif (!this.widgetContainerAbove || !this.widgetContainerBelow) return;\n\t\tthis.renderWidgetContainer(this.widgetContainerAbove, this.extensionWidgetsAbove, true, true);\n\t\tthis.renderWidgetContainer(this.widgetContainerBelow, this.extensionWidgetsBelow, false, false);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate renderWidgetContainer(\n\t\tcontainer: Container,\n\t\twidgets: Map<string, DisposableComponent>,\n\t\tspacerWhenEmpty: boolean,\n\t\tleadingSpacer: boolean,\n\t): void {\n\t\tcontainer.clear();\n\n\t\tif (widgets.size === 0) {\n\t\t\tif (spacerWhenEmpty) {\n\t\t\t\tcontainer.addChild(new Spacer(1));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (leadingSpacer) {\n\t\t\tcontainer.addChild(new Spacer(1));\n\t\t}\n\t\tfor (const component of widgets.values()) {\n\t\t\tcontainer.addChild(component);\n\t\t}\n\t}\n\n\t/**\n\t * Set a custom footer component, or restore the built-in footer.\n\t */\n\tprivate setExtensionFooter(factory: ExtensionFooterFactory | undefined): void {\n\t\t// Dispose existing custom footer\n\t\tif (this.customFooter?.dispose) {\n\t\t\tthis.customFooter.dispose();\n\t\t}\n\n\t\tthis.footerContainer.clear();\n\t\tif (factory) {\n\t\t\t// Create and add custom footer, passing the data provider\n\t\t\tthis.customFooter = factory(this.ui, theme, this.footerDataProvider);\n\t\t\tthis.footerContainer.addChild(this.customFooter);\n\t\t} else {\n\t\t\t// Restore built-in footer\n\t\t\tthis.customFooter = undefined;\n\t\t\tthis.footerContainer.addChild(this.footer);\n\t\t}\n\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set a custom header component, or restore the built-in header.\n\t */\n\tprivate setExtensionHeader(factory: ExtensionHeaderFactory | undefined): void {\n\t\t// Header may not be initialized yet if called during early initialization\n\t\tif (!this.builtInHeader) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Dispose existing custom header\n\t\tif (this.customHeader?.dispose) {\n\t\t\tthis.customHeader.dispose();\n\t\t}\n\n\t\t// Find the index of the current header in the header container\n\t\tconst currentHeader = this.customHeader || this.builtInHeader;\n\t\tconst index = this.headerContainer.children.indexOf(currentHeader);\n\n\t\tif (factory) {\n\t\t\t// Create and add custom header\n\t\t\tthis.customHeader = factory(this.ui, theme);\n\t\t\tif (isExpandable(this.customHeader)) {\n\t\t\t\tthis.customHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.headerContainer.children[index] = this.customHeader;\n\t\t\t} else {\n\t\t\t\t// If not found (e.g. builtInHeader was never added), add at the top\n\t\t\t\tthis.headerContainer.children.unshift(this.customHeader);\n\t\t\t}\n\t\t} else {\n\t\t\t// Restore built-in header\n\t\t\tthis.customHeader = undefined;\n\t\t\tif (isExpandable(this.builtInHeader)) {\n\t\t\t\tthis.builtInHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.headerContainer.children[index] = this.builtInHeader;\n\t\t\t}\n\t\t}\n\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate addExtensionTerminalInputListener(handler: TerminalInputHandler): () => void {\n\t\tconst subscription = { handler, unsubscribe: this.ui.addInputListener(handler) };\n\t\tthis.extensionTerminalInputSubscriptions.add(subscription);\n\t\treturn () => {\n\t\t\tsubscription.unsubscribe();\n\t\t\tthis.extensionTerminalInputSubscriptions.delete(subscription);\n\t\t};\n\t}\n\n\tprivate rebindExtensionTerminalInputListeners(): void {\n\t\tfor (const subscription of this.extensionTerminalInputSubscriptions) {\n\t\t\tsubscription.unsubscribe();\n\t\t\tsubscription.unsubscribe = this.ui.addInputListener(subscription.handler);\n\t\t}\n\t}\n\n\tprivate clearExtensionTerminalInputListeners(): void {\n\t\tfor (const subscription of this.extensionTerminalInputSubscriptions) subscription.unsubscribe();\n\t\tthis.extensionTerminalInputSubscriptions.clear();\n\t}\n\n\t/**\n\t * Create the ExtensionUIContext for extensions.\n\t */\n\tprivate createExtensionUIContext(): ExtensionUIContext {\n\t\treturn {\n\t\t\tselect: (title, options, opts) => this.showExtensionSelector(title, options, opts),\n\t\t\tconfirm: (title, message, opts) => this.showExtensionConfirm(title, message, opts),\n\t\t\tinput: (title, placeholder, opts) => this.showExtensionInput(title, placeholder, opts),\n\t\t\tnotify: (message, type, options) => this.showExtensionNotify(message, type, options),\n\t\t\tonTerminalInput: (handler) => this.addExtensionTerminalInputListener(handler),\n\t\t\tsetStatus: (key, text) => this.setExtensionStatus(key, text),\n\t\t\tsetWorkingMessage: (message) => {\n\t\t\t\tthis.workingMessage = message;\n\t\t\t\tif (this.loadingAnimation && this.hookExecutionActivityDepth === 0) {\n\t\t\t\t\tthis.loadingAnimation.setMessage(this.getWorkingLoaderMessage());\n\t\t\t\t}\n\t\t\t},\n\t\t\tsetWorkingVisible: (visible) => this.setWorkingVisible(visible),\n\t\t\tsetWorkingIndicator: (options) => this.setWorkingIndicator(options),\n\t\t\tsetHiddenThinkingLabel: (label) => this.setHiddenThinkingLabel(label),\n\t\t\tsetWidget: (key, content, options) => this.setExtensionWidget(key, content, options),\n\t\t\tsetFooter: (factory) => this.setExtensionFooter(factory),\n\t\t\tsetHeader: (factory) => this.setExtensionHeader(factory),\n\t\t\tsetTitle: (title) => this.ui.terminal.setTitle(title),\n\t\t\tcustom: (factory, options) => this.showExtensionCustom(factory, options),\n\t\t\tpasteToEditor: (text) => this.editor.handleInput(`\\x1b[200~${text}\\x1b[201~`),\n\t\t\tsetEditorText: (text) => this.editor.setText(text),\n\t\t\tgetEditorText: () => this.editor.getExpandedText?.() ?? this.editor.getText(),\n\t\t\teditor: (title, prefill) => this.showExtensionEditor(title, prefill),\n\t\t\taddAutocompleteProvider: (factory) => {\n\t\t\t\tthis.autocompleteProviderWrappers.push(factory);\n\t\t\t\tthis.setupAutocompleteProvider();\n\t\t\t},\n\t\t\tsetEditorComponent: (factory) => this.setCustomEditorComponent(factory),\n\t\t\tgetEditorComponent: () => this.editorComponentFactory,\n\t\t\tget theme() {\n\t\t\t\treturn theme;\n\t\t\t},\n\t\t\tgetAllThemes: () => getAvailableThemesWithPaths(),\n\t\t\tgetTheme: (name) => getThemeByName(name),\n\t\t\tsetTheme: (themeOrName) => {\n\t\t\t\tif (themeOrName instanceof Theme) {\n\t\t\t\t\tsetThemeInstance(themeOrName);\n\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\treturn { success: true };\n\t\t\t\t}\n\t\t\t\tconst result = setTheme(themeOrName, true);\n\t\t\t\tif (result.success) {\n\t\t\t\t\tif (this.settingsManager.getTheme() !== themeOrName) {\n\t\t\t\t\t\tthis.settingsManager.setTheme(themeOrName);\n\t\t\t\t\t}\n\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tgetToolsExpanded: () => this.toolOutputExpanded,\n\t\t\tsetToolsExpanded: (expanded) => this.setToolsExpanded(expanded),\n\t\t};\n\t}\n\n\t/**\n\t * Show a selector for extensions.\n\t */\n\tprivate showExtensionSelector(\n\t\ttitle: string,\n\t\toptions: string[],\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tif (opts?.signal?.aborted) {\n\t\t\t\tresolve(undefined);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\tresolve(undefined);\n\t\t\t};\n\t\t\topts?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tthis.extensionSelector = new ExtensionSelectorComponent(\n\t\t\t\ttitle,\n\t\t\t\toptions,\n\t\t\t\t(option) => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\t\tresolve(option);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionSelector();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\t{ tui: this.ui, timeout: opts?.timeout, onToggleToolsExpanded: () => this.toggleToolOutputExpansion() },\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionSelector);\n\t\t\tthis.ui.setFocus(this.extensionSelector);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension selector.\n\t */\n\tprivate hideExtensionSelector(): void {\n\t\tthis.extensionSelector?.dispose();\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionSelector = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a confirmation dialog for extensions.\n\t */\n\tprivate async showExtensionConfirm(\n\t\ttitle: string,\n\t\tmessage: string,\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise<boolean> {\n\t\tconst result = await this.showExtensionSelector(`${title}\\n${message}`, [\"Yes\", \"No\"], opts);\n\t\treturn result === \"Yes\";\n\t}\n\n\tprivate async promptForMissingSessionCwd(error: MissingSessionCwdError): Promise<string | undefined> {\n\t\tconst confirmed = await this.showExtensionConfirm(\n\t\t\t\"Session cwd not found\",\n\t\t\tformatMissingSessionCwdPrompt(error.issue),\n\t\t);\n\t\treturn confirmed ? error.issue.fallbackCwd : undefined;\n\t}\n\n\t/**\n\t * Show a text input for extensions.\n\t */\n\tprivate showExtensionInput(\n\t\ttitle: string,\n\t\tplaceholder?: string,\n\t\topts?: ExtensionUIDialogOptions,\n\t): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tif (opts?.signal?.aborted) {\n\t\t\t\tresolve(undefined);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst onAbort = () => {\n\t\t\t\tthis.hideExtensionInput();\n\t\t\t\tresolve(undefined);\n\t\t\t};\n\t\t\topts?.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\tthis.extensionInput = new ExtensionInputComponent(\n\t\t\t\ttitle,\n\t\t\t\tplaceholder,\n\t\t\t\t(value) => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionInput();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\topts?.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tthis.hideExtensionInput();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\t{ tui: this.ui, timeout: opts?.timeout },\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionInput);\n\t\t\tthis.ui.setFocus(this.extensionInput);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension input.\n\t */\n\tprivate hideExtensionInput(): void {\n\t\tthis.extensionInput?.dispose();\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionInput = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a multi-line editor for extensions (with Ctrl+G support).\n\t */\n\tprivate showExtensionEditor(title: string, prefill?: string): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.extensionEditor = new ExtensionEditorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.keybindings,\n\t\t\t\ttitle,\n\t\t\t\tprefill,\n\t\t\t\t(value) => {\n\t\t\t\t\tthis.hideExtensionEditor();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tthis.hideExtensionEditor();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t\tundefined,\n\t\t\t\tthis.settingsManager.getExternalEditorCommand(),\n\t\t\t);\n\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.extensionEditor);\n\t\t\tthis.ui.setFocus(this.extensionEditor);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\t/**\n\t * Hide the extension editor.\n\t */\n\tprivate hideExtensionEditor(): void {\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(this.editor);\n\t\tthis.extensionEditor = undefined;\n\t\tthis.ui.setFocus(this.editor);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Set a custom editor component from an extension.\n\t * Pass undefined to restore the default editor.\n\t */\n\tprivate configureCustomEditorPresentation(editor: EditorComponent): void {\n\t\tif (editor.borderColor !== undefined) editor.borderColor = this.defaultEditor.borderColor;\n\t\tif (editor.setPaddingX !== undefined) editor.setPaddingX(this.defaultEditor.getPaddingX());\n\t\tif (editor.setAutocompleteProvider && this.autocompleteProvider) {\n\t\t\teditor.setAutocompleteProvider(this.autocompleteProvider);\n\t\t}\n\t}\n\n\tprivate inheritAppEditorHandlers(editor: EditorComponent): void {\n\t\t// Use duck typing because instanceof fails across jiti module boundaries.\n\t\tconst customEditor = editor as unknown as Record<string, unknown>;\n\t\tif (!(\"actionHandlers\" in customEditor) || !(customEditor.actionHandlers instanceof Map)) return;\n\t\tif (!customEditor.onEscape) customEditor.onEscape = () => this.defaultEditor.onEscape?.();\n\t\tif (!customEditor.onCtrlD) customEditor.onCtrlD = () => this.defaultEditor.onCtrlD?.();\n\t\tif (!customEditor.onPasteImage) customEditor.onPasteImage = () => this.defaultEditor.onPasteImage?.();\n\t\tif (!customEditor.onExtensionShortcut) {\n\t\t\tcustomEditor.onExtensionShortcut = (data: string) => this.defaultEditor.onExtensionShortcut?.(data);\n\t\t}\n\t\tfor (const [action, handler] of this.defaultEditor.actionHandlers) {\n\t\t\t(customEditor.actionHandlers as Map<string, () => void>).set(action, handler);\n\t\t}\n\t}\n\n\tprivate createCustomEditorComponent(factory: EditorFactory, text: string): EditorComponent {\n\t\tconst editor = factory(this.ui, getEditorTheme(), this.keybindings);\n\t\teditor.onSubmit = this.defaultEditor.onSubmit;\n\t\teditor.onChange = this.defaultEditor.onChange;\n\t\teditor.setText(text);\n\t\tthis.configureCustomEditorPresentation(editor);\n\t\tthis.inheritAppEditorHandlers(editor);\n\t\treturn editor;\n\t}\n\n\tprivate setCustomEditorComponent(factory: EditorFactory | undefined): void {\n\t\tthis.editorComponentFactory = factory;\n\t\tconst currentText = this.editor.getText();\n\t\tthis.editorContainer.clear();\n\t\tif (factory) {\n\t\t\tthis.editor = this.createCustomEditorComponent(factory, currentText);\n\t\t} else {\n\t\t\tthis.defaultEditor.setText(currentText);\n\t\t\tthis.editor = this.defaultEditor;\n\t\t}\n\t\tthis.editorContainer.addChild(this.editor as Component);\n\t\tthis.ui.setFocus(this.editor as Component);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Show a notification for extensions.\n\t */\n\tprivate showExtensionNotify(\n\t\tmessage: string,\n\t\ttype?: ExtensionNotificationType,\n\t\toptions?: ExtensionNotificationOptions,\n\t): void {\n\t\tif (options?.hookEvent === \"Stop\") {\n\t\t\tthis.pendingStopHookNotifications.push({ message, type });\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"error\") {\n\t\t\tthis.showError(message);\n\t\t} else if (type === \"warning\") {\n\t\t\tthis.showWarning(message);\n\t\t} else {\n\t\t\tthis.showStatus(message);\n\t\t}\n\t}\n\n\tprivate getExtensionOverlayOptions(\n\t\tcomponent: DisposableComponent,\n\t\toptions?: ExtensionCustomOptions,\n\t): OverlayOptions | undefined {\n\t\tif (options?.overlayOptions) {\n\t\t\treturn typeof options.overlayOptions === \"function\" ? options.overlayOptions() : options.overlayOptions;\n\t\t}\n\t\tconst width = (component as { width?: number }).width;\n\t\treturn width ? { width } : undefined;\n\t}\n\n\tprivate mountExtensionCustomComponent(\n\t\tcomponent: DisposableComponent,\n\t\tisOverlay: boolean,\n\t\toptions?: ExtensionCustomOptions,\n\t): void {\n\t\tif (isOverlay) {\n\t\t\tconst handle = this.ui.showOverlay(component, this.getExtensionOverlayOptions(component, options));\n\t\t\toptions?.onHandle?.(handle);\n\t\t\treturn;\n\t\t}\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(component);\n\t\tthis.ui.setFocus(component);\n\t\tthis.ui.requestRender();\n\t}\n\n\t/** Show a custom component with keyboard focus. Overlay mode renders on top of existing content. */\n\tprivate async showExtensionCustom<T>(\n\t\tfactory: ExtensionCustomFactory<T>,\n\t\toptions?: ExtensionCustomOptions,\n\t): Promise<T> {\n\t\tconst savedText = this.editor.getText();\n\t\tconst isOverlay = options?.overlay ?? false;\n\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.editor.setText(savedText);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet component: DisposableComponent;\n\t\t\tlet closed = false;\n\n\t\t\tconst close = (result: T) => {\n\t\t\t\tif (closed) return;\n\t\t\t\tclosed = true;\n\t\t\t\tif (isOverlay) this.ui.hideOverlay();\n\t\t\t\telse restoreEditor();\n\t\t\t\t// Note: both branches above already call requestRender\n\t\t\t\tresolve(result);\n\t\t\t\ttry {\n\t\t\t\t\tcomponent?.dispose?.();\n\t\t\t\t} catch {\n\t\t\t\t\t/* ignore dispose errors */\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tPromise.resolve(factory(this.ui, theme, this.keybindings, close))\n\t\t\t\t.then((resolvedComponent) => {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tcomponent = resolvedComponent;\n\t\t\t\t\tthis.mountExtensionCustomComponent(component, isOverlay, options);\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tif (closed) return;\n\t\t\t\t\tif (!isOverlay) restoreEditor();\n\t\t\t\t\treject(err);\n\t\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Show an extension error in the UI.\n\t */\n\tprivate showExtensionError(extensionPath: string, error: string, stack?: string): void {\n\t\tconst errorMsg = `Extension \"${extensionPath}\" error: ${error}`;\n\t\tconst errorText = new Text(theme.fg(\"error\", errorMsg), 1, 0);\n\t\tthis.chatContainer.addChild(errorText);\n\t\tif (stack) {\n\t\t\t// Show stack trace in dim color, indented\n\t\t\tconst stackLines = stack\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.slice(1) // Skip first line (duplicates error message)\n\t\t\t\t.map((line) => theme.fg(\"dim\", ` ${line.trim()}`))\n\t\t\t\t.join(\"\\n\");\n\t\t\tif (stackLines) {\n\t\t\t\tthis.chatContainer.addChild(new Text(stackLines, 1, 0));\n\t\t\t}\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\t// =========================================================================\n\t// Key Handlers\n\t// =========================================================================\n\tprivate handleEmptyEditorEscape(): void {\n\t\tconst action = this.settingsManager.getDoubleEscapeAction();\n\t\tif (action === \"none\") return;\n\t\tconst now = Date.now();\n\t\tif (now - this.lastEscapeTime >= 500) {\n\t\t\tthis.lastEscapeTime = now;\n\t\t\treturn;\n\t\t}\n\t\tif (action === \"tree\") this.showTreeSelector();\n\t\telse this.showUserMessageSelector();\n\t\tthis.lastEscapeTime = 0;\n\t}\n\n\tprivate handleEditorEscape(): void {\n\t\tif (this.session.isStreaming) {\n\t\t\tthis.restoreQueuedMessagesToEditor({ abort: true });\n\t\t\treturn;\n\t\t}\n\t\tif (this.session.isBashRunning) {\n\t\t\tthis.session.abortBash();\n\t\t\treturn;\n\t\t}\n\t\tif (this.isBashMode) {\n\t\t\tthis.editor.setText(\"\");\n\t\t\tthis.isBashMode = false;\n\t\t\tthis.updateEditorBorderColor();\n\t\t\treturn;\n\t\t}\n\t\tif (!this.editor.getText().trim()) this.handleEmptyEditorEscape();\n\t}\n\n\tprivate setupKeyHandlers(): void {\n\t\t// Set up handlers on defaultEditor - they use this.editor for text access\n\t\t// so they work correctly regardless of which editor is active\n\t\tthis.defaultEditor.onEscape = () => this.handleEditorEscape();\n\n\t\t// Register app action handlers\n\t\tthis.defaultEditor.onAction(\"app.clear\", () => this.handleCtrlC());\n\t\tthis.defaultEditor.onCtrlD = () => this.handleCtrlD();\n\t\tthis.defaultEditor.onAction(\"app.suspend\", () => this.handleCtrlZ());\n\t\tthis.defaultEditor.onAction(\"app.thinking.cycle\", () => this.cycleThinkingLevel());\n\t\tthis.defaultEditor.onAction(\"app.model.cycleForward\", () => this.cycleModel(\"forward\"));\n\t\tthis.defaultEditor.onAction(\"app.model.cycleBackward\", () => this.cycleModel(\"backward\"));\n\n\t\t// Global debug handler on TUI (works regardless of focus)\n\t\tthis.ui.onDebug = () => this.handleDebugCommand();\n\t\tthis.defaultEditor.onAction(\"app.model.select\", () => this.showModelSelector());\n\t\tthis.defaultEditor.onAction(\"app.tools.expand\", () => this.toggleToolOutputExpansion());\n\t\tthis.defaultEditor.onAction(\"app.thinking.toggle\", () => this.toggleThinkingBlockVisibility());\n\t\tthis.defaultEditor.onAction(\"app.editor.external\", () => this.openExternalEditor());\n\t\tthis.defaultEditor.onAction(\"app.message.copy\", () => void this.handleCopyCommand({ flashConfirmation: true }));\n\t\tthis.defaultEditor.onAction(\"app.message.followUp\", () => this.handleFollowUp());\n\t\tthis.defaultEditor.onAction(\"app.message.dequeue\", () => this.handleDequeue());\n\t\tthis.defaultEditor.onAction(\"app.session.new\", () => this.handleClearCommand());\n\t\tthis.defaultEditor.onAction(\"app.session.tree\", () => this.showTreeSelector());\n\t\tthis.defaultEditor.onAction(\"app.session.fork\", () => this.showUserMessageSelector());\n\t\tthis.defaultEditor.onAction(\"app.session.resume\", () => this.showSessionSelector());\n\n\t\tthis.defaultEditor.onChange = (text: string) => {\n\t\t\tconst wasBashMode = this.isBashMode;\n\t\t\tthis.isBashMode = text.trimStart().startsWith(\"!\");\n\t\t\tif (wasBashMode !== this.isBashMode) {\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t}\n\t\t};\n\n\t\t// Handle clipboard paste (triggered on Ctrl+V). Images are attached by path;\n\t\t// otherwise, paste plain text from the system clipboard.\n\t\tthis.defaultEditor.onPasteImage = () => {\n\t\t\tvoid this.handleClipboardPaste();\n\t\t};\n\t}\n\n\tprivate async handleClipboardPaste(): Promise<void> {\n\t\ttry {\n\t\t\tconst image = await readClipboardImage();\n\t\t\tif (image) {\n\t\t\t\tconst tmpDir = os.tmpdir();\n\t\t\t\tconst ext = extensionForImageMimeType(image.mimeType) ?? \"png\";\n\t\t\t\tconst fileName = `grip-clipboard-${crypto.randomUUID()}.${ext}`;\n\t\t\t\tconst filePath = path.join(tmpDir, fileName);\n\t\t\t\tfs.writeFileSync(filePath, Buffer.from(image.bytes));\n\n\t\t\t\tthis.editor.insertTextAtCursor?.(filePath);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst text = await readClipboardText();\n\t\t\tif (text) {\n\t\t\t\tthis.editor.insertTextAtCursor?.(text);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t}\n\t\t} catch {\n\t\t\t// Silently ignore clipboard errors (may not have permission, etc.)\n\t\t}\n\t}\n\n\tprivate async handleRightClickPaste(): Promise<void> {\n\t\tconst target = this.renderer.getFocusedComponent();\n\t\tconst handleInput = target?.handleInput;\n\t\tif (!target || !handleInput) return;\n\t\ttry {\n\t\t\tconst text = await readClipboardText();\n\t\t\tif (!text || this.renderer.getFocusedComponent() !== target) return;\n\t\t\thandleInput.call(target, `\\x1b[200~${text}\\x1b[201~`);\n\t\t\tthis.ui.requestRender();\n\t\t} catch {\n\t\t\t// Silently ignore clipboard errors (may not have permission, etc.)\n\t\t}\n\t}\n\n\tprivate matchesEditorCommand(text: string, command: string): boolean {\n\t\treturn text === command || text.startsWith(`${command} `);\n\t}\n\n\tprivate handleCompressionToggleCommand(text: string, command: string): void {\n\t\tthis.editor.setText(\"\");\n\t\tconst action = text.slice(command.length).trim();\n\t\tconst detection = command === \"/compress-detection\";\n\t\tif (action && action !== \"on\" && action !== \"off\") {\n\t\t\tthis.showWarning(`Usage: ${command} [on|off]`);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tif (action) {\n\t\t\t\tif (detection) this.session.setCompressionDetectionEnabled(action === \"on\");\n\t\t\t\telse this.session.setContextCompressionEnabled(action === \"on\");\n\t\t\t}\n\t\t\tconst enabled = detection ? this.session.compressionDetectionEnabled : this.session.contextCompressionEnabled;\n\t\t\tthis.showStatus(\n\t\t\t\t`${detection ? \"Compression detection\" : \"Context compression\"} ${enabled ? \"enabled\" : \"disabled\"} for this session`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate resolveParameterizedEditorCommand(text: string): EditorCommandAction | undefined {\n\t\tif (this.matchesEditorCommand(text, \"/cd\")) {\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleCdCommand(text);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/profile\")) {\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleProfileCommand(text);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/model\")) {\n\t\t\tconst searchTerm = text.slice(\"/model\".length).trim() || undefined;\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleModelCommand(searchTerm);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tconst compressionCommand = [\"/context-compression\", \"/compress-detection\"].find((command) =>\n\t\t\tthis.matchesEditorCommand(text, command),\n\t\t);\n\t\tif (compressionCommand) return { run: () => this.handleCompressionToggleCommand(text, compressionCommand) };\n\t\tif (this.matchesEditorCommand(text, \"/compress-detection-model\")) {\n\t\t\tconst searchTerm = text.slice(\"/compress-detection-model\".length).trim();\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleCompressionDetectionModelCommand(searchTerm);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/export\")) {\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tawait this.handleExportCommand(text);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/import\")) {\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tawait this.handleImportCommand(text);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/name\")) {\n\t\t\treturn {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleNameCommand(text);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/hooks\")) {\n\t\t\treturn {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleHooksCommand(text);\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (text === \"/sandbox\" || /^\\/sandbox\\s/.test(text)) {\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleSandboxCommand(text);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (this.matchesEditorCommand(text, \"/compact\")) {\n\t\t\tconst customInstructions = text.slice(\"/compact\".length).trim() || undefined;\n\t\t\treturn {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleCompactCommand(customInstructions);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate resolveExactEditorCommand(text: string): EditorCommandAction | undefined {\n\t\tconst commands: Partial<Record<string, EditorCommandAction>> = {\n\t\t\t\"/settings\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showSettingsSelector();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/scoped-models\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.showModelsSelector();\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/share\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tawait this.handleShareCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/copy\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tawait this.handleCopyCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/session\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleSessionCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/changelog\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleChangelogCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/hotkeys\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleHotkeysCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/fork\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showUserMessageSelector();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/clone\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleCloneCommand();\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/tree\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showTreeSelector();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/login\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showOAuthSelector(\"login\");\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/logout\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showOAuthSelector(\"logout\");\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/new\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleClearCommand();\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/reload\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.handleReloadCommand();\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/debug\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.handleDebugCommand();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/resume\": {\n\t\t\t\trun: () => {\n\t\t\t\t\tthis.showSessionSelector();\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"/quit\": {\n\t\t\t\trun: async () => {\n\t\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\t\tawait this.shutdown();\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t\treturn commands[text];\n\t}\n\n\tprivate async handleBuiltInEditorCommand(text: string): Promise<boolean> {\n\t\tconst action = this.resolveParameterizedEditorCommand(text) ?? this.resolveExactEditorCommand(text);\n\t\tif (!action) return false;\n\t\tawait action.run();\n\t\treturn true;\n\t}\n\n\tprivate async handleBashEditorSubmission(text: string): Promise<boolean> {\n\t\tif (!text.startsWith(\"!\")) return false;\n\t\tconst isExcluded = text.startsWith(\"!!\");\n\t\tconst command = isExcluded ? text.slice(2).trim() : text.slice(1).trim();\n\t\tif (!command) return false;\n\t\tif (this.session.isBashRunning) {\n\t\t\tthis.showWarning(\"A bash command is already running. Press Esc to cancel it first.\");\n\t\t\tthis.editor.setText(text);\n\t\t\treturn true;\n\t\t}\n\t\tthis.editor.addToHistory?.(text);\n\t\tawait this.handleBashCommand(command, isExcluded);\n\t\tthis.isBashMode = false;\n\t\tthis.updateEditorBorderColor();\n\t\treturn true;\n\t}\n\n\tprivate async handleCompactingEditorSubmission(text: string): Promise<boolean> {\n\t\tif (!this.session.isCompacting) return false;\n\t\tif (this.isExtensionCommand(text)) {\n\t\t\tthis.editor.addToHistory?.(text);\n\t\t\tthis.editor.setText(\"\");\n\t\t\tawait this.session.prompt(text);\n\t\t} else {\n\t\t\tthis.queueCompactionMessage(text, \"steer\");\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate async handleStreamingEditorSubmission(text: string): Promise<boolean> {\n\t\tif (!this.session.isStreaming) return false;\n\t\tthis.editor.addToHistory?.(text);\n\t\tthis.editor.setText(\"\");\n\t\tawait this.session.prompt(text, { streamingBehavior: \"steer\" });\n\t\tthis.updatePendingMessagesDisplay();\n\t\tthis.ui.requestRender();\n\t\treturn true;\n\t}\n\n\tprivate submitEditorInput(text: string): void {\n\t\tthis.flushPendingBashComponents();\n\t\tif (this.onInputCallback) this.onInputCallback(text);\n\t\telse this.pendingUserInputs.push(text);\n\t\tthis.editor.addToHistory?.(text);\n\t}\n\n\tprivate async handleEditorSubmit(text: string): Promise<void> {\n\t\tconst submittedText = text.trim();\n\t\tif (!submittedText) return;\n\t\t// Keep attempted commands as well as accepted prompts available through editor history.\n\t\tthis.editor.addToHistory?.(submittedText);\n\t\tif (await this.handleBuiltInEditorCommand(submittedText)) return;\n\t\tif (await this.handleBashEditorSubmission(submittedText)) return;\n\t\tif (await this.handleCompactingEditorSubmission(submittedText)) return;\n\t\tif (await this.handleStreamingEditorSubmission(submittedText)) return;\n\t\tthis.submitEditorInput(submittedText);\n\t}\n\n\tprivate setupEditorSubmitHandler(): void {\n\t\tthis.defaultEditor.onSubmit = (text: string) => this.handleEditorSubmit(text);\n\t}\n\n\tprivate addHookExecutionNotice(notice: HookExecutionNotice): void {\n\t\tconst activeSession = this.activeSession;\n\t\tif (this.hookExecutionSession !== activeSession) {\n\t\t\tthis.hookExecutionSession = activeSession;\n\t\t\tthis.hookExecutionNotices = [];\n\t\t\tfor (const component of this.hookExecutionComponents) this.chatContainer.removeChild(component);\n\t\t\tthis.hookExecutionComponents = [];\n\t\t\tthis.resetHookExecutionGrouping();\n\t\t}\n\t\tif (!this.appendHookExecutionNoticeToActiveGroup(notice)) this.addHookExecutionNoticeCard(notice);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate appendHookExecutionNoticeToActiveGroup(notice: HookExecutionNotice): boolean {\n\t\tif (!this.hookExecutionTurnActive || !isToolHookEvent(notice.event)) return false;\n\t\tconst activeGroup = this.activeToolHookExecutionGroups.get(notice.event);\n\t\tif (!activeGroup) return false;\n\t\tconst component = this.hookExecutionComponents[this.hookExecutionNotices.indexOf(activeGroup)];\n\t\tif (!component) return false;\n\t\tactiveGroup.push(notice);\n\t\tcomponent.appendNotice(notice);\n\t\treturn true;\n\t}\n\n\tprivate addHookExecutionNoticeCard(notice: HookExecutionNotice): void {\n\t\tconst group = [notice];\n\t\tthis.hookExecutionNotices.push(group);\n\t\tconst component = new HookExecutionComponent(notice, this.getMarkdownThemeWithSettings());\n\t\tif (notice.event === \"Stop\") {\n\t\t\tfor (const notification of this.pendingStopHookNotifications) component.appendAnnotation(notification.message);\n\t\t\tthis.pendingStopHookNotifications = [];\n\t\t}\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.hookExecutionComponents.push(component);\n\t\tthis.chatContainer.addChild(component);\n\t\tif (this.hookExecutionTurnActive && isToolHookEvent(notice.event)) {\n\t\t\tthis.activeToolHookExecutionGroups.set(notice.event, group);\n\t\t}\n\t\tthis.trimHookExecutionNotices();\n\t}\n\n\tprivate trimHookExecutionNotices(): void {\n\t\tif (this.hookExecutionNotices.length <= MAX_TUI_HOOK_EXECUTION_NOTICES) return;\n\t\tconst oldestGroup = this.hookExecutionNotices.shift();\n\t\tif (oldestGroup) {\n\t\t\tfor (const [event, active] of this.activeToolHookExecutionGroups) {\n\t\t\t\tif (active === oldestGroup) this.activeToolHookExecutionGroups.delete(event);\n\t\t\t}\n\t\t}\n\t\tconst oldestComponent = this.hookExecutionComponents.shift();\n\t\tif (oldestComponent) this.chatContainer.removeChild(oldestComponent);\n\t}\n\n\tprivate resetHookExecutionGrouping(): void {\n\t\tthis.hookExecutionTurnActive = false;\n\t\tthis.activeToolHookExecutionGroups.clear();\n\t}\n\n\tprivate subscribeToAgent(): void {\n\t\tthis.unsubscribe = this.session.subscribe(async (event) => {\n\t\t\tawait this.handleEvent(event);\n\t\t});\n\t\tthis.hookExecutionUnsubscribe = this.session.subscribeToHookExecutions((notice) => {\n\t\t\tthis.addHookExecutionNotice(notice);\n\t\t});\n\t\tthis.hookExecutionActivityUnsubscribe = this.session.subscribeToHookExecutionActivity((active) => {\n\t\t\tthis.handleHookExecutionActivity(active);\n\t\t});\n\t}\n\n\tprivate handleAgentStart(): void {\n\t\tthis.pendingTools.clear();\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(true);\n\t\tif (this.retryEscapeHandler) {\n\t\t\tthis.defaultEditor.onEscape = this.retryEscapeHandler;\n\t\t\tthis.retryEscapeHandler = undefined;\n\t\t}\n\t\tthis.retryCountdown?.dispose();\n\t\tthis.retryCountdown = undefined;\n\t\tthis.retryLoader?.stop();\n\t\tthis.retryLoader = undefined;\n\t\tthis.stopWorkingLoader();\n\t\tif (this.workingVisible) {\n\t\t\tthis.loadingAnimation = this.createWorkingLoader();\n\t\t\tthis.statusContainer.addChild(this.loadingAnimation);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate createPendingToolComponent(toolName: string, toolCallId: string, args: unknown): ToolExecutionComponent {\n\t\tconst component = new ToolExecutionComponent(\n\t\t\ttoolName,\n\t\t\ttoolCallId,\n\t\t\targs,\n\t\t\t{\n\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t},\n\t\t\tthis.getRegisteredToolDefinition(toolName),\n\t\t\tthis.ui,\n\t\t\tthis.activeSession.getCwd(),\n\t\t);\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(component);\n\t\tthis.pendingTools.set(toolCallId, component);\n\t\treturn component;\n\t}\n\n\tprivate handleMessageStart(message: AgentMessage): void {\n\t\tif (message.role === \"custom\") {\n\t\t\tthis.addMessageToChat(message);\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (message.role === \"user\") {\n\t\t\tthis.addMessageToChat(message);\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\t\tif (message.role !== \"assistant\") return;\n\t\tthis.streamingComponent = new AssistantMessageComponent(\n\t\t\tundefined,\n\t\t\tthis.hideThinkingBlock,\n\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\tthis.hiddenThinkingLabel,\n\t\t\tthis.outputPad,\n\t\t\tthis.getMarkdownTransformers(),\n\t\t);\n\t\tthis.streamingMessage = message;\n\t\tthis.chatContainer.addChild(this.streamingComponent);\n\t\tthis.streamingComponent.updateContent(message, true);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate updateStreamingToolComponents(message: AssistantMessage): void {\n\t\tfor (const content of message.content) {\n\t\t\tif (content.type !== \"toolCall\") continue;\n\t\t\tconst component = this.pendingTools.get(content.id);\n\t\t\tif (component) component.updateArgs(content.arguments);\n\t\t\telse this.createPendingToolComponent(content.name, content.id, content.arguments);\n\t\t}\n\t}\n\n\tprivate handleMessageUpdate(message: AgentMessage): void {\n\t\tif (!this.streamingComponent || message.role !== \"assistant\") return;\n\t\tthis.streamingMessage = message;\n\t\tthis.streamingComponent.updateContent(message, true);\n\t\tthis.updateStreamingToolComponents(message);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate getAbortedStreamingMessage(message: AssistantMessage): AssistantMessage {\n\t\tconst retryAttempt = this.session.retryAttempt;\n\t\tconst errorMessage =\n\t\t\tretryAttempt > 0\n\t\t\t\t? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? \"s\" : \"\"}`\n\t\t\t\t: \"Operation aborted\";\n\t\treturn { ...message, errorMessage };\n\t}\n\n\tprivate failPendingTools(errorMessage: string): void {\n\t\tfor (const component of this.pendingTools.values()) {\n\t\t\tcomponent.updateResult({\n\t\t\t\tcontent: [{ type: \"text\", text: errorMessage }],\n\t\t\t\tisError: true,\n\t\t\t});\n\t\t}\n\t\tthis.pendingTools.clear();\n\t}\n\n\tprivate completePendingToolArguments(): void {\n\t\tfor (const component of this.pendingTools.values()) component.setArgsComplete();\n\t}\n\n\tprivate handleMessageEnd(message: AgentMessage): void {\n\t\tif (message.role === \"user\") return;\n\t\tif (this.streamingComponent && message.role === \"assistant\") {\n\t\t\tthis.streamingMessage = message.stopReason === \"aborted\" ? this.getAbortedStreamingMessage(message) : message;\n\t\t\tthis.streamingComponent.updateContent(this.streamingMessage, false);\n\t\t\tif (message.stopReason === \"aborted\" || message.stopReason === \"error\") {\n\t\t\t\tthis.failPendingTools(this.streamingMessage.errorMessage || \"Error\");\n\t\t\t} else {\n\t\t\t\tthis.completePendingToolArguments();\n\t\t\t}\n\t\t\tthis.streamingComponent = undefined;\n\t\t\tthis.streamingMessage = undefined;\n\t\t\tthis.footer.invalidate();\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleAgentEnd(): void {\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(false);\n\t\tif (this.loadingAnimation) this.stopWorkingLoader();\n\t\tif (this.streamingComponent) {\n\t\t\tthis.chatContainer.removeChild(this.streamingComponent);\n\t\t\tthis.streamingComponent = undefined;\n\t\t\tthis.streamingMessage = undefined;\n\t\t}\n\t\tthis.pendingTools.clear();\n\t\tif (this.compressionDetectionActive) this.handleCompressionDetectionActivity(true);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate getCompactionLoaderLabel(reason: CompactionDisplayReason): string {\n\t\tconst cancelHint = `(${keyText(\"app.interrupt\")} to cancel)`;\n\t\tif (reason === \"manual\") return `Compacting context... ${cancelHint}`;\n\t\tconst prefix = reason === \"overflow\" ? \"Context overflow detected, \" : \"\";\n\t\treturn `${prefix}Auto-compacting... ${cancelHint}`;\n\t}\n\n\tprivate handleCompactionStart(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"compaction_start\") return;\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(true);\n\t\tthis.autoCompactionEscapeHandler = this.defaultEditor.onEscape;\n\t\tthis.defaultEditor.onEscape = () => this.session.abortCompaction();\n\t\tthis.statusContainer.clear();\n\t\tthis.autoCompactionLoader = new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tthis.getCompactionLoaderLabel(event.reason),\n\t\t);\n\t\tthis.statusContainer.addChild(this.autoCompactionLoader);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate restoreAfterCompaction(): void {\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(false);\n\t\tif (this.autoCompactionEscapeHandler) {\n\t\t\tthis.defaultEditor.onEscape = this.autoCompactionEscapeHandler;\n\t\t\tthis.autoCompactionEscapeHandler = undefined;\n\t\t}\n\t\tif (this.autoCompactionLoader) {\n\t\t\tthis.autoCompactionLoader.stop();\n\t\t\tthis.autoCompactionLoader = undefined;\n\t\t\tthis.statusContainer.clear();\n\t\t}\n\t}\n\n\tprivate showCompactionError(reason: CompactionDisplayReason, errorMessage: string): void {\n\t\tif (reason === \"manual\") {\n\t\t\tthis.showError(errorMessage);\n\t\t\treturn;\n\t\t}\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"error\", errorMessage), 1, 0));\n\t}\n\n\tprivate handleCompactionEnd(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"compaction_end\") return;\n\t\tthis.restoreAfterCompaction();\n\t\tif (event.aborted) {\n\t\t\tif (event.reason === \"manual\") this.showError(\"Compaction cancelled\");\n\t\t\telse this.showStatus(\"Auto-compaction cancelled\");\n\t\t} else if (event.result) {\n\t\t\tthis.chatContainer.clear();\n\t\t\tthis.hookExecutionNotices = [];\n\t\t\tthis.hookExecutionComponents = [];\n\t\t\tthis.resetHookExecutionGrouping();\n\t\t\tthis.rebuildChatFromMessages();\n\t\t\tthis.addMessageToChat(\n\t\t\t\tcreateCompactionSummaryMessage(event.result.summary, event.result.tokensBefore, new Date().toISOString()),\n\t\t\t);\n\t\t\tthis.footer.invalidate();\n\t\t} else if (event.errorMessage) {\n\t\t\tthis.showCompactionError(event.reason, event.errorMessage);\n\t\t}\n\t\tconst resumeViaCurrentRun = event.reason !== \"manual\" && event.result !== undefined;\n\t\tvoid this.flushCompactionQueue({ willRetry: event.willRetry || resumeViaCurrentRun });\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleAutoRetryStart(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"auto_retry_start\") return;\n\t\tthis.retryEscapeHandler = this.defaultEditor.onEscape;\n\t\tthis.defaultEditor.onEscape = () => this.session.abortRetry();\n\t\tthis.statusContainer.clear();\n\t\tthis.retryCountdown?.dispose();\n\t\tconst retryMessage = (seconds: number) =>\n\t\t\t`Retrying (${event.attempt}/${event.maxAttempts}) in ${seconds}s... (${keyText(\"app.interrupt\")} to cancel)`;\n\t\tthis.retryLoader = new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"warning\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tretryMessage(Math.ceil(event.delayMs / 1000)),\n\t\t);\n\t\tthis.retryCountdown = new CountdownTimer(\n\t\t\tevent.delayMs,\n\t\t\tthis.ui,\n\t\t\t(seconds) => this.retryLoader?.setMessage(retryMessage(seconds)),\n\t\t\t() => {\n\t\t\t\tthis.retryCountdown = undefined;\n\t\t\t},\n\t\t);\n\t\tthis.statusContainer.addChild(this.retryLoader);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleAutoRetryEnd(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"auto_retry_end\") return;\n\t\tif (this.retryEscapeHandler) {\n\t\t\tthis.defaultEditor.onEscape = this.retryEscapeHandler;\n\t\t\tthis.retryEscapeHandler = undefined;\n\t\t}\n\t\tthis.retryCountdown?.dispose();\n\t\tthis.retryCountdown = undefined;\n\t\tif (this.retryLoader) {\n\t\t\tthis.retryLoader.stop();\n\t\t\tthis.retryLoader = undefined;\n\t\t\tthis.statusContainer.clear();\n\t\t}\n\t\tif (!event.success) {\n\t\t\tthis.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || \"Unknown error\"}`);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleSummarizationRetryScheduled(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"summarization_retry_scheduled\") return;\n\t\tthis.showError(event.errorMessage);\n\t\tthis.autoCompactionLoader?.stop();\n\t\tthis.autoCompactionLoader = undefined;\n\t\tthis.branchSummaryLoader?.stop();\n\t\tthis.branchSummaryLoader = undefined;\n\t\tthis.summarizationRetryCountdown?.dispose();\n\t\tthis.summarizationRetryLoader?.stop();\n\t\tthis.statusContainer.clear();\n\t\tconst retryMessage = (seconds: number) =>\n\t\t\t`Retrying summary (${event.attempt}/${event.maxAttempts}) in ${seconds}s... (${keyText(\"app.interrupt\")} to cancel)`;\n\t\tthis.summarizationRetryLoader = new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"warning\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\tretryMessage(Math.ceil(event.delayMs / 1000)),\n\t\t);\n\t\tthis.summarizationRetryCountdown = new CountdownTimer(\n\t\t\tevent.delayMs,\n\t\t\tthis.ui,\n\t\t\t(seconds) => this.summarizationRetryLoader?.setMessage(retryMessage(seconds)),\n\t\t\t() => {\n\t\t\t\tthis.summarizationRetryCountdown = undefined;\n\t\t\t},\n\t\t);\n\t\tthis.statusContainer.addChild(this.summarizationRetryLoader);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleSummarizationRetryAttemptStart(event: AgentSessionEvent): void {\n\t\tif (event.type !== \"summarization_retry_attempt_start\") return;\n\t\tthis.summarizationRetryCountdown?.dispose();\n\t\tthis.summarizationRetryCountdown = undefined;\n\t\tthis.summarizationRetryLoader?.stop();\n\t\tthis.summarizationRetryLoader = undefined;\n\t\tthis.statusContainer.clear();\n\t\tconst cancelHint = `(${keyText(\"app.interrupt\")} to cancel)`;\n\t\tif (event.source === \"branchSummary\") {\n\t\t\tthis.branchSummaryLoader = new Loader(\n\t\t\t\tthis.ui,\n\t\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\t`Summarizing branch... ${cancelHint}`,\n\t\t\t);\n\t\t\tthis.statusContainer.addChild(this.branchSummaryLoader);\n\t\t} else {\n\t\t\tthis.autoCompactionLoader = new Loader(\n\t\t\t\tthis.ui,\n\t\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\tthis.getCompactionLoaderLabel(event.reason),\n\t\t\t);\n\t\t\tthis.statusContainer.addChild(this.autoCompactionLoader);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleSummarizationRetryFinished(): void {\n\t\tthis.summarizationRetryCountdown?.dispose();\n\t\tthis.summarizationRetryCountdown = undefined;\n\t\tif (this.summarizationRetryLoader) {\n\t\t\tthis.summarizationRetryLoader.stop();\n\t\t\tthis.summarizationRetryLoader = undefined;\n\t\t\tthis.statusContainer.clear();\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleEvent(event: AgentSessionEvent): Promise<void> {\n\t\tif (!this.isInitialized) await this.init();\n\t\tthis.footer.invalidate();\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\t\tthis.resetHookExecutionGrouping();\n\t\t\t\tthis.handleAgentStart();\n\t\t\t\tbreak;\n\t\t\tcase \"turn_start\":\n\t\t\t\tthis.hookExecutionTurnActive = true;\n\t\t\t\tthis.activeToolHookExecutionGroups.clear();\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\":\n\t\t\t\tthis.resetHookExecutionGrouping();\n\t\t\t\tbreak;\n\t\t\tcase \"queue_update\":\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\tcase \"compression_detection_activity\":\n\t\t\t\tthis.handleCompressionDetectionActivity(event.active);\n\t\t\t\tbreak;\n\t\t\tcase \"compression_detection_result\":\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\tcase \"state_compressed\":\n\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\tcase \"session_info_changed\":\n\t\t\t\tthis.updateTerminalTitle();\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\tcase \"thinking_level_changed\":\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\t\tthis.handleMessageStart(event.message);\n\t\t\t\tbreak;\n\t\t\tcase \"message_update\":\n\t\t\t\tthis.handleMessageUpdate(event.message);\n\t\t\t\tbreak;\n\t\t\tcase \"message_end\":\n\t\t\t\tthis.handleMessageEnd(event.message);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst component =\n\t\t\t\t\tthis.pendingTools.get(event.toolCallId) ??\n\t\t\t\t\tthis.createPendingToolComponent(event.toolName, event.toolCallId, event.args);\n\t\t\t\tcomponent.markExecutionStarted();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool_execution_update\": {\n\t\t\t\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult({ ...event.partialResult, isError: false }, true);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst component = this.pendingTools.get(event.toolCallId);\n\t\t\t\tif (component) {\n\t\t\t\t\tcomponent.updateResult({ ...event.result, isError: event.isError });\n\t\t\t\t\tthis.pendingTools.delete(event.toolCallId);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis.resetHookExecutionGrouping();\n\t\t\t\tthis.handleAgentEnd();\n\t\t\t\tbreak;\n\t\t\tcase \"agent_settled\":\n\t\t\t\tfor (const notification of this.pendingStopHookNotifications) {\n\t\t\t\t\tthis.showExtensionNotify(notification.message, notification.type);\n\t\t\t\t}\n\t\t\t\tthis.pendingStopHookNotifications = [];\n\t\t\t\tawait this.checkShutdownRequested();\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\tbreak;\n\t\t\tcase \"compaction_start\":\n\t\t\t\tthis.resetHookExecutionGrouping();\n\t\t\t\tthis.handleCompactionStart(event);\n\t\t\t\tbreak;\n\t\t\tcase \"compaction_end\":\n\t\t\t\tthis.handleCompactionEnd(event);\n\t\t\t\tbreak;\n\t\t\tcase \"auto_retry_start\":\n\t\t\t\tthis.handleAutoRetryStart(event);\n\t\t\t\tbreak;\n\t\t\tcase \"auto_retry_end\":\n\t\t\t\tthis.handleAutoRetryEnd(event);\n\t\t\t\tbreak;\n\t\t\tcase \"summarization_retry_scheduled\":\n\t\t\t\tthis.handleSummarizationRetryScheduled(event);\n\t\t\t\tbreak;\n\t\t\tcase \"summarization_retry_attempt_start\":\n\t\t\t\tthis.handleSummarizationRetryAttemptStart(event);\n\t\t\t\tbreak;\n\t\t\tcase \"summarization_retry_finished\":\n\t\t\t\tthis.handleSummarizationRetryFinished();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/** Extract text content from a user message */\n\tprivate getUserMessageText(message: UserMessage): string {\n\t\tif (typeof message.content === \"string\") return message.content;\n\t\treturn message.content\n\t\t\t.filter((content): content is TextContent => content.type === \"text\")\n\t\t\t.map((content) => content.text)\n\t\t\t.join(\"\");\n\t}\n\n\t/**\n\t * Show a status message in the chat.\n\t *\n\t * If multiple status messages are emitted back-to-back (without anything else being added to the chat),\n\t * we update the previous status line instead of appending new ones to avoid log spam.\n\t */\n\tprivate showStatus(message: string): void {\n\t\tconst children = this.chatContainer.children;\n\t\tconst last = children.length > 0 ? children[children.length - 1] : undefined;\n\t\tconst secondLast = children.length > 1 ? children[children.length - 2] : undefined;\n\n\t\tif (last && secondLast && last === this.lastStatusText && secondLast === this.lastStatusSpacer) {\n\t\t\tthis.lastStatusText.setText(theme.fg(\"dim\", message));\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tconst spacer = new Spacer(1);\n\t\tconst text = new Text(theme.fg(\"dim\", message), 1, 0);\n\t\tthis.chatContainer.addChild(spacer);\n\t\tthis.chatContainer.addChild(text);\n\t\tthis.lastStatusSpacer = spacer;\n\t\tthis.lastStatusText = text;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate addBashExecutionMessage(message: BashExecutionMessage): void {\n\t\tconst component = new BashExecutionComponent(message.command, this.ui, message.excludeFromContext);\n\t\tif (message.output) component.appendOutput(message.output);\n\t\tcomponent.setComplete(\n\t\t\tmessage.exitCode,\n\t\t\tmessage.cancelled,\n\t\t\tmessage.truncated ? ({ truncated: true } as TruncationResult) : undefined,\n\t\t\tmessage.fullOutputPath,\n\t\t);\n\t\tthis.chatContainer.addChild(component);\n\t}\n\n\tprivate addCustomMessage(message: CustomMessage): void {\n\t\tif (!message.display) return;\n\t\tif (message.customType === HOOK_EXECUTION_CUSTOM_TYPE) {\n\t\t\tconst notice = parseHookExecutionNotice(message.content);\n\t\t\tif (!notice) return;\n\t\t\tif (!this.appendHookExecutionNoticeToActiveGroup(notice)) this.addHookExecutionNoticeCard(notice);\n\t\t\treturn;\n\t\t}\n\t\tconst renderer = this.session.extensionRunner.getMessageRenderer(message.customType);\n\t\tconst component = new CustomMessageComponent(message, renderer, this.getMarkdownThemeWithSettings());\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(component);\n\t}\n\n\tprivate addCompactionSummaryMessage(message: CompactionSummaryMessage): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tconst component = new CompactionSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(component);\n\t}\n\n\tprivate addBranchSummaryMessage(message: BranchSummaryMessage): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tconst component = new BranchSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(component);\n\t}\n\n\tprivate createUserMessageComponent(text: string): UserMessageComponent {\n\t\treturn new UserMessageComponent(\n\t\t\ttext,\n\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\tthis.outputPad,\n\t\t\tthis.getMarkdownTransformers(),\n\t\t);\n\t}\n\n\tprivate addUserMessageContent(text: string): void {\n\t\tconst skillBlock = parseSkillBlock(text);\n\t\tif (!skillBlock) {\n\t\t\tthis.chatContainer.addChild(this.createUserMessageComponent(text));\n\t\t\treturn;\n\t\t}\n\t\tconst skillComponent = new SkillInvocationMessageComponent(skillBlock, this.getMarkdownThemeWithSettings());\n\t\tskillComponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(skillComponent);\n\t\tif (skillBlock.userMessage) {\n\t\t\tthis.chatContainer.addChild(this.createUserMessageComponent(skillBlock.userMessage));\n\t\t}\n\t}\n\n\tprivate addUserMessage(message: UserMessage, options?: AddMessageToChatOptions): void {\n\t\tconst textContent = this.getUserMessageText(message);\n\t\tif (!textContent) return;\n\t\tif (this.chatContainer.children.length > 0) this.chatContainer.addChild(new Spacer(1));\n\t\tthis.addUserMessageContent(textContent);\n\t\tif (options?.populateHistory) this.editor.addToHistory?.(textContent);\n\t}\n\n\tprivate addAssistantMessage(message: AssistantMessage): void {\n\t\tthis.chatContainer.addChild(\n\t\t\tnew AssistantMessageComponent(\n\t\t\t\tmessage,\n\t\t\t\tthis.hideThinkingBlock,\n\t\t\t\tthis.getMarkdownThemeWithSettings(),\n\t\t\t\tthis.hiddenThinkingLabel,\n\t\t\t\tthis.outputPad,\n\t\t\t\tthis.getMarkdownTransformers(),\n\t\t\t),\n\t\t);\n\t}\n\n\tprivate addMessageToChat(message: AgentMessage, options?: AddMessageToChatOptions): void {\n\t\tswitch (message.role) {\n\t\t\tcase \"bashExecution\":\n\t\t\t\tthis.addBashExecutionMessage(message);\n\t\t\t\tbreak;\n\t\t\tcase \"custom\":\n\t\t\t\tthis.addCustomMessage(message);\n\t\t\t\tbreak;\n\t\t\tcase \"compactionSummary\":\n\t\t\t\tthis.addCompactionSummaryMessage(message);\n\t\t\t\tbreak;\n\t\t\tcase \"branchSummary\":\n\t\t\t\tthis.addBranchSummaryMessage(message);\n\t\t\t\tbreak;\n\t\t\tcase \"user\":\n\t\t\t\tthis.addUserMessage(message, options);\n\t\t\t\tbreak;\n\t\t\tcase \"assistant\":\n\t\t\t\tthis.addAssistantMessage(message);\n\t\t\t\tbreak;\n\t\t\tcase \"toolResult\":\n\t\t\t\tbreak;\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustive: never = message;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate renderTranscriptToolCall(toolCall: ToolCall): ToolExecutionComponent {\n\t\tconst component = new ToolExecutionComponent(\n\t\t\ttoolCall.name,\n\t\t\ttoolCall.id,\n\t\t\ttoolCall.arguments,\n\t\t\t{\n\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t},\n\t\t\tthis.getRegisteredToolDefinition(toolCall.name),\n\t\t\tthis.ui,\n\t\t\tthis.activeSession.getCwd(),\n\t\t);\n\t\tcomponent.setExpanded(this.toolOutputExpanded);\n\t\tthis.chatContainer.addChild(component);\n\t\treturn component;\n\t}\n\n\tprivate getTranscriptToolFailure(message: AssistantMessage): string | undefined {\n\t\tif (message.stopReason === \"error\") return message.errorMessage || \"Error\";\n\t\tif (message.stopReason !== \"aborted\") return undefined;\n\t\tconst retryAttempt = this.session.retryAttempt;\n\t\tif (retryAttempt === 0) return \"Operation aborted\";\n\t\treturn `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? \"s\" : \"\"}`;\n\t}\n\n\tprivate renderAssistantTranscriptMessage(\n\t\tmessage: AssistantMessage,\n\t\tpendingTools: Map<string, ToolExecutionComponent>,\n\t): void {\n\t\tthis.addMessageToChat(message);\n\t\tconst failure = this.getTranscriptToolFailure(message);\n\t\tfor (const content of message.content) {\n\t\t\tif (content.type !== \"toolCall\") continue;\n\t\t\tconst component = this.renderTranscriptToolCall(content);\n\t\t\tif (failure !== undefined) {\n\t\t\t\tcomponent.updateResult({ content: [{ type: \"text\", text: failure }], isError: true });\n\t\t\t} else {\n\t\t\t\tpendingTools.set(content.id, component);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate applyTranscriptToolResult(\n\t\tmessage: ToolResultMessage,\n\t\tpendingTools: Map<string, ToolExecutionComponent>,\n\t): void {\n\t\tconst component = pendingTools.get(message.toolCallId);\n\t\tif (!component) return;\n\t\tcomponent.updateResult(message);\n\t\tpendingTools.delete(message.toolCallId);\n\t}\n\n\tprivate renderTranscriptMessage(\n\t\tmessage: AgentMessage,\n\t\tpendingTools: Map<string, ToolExecutionComponent>,\n\t\toptions: RenderSessionContextOptions,\n\t): void {\n\t\tif (message.role === \"assistant\") {\n\t\t\tthis.renderAssistantTranscriptMessage(message, pendingTools);\n\t\t\treturn;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tthis.applyTranscriptToolResult(message, pendingTools);\n\t\t\treturn;\n\t\t}\n\t\tthis.addMessageToChat(message, options);\n\t}\n\n\t/**\n\t * Render session context to chat. Used for initial load and rebuild after compaction.\n\t * @param sessionContext Session context to render\n\t * @param options.updateFooter Update footer state\n\t * @param options.populateHistory Add user messages to editor history\n\t */\n\tprivate renderSessionContext(sessionContext: SessionContext, options: RenderSessionContextOptions = {}): void {\n\t\tthis.pendingTools.clear();\n\t\tconst renderedPendingTools = new Map<string, ToolExecutionComponent>();\n\t\tif (options.updateFooter) {\n\t\t\tthis.footer.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t}\n\t\tfor (const message of sessionContext.messages) {\n\t\t\tif (message.role === \"user\" || message.role === \"assistant\") this.resetHookExecutionGrouping();\n\t\t\tthis.renderTranscriptMessage(message, renderedPendingTools, options);\n\t\t\tif (message.role === \"assistant\") this.hookExecutionTurnActive = true;\n\t\t}\n\t\tthis.resetHookExecutionGrouping();\n\t\tfor (const [toolCallId, component] of renderedPendingTools) {\n\t\t\tthis.pendingTools.set(toolCallId, component);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\trenderInitialMessages(): void {\n\t\tthis.transcriptRendered = true;\n\t\tthis.hookExecutionSession = this.activeSession;\n\t\tthis.hookExecutionNotices = [];\n\t\tthis.hookExecutionComponents = [];\n\t\tthis.resetHookExecutionGrouping();\n\t\t// Get aligned messages and entries from session context\n\t\tconst context = this.activeSession.buildSessionContext();\n\t\tthis.renderSessionContext(context, {\n\t\t\tupdateFooter: true,\n\t\t\tpopulateHistory: true,\n\t\t});\n\n\t\t// Show compaction info if session was compacted\n\t\tconst allEntries = this.activeSession.getEntries();\n\t\tconst compactionCount = allEntries.filter((e) => e.type === \"compaction\").length;\n\t\tif (compactionCount > 0) {\n\t\t\tconst times = compactionCount === 1 ? \"1 time\" : `${compactionCount} times`;\n\t\t\tthis.showStatus(`Session compacted ${times}`);\n\t\t}\n\t}\n\n\tasync getUserInput(): Promise<string> {\n\t\tconst queuedInput = this.pendingUserInputs.shift();\n\t\tif (queuedInput !== undefined) {\n\t\t\treturn queuedInput;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.onInputCallback = (text: string) => {\n\t\t\t\tthis.onInputCallback = undefined;\n\t\t\t\tresolve(text);\n\t\t\t};\n\t\t});\n\t}\n\n\tprivate rebuildChatFromMessages(): void {\n\t\tthis.chatContainer.clear();\n\t\tthis.hookExecutionSession = this.activeSession;\n\t\tthis.hookExecutionNotices = [];\n\t\tthis.hookExecutionComponents = [];\n\t\tthis.resetHookExecutionGrouping();\n\t\tconst context = this.activeSession.buildSessionContext();\n\t\tthis.renderSessionContext(context);\n\t}\n\n\t// =========================================================================\n\t// Key handlers\n\t// =========================================================================\n\n\tprivate handleCtrlC(): void {\n\t\tconst now = Date.now();\n\t\tif (now - this.lastSigintTime < 500) {\n\t\t\tvoid this.shutdown();\n\t\t} else {\n\t\t\tthis.clearEditor();\n\t\t\tthis.lastSigintTime = now;\n\t\t}\n\t}\n\n\tprivate handleCtrlD(): void {\n\t\t// Only called when editor is empty (enforced by CustomEditor)\n\t\tvoid this.shutdown();\n\t}\n\n\t/**\n\t * Gracefully shutdown the agent.\n\t * Stops the TUI before emitting shutdown events so extension UI cleanup cannot\n\t * repaint the final frame while the process is exiting.\n\t */\n\tprivate isShuttingDown = false;\n\n\tprivate async shutdown(options?: ShutdownOptions): Promise<void> {\n\t\tif (this.isShuttingDown) return;\n\t\tthis.isShuttingDown = true;\n\t\tthis.unregisterSignalHandlers();\n\n\t\tif (options?.fromSignal) {\n\t\t\t// Signal-triggered shutdown (SIGTERM/SIGHUP). Emit extension cleanup\n\t\t\t// (session_shutdown) BEFORE touching the terminal. Extension teardown\n\t\t\t// such as removing sockets does not write to the tty, so it must not be\n\t\t\t// skipped if a later terminal-restore write fails on a dead or stalled\n\t\t\t// terminal. If the terminal is gone, the restore writes below emit EIO,\n\t\t\t// which the stdout/stderr error handler turns into emergencyTerminalExit;\n\t\t\t// the render loop is already idle, so this cannot hot-spin (see #4144).\n\t\t\tconst shutdownErrors = await this.disposeRuntimeResources();\n\t\t\tawait this.ui.terminal.drainInput(1000);\n\t\t\tthis.stop(this.settingsManager.getFullscreenExitOutput());\n\t\t\tfor (const error of shutdownErrors) console.error(\"Grip shutdown cleanup failed:\", error);\n\t\t\tprocess.exit(0);\n\t\t}\n\n\t\t// Interactive quit (Ctrl+D, Ctrl+C, /quit, extension shutdown()). Stop the\n\t\t// TUI before emitting shutdown events so extension UI cleanup cannot repaint\n\t\t// the final frame while the process is exiting.\n\t\t// Drain any in-flight Kitty key release events before stopping.\n\t\t// This prevents escape sequences from leaking to the parent shell over slow SSH.\n\t\tawait this.ui.terminal.drainInput(1000);\n\n\t\tthis.stop(this.settingsManager.getFullscreenExitOutput());\n\t\tconst shutdownErrors = await this.disposeRuntimeResources();\n\t\tfor (const error of shutdownErrors) console.error(\"Grip shutdown cleanup failed:\", error);\n\t\tprocess.exit(0);\n\t}\n\n\tprivate emergencyTerminalExit(): never {\n\t\tthis.isShuttingDown = true;\n\t\tthis.unregisterSignalHandlers();\n\t\tkillTrackedDetachedChildren();\n\t\t// The terminal is gone. Do not run normal shutdown because TUI and\n\t\t// extension cleanup can write restore sequences and re-trigger EIO.\n\t\tprocess.exit(129);\n\t}\n\n\t/**\n\t * Last-resort handler for uncaught exceptions. The TUI puts stdin into raw\n\t * mode and hides the cursor; without this handler, an uncaught throw from\n\t * anywhere (e.g. an extension's async `ChildProcess.on(\"exit\")` callback)\n\t * tears down the process while leaving the terminal in raw mode with no\n\t * cursor, requiring `stty sane && reset` to recover.\n\t *\n\t * Unlike emergencyTerminalExit, the terminal is still alive here, so we\n\t * call ui.stop() to restore cooked mode, the cursor, and disable bracketed\n\t * paste / Kitty / modifyOtherKeys sequences.\n\t */\n\tprivate uncaughtCrash(error: Error): never {\n\t\tif (this.isShuttingDown) {\n\t\t\tprocess.exit(1);\n\t\t}\n\t\tthis.isShuttingDown = true;\n\t\ttry {\n\t\t\tthis.unregisterSignalHandlers();\n\t\t} catch {}\n\t\ttry {\n\t\t\tkillTrackedDetachedChildren();\n\t\t} catch {}\n\t\ttry {\n\t\t\tthis.stopInteractiveTui(\"transcript\");\n\t\t} catch {}\n\t\tconsole.error(\"grip exiting due to uncaughtException:\");\n\t\tconsole.error(error);\n\t\tprocess.exit(1);\n\t}\n\n\t/**\n\t * Check if shutdown was requested and perform shutdown if so.\n\t */\n\tprivate async checkShutdownRequested(): Promise<void> {\n\t\tif (!this.shutdownRequested) return;\n\t\tawait this.shutdown();\n\t}\n\n\tprivate registerSignalHandlers(): void {\n\t\tthis.unregisterSignalHandlers();\n\n\t\tconst signals: NodeJS.Signals[] = [\"SIGTERM\"];\n\t\tif (process.platform !== \"win32\") {\n\t\t\tsignals.push(\"SIGHUP\");\n\t\t}\n\n\t\tfor (const signal of signals) {\n\t\t\tconst handler = () => {\n\t\t\t\t// SIGHUP no longer hard-exits: graceful shutdown emits session_shutdown\n\t\t\t\t// first, then attempts terminal restore. A genuinely dead terminal\n\t\t\t\t// surfaces as an EIO on the restore writes, which the stdout/stderr\n\t\t\t\t// error handler converts into emergencyTerminalExit (see #4144, #5080).\n\t\t\t\tkillTrackedDetachedChildren();\n\t\t\t\tvoid this.shutdown({ fromSignal: true });\n\t\t\t};\n\t\t\tprocess.prependListener(signal, handler);\n\t\t\tthis.signalCleanupHandlers.push(() => process.off(signal, handler));\n\t\t}\n\n\t\tconst terminalErrorHandler = (error: Error) => {\n\t\t\tif (isDeadTerminalError(error)) {\n\t\t\t\tthis.emergencyTerminalExit();\n\t\t\t}\n\t\t\tthrow error;\n\t\t};\n\t\tprocess.stdout.on(\"error\", terminalErrorHandler);\n\t\tprocess.stderr.on(\"error\", terminalErrorHandler);\n\t\tthis.signalCleanupHandlers.push(() => process.stdout.off(\"error\", terminalErrorHandler));\n\t\tthis.signalCleanupHandlers.push(() => process.stderr.off(\"error\", terminalErrorHandler));\n\n\t\t// Restore the terminal before the process dies on any uncaught throw.\n\t\t// Without this, an unhandled exception from extension code (or anywhere\n\t\t// in grip) leaves the terminal in raw mode with no cursor.\n\t\tconst uncaughtExceptionHandler = (error: Error) => this.uncaughtCrash(error);\n\t\tprocess.prependListener(\"uncaughtException\", uncaughtExceptionHandler);\n\t\tthis.signalCleanupHandlers.push(() => process.off(\"uncaughtException\", uncaughtExceptionHandler));\n\t}\n\n\tprivate unregisterSignalHandlers(): void {\n\t\tfor (const cleanup of this.signalCleanupHandlers) {\n\t\t\tcleanup();\n\t\t}\n\t\tthis.signalCleanupHandlers = [];\n\t}\n\n\tprivate handleCtrlZ(): void {\n\t\tif (process.platform === \"win32\") {\n\t\t\tthis.showStatus(\"Suspend to background is not supported on Windows\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Keep the event loop alive while suspended. Without this, stopping the TUI\n\t\t// can leave Node with no ref'ed handles, causing the process to exit on fg\n\t\t// before the SIGCONT handler gets a chance to restore the terminal.\n\t\tconst suspendKeepAlive = setInterval(() => {}, 2 ** 30);\n\n\t\t// Ignore SIGINT while suspended so Ctrl+C in the terminal does not\n\t\t// kill the backgrounded process. The handler is removed on resume.\n\t\tconst ignoreSigint = () => {};\n\t\tprocess.on(\"SIGINT\", ignoreSigint);\n\n\t\t// Set up handler to restore TUI when resumed\n\t\tprocess.once(\"SIGCONT\", () => {\n\t\t\tclearInterval(suspendKeepAlive);\n\t\t\tprocess.removeListener(\"SIGINT\", ignoreSigint);\n\t\t\tthis.ui.start();\n\t\t\tthis.ui.requestRender(true);\n\t\t});\n\n\t\ttry {\n\t\t\t// Stop the TUI (restore terminal to normal mode)\n\t\t\tthis.ui.stop({ preserveScreen: true });\n\n\t\t\t// Send SIGTSTP to process group (pid=0 means all processes in group)\n\t\t\tprocess.kill(0, \"SIGTSTP\");\n\t\t} catch (error) {\n\t\t\tclearInterval(suspendKeepAlive);\n\t\t\tprocess.removeListener(\"SIGINT\", ignoreSigint);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async handleFollowUp(): Promise<void> {\n\t\tconst text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();\n\t\tif (!text) return;\n\n\t\t// Queue input during compaction (extension commands execute immediately)\n\t\tif (this.session.isCompacting) {\n\t\t\tif (this.isExtensionCommand(text)) {\n\t\t\t\tthis.editor.addToHistory?.(text);\n\t\t\t\tthis.editor.setText(\"\");\n\t\t\t\tawait this.session.prompt(text);\n\t\t\t} else {\n\t\t\t\tthis.queueCompactionMessage(text, \"followUp\");\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Alt+Enter queues a follow-up message (waits until agent finishes)\n\t\t// This handles extension commands (execute immediately), prompt template expansion, and queueing\n\t\tif (this.session.isStreaming) {\n\t\t\tthis.editor.addToHistory?.(text);\n\t\t\tthis.editor.setText(\"\");\n\t\t\tawait this.session.prompt(text, { streamingBehavior: \"followUp\" });\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tthis.ui.requestRender();\n\t\t}\n\t\t// If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)\n\t\telse if (this.editor.onSubmit) {\n\t\t\tthis.editor.setText(\"\");\n\t\t\tthis.editor.onSubmit(text);\n\t\t}\n\t}\n\n\tprivate handleDequeue(): void {\n\t\tconst restored = this.restoreQueuedMessagesToEditor();\n\t\tif (restored === 0) {\n\t\t\tthis.showStatus(\"No queued messages to restore\");\n\t\t} else {\n\t\t\tthis.showStatus(`Restored ${restored} queued message${restored > 1 ? \"s\" : \"\"} to editor`);\n\t\t}\n\t}\n\n\tprivate updateEditorBorderColor(): void {\n\t\tif (this.isBashMode) {\n\t\t\tthis.editor.borderColor = theme.getBashModeBorderColor();\n\t\t} else {\n\t\t\tconst level = this.session.thinkingLevel || \"off\";\n\t\t\tthis.editor.borderColor = theme.getThinkingBorderColor(level);\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate cycleThinkingLevel(): void {\n\t\tconst newLevel = this.session.cycleThinkingLevel();\n\t\tif (newLevel === undefined) {\n\t\t\tthis.showStatus(\"Current model does not support thinking\");\n\t\t} else {\n\t\t\tthis.footer.invalidate();\n\t\t\tthis.updateEditorBorderColor();\n\t\t\tthis.showStatus(`Thinking level: ${newLevel}`);\n\t\t}\n\t}\n\n\tprivate async cycleModel(direction: ModelCycleDirection): Promise<void> {\n\t\ttry {\n\t\t\tconst result = await this.session.cycleModel(direction);\n\t\t\tif (result === undefined) {\n\t\t\t\tconst msg = this.session.scopedModels.length > 0 ? \"Only one model in scope\" : \"Only one model available\";\n\t\t\t\tthis.showStatus(msg);\n\t\t\t} else {\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tconst thinkingStr =\n\t\t\t\t\tresult.model.reasoning && result.thinkingLevel !== \"off\" ? ` (thinking: ${result.thinkingLevel})` : \"\";\n\t\t\t\tthis.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`);\n\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(result.model);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate toggleToolOutputExpansion(): void {\n\t\tthis.setToolsExpanded(!this.toolOutputExpanded);\n\t}\n\n\tprivate setToolsExpanded(expanded: boolean): void {\n\t\tthis.toolOutputExpanded = expanded;\n\t\tconst activeHeader = this.customHeader ?? this.builtInHeader;\n\t\tif (isExpandable(activeHeader)) {\n\t\t\tactiveHeader.setExpanded(expanded);\n\t\t}\n\t\tconst expandableContainers = this.loadedResourcesContainer\n\t\t\t? [this.loadedResourcesContainer, this.chatContainer]\n\t\t\t: [this.chatContainer];\n\t\tfor (const container of expandableContainers) {\n\t\t\tfor (const child of container.children) {\n\t\t\t\tif (isExpandable(child)) {\n\t\t\t\t\tchild.setExpanded(expanded);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate toggleThinkingBlockVisibility(): void {\n\t\tthis.hideThinkingBlock = !this.hideThinkingBlock;\n\t\tthis.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);\n\n\t\t// Rebuild chat from session messages\n\t\tthis.chatContainer.clear();\n\t\tthis.rebuildChatFromMessages();\n\n\t\t// If streaming, re-add the streaming component with updated visibility and re-render\n\t\tif (this.streamingComponent && this.streamingMessage) {\n\t\t\tthis.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);\n\t\t\tthis.streamingComponent.updateContent(this.streamingMessage);\n\t\t\tthis.chatContainer.addChild(this.streamingComponent);\n\t\t}\n\n\t\tthis.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? \"hidden\" : \"visible\"}`);\n\t}\n\n\tprivate async openExternalEditor(): Promise<void> {\n\t\tconst editorCmd = this.settingsManager.getExternalEditorCommand();\n\t\tif (!editorCmd) {\n\t\t\tthis.showWarning(\"No editor configured. Set externalEditor in settings.json or $VISUAL/$EDITOR.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst currentText = this.editor.getExpandedText?.() ?? this.editor.getText();\n\t\tconst tmpFile = path.join(os.tmpdir(), `grip-editor-${Date.now()}.grip.md`);\n\n\t\ttry {\n\t\t\t// Write current content to temp file\n\t\t\tfs.writeFileSync(tmpFile, currentText, \"utf-8\");\n\n\t\t\t// Stop TUI to release terminal\n\t\t\tthis.ui.stop({ preserveScreen: true });\n\n\t\t\t// Split by space to support editor arguments (e.g., \"code --wait\")\n\t\t\tconst [editor, ...editorArgs] = editorCmd.split(\" \");\n\n\t\t\tprocess.stdout.write(`Launching external editor: ${editorCmd}\\nGrip will resume when the editor exits.\\n`);\n\n\t\t\t// Do not use spawnSync here. On Windows, synchronous child_process calls can keep\n\t\t\t// Node/libuv's console input read active after ui.stop() pauses stdin, racing\n\t\t\t// vim/nvim for the console input buffer until Ctrl+C cancels the pending read.\n\t\t\tconst status = await new Promise<number | null>((resolve) => {\n\t\t\t\tconst child = spawn(editor, [...editorArgs, tmpFile], {\n\t\t\t\t\tstdio: \"inherit\",\n\t\t\t\t\tshell: process.platform === \"win32\",\n\t\t\t\t});\n\t\t\t\tchild.on(\"error\", () => resolve(null));\n\t\t\t\tchild.on(\"close\", (code) => resolve(code));\n\t\t\t});\n\n\t\t\t// On successful exit (status 0), replace editor content\n\t\t\tif (status === 0) {\n\t\t\t\tconst newContent = fs.readFileSync(tmpFile, \"utf-8\").replace(/\\n$/, \"\");\n\t\t\t\tthis.editor.setText(newContent);\n\t\t\t}\n\t\t\t// On non-zero exit, keep original text (no action needed)\n\t\t} finally {\n\t\t\t// Clean up temp file\n\t\t\ttry {\n\t\t\t\tfs.unlinkSync(tmpFile);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\n\t\t\t// Restart TUI\n\t\t\tthis.ui.start();\n\t\t\t// Force full re-render since external editor uses alternate screen\n\t\t\tthis.ui.requestRender(true);\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// UI helpers\n\t// =========================================================================\n\n\tclearEditor(): void {\n\t\tthis.editor.setText(\"\");\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowError(errorMessage: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"error\", `Error: ${errorMessage}`), 1, 0));\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowWarning(warningMessage: string): void {\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"warning\", `Warning: ${warningMessage}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowNewVersionNotification(release: LatestGripRelease): void {\n\t\tconst action = theme.fg(\"accent\", `${APP_NAME} update`);\n\t\tconst updateInstruction =\n\t\t\ttheme.fg(\"muted\", `New ${PACKAGE_NAME} version ${release.version} is available. Run `) + action;\n\t\tconst changelogUrl = \"https://github.com/greppleai/grip/blob/main/packages/coding-agent/CHANGELOG.md\";\n\t\tconst changelogLink = getCapabilities().hyperlinks\n\t\t\t? hyperlink(theme.fg(\"accent\", \"open changelog\"), changelogUrl)\n\t\t\t: theme.fg(\"accent\", changelogUrl);\n\t\tconst changelogLine = theme.fg(\"muted\", \"Changelog: \") + changelogLink;\n\t\tconst note = release.note?.trim();\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(`${theme.bold(theme.fg(\"warning\", \"Update Available\"))}\\n${updateInstruction}`, 1, 0),\n\t\t);\n\t\tif (note) {\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(\n\t\t\t\tnew Markdown(note, 1, 0, this.getMarkdownThemeWithSettings(), {\n\t\t\t\t\tcolor: (text) => theme.fg(\"muted\", text),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t}\n\t\tthis.chatContainer.addChild(new Text(changelogLine, 1, 0));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.ui.requestRender();\n\t}\n\n\tshowPackageUpdateNotification(packages: string[]): void {\n\t\tconst action = theme.fg(\"accent\", `${APP_NAME} update`);\n\t\tconst updateInstruction = theme.fg(\"muted\", \"Package updates are available. Run \") + action;\n\t\tconst packageLines = packages.map((pkg) => `- ${pkg}`).join(\"\\n\");\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(\n\t\t\t\t`${theme.bold(theme.fg(\"warning\", \"Package Updates Available\"))}\\n${updateInstruction}\\n${theme.fg(\"muted\", \"Packages:\")}\\n${packageLines}`,\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\tthis.chatContainer.addChild(new DynamicBorder((text) => theme.fg(\"warning\", text)));\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Get all queued messages (read-only).\n\t * Combines session queue and compaction queue.\n\t */\n\tprivate getAllQueuedMessages(): QueuedMessages {\n\t\treturn {\n\t\t\tsteering: [\n\t\t\t\t...this.session.getSteeringMessages(),\n\t\t\t\t...this.compactionQueuedMessages.filter((msg) => msg.mode === \"steer\").map((msg) => msg.text),\n\t\t\t],\n\t\t\tfollowUp: [\n\t\t\t\t...this.session.getFollowUpMessages(),\n\t\t\t\t...this.compactionQueuedMessages.filter((msg) => msg.mode === \"followUp\").map((msg) => msg.text),\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Clear all queued messages and return their contents.\n\t * Clears both session queue and compaction queue.\n\t */\n\tprivate clearAllQueues(): QueuedMessages {\n\t\tconst { steering, followUp } = this.session.clearQueue();\n\t\tconst compactionSteering = this.compactionQueuedMessages\n\t\t\t.filter((msg) => msg.mode === \"steer\")\n\t\t\t.map((msg) => msg.text);\n\t\tconst compactionFollowUp = this.compactionQueuedMessages\n\t\t\t.filter((msg) => msg.mode === \"followUp\")\n\t\t\t.map((msg) => msg.text);\n\t\tthis.compactionQueuedMessages = [];\n\t\treturn {\n\t\t\tsteering: [...steering, ...compactionSteering],\n\t\t\tfollowUp: [...followUp, ...compactionFollowUp],\n\t\t};\n\t}\n\n\tprivate updatePendingMessagesDisplay(): void {\n\t\tthis.pendingMessagesContainer.clear();\n\t\tconst { steering: steeringMessages, followUp: followUpMessages } = this.getAllQueuedMessages();\n\t\tif (steeringMessages.length > 0 || followUpMessages.length > 0) {\n\t\t\tthis.pendingMessagesContainer.addChild(new Spacer(1));\n\t\t\tfor (const message of steeringMessages) {\n\t\t\t\tconst text = theme.fg(\"dim\", `Steering: ${message}`);\n\t\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));\n\t\t\t}\n\t\t\tfor (const message of followUpMessages) {\n\t\t\t\tconst text = theme.fg(\"dim\", `Follow-up: ${message}`);\n\t\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));\n\t\t\t}\n\t\t\tconst dequeueHint = this.getAppKeyDisplay(\"app.message.dequeue\");\n\t\t\tconst hintText = theme.fg(\"dim\", `↳ ${dequeueHint} to edit all queued messages`);\n\t\t\tthis.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));\n\t\t}\n\t}\n\n\tprivate restoreQueuedMessagesToEditor(options?: RestoreQueuedMessagesOptions): number {\n\t\tconst { steering, followUp } = this.clearAllQueues();\n\t\tconst allQueued = [...steering, ...followUp];\n\t\tif (allQueued.length === 0) {\n\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\tif (options?.abort) {\n\t\t\t\tthis.agent.abort();\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t\tconst queuedText = allQueued.join(\"\\n\\n\");\n\t\tconst currentText = options?.currentText ?? this.editor.getText();\n\t\tconst combinedText = [queuedText, currentText].filter((t) => t.trim()).join(\"\\n\\n\");\n\t\tthis.editor.setText(combinedText);\n\t\tthis.updatePendingMessagesDisplay();\n\t\tif (options?.abort) {\n\t\t\tthis.agent.abort();\n\t\t}\n\t\treturn allQueued.length;\n\t}\n\n\tprivate queueCompactionMessage(text: string, mode: StreamingBehavior): void {\n\t\tthis.compactionQueuedMessages.push({ text, mode });\n\t\tthis.editor.addToHistory?.(text);\n\t\tthis.editor.setText(\"\");\n\t\tthis.updatePendingMessagesDisplay();\n\t\tthis.showStatus(\"Queued message for after compaction\");\n\t}\n\n\tprivate isExtensionCommand(text: string): boolean {\n\t\tif (!text.startsWith(\"/\")) return false;\n\n\t\tconst extensionRunner = this.session.extensionRunner;\n\n\t\tconst spaceIndex = text.indexOf(\" \");\n\t\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\t\treturn !!extensionRunner.getCommand(commandName);\n\t}\n\n\tprivate async sendQueuedCompactionMessage(message: CompactionQueuedMessage): Promise<void> {\n\t\tif (this.isExtensionCommand(message.text)) {\n\t\t\tawait this.session.prompt(message.text);\n\t\t} else if (message.mode === \"followUp\") {\n\t\t\tawait this.session.followUp(message.text);\n\t\t} else {\n\t\t\tawait this.session.steer(message.text);\n\t\t}\n\t}\n\n\tprivate restoreCompactionQueue(queuedMessages: CompactionQueuedMessage[], error: unknown): void {\n\t\tthis.session.clearQueue();\n\t\tthis.compactionQueuedMessages = queuedMessages;\n\t\tthis.updatePendingMessagesDisplay();\n\t\tthis.showError(\n\t\t\t`Failed to send queued message${queuedMessages.length > 1 ? \"s\" : \"\"}: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`,\n\t\t);\n\t}\n\n\tprivate async flushNewCompactionQueue(queuedMessages: CompactionQueuedMessage[]): Promise<void> {\n\t\tconst firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text));\n\t\tif (firstPromptIndex === -1) {\n\t\t\tfor (const message of queuedMessages) await this.session.prompt(message.text);\n\t\t\treturn;\n\t\t}\n\t\tconst preCommands = queuedMessages.slice(0, firstPromptIndex);\n\t\tconst firstPrompt = queuedMessages[firstPromptIndex];\n\t\tconst rest = queuedMessages.slice(firstPromptIndex + 1);\n\t\tfor (const message of preCommands) await this.session.prompt(message.text);\n\t\tconst promptPromise = this.session.prompt(firstPrompt.text).catch((error) => {\n\t\t\tthis.restoreCompactionQueue(queuedMessages, error);\n\t\t});\n\t\tfor (const message of rest) await this.sendQueuedCompactionMessage(message);\n\t\tthis.updatePendingMessagesDisplay();\n\t\tvoid promptPromise;\n\t}\n\n\tprivate async flushCompactionQueue(options?: FlushCompactionQueueOptions): Promise<void> {\n\t\tif (this.compactionQueuedMessages.length === 0) return;\n\t\tconst queuedMessages = [...this.compactionQueuedMessages];\n\t\tthis.compactionQueuedMessages = [];\n\t\tthis.updatePendingMessagesDisplay();\n\t\ttry {\n\t\t\tif (options?.willRetry) {\n\t\t\t\t// When retry is pending, queue messages for the retry turn.\n\t\t\t\tfor (const message of queuedMessages) await this.sendQueuedCompactionMessage(message);\n\t\t\t\tthis.updatePendingMessagesDisplay();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.flushNewCompactionQueue(queuedMessages);\n\t\t} catch (error) {\n\t\t\tthis.restoreCompactionQueue(queuedMessages, error);\n\t\t}\n\t}\n\n\t/** Move pending bash components from pending area to chat */\n\tprivate flushPendingBashComponents(): void {\n\t\tfor (const component of this.pendingBashComponents) {\n\t\t\tthis.pendingMessagesContainer.removeChild(component);\n\t\t\tthis.chatContainer.addChild(component);\n\t\t}\n\t\tthis.pendingBashComponents = [];\n\t}\n\n\t// =========================================================================\n\t// Selectors\n\t// =========================================================================\n\n\t/**\n\t * Shows a selector component in place of the editor.\n\t * @param create Factory that receives a `done` callback and returns the component and focus target\n\t */\n\tprivate showSelector(create: SelectorFactory): void {\n\t\tconst done = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t};\n\t\tconst { component, focus } = create(done);\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(component);\n\t\tthis.ui.setFocus(focus);\n\t\tthis.ui.requestRender();\n\t}\n\tprivate updateOutputPad(padding: number): void {\n\t\tthis.settingsManager.setOutputPad(padding);\n\t\tthis.outputPad = padding;\n\t\tif (!this.streamingComponent && !this.session.isStreaming) {\n\t\t\tthis.rebuildChatFromMessages();\n\t\t\treturn;\n\t\t}\n\t\tfor (const child of this.chatContainer.children) {\n\t\t\tif (child instanceof AssistantMessageComponent || child instanceof UserMessageComponent) {\n\t\t\t\tchild.setOutputPad(padding);\n\t\t\t}\n\t\t}\n\t\tthis.streamingComponent?.setOutputPad(padding);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate showSettingsSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tlet selector: SettingsSelectorComponent | undefined;\n\t\t\tselector = new SettingsSelectorComponent(\n\t\t\t\t{\n\t\t\t\t\tautoCompact: this.session.autoCompactionEnabled,\n\t\t\t\t\tshowImages: this.settingsManager.getShowImages(),\n\t\t\t\t\timageWidthCells: this.settingsManager.getImageWidthCells(),\n\t\t\t\t\tautoResizeImages: this.settingsManager.getImageAutoResize(),\n\t\t\t\t\tblockImages: this.settingsManager.getBlockImages(),\n\t\t\t\t\tenableSkillCommands: this.settingsManager.getEnableSkillCommands(),\n\t\t\t\t\tenableSubagents: this.session.subagentsEnabled,\n\t\t\t\t\tsteeringMode: this.session.steeringMode,\n\t\t\t\t\tfollowUpMode: this.session.followUpMode,\n\t\t\t\t\ttransport: this.settingsManager.getTransport(),\n\t\t\t\t\tthinkingLevel: this.session.thinkingLevel,\n\t\t\t\t\tavailableThinkingLevels: this.session.getAvailableThinkingLevels(),\n\t\t\t\t\tcurrentTheme: this.settingsManager.getTheme() || \"dark\",\n\t\t\t\t\tavailableThemes: getAvailableThemes(),\n\t\t\t\t\thideThinkingBlock: this.hideThinkingBlock,\n\t\t\t\t\tmermaidRenderingMode: this.settingsManager.getMermaidRenderingMode(),\n\t\t\t\t\tcollapseChangelog: this.settingsManager.getCollapseChangelog(),\n\t\t\t\t\tenableInstallTelemetry: this.settingsManager.getEnableInstallTelemetry(),\n\t\t\t\t\tdoubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),\n\t\t\t\t\ttreeFilterMode: this.settingsManager.getTreeFilterMode(),\n\t\t\t\t\tshowHardwareCursor: this.settingsManager.getShowHardwareCursor(),\n\t\t\t\t\teditorPaddingX: this.settingsManager.getEditorPaddingX(),\n\t\t\t\t\toutputPad: this.settingsManager.getOutputPad(),\n\t\t\t\t\tautocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(),\n\t\t\t\t\tquietStartup: this.settingsManager.getQuietStartup(),\n\t\t\t\t\tclearOnShrink: this.settingsManager.getClearOnShrink(),\n\t\t\t\t\tshowTerminalProgress: this.settingsManager.getShowTerminalProgress(),\n\t\t\t\t\ttuiMode: this.ui.mode,\n\t\t\t\t\tfullscreenExitOutput: this.settingsManager.getFullscreenExitOutput(),\n\t\t\t\t\tfullscreenScrollbar: this.settingsManager.getFullscreenScrollbar(),\n\t\t\t\t\thttpIdleTimeoutMs: this.settingsManager.getHttpIdleTimeoutMs(),\n\t\t\t\t\twarnings: this.settingsManager.getWarnings(),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonAutoCompactChange: (enabled) => {\n\t\t\t\t\t\tthis.session.setAutoCompactionEnabled(enabled);\n\t\t\t\t\t\tthis.footer.setAutoCompactEnabled(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonShowImagesChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowImages(enabled);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof ToolExecutionComponent) {\n\t\t\t\t\t\t\t\tchild.setShowImages(enabled);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonImageWidthCellsChange: (width) => {\n\t\t\t\t\t\tthis.settingsManager.setImageWidthCells(width);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof ToolExecutionComponent) {\n\t\t\t\t\t\t\t\tchild.setImageWidthCells(width);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonAutoResizeImagesChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setImageAutoResize(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonBlockImagesChange: (blocked) => {\n\t\t\t\t\t\tthis.settingsManager.setBlockImages(blocked);\n\t\t\t\t\t},\n\t\t\t\t\tonEnableSkillCommandsChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setEnableSkillCommands(enabled);\n\t\t\t\t\t\tthis.setupAutocompleteProvider();\n\t\t\t\t\t},\n\t\t\t\t\tonEnableSubagentsChange: (enabled) => {\n\t\t\t\t\t\tthis.session.setSubagentsEnabled(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonSteeringModeChange: (mode) => {\n\t\t\t\t\t\tthis.session.setSteeringMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonFollowUpModeChange: (mode) => {\n\t\t\t\t\t\tthis.session.setFollowUpMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonTransportChange: (transport) => {\n\t\t\t\t\t\tthis.settingsManager.setTransport(transport);\n\t\t\t\t\t\tthis.session.agent.transport = transport;\n\t\t\t\t\t},\n\t\t\t\t\tonThinkingLevelChange: (level) => {\n\t\t\t\t\t\tthis.session.setThinkingLevel(level);\n\t\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\t},\n\t\t\t\t\tonThemeChange: (themeName) => {\n\t\t\t\t\t\tconst result = setTheme(themeName, true);\n\t\t\t\t\t\tthis.settingsManager.setTheme(themeName);\n\t\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\t\tthis.showError(`Failed to load theme \"${themeName}\": ${result.error}\\nFell back to dark theme.`);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonThemePreview: (themeName) => {\n\t\t\t\t\t\tconst result = setTheme(themeName, true);\n\t\t\t\t\t\tif (result.success) {\n\t\t\t\t\t\t\tthis.ui.invalidate();\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonHideThinkingBlockChange: (hidden) => {\n\t\t\t\t\t\tthis.hideThinkingBlock = hidden;\n\t\t\t\t\t\tthis.settingsManager.setHideThinkingBlock(hidden);\n\t\t\t\t\t\tfor (const child of this.chatContainer.children) {\n\t\t\t\t\t\t\tif (child instanceof AssistantMessageComponent) {\n\t\t\t\t\t\t\t\tchild.setHideThinkingBlock(hidden);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.chatContainer.clear();\n\t\t\t\t\t\tthis.rebuildChatFromMessages();\n\t\t\t\t\t},\n\t\t\t\t\tonMermaidRenderingModeChange: (mode) => {\n\t\t\t\t\t\tthis.settingsManager.setMermaidRenderingMode(mode);\n\t\t\t\t\t\tthis.chatContainer.invalidate();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t},\n\t\t\t\t\tonCollapseChangelogChange: (collapsed) => {\n\t\t\t\t\t\tthis.settingsManager.setCollapseChangelog(collapsed);\n\t\t\t\t\t},\n\t\t\t\t\tonEnableInstallTelemetryChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setEnableInstallTelemetry(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonQuietStartupChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setQuietStartup(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonDoubleEscapeActionChange: (action) => {\n\t\t\t\t\t\tthis.settingsManager.setDoubleEscapeAction(action);\n\t\t\t\t\t},\n\t\t\t\t\tonTreeFilterModeChange: (mode) => {\n\t\t\t\t\t\tthis.settingsManager.setTreeFilterMode(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonShowHardwareCursorChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowHardwareCursor(enabled);\n\t\t\t\t\t\tthis.ui.setShowHardwareCursor(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonEditorPaddingXChange: (padding) => {\n\t\t\t\t\t\tthis.settingsManager.setEditorPaddingX(padding);\n\t\t\t\t\t\tthis.defaultEditor.setPaddingX(padding);\n\t\t\t\t\t\tif (this.editor !== this.defaultEditor && this.editor.setPaddingX !== undefined) {\n\t\t\t\t\t\t\tthis.editor.setPaddingX(padding);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonOutputPadChange: (padding) => this.updateOutputPad(padding),\n\t\t\t\t\tonAutocompleteMaxVisibleChange: (maxVisible) => {\n\t\t\t\t\t\tthis.settingsManager.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\tthis.defaultEditor.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\tif (this.editor !== this.defaultEditor && this.editor.setAutocompleteMaxVisible !== undefined) {\n\t\t\t\t\t\t\tthis.editor.setAutocompleteMaxVisible(maxVisible);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tonClearOnShrinkChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setClearOnShrink(enabled);\n\t\t\t\t\t\tthis.ui.setClearOnShrink(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonShowTerminalProgressChange: (enabled) => {\n\t\t\t\t\t\tthis.settingsManager.setShowTerminalProgress(enabled);\n\t\t\t\t\t},\n\t\t\t\t\tonTuiModeChange: (mode) => {\n\t\t\t\t\t\tif (!this.switchTuiMode(mode)) {\n\t\t\t\t\t\t\tselector?.getSettingsList().updateValue(\"tui-mode\", this.ui.mode);\n\t\t\t\t\t\t\tthis.showStatus(\"Close active overlays before changing TUI mode\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.settingsManager.setTuiMode(mode);\n\t\t\t\t\t\tthis.showStatus(`TUI mode: ${mode}`);\n\t\t\t\t\t},\n\t\t\t\t\tonFullscreenExitOutputChange: (output) => {\n\t\t\t\t\t\tthis.settingsManager.setFullscreenExitOutput(output);\n\t\t\t\t\t},\n\t\t\t\t\tonFullscreenScrollbarChange: (mode) => {\n\t\t\t\t\t\tthis.settingsManager.setFullscreenScrollbar(mode);\n\t\t\t\t\t\tthis.transcriptScrollView?.setScrollbar(mode);\n\t\t\t\t\t},\n\t\t\t\t\tonHttpIdleTimeoutMsChange: (timeoutMs) => {\n\t\t\t\t\t\tthis.settingsManager.setHttpIdleTimeoutMs(timeoutMs);\n\t\t\t\t\t},\n\t\t\t\t\tonWarningsChange: (warnings) => {\n\t\t\t\t\t\tthis.settingsManager.setWarnings(warnings);\n\t\t\t\t\t},\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getSettingsList() };\n\t\t});\n\t}\n\n\tprivate async handleModelCommand(searchTerm?: string): Promise<void> {\n\t\tif (!searchTerm) {\n\t\t\tthis.showModelSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst model = await this.findExactModelMatch(searchTerm);\n\t\tif (model) {\n\t\t\ttry {\n\t\t\t\tawait this.session.setModel(model);\n\t\t\t\tthis.footer.invalidate();\n\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\tthis.showStatus(`Model: ${model.id}`);\n\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(model);\n\t\t\t} catch (error) {\n\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showModelSelector(searchTerm);\n\t}\n\tprivate async handleCompressionDetectionModelCommand(searchTerm: string): Promise<void> {\n\t\tif ([\"clear\", \"off\", \"none\"].includes(searchTerm.toLowerCase())) {\n\t\t\tthis.session.setCompressionDetectionModel(undefined);\n\t\t\tthis.showStatus(\"Background compression detection disabled\");\n\t\t\treturn;\n\t\t}\n\t\tif (searchTerm) {\n\t\t\tthis.session.modelRegistry.refresh();\n\t\t\tconst model = findExactModelReferenceMatch(searchTerm, this.session.modelRegistry.getAvailable());\n\t\t\tif (model) {\n\t\t\t\tthis.session.setCompressionDetectionModel(`${model.provider}/${model.id}`);\n\t\t\t\tthis.showStatus(`Compression detection model: ${model.provider}/${model.id}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tconst reference = this.settingsManager.getCompressionDetectionModel();\n\t\tconst [provider, ...idParts] = reference?.split(\"/\") ?? [];\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ModelSelectorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.session.modelRegistry.find(provider, idParts.join(\"/\")),\n\t\t\t\tthis.settingsManager,\n\t\t\t\tthis.session.modelRegistry,\n\t\t\t\t[],\n\t\t\t\t(model) => {\n\t\t\t\t\tthis.session.setCompressionDetectionModel(`${model.provider}/${model.id}`);\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showStatus(`Compression detection model: ${model.provider}/${model.id}`);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tsearchTerm || undefined,\n\t\t\t\tfalse,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async findExactModelMatch(searchTerm: string): Promise<Model<any> | undefined> {\n\t\tconst models = await this.getModelCandidates();\n\t\treturn findExactModelReferenceMatch(searchTerm, models);\n\t}\n\n\tprivate async getModelCandidates(): Promise<Model<any>[]> {\n\t\tif (this.session.scopedModels.length > 0) {\n\t\t\treturn this.session.scopedModels.map((scoped) => scoped.model);\n\t\t}\n\n\t\tthis.session.modelRegistry.refresh();\n\t\ttry {\n\t\t\treturn await this.session.modelRegistry.getAvailable();\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\n\t/** Update the footer's available provider count from current model candidates */\n\tprivate async updateAvailableProviderCount(): Promise<void> {\n\t\tconst models = await this.getModelCandidates();\n\t\tconst uniqueProviders = new Set(models.map((m) => m.provider));\n\t\tthis.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);\n\t}\n\n\tprivate async maybeWarnAboutAnthropicSubscriptionAuth(\n\t\tmodel: Model<any> | undefined = this.session.model,\n\t): Promise<void> {\n\t\tif (this.settingsManager.getWarnings().anthropicExtraUsage === false) {\n\t\t\treturn;\n\t\t}\n\t\tif (this.anthropicSubscriptionWarningShown) {\n\t\t\treturn;\n\t\t}\n\t\tif (model?.provider !== \"anthropic\") {\n\t\t\treturn;\n\t\t}\n\n\t\tconst storedCredential = this.session.modelRegistry.authStorage.get(\"anthropic\");\n\t\tif (storedCredential?.type === \"oauth\") {\n\t\t\tthis.anthropicSubscriptionWarningShown = true;\n\t\t\tthis.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst apiKey = await this.session.modelRegistry.getApiKeyForProvider(model.provider);\n\t\t\tif (!isAnthropicSubscriptionAuthKey(apiKey)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.anthropicSubscriptionWarningShown = true;\n\t\t\tthis.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);\n\t\t} catch {\n\t\t\t// Ignore auth lookup failures for warning-only checks.\n\t\t}\n\t}\n\n\tprivate showModelSelector(initialSearchInput?: string): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ModelSelectorComponent(\n\t\t\t\tthis.ui,\n\t\t\t\tthis.session.model,\n\t\t\t\tthis.settingsManager,\n\t\t\t\tthis.session.modelRegistry,\n\t\t\t\tthis.session.scopedModels,\n\t\t\t\tasync (model) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.session.setModel(model);\n\t\t\t\t\t\tthis.footer.invalidate();\n\t\t\t\t\t\tthis.updateEditorBorderColor();\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.showStatus(`Model: ${model.id}`);\n\t\t\t\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(model);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSearchInput,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async showModelsSelector(): Promise<void> {\n\t\t// Get all available models\n\t\tthis.session.modelRegistry.refresh();\n\t\tconst allModels = this.session.modelRegistry.getAvailable();\n\n\t\tif (allModels.length === 0) {\n\t\t\tthis.showStatus(\"No models available\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Check if session has scoped models (from previous session-only changes or CLI --models)\n\t\tconst sessionScopedModels = this.session.scopedModels;\n\t\tconst hasSessionScope = sessionScopedModels.length > 0;\n\n\t\t// Build enabled model IDs from session state or settings\n\t\tlet currentEnabledIds: string[] | null = null;\n\n\t\tif (hasSessionScope) {\n\t\t\t// Use current session's scoped models\n\t\t\tcurrentEnabledIds = sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);\n\t\t} else {\n\t\t\t// Fall back to settings\n\t\t\tconst patterns = this.settingsManager.getEnabledModels();\n\t\t\tif (patterns !== undefined && patterns.length > 0) {\n\t\t\t\tconst scopedModels = await resolveModelScope(patterns, this.session.modelRegistry);\n\t\t\t\tcurrentEnabledIds = scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);\n\t\t\t}\n\t\t}\n\n\t\t// Helper to update session's scoped models (session-only, no persist)\n\t\tconst updateSessionModels = async (enabledIds: string[] | null) => {\n\t\t\tcurrentEnabledIds = enabledIds === null ? null : [...enabledIds];\n\t\t\tif (enabledIds && enabledIds.length > 0 && enabledIds.length < allModels.length) {\n\t\t\t\tconst newScopedModels = await resolveModelScope(enabledIds, this.session.modelRegistry);\n\t\t\t\tthis.session.setScopedModels(\n\t\t\t\t\tnewScopedModels.map((sm) => ({\n\t\t\t\t\t\tmodel: sm.model,\n\t\t\t\t\t\tthinkingLevel: sm.thinkingLevel,\n\t\t\t\t\t})),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// All enabled or none enabled = no filter\n\t\t\t\tthis.session.setScopedModels([]);\n\t\t\t}\n\t\t\tawait this.updateAvailableProviderCount();\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ScopedModelsSelectorComponent(\n\t\t\t\t{\n\t\t\t\t\tallModels,\n\t\t\t\t\tenabledModelIds: currentEnabledIds,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tonChange: async (enabledIds) => {\n\t\t\t\t\t\tawait updateSessionModels(enabledIds);\n\t\t\t\t\t},\n\t\t\t\t\tonPersist: (enabledIds) => {\n\t\t\t\t\t\t// Persist to settings\n\t\t\t\t\t\tconst newPatterns =\n\t\t\t\t\t\t\tenabledIds === null || enabledIds.length === allModels.length\n\t\t\t\t\t\t\t\t? undefined // All enabled = clear filter\n\t\t\t\t\t\t\t\t: enabledIds;\n\t\t\t\t\t\tthis.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined);\n\t\t\t\t\t\tthis.showStatus(\"Model selection saved to settings\");\n\t\t\t\t\t},\n\t\t\t\t\tonCancel: () => {\n\t\t\t\t\t\tdone();\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showUserMessageSelector(): void {\n\t\tconst userMessages = this.session.getUserMessagesForForking();\n\n\t\tif (userMessages.length === 0) {\n\t\t\tthis.showStatus(\"No messages to fork from\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst initialSelectedId = userMessages[userMessages.length - 1]?.entryId;\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new UserMessageSelectorComponent(\n\t\t\t\tuserMessages.map((m) => ({ id: m.entryId, text: m.text })),\n\t\t\t\tasync (entryId) => {\n\t\t\t\t\tdone();\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst result = await this.runtimeHost.fork(entryId);\n\t\t\t\t\t\tif (result.cancelled) {\n\t\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.renderCurrentSessionState();\n\t\t\t\t\t\tthis.editor.setText(result.selectedText ?? \"\");\n\t\t\t\t\t\tthis.showStatus(\"Forked to new session\");\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSelectedId,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector.getMessageList() };\n\t\t});\n\t}\n\n\tprivate async handleCloneCommand(): Promise<void> {\n\t\tconst leafId = this.activeSession.getLeafId();\n\t\tif (!leafId) {\n\t\t\tthis.showStatus(\"Nothing to clone yet\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.fork(leafId, { position: \"at\" });\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.ui.requestRender();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.editor.setText(\"\");\n\t\t\tthis.showStatus(\"Cloned to new session\");\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate async selectBranchSummaryOptions(entryId: string): Promise<NavigateTreeOptions | undefined> {\n\t\tif (this.settingsManager.getBranchSummarySkipPrompt()) return { summarize: false };\n\n\t\twhile (true) {\n\t\t\tconst summaryChoice = await this.showExtensionSelector(\"Summarize branch?\", [\n\t\t\t\t\"No summary\",\n\t\t\t\t\"Summarize\",\n\t\t\t\t\"Summarize with custom prompt\",\n\t\t\t]);\n\t\t\tif (summaryChoice === undefined) {\n\t\t\t\tthis.showTreeSelector(entryId);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tif (summaryChoice !== \"Summarize with custom prompt\") {\n\t\t\t\treturn { summarize: summaryChoice !== \"No summary\" };\n\t\t\t}\n\n\t\t\tconst customInstructions = await this.showExtensionEditor(\"Custom summarization instructions\");\n\t\t\tif (customInstructions !== undefined) return { summarize: true, customInstructions };\n\t\t}\n\t}\n\n\tprivate async navigateToTreeEntry(entryId: string, options: NavigateTreeOptions): Promise<void> {\n\t\tconst originalOnEscape = this.defaultEditor.onEscape;\n\t\tif (options.summarize) {\n\t\t\tthis.defaultEditor.onEscape = () => {\n\t\t\t\tthis.session.abortBranchSummary();\n\t\t\t};\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.branchSummaryLoader = new Loader(\n\t\t\t\tthis.ui,\n\t\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\t`Summarizing branch... (${keyText(\"app.interrupt\")} to cancel)`,\n\t\t\t);\n\t\t\tthis.statusContainer.addChild(this.branchSummaryLoader);\n\t\t\tthis.ui.requestRender();\n\t\t}\n\n\t\ttry {\n\t\t\tconst result = await this.session.navigateTree(entryId, options);\n\t\t\tif (result.aborted) {\n\t\t\t\tthis.showStatus(\"Branch summarization cancelled\");\n\t\t\t\tthis.showTreeSelector(entryId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.showStatus(\"Navigation cancelled\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.chatContainer.clear();\n\t\t\tthis.renderInitialMessages();\n\t\t\tif (result.editorText && !this.editor.getText().trim()) this.editor.setText(result.editorText);\n\t\t\tthis.showStatus(\"Navigated to selected point\");\n\t\t\tvoid this.flushCompactionQueue({ willRetry: false });\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t} finally {\n\t\t\tif (this.branchSummaryLoader) {\n\t\t\t\tthis.branchSummaryLoader.stop();\n\t\t\t\tthis.branchSummaryLoader = undefined;\n\t\t\t\tthis.statusContainer.clear();\n\t\t\t}\n\t\t\tthis.defaultEditor.onEscape = originalOnEscape;\n\t\t}\n\t}\n\n\tprivate async handleTreeSelection(\n\t\tentryId: string,\n\t\tcurrentLeafId: string | null,\n\t\tcloseSelector: () => void,\n\t): Promise<void> {\n\t\tif (entryId === currentLeafId) {\n\t\t\tcloseSelector();\n\t\t\tthis.showStatus(\"Already at this point\");\n\t\t\treturn;\n\t\t}\n\n\t\tcloseSelector();\n\t\tconst options = await this.selectBranchSummaryOptions(entryId);\n\t\tif (options) await this.navigateToTreeEntry(entryId, options);\n\t}\n\n\tprivate showTreeSelector(initialSelectedId?: string): void {\n\t\tconst tree = this.activeSession.getTree();\n\t\tconst realLeafId = this.activeSession.getLeafId();\n\t\tconst initialFilterMode = this.settingsManager.getTreeFilterMode();\n\n\t\tif (tree.length === 0) {\n\t\t\tthis.showStatus(\"No entries in session\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new TreeSelectorComponent(\n\t\t\t\ttree,\n\t\t\t\trealLeafId,\n\t\t\t\tthis.ui.terminal.rows,\n\t\t\t\t(entryId) => this.handleTreeSelection(entryId, realLeafId, done),\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\t(entryId, label) => {\n\t\t\t\t\tthis.activeSession.appendLabelChange(entryId, label);\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tinitialSelectedId,\n\t\t\t\tinitialFilterMode,\n\t\t\t);\n\t\t\tselector.onCopy = async (text) => {\n\t\t\t\tif (!text) {\n\t\t\t\t\tthis.showError(\"Selected entry has no text to copy\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait copyToClipboard(text);\n\t\t\t\t\tthis.showStatus(\"Copied selected message to clipboard\");\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showSessionSelector(): void {\n\t\tthis.showSelector((done) => {\n\t\t\tconst activeSessionReference = this.activeSession.getSessionReference();\n\t\t\tconst isRemoteSession = activeSessionReference?.startsWith(\"remote:\") ?? false;\n\t\t\tconst renameSession = isRemoteSession\n\t\t\t\t? undefined\n\t\t\t\t: async (sessionFilePath: string, nextName: string | undefined) => {\n\t\t\t\t\t\tconst next = (nextName ?? \"\").trim();\n\t\t\t\t\t\tif (!next) return;\n\t\t\t\t\t\tconst mgr = new LocalSessionManager({ cwd: process.cwd() }).openReference(sessionFilePath);\n\t\t\t\t\t\tmgr.appendSessionInfo(next);\n\t\t\t\t\t};\n\t\t\tconst selector = new SessionSelectorComponent(\n\t\t\t\t(onProgress) => this.runtimeHost.listSessions(onProgress),\n\t\t\t\t(onProgress) => this.runtimeHost.listAllSessions(onProgress),\n\n\t\t\t\tasync (sessionPath) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tawait this.handleResumeSession(sessionPath);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tvoid this.shutdown();\n\t\t\t\t},\n\t\t\t\t() => this.ui.requestRender(),\n\t\t\t\t{\n\t\t\t\t\trenameSession,\n\t\t\t\t\tshowRenameHint: !isRemoteSession,\n\t\t\t\t\tkeybindings: this.keybindings,\n\t\t\t\t},\n\n\t\t\t\tactiveSessionReference,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async handleResumeSession(\n\t\tsessionPath: string,\n\t\toptions?: ExtensionSwitchSessionOptions,\n\t): Promise<SessionResumeResult> {\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t}\n\t\tthis.statusContainer.clear();\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.switchSession(sessionPath, {\n\t\t\t\twithSession: options?.withSession,\n\t\t\t});\n\t\t\tif (result.cancelled) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.showStatus(\"Resumed session\");\n\t\t\treturn result;\n\t\t} catch (error: unknown) {\n\t\t\tif (error instanceof MissingSessionCwdError) {\n\t\t\t\tconst selectedCwd = await this.promptForMissingSessionCwd(error);\n\t\t\t\tif (!selectedCwd) {\n\t\t\t\t\tthis.showStatus(\"Resume cancelled\");\n\t\t\t\t\treturn { cancelled: true };\n\t\t\t\t}\n\t\t\t\tconst result = await this.runtimeHost.switchSession(sessionPath, {\n\t\t\t\t\tcwdOverride: selectedCwd,\n\t\t\t\t\twithSession: options?.withSession,\n\t\t\t\t});\n\t\t\t\tif (result.cancelled) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t\tthis.renderCurrentSessionState();\n\t\t\t\tthis.showStatus(\"Resumed session in current cwd\");\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\treturn this.handleFatalRuntimeError(\"Failed to resume session\", error);\n\t\t}\n\t}\n\n\tprivate getLoginProviderOptions(authType?: ProviderAuthenticationType): AuthSelectorProvider[] {\n\t\tconst authStorage = this.session.modelRegistry.authStorage;\n\t\tconst oauthProviders = authStorage.getOAuthProviders();\n\t\tconst oauthProviderIds = new Set(oauthProviders.map((provider) => provider.id));\n\t\tconst options: AuthSelectorProvider[] = oauthProviders.map((provider) => ({\n\t\t\tid: provider.id,\n\t\t\tname: provider.name,\n\t\t\tauthType: \"oauth\",\n\t\t}));\n\n\t\tconst modelProviders = new Set(this.session.modelRegistry.getAll().map((model) => model.provider));\n\t\tfor (const providerId of modelProviders) {\n\t\t\tif (!isApiKeyLoginProvider(providerId, oauthProviderIds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toptions.push({\n\t\t\t\tid: providerId,\n\t\t\t\tname: this.session.modelRegistry.getProviderDisplayName(providerId),\n\t\t\t\tauthType: \"api_key\",\n\t\t\t});\n\t\t}\n\n\t\tconst filteredOptions = authType ? options.filter((option) => option.authType === authType) : options;\n\t\treturn filteredOptions.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate getLogoutProviderOptions(): AuthSelectorProvider[] {\n\t\tconst authStorage = this.session.modelRegistry.authStorage;\n\t\tconst options: AuthSelectorProvider[] = [];\n\n\t\tfor (const providerId of authStorage.list()) {\n\t\t\tconst credential = authStorage.get(providerId);\n\t\t\tif (!credential) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\toptions.push({\n\t\t\t\tid: providerId,\n\t\t\t\tname: this.session.modelRegistry.getProviderDisplayName(providerId),\n\t\t\t\tauthType: credential.type,\n\t\t\t});\n\t\t}\n\n\t\treturn options.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tprivate showLoginAuthTypeSelector(): void {\n\t\tconst subscriptionLabel = \"Use a subscription\";\n\t\tconst apiKeyLabel = \"Use an API key\";\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\t\"Select authentication method:\",\n\t\t\t\t[subscriptionLabel, apiKeyLabel],\n\t\t\t\t(option) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tconst authType = option === subscriptionLabel ? \"oauth\" : \"api_key\";\n\t\t\t\t\tthis.showLoginProviderSelector(authType);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate showLoginProviderSelector(authType: ProviderAuthenticationType): void {\n\t\tconst providerOptions = this.getLoginProviderOptions(authType);\n\t\tif (providerOptions.length === 0) {\n\t\t\tthis.showStatus(\n\t\t\t\tauthType === \"oauth\" ? \"No subscription providers available.\" : \"No API key providers available.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\t\"login\",\n\t\t\t\tthis.session.modelRegistry.authStorage,\n\t\t\t\tproviderOptions,\n\t\t\t\tasync (providerId: string) => {\n\t\t\t\t\tdone();\n\n\t\t\t\t\tconst providerOption = providerOptions.find((provider) => provider.id === providerId);\n\t\t\t\t\tif (!providerOption) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (providerOption.authType === \"oauth\") {\n\t\t\t\t\t\tawait this.showLoginDialog(providerOption.id, providerOption.name);\n\t\t\t\t\t} else if (providerOption.id === BEDROCK_PROVIDER_ID) {\n\t\t\t\t\t\tthis.showBedrockSetupDialog(providerOption.id, providerOption.name);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.showApiKeyLoginDialog(providerOption.id, providerOption.name);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\t\t},\n\t\t\t\t(providerId) => this.session.modelRegistry.getProviderAuthStatus(providerId),\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async showOAuthSelector(mode: AuthenticationOperation): Promise<void> {\n\t\tif (mode === \"login\") {\n\t\t\tthis.showLoginAuthTypeSelector();\n\t\t\treturn;\n\t\t}\n\n\t\tconst providerOptions = this.getLogoutProviderOptions();\n\t\tif (providerOptions.length === 0) {\n\t\t\tthis.showStatus(\n\t\t\t\t\"No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.showSelector((done) => {\n\t\t\tconst selector = new OAuthSelectorComponent(\n\t\t\t\tmode,\n\t\t\t\tthis.session.modelRegistry.authStorage,\n\t\t\t\tproviderOptions,\n\t\t\t\tasync (providerId: string) => {\n\t\t\t\t\tdone();\n\n\t\t\t\t\tconst providerOption = providerOptions.find((provider) => provider.id === providerId);\n\t\t\t\t\tif (!providerOption) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.session.modelRegistry.authStorage.logout(providerOption.id);\n\t\t\t\t\t\tthis.session.modelRegistry.refresh();\n\t\t\t\t\t\tawait this.updateAvailableProviderCount();\n\t\t\t\t\t\tconst message =\n\t\t\t\t\t\t\tproviderOption.authType === \"oauth\"\n\t\t\t\t\t\t\t\t? `Logged out of ${providerOption.name}`\n\t\t\t\t\t\t\t\t: `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;\n\t\t\t\t\t\tthis.showStatus(message);\n\t\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\t\tthis.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t}\n\n\tprivate async selectProviderDefaultModelAfterAuthentication(\n\t\tproviderId: string,\n\t\tactionLabel: string,\n\t): Promise<ProviderAuthenticationModelSelection> {\n\t\tconst availableModels = this.session.modelRegistry.getAvailable();\n\t\tconst providerModels = availableModels.filter((model) => model.provider === providerId);\n\t\tif (!hasDefaultModelProvider(providerId)) {\n\t\t\treturn {\n\t\t\t\tselectionError: `${actionLabel}, but no default model is configured for provider \"${providerId}\". Use /model to select a model.`,\n\t\t\t};\n\t\t}\n\t\tif (providerModels.length === 0) {\n\t\t\treturn {\n\t\t\t\tselectionError: `${actionLabel}, but no models are available for that provider. Use /model to select a model.`,\n\t\t\t};\n\t\t}\n\t\tconst defaultModelId = defaultModelPerProvider[providerId];\n\t\tconst selectedModel = providerModels.find((model) => model.id === defaultModelId);\n\t\tif (!selectedModel) {\n\t\t\treturn {\n\t\t\t\tselectionError: `${actionLabel}, but its default model \"${defaultModelId}\" is not available. Use /model to select a model.`,\n\t\t\t};\n\t\t}\n\t\ttry {\n\t\t\tawait this.session.setModel(selectedModel);\n\t\t\treturn { selectedModel };\n\t\t} catch (error: unknown) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\treturn {\n\t\t\t\tselectionError: `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`,\n\t\t\t};\n\t\t}\n\t}\n\n\tprivate showCompletedProviderAuthentication(\n\t\tactionLabel: string,\n\t\tselection: ProviderAuthenticationModelSelection,\n\t): void {\n\t\tif (selection.selectedModel) {\n\t\t\tthis.showStatus(\n\t\t\t\t`${actionLabel}. Selected ${selection.selectedModel.id}. Credentials saved to ${getAuthPath()}`,\n\t\t\t);\n\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth(selection.selectedModel);\n\t\t\treturn;\n\t\t}\n\t\tthis.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);\n\t\tif (selection.selectionError) {\n\t\t\tthis.showError(selection.selectionError);\n\t\t} else {\n\t\t\tvoid this.maybeWarnAboutAnthropicSubscriptionAuth();\n\t\t}\n\t}\n\n\tprivate async completeProviderAuthentication(\n\t\tproviderId: string,\n\t\tproviderName: string,\n\t\tauthType: ProviderAuthenticationType,\n\t\tpreviousModel: Model<any> | undefined,\n\t): Promise<void> {\n\t\tthis.session.modelRegistry.refresh();\n\t\tconst actionLabel = authType === \"oauth\" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;\n\t\tlet selection: ProviderAuthenticationModelSelection = {};\n\t\tif (isUnknownModel(previousModel)) {\n\t\t\tselection = await this.selectProviderDefaultModelAfterAuthentication(providerId, actionLabel);\n\t\t}\n\n\t\tawait this.updateAvailableProviderCount();\n\t\tthis.footer.invalidate();\n\t\tthis.updateEditorBorderColor();\n\t\tthis.showCompletedProviderAuthentication(actionLabel, selection);\n\t}\n\n\tprivate showBedrockSetupDialog(providerId: string, providerName: string): void {\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui,\n\t\t\tproviderId,\n\t\t\t() => restoreEditor(),\n\t\t\tproviderName,\n\t\t\t\"Amazon Bedrock setup\",\n\t\t);\n\t\tdialog.showInfo([\n\t\t\ttheme.fg(\"text\", \"Amazon Bedrock uses AWS credentials instead of a single API key.\"),\n\t\t\ttheme.fg(\"text\", \"Configure an AWS profile, IAM keys, bearer token, or role-based credentials.\"),\n\t\t\ttheme.fg(\"muted\", \"See:\"),\n\t\t\ttheme.fg(\"accent\", ` ${path.join(getDocsPath(), \"providers.md\")}`),\n\t\t]);\n\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async showApiKeyLoginDialog(providerId: string, providerName: string): Promise<void> {\n\t\tconst previousModel = this.session.model;\n\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui,\n\t\t\tproviderId,\n\t\t\t(_success, _message) => {\n\t\t\t\t// Completion handled below\n\t\t\t},\n\t\t\tproviderName,\n\t\t);\n\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tconst apiKey = (await dialog.showPrompt(\"Enter API key:\")).trim();\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(\"API key cannot be empty.\");\n\t\t\t}\n\n\t\t\tthis.session.modelRegistry.authStorage.set(providerId, { type: \"api_key\", key: apiKey });\n\n\t\t\trestoreEditor();\n\t\t\tawait this.completeProviderAuthentication(providerId, providerName, \"api_key\", previousModel);\n\t\t} catch (error: unknown) {\n\t\t\trestoreEditor();\n\t\t\tconst errorMsg = error instanceof Error ? error.message : String(error);\n\t\t\tif (errorMsg !== \"Login cancelled\") {\n\t\t\t\tthis.showError(`Failed to save API key for ${providerName}: ${errorMsg}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate showOAuthLoginSelect(dialog: LoginDialogComponent, prompt: OAuthSelectPrompt): Promise<string | undefined> {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst restoreDialog = () => {\n\t\t\t\tthis.editorContainer.clear();\n\t\t\t\tthis.editorContainer.addChild(dialog);\n\t\t\t\tthis.ui.setFocus(dialog);\n\t\t\t\tthis.ui.requestRender();\n\t\t\t};\n\t\t\tconst labels = prompt.options.map((option) => option.label);\n\t\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\t\tprompt.message,\n\t\t\t\tlabels,\n\t\t\t\t(optionLabel) => {\n\t\t\t\t\trestoreDialog();\n\t\t\t\t\tresolve(prompt.options.find((option) => option.label === optionLabel)?.id);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\trestoreDialog();\n\t\t\t\t\tresolve(undefined);\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(selector);\n\t\t\tthis.ui.setFocus(selector);\n\t\t\tthis.ui.requestRender();\n\t\t});\n\t}\n\n\tprivate async showLoginDialog(providerId: string, providerName: string): Promise<void> {\n\t\tconst providerInfo = this.session.modelRegistry.authStorage\n\t\t\t.getOAuthProviders()\n\t\t\t.find((provider) => provider.id === providerId);\n\t\tconst previousModel = this.session.model;\n\n\t\t// Providers that use callback servers (can paste redirect URL)\n\t\tconst usesCallbackServer = providerInfo?.usesCallbackServer ?? false;\n\n\t\t// Create login dialog component\n\t\tconst dialog = new LoginDialogComponent(\n\t\t\tthis.ui,\n\t\t\tproviderId,\n\t\t\t(_success, _message) => {\n\t\t\t\t// Completion handled below\n\t\t\t},\n\t\t\tproviderName,\n\t\t);\n\n\t\t// Show dialog in editor container\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(dialog);\n\t\tthis.ui.setFocus(dialog);\n\t\tthis.ui.requestRender();\n\n\t\t// Promise for manual code input (racing with callback server)\n\t\tlet manualCodeResolve: ((code: string) => void) | undefined;\n\t\tlet manualCodeReject: ((err: Error) => void) | undefined;\n\t\tconst manualCodePromise = new Promise<string>((resolve, reject) => {\n\t\t\tmanualCodeResolve = resolve;\n\t\t\tmanualCodeReject = reject;\n\t\t});\n\n\t\t// Restore editor helper\n\t\tconst restoreEditor = () => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tawait this.session.modelRegistry.authStorage.login(providerId as OAuthProviderId, {\n\t\t\t\tonAuth: (info: OAuthAuthInfo) => {\n\t\t\t\t\tdialog.showAuth(info.url, info.instructions);\n\n\t\t\t\t\tif (usesCallbackServer) {\n\t\t\t\t\t\t// Show input for manual paste, racing with callback\n\t\t\t\t\t\tdialog\n\t\t\t\t\t\t\t.showManualInput(\"Paste redirect URL below, or complete login in browser:\")\n\t\t\t\t\t\t\t.then((value) => {\n\t\t\t\t\t\t\t\tif (value && manualCodeResolve) {\n\t\t\t\t\t\t\t\t\tmanualCodeResolve(value);\n\t\t\t\t\t\t\t\t\tmanualCodeResolve = undefined;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\t\t\tif (manualCodeReject) {\n\t\t\t\t\t\t\t\t\tmanualCodeReject(new Error(\"Login cancelled\"));\n\t\t\t\t\t\t\t\t\tmanualCodeReject = undefined;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\t// For Anthropic: onPrompt is called immediately after\n\t\t\t\t},\n\n\t\t\t\tonDeviceCode: (info) => {\n\t\t\t\t\tdialog.showDeviceCode(info);\n\t\t\t\t\tdialog.showWaiting(\"Waiting for authentication...\");\n\t\t\t\t},\n\n\t\t\t\tonPrompt: async (prompt: OAuthPrompt) => {\n\t\t\t\t\treturn dialog.showPrompt(prompt.message, prompt.placeholder);\n\t\t\t\t},\n\n\t\t\t\tonProgress: (message: string) => {\n\t\t\t\t\tdialog.showProgress(message);\n\t\t\t\t},\n\n\t\t\t\tonSelect: (prompt: OAuthSelectPrompt) => this.showOAuthLoginSelect(dialog, prompt),\n\n\t\t\t\tonManualCodeInput: () => manualCodePromise,\n\n\t\t\t\tsignal: dialog.signal,\n\t\t\t});\n\n\t\t\t// Success\n\t\t\trestoreEditor();\n\t\t\tawait this.completeProviderAuthentication(providerId, providerName, \"oauth\", previousModel);\n\t\t} catch (error: unknown) {\n\t\t\trestoreEditor();\n\t\t\tconst errorMsg = error instanceof Error ? error.message : String(error);\n\t\t\tif (errorMsg !== \"Login cancelled\") {\n\t\t\t\tthis.showError(`Failed to login to ${providerName}: ${errorMsg}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Command handlers\n\tprivate async handleCdCommand(text: string): Promise<void> {\n\t\tif (!this.session.isIdle || this.session.isBashRunning) {\n\t\t\tthis.showWarning(\"Wait for the current operation to finish before changing directories.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.session.supportsDirectoryChange()) {\n\t\t\tthis.showWarning(\"Changing directories is not supported with the active workspace backend.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst argument = this.getPathCommandArgument(text, \"/cd\");\n\t\tif (text !== \"/cd\" && !argument) {\n\t\t\tthis.showError(\"Usage: /cd [directory]\");\n\t\t\treturn;\n\t\t}\n\t\tconst requestedPath = argument ?? os.homedir();\n\t\tconst targetDirectory = resolveDirectoryPath(requestedPath, this.activeSession.getCwd());\n\t\tif (!targetDirectory) {\n\t\t\tthis.showError(`Directory not found: ${requestedPath}`);\n\t\t\treturn;\n\t\t}\n\n\t\tif (targetDirectory === resolveDirectoryPath(this.activeSession.getCwd(), this.activeSession.getCwd())) {\n\t\t\tthis.showStatus(`Working directory: ${targetDirectory}`);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.changeDirectory(targetDirectory);\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.showStatus(\"Directory change cancelled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.showStatus(`Working directory: ${targetDirectory}`);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.showError(\n\t\t\t\tthis.activeSession.getCwd() === targetDirectory\n\t\t\t\t\t? `Working directory changed, but the runtime failed to rebind: ${message}`\n\t\t\t\t\t: `Failed to change directory: ${message}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async handleProfileCommand(text: string): Promise<void> {\n\t\tconst match = text.match(/^\\/profile\\s+(create|use)\\s+(\\S+)$/);\n\t\tif (!match) {\n\t\t\tthis.showError(\"Usage: /profile create <name> | /profile use <name>\");\n\t\t\treturn;\n\t\t}\n\t\tconst action = match[1];\n\t\tconst name = match[2]!;\n\t\tif (!isValidModelProfileName(name)) {\n\t\t\tthis.showError(\"Profile names must be 1-64 letters, numbers, dots, underscores, or hyphens.\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (action === \"create\") {\n\t\t\tconst currentScope = this.session.scopedModels;\n\t\t\tconst patterns =\n\t\t\t\tcurrentScope.length > 0\n\t\t\t\t\t? currentScope.map(\n\t\t\t\t\t\t\t(scoped) =>\n\t\t\t\t\t\t\t\t`${scoped.model.provider}/${scoped.model.id}${scoped.thinkingLevel ? `:${scoped.thinkingLevel}` : \"\"}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t: this.session.modelRegistry.getAvailable().map((model) => `${model.provider}/${model.id}`);\n\t\t\tif (patterns.length === 0) {\n\t\t\t\tthis.showError(\"Cannot create a profile because no models are available.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst exists = Object.hasOwn(this.settingsManager.getModelProfiles(), name);\n\t\t\tthis.settingsManager.setModelProfile(name, patterns);\n\t\t\tthis.showStatus(`${exists ? \"Updated\" : \"Created\"} profile \"${name}\" with ${patterns.length} models`);\n\t\t\treturn;\n\t\t}\n\n\t\tconst profiles = this.settingsManager.getModelProfiles();\n\t\tif (!Object.hasOwn(profiles, name)) {\n\t\t\tthis.showError(`Unknown profile: ${name}`);\n\t\t\treturn;\n\t\t}\n\t\tconst patterns = profiles[name]!;\n\t\tconst scopedModels = await resolveModelScope(patterns, this.session.modelRegistry);\n\t\tif (scopedModels.length === 0) {\n\t\t\tthis.showError(`Profile \"${name}\" has no available models`);\n\t\t\treturn;\n\t\t}\n\t\tthis.session.setScopedModels(scopedModels);\n\t\tthis.settingsManager.setEnabledModels([...patterns]);\n\t\tawait this.updateAvailableProviderCount();\n\t\tthis.ui.requestRender();\n\t\tthis.showStatus(`Using profile \"${name}\" with ${scopedModels.length} models`);\n\t}\n\n\t// =========================================================================\n\n\tprivate async handleReloadCommand(): Promise<void> {\n\t\tif (this.session.isStreaming) {\n\t\t\tthis.showWarning(\"Wait for the current response to finish before reloading.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.session.isCompacting) {\n\t\t\tthis.showWarning(\"Wait for compaction to finish before reloading.\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.resetExtensionUI();\n\n\t\tconst reloadBox = new Container();\n\t\tconst borderColor = (s: string) => theme.fg(\"border\", s);\n\t\treloadBox.addChild(new DynamicBorder(borderColor));\n\t\treloadBox.addChild(new Spacer(1));\n\t\treloadBox.addChild(\n\t\t\tnew Text(\n\t\t\t\ttheme.fg(\"muted\", \"Reloading keybindings, hooks, extensions, skills, rules, prompts, themes...\"),\n\t\t\t\t1,\n\t\t\t\t0,\n\t\t\t),\n\t\t);\n\t\treloadBox.addChild(new Spacer(1));\n\t\treloadBox.addChild(new DynamicBorder(borderColor));\n\n\t\tconst previousEditor = this.editor;\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(reloadBox);\n\t\tthis.ui.setFocus(reloadBox);\n\t\tthis.ui.requestRender(true);\n\t\tawait new Promise((resolve) => process.nextTick(resolve));\n\n\t\tconst dismissReloadBox = (editor: Component) => {\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(editor);\n\t\t\tthis.ui.setFocus(editor);\n\t\t\tthis.updateToolBackendStatus();\n\t\t\tthis.ui.requestRender();\n\t\t};\n\n\t\ttry {\n\t\t\tawait this.session.reload();\n\t\t\tthis.keybindings.reload();\n\t\t\tconst activeHeader = this.customHeader ?? this.builtInHeader;\n\t\t\tif (isExpandable(activeHeader)) {\n\t\t\t\tactiveHeader.setExpanded(this.toolOutputExpanded);\n\t\t\t}\n\t\t\tsetRegisteredThemes(this.session.resourceLoader.getThemes().themes);\n\t\t\tthis.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();\n\t\t\tthis.outputPad = this.settingsManager.getOutputPad();\n\t\t\tconst themeName = this.settingsManager.getTheme();\n\t\t\tconst themeResult = themeName ? setTheme(themeName, true) : { success: true };\n\t\t\tif (!themeResult.success) {\n\t\t\t\tthis.showError(`Failed to load theme \"${themeName}\": ${themeResult.error}\\nFell back to dark theme.`);\n\t\t\t}\n\t\t\tconst editorPaddingX = this.settingsManager.getEditorPaddingX();\n\t\t\tconst autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();\n\t\t\tthis.defaultEditor.setPaddingX(editorPaddingX);\n\t\t\tthis.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);\n\t\t\tif (this.editor !== this.defaultEditor) {\n\t\t\t\tthis.editor.setPaddingX?.(editorPaddingX);\n\t\t\t\tthis.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);\n\t\t\t}\n\t\t\tthis.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());\n\t\t\tthis.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());\n\t\t\tthis.setupAutocompleteProvider();\n\t\t\tconst runner = this.session.extensionRunner;\n\t\t\tthis.setupExtensionShortcuts(runner);\n\t\t\tthis.rebuildChatFromMessages();\n\t\t\tdismissReloadBox(this.editor as Component);\n\t\t\tthis.showLoadedResources({\n\t\t\t\tforce: false,\n\t\t\t\tshowDiagnosticsWhenQuiet: true,\n\t\t\t});\n\t\t\tthis.showRuntimeDiagnostics();\n\t\t\tconst modelsJsonError = this.session.modelRegistry.getError();\n\t\t\tif (modelsJsonError) {\n\t\t\t\tthis.showError(`models.json error: ${modelsJsonError}`);\n\t\t\t}\n\t\t\tthis.showStatus(\"Reloaded keybindings, hooks, extensions, skills, rules, prompts, themes\");\n\t\t} catch (error) {\n\t\t\tdismissReloadBox(previousEditor as Component);\n\t\t\tthis.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\n\tprivate async handleExportCommand(text: string): Promise<void> {\n\t\tconst outputPath = this.getPathCommandArgument(text, \"/export\");\n\n\t\ttry {\n\t\t\tif (outputPath?.endsWith(\".jsonl\")) {\n\t\t\t\tconst filePath = this.session.exportToJsonl(outputPath);\n\t\t\t\tthis.showStatus(`Session exported to: ${filePath}`);\n\t\t\t} else {\n\t\t\t\tconst filePath = await this.session.exportToHtml(outputPath);\n\t\t\t\tthis.showStatus(`Session exported to: ${filePath}`);\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(`Failed to export session: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\t}\n\n\tprivate getPathCommandArgument(text: string, command: SessionPathCommand): string | undefined {\n\t\tif (text === command) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!text.startsWith(`${command} `)) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst argsString = text.slice(command.length + 1).trimStart();\n\t\tif (!argsString) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst firstChar = argsString[0];\n\t\tif (firstChar === '\"' || firstChar === \"'\") {\n\t\t\tconst closingQuoteIndex = argsString.indexOf(firstChar, 1);\n\t\t\tif (closingQuoteIndex < 0) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn argsString.slice(1, closingQuoteIndex);\n\t\t}\n\n\t\tconst firstWhitespaceIndex = argsString.search(/\\s/);\n\t\tif (firstWhitespaceIndex < 0) {\n\t\t\treturn argsString;\n\t\t}\n\t\treturn argsString.slice(0, firstWhitespaceIndex);\n\t}\n\n\tprivate async handleImportCommand(text: string): Promise<void> {\n\t\tconst inputPath = this.getPathCommandArgument(text, \"/import\");\n\t\tif (!inputPath) {\n\t\t\tthis.showError(\"Usage: /import <path.jsonl>\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst confirmed = await this.showExtensionConfirm(\"Import session\", `Replace current session with ${inputPath}?`);\n\t\tif (!confirmed) {\n\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tif (this.loadingAnimation) {\n\t\t\t\tthis.loadingAnimation.stop();\n\t\t\t\tthis.loadingAnimation = undefined;\n\t\t\t}\n\t\t\tthis.statusContainer.clear();\n\t\t\tconst result = await this.runtimeHost.importFromJsonl(inputPath);\n\t\t\tif (result.cancelled) {\n\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.showStatus(`Session imported from: ${inputPath}`);\n\t\t} catch (error: unknown) {\n\t\t\tif (error instanceof MissingSessionCwdError) {\n\t\t\t\tconst selectedCwd = await this.promptForMissingSessionCwd(error);\n\t\t\t\tif (!selectedCwd) {\n\t\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst result = await this.runtimeHost.importFromJsonl(inputPath, selectedCwd);\n\t\t\t\tif (result.cancelled) {\n\t\t\t\t\tthis.showStatus(\"Import cancelled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.renderCurrentSessionState();\n\t\t\t\tthis.showStatus(`Session imported from: ${inputPath}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (error instanceof SessionImportFileNotFoundError) {\n\t\t\t\tthis.showError(`Failed to import session: ${error.message}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.handleFatalRuntimeError(\"Failed to import session\", error);\n\t\t}\n\t}\n\n\tprivate async handleShareCommand(): Promise<void> {\n\t\t// Check if gh is available and logged in\n\t\ttry {\n\t\t\tconst authResult = spawnSync(\"gh\", [\"auth\", \"status\"], { encoding: \"utf-8\" });\n\t\t\tif (authResult.status !== 0) {\n\t\t\t\tthis.showError(\"GitHub CLI is not logged in. Run 'gh auth login' first.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.showError(\"GitHub CLI (gh) is not installed. Install it from https://cli.github.com/\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Export to a temp file\n\t\tconst tmpFile = path.join(os.tmpdir(), \"session.html\");\n\t\ttry {\n\t\t\tawait this.session.exportToHtml(tmpFile);\n\t\t} catch (error: unknown) {\n\t\t\tthis.showError(`Failed to export session: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Show cancellable loader, replacing the editor\n\t\tconst loader = new BorderedLoader(this.ui, theme, \"Creating gist...\");\n\t\tthis.editorContainer.clear();\n\t\tthis.editorContainer.addChild(loader);\n\t\tthis.ui.setFocus(loader);\n\t\tthis.ui.requestRender();\n\n\t\tconst restoreEditor = () => {\n\t\t\tloader.dispose();\n\t\t\tthis.editorContainer.clear();\n\t\t\tthis.editorContainer.addChild(this.editor);\n\t\t\tthis.ui.setFocus(this.editor);\n\t\t\ttry {\n\t\t\t\tfs.unlinkSync(tmpFile);\n\t\t\t} catch {\n\t\t\t\t// Ignore cleanup errors\n\t\t\t}\n\t\t};\n\n\t\t// Create a secret gist asynchronously\n\t\tlet proc: ReturnType<typeof spawn> | null = null;\n\n\t\tloader.onAbort = () => {\n\t\t\tproc?.kill();\n\t\t\trestoreEditor();\n\t\t\tthis.showStatus(\"Share cancelled\");\n\t\t};\n\n\t\ttry {\n\t\t\tconst result = await new Promise<{ stdout: string; stderr: string; code: number | null }>((resolve) => {\n\t\t\t\tproc = spawn(\"gh\", [\"gist\", \"create\", \"--public=false\", tmpFile]);\n\t\t\t\tlet stdout = \"\";\n\t\t\t\tlet stderr = \"\";\n\t\t\t\tproc.stdout?.on(\"data\", (data) => {\n\t\t\t\t\tstdout += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.stderr?.on(\"data\", (data) => {\n\t\t\t\t\tstderr += data.toString();\n\t\t\t\t});\n\t\t\t\tproc.on(\"close\", (code) => resolve({ stdout, stderr, code }));\n\t\t\t});\n\n\t\t\tif (loader.signal.aborted) return;\n\n\t\t\trestoreEditor();\n\n\t\t\tif (result.code !== 0) {\n\t\t\t\tconst errorMsg = result.stderr?.trim() || \"Unknown error\";\n\t\t\t\tthis.showError(`Failed to create gist: ${errorMsg}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Extract gist ID from the URL returned by gh\n\t\t\t// gh returns something like: https://gist.github.com/username/GIST_ID\n\t\t\tconst gistUrl = result.stdout?.trim();\n\t\t\tconst gistId = gistUrl?.split(\"/\").pop();\n\t\t\tif (!gistId) {\n\t\t\t\tthis.showError(\"Failed to parse gist ID from gh output\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Create the preview URL\n\t\t\tconst previewUrl = getShareViewerUrl(gistId);\n\t\t\tthis.showStatus(`Share URL: ${previewUrl}\\nGist: ${gistUrl}`);\n\t\t} catch (error: unknown) {\n\t\t\tif (!loader.signal.aborted) {\n\t\t\t\trestoreEditor();\n\t\t\t\tthis.showError(`Failed to create gist: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async handleCopyCommand(options: CopyCommandOptions = {}): Promise<void> {\n\t\tconst text = this.session.getLastAssistantText();\n\t\tif (!text) {\n\t\t\tthis.showError(\"No agent messages to copy yet.\");\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tawait copyToClipboard(text);\n\t\t\tif (options.flashConfirmation && this.ui instanceof TuiAltScreen) {\n\t\t\t\tthis.ui.flash(\"Copied!\");\n\t\t\t} else {\n\t\t\t\tthis.showStatus(\"Copied last agent message to clipboard\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.showError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\tprivate handleHooksCommand(text: string): void {\n\t\tconst action = text.slice(\"/hooks\".length).trim();\n\t\tif (action !== \"enable\" && action !== \"disable\") {\n\t\t\tthis.showWarning(\"Usage: /hooks <enable|disable>\");\n\t\t\treturn;\n\t\t}\n\t\tconst enabled = action === \"enable\";\n\t\tthis.session.setHooksEnabled(enabled);\n\t\tthis.showStatus(`Hooks ${enabled ? \"enabled\" : \"disabled\"} for this session`);\n\t}\n\n\tprivate handleNameCommand(text: string): void {\n\t\tconst name = text.replace(/^\\/name\\s*/, \"\").trim();\n\t\tif (!name) {\n\t\t\tconst currentName = this.activeSession.getSessionName();\n\t\t\tif (currentName) {\n\t\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", `Session name: ${currentName}`), 1, 0));\n\t\t\t} else {\n\t\t\t\tthis.showWarning(\"Usage: /name <name>\");\n\t\t\t}\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.session.setSessionName(name);\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(theme.fg(\"dim\", `Session name set: ${name}`), 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate refreshUiAfterBackendChange(): void {\n\t\tthis.rebuildChatFromMessages();\n\t\tthis.showRuntimeDiagnostics();\n\t\tthis.setupAutocompleteProvider();\n\t\tthis.showLoadedResources({ force: true, showDiagnosticsWhenQuiet: true });\n\t}\n\tprivate createLimaSandboxService(): LimaSandboxService {\n\t\treturn new LimaSandboxService({\n\t\t\tsettingsManager: this.settingsManager,\n\t\t\tmanagedInstances: this.managedLimaInstances,\n\t\t});\n\t}\n\n\tprivate async disposeRuntimeResources(): Promise<Error[]> {\n\t\tconst limaSandboxService = this.createLimaSandboxService();\n\t\tconst errors: Error[] = [];\n\t\ttry {\n\t\t\tawait this.runtimeHost.dispose();\n\t\t} catch (error) {\n\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t\ttry {\n\t\t\tawait limaSandboxService.stopManagedInstances();\n\t\t} catch (error) {\n\t\t\terrors.push(error instanceof Error ? error : new Error(String(error)));\n\t\t}\n\t\treturn errors;\n\t}\n\n\tprivate async restoreCurrentSessionSandbox(): Promise<void> {\n\t\tthis.activeSandboxContainerId = undefined;\n\t\tthis.activeSandboxBackendConnected = false;\n\t\tconst state = this.sessionSandboxStates.get(getSessionSandboxKey(this.activeSession));\n\t\tif (!state) return;\n\t\tthis.activeSandboxContainerId = state.containerId;\n\t\ttry {\n\t\t\tawait this.session.activateSandboxDaemon({\n\t\t\t\turl: state.url,\n\t\t\t\ttoken: state.token,\n\t\t\t\texpectedCwd: state.expectedCwd,\n\t\t\t});\n\t\t\tthis.activeSandboxBackendConnected = true;\n\t\t} catch (error) {\n\t\t\tif (!state.containerId) this.sessionSandboxStates.delete(getSessionSandboxKey(this.activeSession));\n\t\t\tthis.showWarning(\n\t\t\t\t`Could not restore this session's sandbox: ${redactSecrets(error instanceof Error ? error.message : String(error))}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate hasSandboxActivationConflict(sessionKey: string): boolean {\n\t\treturn (\n\t\t\tthis.activeSandboxBackendConnected ||\n\t\t\tthis.activeSandboxContainerId !== undefined ||\n\t\t\t[...(this.managedLimaInstances?.values() ?? [])].some(\n\t\t\t\t(instance) => instance.ownerId === this.activeSession.getSessionId(),\n\t\t\t) ||\n\t\t\tthis.sessionSandboxStates.has(sessionKey)\n\t\t);\n\t}\n\n\tprivate ensureSandboxCanActivate(sessionKey: string): boolean {\n\t\tif (!this.hasSandboxActivationConflict(sessionKey)) return true;\n\t\tthis.showWarning(\n\t\t\t\"A sandbox backend is already active or awaiting cleanup. Run /sandbox stop before starting or attaching another.\",\n\t\t);\n\t\treturn false;\n\t}\n\n\tprivate async clearSandboxBackend(sessionKey: string): Promise<void> {\n\t\tif (!this.activeSandboxBackendConnected && this.sessionSandboxStates.has(sessionKey)) {\n\t\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.showStatus(\"Stale sandbox state cleared\");\n\t\t\treturn;\n\t\t}\n\t\tawait this.session.clearRemoteSandbox();\n\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\tthis.activeSandboxContainerId = undefined;\n\t\tthis.activeSandboxBackendConnected = false;\n\t\tthis.refreshUiAfterBackendChange();\n\t\tthis.updateToolBackendStatus();\n\t\tthis.showStatus(\"Sandbox backend cleared\");\n\t}\n\n\tprivate async attachSandboxBackend(url: string, service: SandboxService, sessionKey: string): Promise<void> {\n\t\tconst currentBackend = this.session.getToolBackendInfo();\n\t\tconst expectedCwd =\n\t\t\tcurrentBackend.type === \"remote\" && !currentBackend.configured\n\t\t\t\t? currentBackend.cwd\n\t\t\t\t: service.resolveConfig().workspaceMountPath;\n\t\tconst token = process.env.GRIP_REMOTE_TOKEN ?? \"\";\n\t\tconst info = await this.session.activateSandboxDaemon({ url, token, expectedCwd });\n\t\tthis.activeSandboxContainerId = undefined;\n\t\tthis.activeSandboxBackendConnected = true;\n\t\tthis.sessionSandboxStates.set(sessionKey, { type: \"daemon\", url, token, expectedCwd });\n\t\tthis.refreshUiAfterBackendChange();\n\t\tthis.updateToolBackendStatus();\n\t\tthis.showStatus([`Sandbox attached: ${redactSecrets(url)}`, this.formatToolBackendStatus(info)].join(\"\\n\"));\n\t}\n\n\tprivate showSandboxStartupLoader(): Loader | undefined {\n\t\tif (!this.statusContainer || !this.ui) return undefined;\n\t\tconst loader = new Loader(\n\t\t\tthis.ui,\n\t\t\t(spinner) => theme.fg(\"accent\", spinner),\n\t\t\t(text) => theme.fg(\"muted\", text),\n\t\t\t\"Starting sandbox...\",\n\t\t);\n\t\tthis.statusContainer.clear();\n\t\tthis.statusContainer.addChild(loader);\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(true);\n\t\tthis.ui.requestRender();\n\t\treturn loader;\n\t}\n\n\tprivate hideSandboxStartupLoader(loader: Loader | undefined): void {\n\t\tloader?.stop();\n\t\tif (!loader) return;\n\t\tthis.statusContainer.clear();\n\t\tif (this.settingsManager.getShowTerminalProgress()) this.ui.terminal.setProgress(false);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async activateStartedSandbox(\n\t\tservice: SandboxService,\n\t\tworkspaceRoot: string,\n\t\tresult: SandboxStartResult,\n\t): Promise<ToolBackendInfo> {\n\t\tlet info: ToolBackendInfo | undefined;\n\t\tlet lastActivationError: unknown;\n\t\tfor (let attempt = 0; attempt < 10; attempt++) {\n\t\t\ttry {\n\t\t\t\tinfo = await this.session.activateSandboxDaemon({\n\t\t\t\t\turl: result.daemonUrl,\n\t\t\t\t\ttoken: result.token,\n\t\t\t\t\texpectedCwd: result.workspaceMountPath,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t} catch (error) {\n\t\t\t\tlastActivationError = error;\n\t\t\t\tif (attempt < 9) await new Promise((resolve) => setTimeout(resolve, 500));\n\t\t\t}\n\t\t}\n\t\tif (info) return info;\n\n\t\tconst activationError =\n\t\t\tlastActivationError instanceof Error ? lastActivationError : new Error(String(lastActivationError));\n\t\tif (result.daemonUrl.startsWith(\"grip+ws:\")) {\n\t\t\t// A shared-VM attach owns only its channel, never the VM or guest daemon.\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\tthrow activationError;\n\t\t}\n\t\ttry {\n\t\t\tawait service.stop({ workspaceRoot, currentContainerId: result.containerId });\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t} catch (cleanupError) {\n\t\t\tthis.activeSandboxContainerId = result.containerId;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\tconst cleanupMessage = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);\n\t\t\tthrow new Error(`${activationError.message}; failed to stop started sandbox: ${cleanupMessage}`);\n\t\t}\n\t\tthrow activationError;\n\t}\n\n\tprivate async startSandboxBackend(\n\t\tcommand: SandboxStartUserCommand,\n\t\tservice: SandboxService,\n\t\tworkspaceRoot: string,\n\t\tsessionKey: string,\n\t\tupdatingAttached = false,\n\t): Promise<void> {\n\t\tconst loader = this.showSandboxStartupLoader();\n\t\ttry {\n\t\t\tconst result = await service.start({\n\t\t\t\tworkspaceRoot,\n\t\t\t\t...(command.name ? { name: command.name } : {}),\n\t\t\t\t...(command.template ? { limaTemplate: command.template } : {}),\n\t\t\t\t...(command.update ? { update: true } : {}),\n\t\t\t\tsessionId: this.activeSession.getSessionId(),\n\t\t\t});\n\t\t\tif (updatingAttached) {\n\t\t\t\tawait this.session.abort();\n\t\t\t\tawait this.session.clearRemoteSandbox();\n\t\t\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\t}\n\t\t\tthis.activeSandboxContainerId = result.containerId;\n\t\t\tconst info = await this.activateStartedSandbox(service, workspaceRoot, result);\n\t\t\tthis.activeSandboxBackendConnected = true;\n\t\t\tthis.sessionSandboxStates.set(sessionKey, {\n\t\t\t\ttype: \"daemon\",\n\t\t\t\turl: result.daemonUrl,\n\t\t\t\ttoken: result.token,\n\t\t\t\texpectedCwd: result.workspaceMountPath,\n\t\t\t\tcontainerId: result.containerId,\n\t\t\t});\n\t\t\tthis.refreshUiAfterBackendChange();\n\t\t\tthis.updateToolBackendStatus();\n\t\t\tthis.showStatus(\n\t\t\t\t[\n\t\t\t\t\tcommand.update\n\t\t\t\t\t\t? formatSandboxStartResult(result).replace(\"Sandbox started:\", \"Sandbox updated:\")\n\t\t\t\t\t\t: formatSandboxStartResult(result),\n\t\t\t\t\tthis.formatToolBackendStatus(info),\n\t\t\t\t].join(\"\\n\"),\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.hideSandboxStartupLoader(loader);\n\t\t}\n\t}\n\n\tprivate sandboxContainerIdsMatch(left: string, right: string): boolean {\n\t\treturn left === right || left.startsWith(right) || right.startsWith(left);\n\t}\n\n\tprivate removeSandboxStatesForContainer(containerId: string): void {\n\t\tfor (const [key, state] of this.sessionSandboxStates) {\n\t\t\tif (\n\t\t\t\tstate.type === \"daemon\" &&\n\t\t\t\tstate.containerId &&\n\t\t\t\tthis.sandboxContainerIdsMatch(containerId, state.containerId)\n\t\t\t) {\n\t\t\t\tthis.sessionSandboxStates.delete(key);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async reconcileStoppedSandbox(result: SandboxStopResult, sessionKey: string): Promise<void> {\n\t\tif (result.status === \"not-found\") {\n\t\t\tif (!this.activeSandboxContainerId) return;\n\t\t\tif (this.activeSandboxBackendConnected) {\n\t\t\t\tawait this.session.clearRemoteSandbox();\n\t\t\t\tthis.refreshUiAfterBackendChange();\n\t\t\t\tthis.updateToolBackendStatus();\n\t\t\t}\n\t\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.removeSandboxStatesForContainer(result.container.id);\n\t\tconst activeContainerId = this.activeSandboxContainerId;\n\t\tconst stoppedActiveSandbox =\n\t\t\tactiveContainerId !== undefined && this.sandboxContainerIdsMatch(result.container.id, activeContainerId);\n\t\tif (stoppedActiveSandbox && this.activeSandboxBackendConnected) {\n\t\t\tawait this.session.clearRemoteSandbox();\n\t\t\tthis.refreshUiAfterBackendChange();\n\t\t\tthis.updateToolBackendStatus();\n\t\t}\n\t\tif (stoppedActiveSandbox) {\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t}\n\t}\n\n\tprivate async stopSandboxBackend(\n\t\ttarget: string | undefined,\n\t\tservice: SandboxService,\n\t\tworkspaceRoot: string,\n\t\tsessionKey: string,\n\t): Promise<void> {\n\t\tif (this.activeSandboxBackendConnected && !this.activeSandboxContainerId) {\n\t\t\tawait this.session.clearRemoteSandbox();\n\t\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\tthis.refreshUiAfterBackendChange();\n\t\t\tthis.updateToolBackendStatus();\n\t\t\tthis.showStatus(\"Sandbox detached\");\n\t\t\treturn;\n\t\t}\n\t\tconst attached = this.sessionSandboxStates.get(sessionKey);\n\t\tif (\n\t\t\tattached?.url?.startsWith(\"grip+ws:\") &&\n\t\t\tattached.containerId === this.activeSandboxContainerId &&\n\t\t\t(!target || target === attached.containerId)\n\t\t) {\n\t\t\tif (this.activeSandboxBackendConnected) await this.session.clearRemoteSandbox();\n\t\t\tthis.sessionSandboxStates.delete(sessionKey);\n\t\t\tthis.activeSandboxContainerId = undefined;\n\t\t\tthis.activeSandboxBackendConnected = false;\n\t\t\tthis.refreshUiAfterBackendChange();\n\t\t\tthis.updateToolBackendStatus();\n\t\t\tthis.showStatus(\"Shared sandbox detached; VM and guest daemon remain running\");\n\t\t\treturn;\n\t\t}\n\t\tconst result = await service.stop({\n\t\t\tworkspaceRoot,\n\t\t\ttarget,\n\t\t\tcurrentContainerId: this.activeSandboxContainerId,\n\t\t});\n\t\tawait this.reconcileStoppedSandbox(result, sessionKey);\n\t\tthis.showStatus(formatSandboxStopResult(result));\n\t}\n\n\tprivate async executeSandboxCommand(\n\t\tcommand: SandboxUserCommand,\n\t\tservice: LimaSandboxService,\n\t\tworkspaceRoot: string,\n\t\tsessionKey: string,\n\t): Promise<void> {\n\t\tswitch (command.subcommand) {\n\t\t\tcase \"status\":\n\t\t\t\tthis.showStatus(this.formatToolBackendStatus(this.session.getToolBackendInfo()));\n\t\t\t\treturn;\n\t\t\tcase \"clear\":\n\t\t\t\tawait this.clearSandboxBackend(sessionKey);\n\t\t\t\treturn;\n\t\t\tcase \"attach\":\n\t\t\t\tif (!this.ensureSandboxCanActivate(sessionKey)) return;\n\t\t\t\tawait this.attachSandboxBackend(command.url, service, sessionKey);\n\t\t\t\treturn;\n\t\t\tcase \"start\": {\n\t\t\t\tconst attached = this.sessionSandboxStates.get(sessionKey);\n\t\t\t\tconst updatingAttached =\n\t\t\t\t\tcommand.update === true &&\n\t\t\t\t\tattached?.url.startsWith(\"grip+ws:\") === true &&\n\t\t\t\t\tattached.containerId === command.name &&\n\t\t\t\t\tthis.activeSandboxBackendConnected;\n\t\t\t\tif (!updatingAttached && !this.ensureSandboxCanActivate(sessionKey)) return;\n\t\t\t\tawait this.startSandboxBackend(command, service, workspaceRoot, sessionKey, updatingAttached);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"list\":\n\t\t\t\tthis.showStatus(formatSandboxList(await service.list({ workspaceRoot })));\n\t\t\t\treturn;\n\t\t\tcase \"stop\":\n\t\t\t\tawait this.stopSandboxBackend(command.target, service, workspaceRoot, sessionKey);\n\t\t}\n\t}\n\n\tprivate async handleSandboxCommand(text: string): Promise<void> {\n\t\tlet command: SandboxUserCommand;\n\t\ttry {\n\t\t\tcommand = parseSandboxUserCommand(text);\n\t\t} catch (error) {\n\t\t\tthis.showWarning(error instanceof Error ? error.message : String(error));\n\t\t\treturn;\n\t\t}\n\n\t\tconst service = this.createLimaSandboxService();\n\t\tconst workspaceRoot = this.activeSession.getCwd();\n\t\tconst sessionKey = getSessionSandboxKey(this.activeSession);\n\t\ttry {\n\t\t\tawait this.executeSandboxCommand(command, service, workspaceRoot, sessionKey);\n\t\t} catch (error) {\n\t\t\tthis.showError(redactSecrets(error instanceof Error ? error.message : String(error)));\n\t\t}\n\t}\n\n\tprivate handleSessionCommand(): void {\n\t\tconst stats = this.session.getSessionStats();\n\t\tconst sessionName = this.activeSession.getSessionName();\n\n\t\tlet info = `${theme.bold(\"Session Info\")}\\n\\n`;\n\t\tif (sessionName) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Name:\")} ${sessionName}\\n`;\n\t\t}\n\t\tinfo += `${theme.fg(\"dim\", \"File:\")} ${stats.sessionFile ?? \"In-memory\"}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"ID:\")} ${stats.sessionId}\\n\\n`;\n\t\tinfo += `${theme.bold(\"Messages\")}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"User:\")} ${stats.userMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Assistant:\")} ${stats.assistantMessages}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Tool Calls:\")} ${stats.toolCalls}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Tool Results:\")} ${stats.toolResults}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.totalMessages}\\n\\n`;\n\t\tinfo += `${theme.bold(\"Tokens\")}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Input:\")} ${stats.tokens.input.toLocaleString()}\\n`;\n\t\tinfo += `${theme.fg(\"dim\", \"Output:\")} ${stats.tokens.output.toLocaleString()}\\n`;\n\t\tif (stats.tokens.cacheRead > 0) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Cache Read:\")} ${stats.tokens.cacheRead.toLocaleString()}\\n`;\n\t\t}\n\t\tif (stats.tokens.cacheWrite > 0) {\n\t\t\tinfo += `${theme.fg(\"dim\", \"Cache Write:\")} ${stats.tokens.cacheWrite.toLocaleString()}\\n`;\n\t\t}\n\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.tokens.total.toLocaleString()}\\n`;\n\n\t\tif (stats.cost > 0) {\n\t\t\tinfo += `\\n${theme.bold(\"Cost\")}\\n`;\n\t\t\tinfo += `${theme.fg(\"dim\", \"Total:\")} ${stats.cost.toFixed(4)}`;\n\t\t}\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Text(info, 1, 0));\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate handleChangelogCommand(): void {\n\t\tconst changelogPath = getChangelogPath();\n\t\tconst allEntries = parseChangelog(changelogPath);\n\n\t\tconst changelogMarkdown =\n\t\t\tallEntries.length > 0\n\t\t\t\t? allEntries\n\t\t\t\t\t\t.reverse()\n\t\t\t\t\t\t.map((e) => e.content)\n\t\t\t\t\t\t.join(\"\\n\\n\")\n\t\t\t\t: \"No changelog entries found.\";\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"What's New\")), 1, 0));\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.requestRender();\n\t}\n\n\t/**\n\t * Get capitalized display string for an app keybinding action.\n\t */\n\tprivate getAppKeyDisplay(action: AppKeybinding): string {\n\t\treturn keyDisplayText(action);\n\t}\n\n\t/**\n\t * Get capitalized display string for an editor keybinding action.\n\t */\n\tprivate getEditorKeyDisplay(action: Keybinding): string {\n\t\treturn keyDisplayText(action);\n\t}\n\n\tprivate handleHotkeysCommand(): void {\n\t\t// Navigation keybindings\n\t\tconst cursorUp = this.getEditorKeyDisplay(\"tui.editor.cursorUp\");\n\t\tconst cursorDown = this.getEditorKeyDisplay(\"tui.editor.cursorDown\");\n\t\tconst cursorLeft = this.getEditorKeyDisplay(\"tui.editor.cursorLeft\");\n\t\tconst cursorRight = this.getEditorKeyDisplay(\"tui.editor.cursorRight\");\n\t\tconst cursorWordLeft = this.getEditorKeyDisplay(\"tui.editor.cursorWordLeft\");\n\t\tconst cursorWordRight = this.getEditorKeyDisplay(\"tui.editor.cursorWordRight\");\n\t\tconst cursorLineStart = this.getEditorKeyDisplay(\"tui.editor.cursorLineStart\");\n\t\tconst cursorLineEnd = this.getEditorKeyDisplay(\"tui.editor.cursorLineEnd\");\n\t\tconst jumpForward = this.getEditorKeyDisplay(\"tui.editor.jumpForward\");\n\t\tconst jumpBackward = this.getEditorKeyDisplay(\"tui.editor.jumpBackward\");\n\t\tconst pageUp = this.getEditorKeyDisplay(\"tui.editor.pageUp\");\n\t\tconst pageDown = this.getEditorKeyDisplay(\"tui.editor.pageDown\");\n\n\t\t// Editing keybindings\n\t\tconst submit = this.getEditorKeyDisplay(\"tui.input.submit\");\n\t\tconst newLine = this.getEditorKeyDisplay(\"tui.input.newLine\");\n\t\tconst deleteWordBackward = this.getEditorKeyDisplay(\"tui.editor.deleteWordBackward\");\n\t\tconst deleteWordForward = this.getEditorKeyDisplay(\"tui.editor.deleteWordForward\");\n\t\tconst deleteToLineStart = this.getEditorKeyDisplay(\"tui.editor.deleteToLineStart\");\n\t\tconst deleteToLineEnd = this.getEditorKeyDisplay(\"tui.editor.deleteToLineEnd\");\n\t\tconst yank = this.getEditorKeyDisplay(\"tui.editor.yank\");\n\t\tconst yankPop = this.getEditorKeyDisplay(\"tui.editor.yankPop\");\n\t\tconst undo = this.getEditorKeyDisplay(\"tui.editor.undo\");\n\t\tconst tab = this.getEditorKeyDisplay(\"tui.input.tab\");\n\n\t\t// App keybindings\n\t\tconst interrupt = this.getAppKeyDisplay(\"app.interrupt\");\n\t\tconst clear = this.getAppKeyDisplay(\"app.clear\");\n\t\tconst exit = this.getAppKeyDisplay(\"app.exit\");\n\t\tconst suspend = this.getAppKeyDisplay(\"app.suspend\");\n\t\tconst cycleThinkingLevel = this.getAppKeyDisplay(\"app.thinking.cycle\");\n\t\tconst cycleModelForward = this.getAppKeyDisplay(\"app.model.cycleForward\");\n\t\tconst selectModel = this.getAppKeyDisplay(\"app.model.select\");\n\t\tconst expandTools = this.getAppKeyDisplay(\"app.tools.expand\");\n\t\tconst toggleThinking = this.getAppKeyDisplay(\"app.thinking.toggle\");\n\t\tconst externalEditor = this.getAppKeyDisplay(\"app.editor.external\");\n\t\tconst cycleModelBackward = this.getAppKeyDisplay(\"app.model.cycleBackward\");\n\t\tconst copyMessage = this.getAppKeyDisplay(\"app.message.copy\");\n\t\tconst followUp = this.getAppKeyDisplay(\"app.message.followUp\");\n\t\tconst dequeue = this.getAppKeyDisplay(\"app.message.dequeue\");\n\t\tconst pasteImage = this.getAppKeyDisplay(\"app.clipboard.pasteImage\");\n\n\t\tlet hotkeys = `\n**Navigation**\n| Key | Action |\n|-----|--------|\n| \\`${cursorUp}\\` / \\`${cursorDown}\\` / \\`${cursorLeft}\\` / \\`${cursorRight}\\` | Move cursor / browse history (Up when empty) |\n| \\`${cursorWordLeft}\\` / \\`${cursorWordRight}\\` | Move by word |\n| \\`${cursorLineStart}\\` | Start of line |\n| \\`${cursorLineEnd}\\` | End of line |\n| \\`${jumpForward}\\` | Jump forward to character |\n| \\`${jumpBackward}\\` | Jump backward to character |\n| \\`${pageUp}\\` / \\`${pageDown}\\` | Scroll by page |\n\n**Editing**\n| Key | Action |\n|-----|--------|\n| \\`${submit}\\` | Send message |\n| \\`${newLine}\\` | New line${process.platform === \"win32\" ? \" (Ctrl+Enter on Windows Terminal)\" : \"\"} |\n| \\`${deleteWordBackward}\\` | Delete word backwards |\n| \\`${deleteWordForward}\\` | Delete word forwards |\n| \\`${deleteToLineStart}\\` | Delete to start of line |\n| \\`${deleteToLineEnd}\\` | Delete to end of line |\n| \\`${yank}\\` | Paste the most-recently-deleted text |\n| \\`${yankPop}\\` | Cycle through the deleted text after pasting |\n| \\`${undo}\\` | Undo |\n\n**Other**\n| Key | Action |\n|-----|--------|\n| \\`${tab}\\` | Path completion / accept autocomplete |\n| \\`${interrupt}\\` | Cancel autocomplete / abort streaming |\n| \\`${clear}\\` | Clear editor (first) / exit (second) |\n| \\`${exit}\\` | Exit (when editor is empty) |\n| \\`${suspend}\\` | Suspend to background |\n| \\`${cycleThinkingLevel}\\` | Cycle thinking level |\n| \\`${cycleModelForward}\\` / \\`${cycleModelBackward}\\` | Cycle models |\n| \\`${selectModel}\\` | Open model selector |\n| \\`${expandTools}\\` | Toggle tool output expansion |\n| \\`${toggleThinking}\\` | Toggle thinking block visibility |\n| \\`${externalEditor}\\` | Edit message in external editor |\n| \\`${copyMessage}\\` | Copy last assistant message |\n| \\`${followUp}\\` | Queue follow-up message |\n| \\`${dequeue}\\` | Restore queued messages |\n| \\`${pasteImage}\\` | Paste image or text from clipboard |\n| \\`/\\` | Slash commands |\n| \\`!\\` | Run bash command |\n| \\`!!\\` | Run bash command (excluded from context) |\n`;\n\n\t\t// Add extension-registered shortcuts\n\t\tconst extensionRunner = this.session.extensionRunner;\n\t\tconst shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());\n\t\tif (shortcuts.size > 0) {\n\t\t\thotkeys += `\n**Extensions**\n| Key | Action |\n|-----|--------|\n`;\n\t\t\tfor (const [key, shortcut] of shortcuts) {\n\t\t\t\tconst description = shortcut.description ?? shortcut.extensionPath;\n\t\t\t\tconst keyDisplay = formatKeyText(key, { capitalize: true });\n\t\t\t\thotkeys += `| \\`${keyDisplay}\\` | ${description} |\\n`;\n\t\t\t}\n\t\t}\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.chatContainer.addChild(new Text(theme.bold(theme.fg(\"accent\", \"Keyboard Shortcuts\")), 1, 0));\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings()));\n\t\tthis.chatContainer.addChild(new DynamicBorder());\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleClearCommand(): Promise<void> {\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t}\n\t\tthis.statusContainer.clear();\n\t\ttry {\n\t\t\tconst result = await this.runtimeHost.newSession();\n\t\t\tif (result.cancelled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renderCurrentSessionState();\n\t\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\t\tthis.chatContainer.addChild(new Text(`${theme.fg(\"accent\", \"✓ New session started\")}`, 1, 1));\n\t\t\tthis.ui.requestRender();\n\t\t} catch (error: unknown) {\n\t\t\tawait this.handleFatalRuntimeError(\"Failed to create session\", error);\n\t\t}\n\t}\n\n\tprivate handleDebugCommand(): void {\n\t\tconst width = this.ui.terminal.columns;\n\t\tconst height = this.ui.terminal.rows;\n\t\tconst allLines = this.ui.render(width);\n\n\t\tconst debugLogPath = getDebugLogPath();\n\t\tconst debugData = [\n\t\t\t`Debug output at ${new Date().toISOString()}`,\n\t\t\t`Terminal: ${width}x${height}`,\n\t\t\t`Total lines: ${allLines.length}`,\n\t\t\t\"\",\n\t\t\t\"=== All rendered lines with visible widths ===\",\n\t\t\t...allLines.map((line, idx) => {\n\t\t\t\tconst vw = visibleWidth(line);\n\t\t\t\tconst escaped = JSON.stringify(line);\n\t\t\t\treturn `[${idx}] (w=${vw}) ${escaped}`;\n\t\t\t}),\n\t\t\t\"\",\n\t\t\t\"=== Agent messages (JSONL) ===\",\n\t\t\t...this.session.messages.map((msg) => JSON.stringify(msg)),\n\t\t\t\"\",\n\t\t].join(\"\\n\");\n\n\t\tfs.mkdirSync(path.dirname(debugLogPath), { recursive: true });\n\t\tfs.writeFileSync(debugLogPath, debugData);\n\n\t\tthis.chatContainer.addChild(new Spacer(1));\n\t\tthis.chatContainer.addChild(\n\t\t\tnew Text(`${theme.fg(\"accent\", \"✓ Debug log written\")}\\n${theme.fg(\"muted\", debugLogPath)}`, 1, 1),\n\t\t);\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate createBashExecutionDisplay(\n\t\tcommand: string,\n\t\texcludeFromContext: boolean,\n\t\tisDeferred: boolean,\n\t): BashExecutionComponent {\n\t\tconst component = new BashExecutionComponent(command, this.ui, excludeFromContext);\n\t\tthis.bashComponent = component;\n\t\tif (isDeferred) {\n\t\t\tthis.pendingMessagesContainer.addChild(component);\n\t\t\tthis.pendingBashComponents.push(component);\n\t\t} else {\n\t\t\tthis.chatContainer.addChild(component);\n\t\t}\n\t\treturn component;\n\t}\n\n\tprivate async handleBashCommand(command: string, excludeFromContext = false): Promise<void> {\n\t\tconst extensionRunner = this.session.extensionRunner;\n\n\t\t// Emit user_bash event to let extensions intercept\n\t\tconst eventResult = await extensionRunner.emitUserBash({\n\t\t\ttype: \"user_bash\",\n\t\t\tcommand,\n\t\t\texcludeFromContext,\n\t\t\tcwd: this.activeSession.getCwd(),\n\t\t});\n\n\t\t// If extension returned a full result, use it directly\n\t\tif (eventResult?.result) {\n\t\t\tconst result = eventResult.result;\n\n\t\t\tconst component = this.createBashExecutionDisplay(command, excludeFromContext, this.session.isStreaming);\n\n\t\t\t// Show output and complete\n\t\t\tif (result.output) {\n\t\t\t\tcomponent.appendOutput(result.output);\n\t\t\t}\n\t\t\tcomponent.setComplete(\n\t\t\t\tresult.exitCode,\n\t\t\t\tresult.cancelled,\n\t\t\t\tresult.truncated ? ({ truncated: true, content: result.output } as TruncationResult) : undefined,\n\t\t\t\tresult.fullOutputPath,\n\t\t\t);\n\n\t\t\t// Record the result in session\n\t\t\tthis.session.recordBashResult(command, result, { excludeFromContext });\n\t\t\tthis.bashComponent = undefined;\n\t\t\tthis.ui.requestRender();\n\t\t\treturn;\n\t\t}\n\n\t\t// Normal execution path (possibly with custom operations)\n\t\tconst isDeferred = this.session.isStreaming;\n\t\tthis.createBashExecutionDisplay(command, excludeFromContext, isDeferred);\n\t\tthis.ui.requestRender();\n\n\t\ttry {\n\t\t\tconst result = await this.session.executeBash(\n\t\t\t\tcommand,\n\t\t\t\t(chunk) => {\n\t\t\t\t\tif (this.bashComponent) {\n\t\t\t\t\t\tthis.bashComponent.appendOutput(chunk);\n\t\t\t\t\t\tthis.ui.requestRender();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ excludeFromContext, operations: eventResult?.operations },\n\t\t\t);\n\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(\n\t\t\t\t\tresult.exitCode,\n\t\t\t\t\tresult.cancelled,\n\t\t\t\t\tresult.truncated ? ({ truncated: true, content: result.output } as TruncationResult) : undefined,\n\t\t\t\t\tresult.fullOutputPath,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.bashComponent) {\n\t\t\t\tthis.bashComponent.setComplete(undefined, false);\n\t\t\t}\n\t\t\tthis.showError(`Bash command failed: ${error instanceof Error ? error.message : \"Unknown error\"}`);\n\t\t}\n\n\t\tthis.bashComponent = undefined;\n\t\tthis.ui.requestRender();\n\t}\n\n\tprivate async handleCompactCommand(customInstructions?: string): Promise<void> {\n\t\tconst entries = this.activeSession.getEntries();\n\t\tconst messageCount = entries.filter((e) => e.type === \"message\").length;\n\n\t\tif (messageCount < 2) {\n\t\t\tthis.showWarning(\"Nothing to compact (no messages yet)\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t}\n\t\tthis.statusContainer.clear();\n\n\t\ttry {\n\t\t\tawait this.session.compact(customInstructions);\n\t\t} catch {\n\t\t\t// Ignore, will be emitted as an event\n\t\t}\n\t}\n\n\tstop(fullscreenExitOutput = this.settingsManager.getFullscreenExitOutput()): void {\n\t\tthis.unregisterSignalHandlers();\n\t\tif (this.settingsManager.getShowTerminalProgress()) {\n\t\t\tthis.ui.terminal.setProgress(false);\n\t\t}\n\t\tif (this.loadingAnimation) {\n\t\t\tthis.loadingAnimation.stop();\n\t\t\tthis.loadingAnimation = undefined;\n\t\t}\n\t\tthis.summarizationRetryCountdown?.dispose();\n\t\tthis.summarizationRetryCountdown = undefined;\n\t\tthis.summarizationRetryLoader?.stop();\n\t\tthis.summarizationRetryLoader = undefined;\n\t\tthis.branchSummaryLoader?.stop();\n\t\tthis.branchSummaryLoader = undefined;\n\t\tthis.clearExtensionTerminalInputListeners();\n\t\tthis.footer.dispose();\n\t\tthis.footerDataProvider.dispose();\n\t\tif (this.unsubscribe) {\n\t\t\tthis.unsubscribe();\n\t\t}\n\t\tthis.hookExecutionUnsubscribe?.();\n\t\tthis.hookExecutionUnsubscribe = undefined;\n\t\tthis.hookExecutionActivityUnsubscribe?.();\n\t\tthis.hookExecutionActivityUnsubscribe = undefined;\n\t\tif (this.isInitialized) {\n\t\t\tthis.stopInteractiveTui(fullscreenExitOutput);\n\t\t\tthis.isInitialized = false;\n\t\t}\n\t}\n}\n"]}