@agegr/pi-web 0.2.1

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 (272) hide show
  1. package/.next/BUILD_ID +1 -0
  2. package/.next/package.json +1 -0
  3. package/.next/server/app/_global-error/page/app-paths-manifest.json +3 -0
  4. package/.next/server/app/_global-error/page/build-manifest.json +17 -0
  5. package/.next/server/app/_global-error/page/next-font-manifest.json +6 -0
  6. package/.next/server/app/_global-error/page/react-loadable-manifest.json +1 -0
  7. package/.next/server/app/_global-error/page/server-reference-manifest.json +4 -0
  8. package/.next/server/app/_global-error/page.js +10 -0
  9. package/.next/server/app/_global-error/page.js.map +5 -0
  10. package/.next/server/app/_global-error/page.js.nft.json +1 -0
  11. package/.next/server/app/_global-error/page_client-reference-manifest.js +3 -0
  12. package/.next/server/app/_global-error.html +1 -0
  13. package/.next/server/app/_global-error.meta +15 -0
  14. package/.next/server/app/_global-error.rsc +15 -0
  15. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +5 -0
  16. package/.next/server/app/_global-error.segments/_full.segment.rsc +15 -0
  17. package/.next/server/app/_global-error.segments/_head.segment.rsc +6 -0
  18. package/.next/server/app/_global-error.segments/_index.segment.rsc +5 -0
  19. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -0
  20. package/.next/server/app/_not-found/page/app-paths-manifest.json +3 -0
  21. package/.next/server/app/_not-found/page/build-manifest.json +17 -0
  22. package/.next/server/app/_not-found/page/next-font-manifest.json +6 -0
  23. package/.next/server/app/_not-found/page/react-loadable-manifest.json +1 -0
  24. package/.next/server/app/_not-found/page/server-reference-manifest.json +4 -0
  25. package/.next/server/app/_not-found/page.js +13 -0
  26. package/.next/server/app/_not-found/page.js.map +5 -0
  27. package/.next/server/app/_not-found/page.js.nft.json +1 -0
  28. package/.next/server/app/_not-found/page_client-reference-manifest.js +3 -0
  29. package/.next/server/app/_not-found.html +1 -0
  30. package/.next/server/app/_not-found.meta +16 -0
  31. package/.next/server/app/_not-found.rsc +16 -0
  32. package/.next/server/app/_not-found.segments/_full.segment.rsc +16 -0
  33. package/.next/server/app/_not-found.segments/_head.segment.rsc +6 -0
  34. package/.next/server/app/_not-found.segments/_index.segment.rsc +5 -0
  35. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +5 -0
  36. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +5 -0
  37. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -0
  38. package/.next/server/app/api/agent/[id]/events/route/app-paths-manifest.json +3 -0
  39. package/.next/server/app/api/agent/[id]/events/route/build-manifest.json +9 -0
  40. package/.next/server/app/api/agent/[id]/events/route/server-reference-manifest.json +4 -0
  41. package/.next/server/app/api/agent/[id]/events/route.js +6 -0
  42. package/.next/server/app/api/agent/[id]/events/route.js.map +5 -0
  43. package/.next/server/app/api/agent/[id]/events/route.js.nft.json +1 -0
  44. package/.next/server/app/api/agent/[id]/events/route_client-reference-manifest.js +3 -0
  45. package/.next/server/app/api/agent/[id]/route/app-paths-manifest.json +3 -0
  46. package/.next/server/app/api/agent/[id]/route/build-manifest.json +9 -0
  47. package/.next/server/app/api/agent/[id]/route/server-reference-manifest.json +4 -0
  48. package/.next/server/app/api/agent/[id]/route.js +7 -0
  49. package/.next/server/app/api/agent/[id]/route.js.map +5 -0
  50. package/.next/server/app/api/agent/[id]/route.js.nft.json +1 -0
  51. package/.next/server/app/api/agent/[id]/route_client-reference-manifest.js +3 -0
  52. package/.next/server/app/api/agent/new/route/app-paths-manifest.json +3 -0
  53. package/.next/server/app/api/agent/new/route/build-manifest.json +9 -0
  54. package/.next/server/app/api/agent/new/route/server-reference-manifest.json +4 -0
  55. package/.next/server/app/api/agent/new/route.js +7 -0
  56. package/.next/server/app/api/agent/new/route.js.map +5 -0
  57. package/.next/server/app/api/agent/new/route.js.nft.json +1 -0
  58. package/.next/server/app/api/agent/new/route_client-reference-manifest.js +3 -0
  59. package/.next/server/app/api/files/[...path]/route/app-paths-manifest.json +3 -0
  60. package/.next/server/app/api/files/[...path]/route/build-manifest.json +9 -0
  61. package/.next/server/app/api/files/[...path]/route/server-reference-manifest.json +4 -0
  62. package/.next/server/app/api/files/[...path]/route.js +7 -0
  63. package/.next/server/app/api/files/[...path]/route.js.map +5 -0
  64. package/.next/server/app/api/files/[...path]/route.js.nft.json +1 -0
  65. package/.next/server/app/api/files/[...path]/route_client-reference-manifest.js +3 -0
  66. package/.next/server/app/api/models/route/app-paths-manifest.json +3 -0
  67. package/.next/server/app/api/models/route/build-manifest.json +9 -0
  68. package/.next/server/app/api/models/route/server-reference-manifest.json +4 -0
  69. package/.next/server/app/api/models/route.js +6 -0
  70. package/.next/server/app/api/models/route.js.map +5 -0
  71. package/.next/server/app/api/models/route.js.nft.json +1 -0
  72. package/.next/server/app/api/models/route_client-reference-manifest.js +3 -0
  73. package/.next/server/app/api/models-config/route/app-paths-manifest.json +3 -0
  74. package/.next/server/app/api/models-config/route/build-manifest.json +9 -0
  75. package/.next/server/app/api/models-config/route/server-reference-manifest.json +4 -0
  76. package/.next/server/app/api/models-config/route.js +7 -0
  77. package/.next/server/app/api/models-config/route.js.map +5 -0
  78. package/.next/server/app/api/models-config/route.js.nft.json +1 -0
  79. package/.next/server/app/api/models-config/route_client-reference-manifest.js +3 -0
  80. package/.next/server/app/api/sessions/[id]/context/route/app-paths-manifest.json +3 -0
  81. package/.next/server/app/api/sessions/[id]/context/route/build-manifest.json +9 -0
  82. package/.next/server/app/api/sessions/[id]/context/route/server-reference-manifest.json +4 -0
  83. package/.next/server/app/api/sessions/[id]/context/route.js +7 -0
  84. package/.next/server/app/api/sessions/[id]/context/route.js.map +5 -0
  85. package/.next/server/app/api/sessions/[id]/context/route.js.nft.json +1 -0
  86. package/.next/server/app/api/sessions/[id]/context/route_client-reference-manifest.js +3 -0
  87. package/.next/server/app/api/sessions/[id]/route/app-paths-manifest.json +3 -0
  88. package/.next/server/app/api/sessions/[id]/route/build-manifest.json +9 -0
  89. package/.next/server/app/api/sessions/[id]/route/server-reference-manifest.json +4 -0
  90. package/.next/server/app/api/sessions/[id]/route.js +7 -0
  91. package/.next/server/app/api/sessions/[id]/route.js.map +5 -0
  92. package/.next/server/app/api/sessions/[id]/route.js.nft.json +1 -0
  93. package/.next/server/app/api/sessions/[id]/route_client-reference-manifest.js +3 -0
  94. package/.next/server/app/api/sessions/new/route/app-paths-manifest.json +3 -0
  95. package/.next/server/app/api/sessions/new/route/build-manifest.json +9 -0
  96. package/.next/server/app/api/sessions/new/route/server-reference-manifest.json +4 -0
  97. package/.next/server/app/api/sessions/new/route.js +6 -0
  98. package/.next/server/app/api/sessions/new/route.js.map +5 -0
  99. package/.next/server/app/api/sessions/new/route.js.nft.json +1 -0
  100. package/.next/server/app/api/sessions/new/route_client-reference-manifest.js +3 -0
  101. package/.next/server/app/api/sessions/route/app-paths-manifest.json +3 -0
  102. package/.next/server/app/api/sessions/route/build-manifest.json +9 -0
  103. package/.next/server/app/api/sessions/route/server-reference-manifest.json +4 -0
  104. package/.next/server/app/api/sessions/route.js +7 -0
  105. package/.next/server/app/api/sessions/route.js.map +5 -0
  106. package/.next/server/app/api/sessions/route.js.nft.json +1 -0
  107. package/.next/server/app/api/sessions/route_client-reference-manifest.js +3 -0
  108. package/.next/server/app/favicon.ico/route/app-paths-manifest.json +3 -0
  109. package/.next/server/app/favicon.ico/route/build-manifest.json +9 -0
  110. package/.next/server/app/favicon.ico/route.js +8 -0
  111. package/.next/server/app/favicon.ico/route.js.map +5 -0
  112. package/.next/server/app/favicon.ico/route.js.nft.json +1 -0
  113. package/.next/server/app/favicon.ico.body +0 -0
  114. package/.next/server/app/favicon.ico.meta +1 -0
  115. package/.next/server/app/index.html +1 -0
  116. package/.next/server/app/index.meta +14 -0
  117. package/.next/server/app/index.rsc +15 -0
  118. package/.next/server/app/index.segments/__PAGE__.segment.rsc +6 -0
  119. package/.next/server/app/index.segments/_full.segment.rsc +15 -0
  120. package/.next/server/app/index.segments/_head.segment.rsc +6 -0
  121. package/.next/server/app/index.segments/_index.segment.rsc +5 -0
  122. package/.next/server/app/index.segments/_tree.segment.rsc +2 -0
  123. package/.next/server/app/page/app-paths-manifest.json +3 -0
  124. package/.next/server/app/page/build-manifest.json +17 -0
  125. package/.next/server/app/page/next-font-manifest.json +6 -0
  126. package/.next/server/app/page/react-loadable-manifest.json +1 -0
  127. package/.next/server/app/page/server-reference-manifest.json +4 -0
  128. package/.next/server/app/page.js +14 -0
  129. package/.next/server/app/page.js.map +5 -0
  130. package/.next/server/app/page.js.nft.json +1 -0
  131. package/.next/server/app/page_client-reference-manifest.js +3 -0
  132. package/.next/server/app-paths-manifest.json +16 -0
  133. package/.next/server/chunks/[externals]_next_dist_0h.fyd6._.js +3 -0
  134. package/.next/server/chunks/[externals]_next_dist_0h.fyd6._.js.map +1 -0
  135. package/.next/server/chunks/[root-of-the-server]__002d92q._.js +6 -0
  136. package/.next/server/chunks/[root-of-the-server]__002d92q._.js.map +1 -0
  137. package/.next/server/chunks/[root-of-the-server]__00a-~o4._.js +3 -0
  138. package/.next/server/chunks/[root-of-the-server]__00a-~o4._.js.map +1 -0
  139. package/.next/server/chunks/[root-of-the-server]__06qx74m._.js +5 -0
  140. package/.next/server/chunks/[root-of-the-server]__06qx74m._.js.map +1 -0
  141. package/.next/server/chunks/[root-of-the-server]__0_ehal9._.js +5 -0
  142. package/.next/server/chunks/[root-of-the-server]__0_ehal9._.js.map +1 -0
  143. package/.next/server/chunks/[root-of-the-server]__0a-p9wd._.js +3 -0
  144. package/.next/server/chunks/[root-of-the-server]__0a-p9wd._.js.map +1 -0
  145. package/.next/server/chunks/[root-of-the-server]__0b0kii6._.js +8 -0
  146. package/.next/server/chunks/[root-of-the-server]__0b0kii6._.js.map +1 -0
  147. package/.next/server/chunks/[root-of-the-server]__0cw6f~v._.js +5 -0
  148. package/.next/server/chunks/[root-of-the-server]__0cw6f~v._.js.map +1 -0
  149. package/.next/server/chunks/[root-of-the-server]__0llo_uy._.js +5 -0
  150. package/.next/server/chunks/[root-of-the-server]__0llo_uy._.js.map +1 -0
  151. package/.next/server/chunks/[root-of-the-server]__0rr3q~-._.js +5 -0
  152. package/.next/server/chunks/[root-of-the-server]__0rr3q~-._.js.map +1 -0
  153. package/.next/server/chunks/[root-of-the-server]__0y7g-4j._.js +4 -0
  154. package/.next/server/chunks/[root-of-the-server]__0y7g-4j._.js.map +1 -0
  155. package/.next/server/chunks/[root-of-the-server]__11j~5mn._.js +3 -0
  156. package/.next/server/chunks/[root-of-the-server]__11j~5mn._.js.map +1 -0
  157. package/.next/server/chunks/[turbopack]_runtime.js +903 -0
  158. package/.next/server/chunks/[turbopack]_runtime.js.map +11 -0
  159. package/.next/server/chunks/_next-internal_server_app_api_agent_[id]_events_route_actions_05o7blz.js +3 -0
  160. package/.next/server/chunks/_next-internal_server_app_api_agent_[id]_events_route_actions_05o7blz.js.map +1 -0
  161. package/.next/server/chunks/_next-internal_server_app_api_agent_[id]_route_actions_0kr98j0.js +3 -0
  162. package/.next/server/chunks/_next-internal_server_app_api_agent_[id]_route_actions_0kr98j0.js.map +1 -0
  163. package/.next/server/chunks/_next-internal_server_app_api_agent_new_route_actions_0w3r5tj.js +3 -0
  164. package/.next/server/chunks/_next-internal_server_app_api_agent_new_route_actions_0w3r5tj.js.map +1 -0
  165. package/.next/server/chunks/_next-internal_server_app_api_files_[___path]_route_actions_0_g4akf.js +3 -0
  166. package/.next/server/chunks/_next-internal_server_app_api_files_[___path]_route_actions_0_g4akf.js.map +1 -0
  167. package/.next/server/chunks/_next-internal_server_app_api_models-config_route_actions_0ipr5cq.js +3 -0
  168. package/.next/server/chunks/_next-internal_server_app_api_models-config_route_actions_0ipr5cq.js.map +1 -0
  169. package/.next/server/chunks/_next-internal_server_app_api_models_route_actions_0vfccm4.js +3 -0
  170. package/.next/server/chunks/_next-internal_server_app_api_models_route_actions_0vfccm4.js.map +1 -0
  171. package/.next/server/chunks/_next-internal_server_app_api_sessions_[id]_context_route_actions_0d0pnzf.js +3 -0
  172. package/.next/server/chunks/_next-internal_server_app_api_sessions_[id]_context_route_actions_0d0pnzf.js.map +1 -0
  173. package/.next/server/chunks/_next-internal_server_app_api_sessions_[id]_route_actions_0eo4u5w.js +3 -0
  174. package/.next/server/chunks/_next-internal_server_app_api_sessions_[id]_route_actions_0eo4u5w.js.map +1 -0
  175. package/.next/server/chunks/_next-internal_server_app_api_sessions_new_route_actions_093p~n-.js +3 -0
  176. package/.next/server/chunks/_next-internal_server_app_api_sessions_new_route_actions_093p~n-.js.map +1 -0
  177. package/.next/server/chunks/_next-internal_server_app_api_sessions_route_actions_0y1t9w0.js +3 -0
  178. package/.next/server/chunks/_next-internal_server_app_api_sessions_route_actions_0y1t9w0.js.map +1 -0
  179. package/.next/server/chunks/_next-internal_server_app_favicon_ico_route_actions_095lj93.js +3 -0
  180. package/.next/server/chunks/_next-internal_server_app_favicon_ico_route_actions_095lj93.js.map +1 -0
  181. package/.next/server/chunks/lib_session-reader_ts_07kvkqq._.js +5 -0
  182. package/.next/server/chunks/lib_session-reader_ts_07kvkqq._.js.map +1 -0
  183. package/.next/server/chunks/node_modules_next_04~_e52._.js +13 -0
  184. package/.next/server/chunks/node_modules_next_04~_e52._.js.map +1 -0
  185. package/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_0yubv2d.js +3 -0
  186. package/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_0yubv2d.js.map +1 -0
  187. package/.next/server/chunks/ssr/[root-of-the-server]__00d4x5d._.js +3 -0
  188. package/.next/server/chunks/ssr/[root-of-the-server]__00d4x5d._.js.map +1 -0
  189. package/.next/server/chunks/ssr/[root-of-the-server]__02hi65f._.js +3 -0
  190. package/.next/server/chunks/ssr/[root-of-the-server]__02hi65f._.js.map +1 -0
  191. package/.next/server/chunks/ssr/[root-of-the-server]__06-2p1a._.js +33 -0
  192. package/.next/server/chunks/ssr/[root-of-the-server]__06-2p1a._.js.map +1 -0
  193. package/.next/server/chunks/ssr/[root-of-the-server]__09z7o2x._.js +19 -0
  194. package/.next/server/chunks/ssr/[root-of-the-server]__09z7o2x._.js.map +1 -0
  195. package/.next/server/chunks/ssr/[root-of-the-server]__0jag6jd._.js +3 -0
  196. package/.next/server/chunks/ssr/[root-of-the-server]__0jag6jd._.js.map +1 -0
  197. package/.next/server/chunks/ssr/[root-of-the-server]__0pr3cat._.js +33 -0
  198. package/.next/server/chunks/ssr/[root-of-the-server]__0pr3cat._.js.map +1 -0
  199. package/.next/server/chunks/ssr/[root-of-the-server]__0pspq~2._.js +6 -0
  200. package/.next/server/chunks/ssr/[root-of-the-server]__0pspq~2._.js.map +1 -0
  201. package/.next/server/chunks/ssr/[root-of-the-server]__0w~zl.s._.js +3 -0
  202. package/.next/server/chunks/ssr/[root-of-the-server]__0w~zl.s._.js.map +1 -0
  203. package/.next/server/chunks/ssr/[turbopack]_runtime.js +903 -0
  204. package/.next/server/chunks/ssr/[turbopack]_runtime.js.map +11 -0
  205. package/.next/server/chunks/ssr/_next-internal_server_app__global-error_page_actions_0k77kol.js +3 -0
  206. package/.next/server/chunks/ssr/_next-internal_server_app__global-error_page_actions_0k77kol.js.map +1 -0
  207. package/.next/server/chunks/ssr/_next-internal_server_app__not-found_page_actions_0eq97pa.js +3 -0
  208. package/.next/server/chunks/ssr/_next-internal_server_app__not-found_page_actions_0eq97pa.js.map +1 -0
  209. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_09-gtaw.js +3 -0
  210. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_09-gtaw.js.map +1 -0
  211. package/.next/server/chunks/ssr/app_layout_tsx_13yf0ls._.js +3 -0
  212. package/.next/server/chunks/ssr/app_layout_tsx_13yf0ls._.js.map +1 -0
  213. package/.next/server/chunks/ssr/components_ToolPanel_tsx_0r3vloj._.js +3 -0
  214. package/.next/server/chunks/ssr/components_ToolPanel_tsx_0r3vloj._.js.map +1 -0
  215. package/.next/server/chunks/ssr/components_ToolPanel_tsx_0ybdq6k._.js +3 -0
  216. package/.next/server/chunks/ssr/components_ToolPanel_tsx_0ybdq6k._.js.map +1 -0
  217. package/.next/server/chunks/ssr/node_modules_09w7yel._.js +33 -0
  218. package/.next/server/chunks/ssr/node_modules_09w7yel._.js.map +1 -0
  219. package/.next/server/chunks/ssr/node_modules_0vtdjw7._.js +3 -0
  220. package/.next/server/chunks/ssr/node_modules_0vtdjw7._.js.map +1 -0
  221. package/.next/server/chunks/ssr/node_modules_next_dist_09y1ibj._.js +6 -0
  222. package/.next/server/chunks/ssr/node_modules_next_dist_09y1ibj._.js.map +1 -0
  223. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_0inhx6q._.js +3 -0
  224. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_0inhx6q._.js.map +1 -0
  225. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_forbidden_0ghu-f7.js +3 -0
  226. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_forbidden_0ghu-f7.js.map +1 -0
  227. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_global-error_0lgvd_..js +3 -0
  228. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_global-error_0lgvd_..js.map +1 -0
  229. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_unauthorized_0cjv-23.js +3 -0
  230. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_unauthorized_0cjv-23.js.map +1 -0
  231. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_002l7yi.js +4 -0
  232. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_002l7yi.js.map +1 -0
  233. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_02suzhc.js +4 -0
  234. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_02suzhc.js.map +1 -0
  235. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0nsg22r.js +4 -0
  236. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0nsg22r.js.map +1 -0
  237. package/.next/server/functions-config-manifest.json +4 -0
  238. package/.next/server/interception-route-rewrite-manifest.js +1 -0
  239. package/.next/server/middleware-build-manifest.js +21 -0
  240. package/.next/server/middleware-manifest.json +6 -0
  241. package/.next/server/next-font-manifest.js +1 -0
  242. package/.next/server/next-font-manifest.json +6 -0
  243. package/.next/server/pages/404.html +1 -0
  244. package/.next/server/pages/500.html +1 -0
  245. package/.next/server/pages-manifest.json +4 -0
  246. package/.next/server/prefetch-hints.json +1 -0
  247. package/.next/server/server-reference-manifest.js +1 -0
  248. package/.next/server/server-reference-manifest.json +5 -0
  249. package/.next/static/chunks/0-j.wjqnc6zff.js +1 -0
  250. package/.next/static/chunks/02i7dfk78~t~2.js +4 -0
  251. package/.next/static/chunks/02p06lvcsni3l.js +1 -0
  252. package/.next/static/chunks/03~yq9q893hmn.js +1 -0
  253. package/.next/static/chunks/09dho1gmydle0.js +1 -0
  254. package/.next/static/chunks/0_mdnxjv887c..css +1 -0
  255. package/.next/static/chunks/0cj37tl-sc0gx.js +2 -0
  256. package/.next/static/chunks/0h4bblvd1oiwg.js +1 -0
  257. package/.next/static/chunks/0j-yjan8jn-8-.js +31 -0
  258. package/.next/static/chunks/0lpjxrppxb_hc.js +1 -0
  259. package/.next/static/chunks/turbopack-04u~j1o-remaj.js +1 -0
  260. package/.next/static/h_DPSqE34dYtPmxavamVm/_buildManifest.js +11 -0
  261. package/.next/static/h_DPSqE34dYtPmxavamVm/_clientMiddlewareManifest.js +1 -0
  262. package/.next/static/h_DPSqE34dYtPmxavamVm/_ssgManifest.js +1 -0
  263. package/.next/static/media/favicon.0~uco8ba8mwit.ico +0 -0
  264. package/README.md +62 -0
  265. package/bin/pi-web.js +24 -0
  266. package/next.config.ts +8 -0
  267. package/package.json +43 -0
  268. package/public/file.svg +1 -0
  269. package/public/globe.svg +1 -0
  270. package/public/next.svg +1 -0
  271. package/public/vercel.svg +1 -0
  272. package/public/window.svg +1 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../lib/session-reader.ts","../../../lib/normalize.ts","../../../lib/system-prompt-off.ts","../../../lib/rpc-manager.ts","../../../app/api/agent/%5Bid%5D/events/route.ts","../../../node_modules/next/src/build/templates/app-route.ts"],"sourcesContent":["import { readFileSync, readdirSync, statSync, existsSync } from \"fs\";\nimport { join } from \"path\";\nimport { homedir } from \"os\";\nimport type {\n FileEntry,\n SessionEntry,\n SessionHeader,\n SessionInfo,\n SessionTreeNode,\n SessionMessageEntry,\n SessionInfoEntry,\n LabelEntry,\n AgentMessage,\n SessionContext,\n CompactionEntry,\n TextContent,\n} from \"./types\";\nimport { normalizeToolCalls } from \"./normalize\";\n\nfunction getAgentDir(): string {\n const envDir = process.env.PI_CODING_AGENT_DIR;\n if (envDir) {\n if (envDir === \"~\") return homedir();\n if (envDir.startsWith(\"~/\")) return homedir() + envDir.slice(1);\n return envDir;\n }\n return join(homedir(), \".pi\", \"agent\");\n}\n\nexport function getSessionsDir(): string {\n return join(getAgentDir(), \"sessions\");\n}\n\nexport interface ModelInfo {\n id: string;\n name: string;\n provider: string;\n}\n\n// Build a map of \"provider:modelId\" -> ModelInfo from ~/.pi/agent/models.json\nlet _modelCache: Map<string, ModelInfo> | null = null;\nfunction getModelCache(): Map<string, ModelInfo> {\n if (_modelCache) return _modelCache;\n _modelCache = new Map();\n const path = join(getAgentDir(), \"models.json\");\n if (!existsSync(path)) return _modelCache;\n try {\n const data = JSON.parse(readFileSync(path, \"utf8\")) as {\n providers?: Record<string, { models?: { id: string; name?: string }[] }>;\n };\n for (const [provider, providerData] of Object.entries(data.providers ?? {})) {\n for (const model of providerData.models ?? []) {\n if (model.id && model.name) {\n _modelCache.set(`${provider}:${model.id}`, { id: model.id, name: model.name, provider });\n }\n }\n }\n } catch { /* ignore */ }\n return _modelCache;\n}\n\nexport function getModelNameMap(): Map<string, string> {\n const result = new Map<string, string>();\n for (const info of getModelCache().values()) result.set(info.id, info.name);\n return result;\n}\n\nexport function getModelList(): ModelInfo[] {\n return Array.from(getModelCache().values());\n}\n\nexport function invalidateModelCache(): void {\n _modelCache = null;\n}\n\nexport function getDefaultModel(): { provider: string; modelId: string } | null {\n const path = join(getAgentDir(), \"settings.json\");\n if (!existsSync(path)) return null;\n try {\n const data = JSON.parse(readFileSync(path, \"utf8\")) as {\n defaultProvider?: string;\n defaultModel?: string;\n };\n if (!data.defaultProvider) return null;\n if (data.defaultModel) {\n return { provider: data.defaultProvider, modelId: data.defaultModel };\n }\n // Only provider saved — pick the first model from that provider in models.json\n const first = Array.from(getModelCache().values()).find((m) => m.provider === data.defaultProvider);\n if (first) return { provider: first.provider, modelId: first.id };\n } catch { /* ignore */ }\n return null;\n}\n\nexport function parseSessionFile(filePath: string): FileEntry[] {\n if (!existsSync(filePath)) return [];\n const content = readFileSync(filePath, \"utf8\");\n const entries: FileEntry[] = [];\n for (const line of content.trim().split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n entries.push(JSON.parse(line) as FileEntry);\n } catch {\n // skip malformed lines\n }\n }\n return entries;\n}\n\nfunction extractTextContent(message: AgentMessage): string {\n const content = (message as { content: unknown }).content;\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .filter((b): b is TextContent => b.type === \"text\")\n .map((b) => b.text)\n .join(\" \");\n}\n\n// Extract session UUID from a session file path like \".../2026-03-18T12-11-02-213Z_20a1e7e5-991f-4b91-856d-14dd2d256f20.jsonl\"\nfunction extractSessionIdFromPath(filePath: string): string | undefined {\n const base = filePath.replace(/\\\\/g, \"/\").split(\"/\").pop() ?? \"\";\n // format: <timestamp>_<uuid>.jsonl\n const match = base.match(/_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\.jsonl$/i);\n return match?.[1];\n}\n\nexport function buildSessionInfo(filePath: string): SessionInfo | null {\n try {\n const entries = parseSessionFile(filePath);\n if (entries.length === 0) return null;\n\n // Skip files without a valid session header (incomplete fork artifacts)\n const maybeHeader = entries[0] as SessionHeader;\n if (maybeHeader.type !== \"session\") return null;\n\n const stats = statSync(filePath);\n const id = maybeHeader.id;\n const cwd = maybeHeader.cwd ?? \"\";\n const created = maybeHeader.timestamp;\n const parentSessionId = maybeHeader.parentSession\n ? extractSessionIdFromPath(maybeHeader.parentSession)\n : undefined;\n\n let messageCount = 0;\n let firstMessage = \"\";\n let name: string | undefined;\n\n for (const entry of entries) {\n if (entry.type === \"session_info\") {\n const e = entry as SessionInfoEntry;\n if (e.name) name = e.name.trim();\n }\n if (entry.type !== \"message\") continue;\n messageCount++;\n const msg = (entry as SessionMessageEntry).message;\n if (msg.role !== \"user\" && msg.role !== \"assistant\") continue;\n const text = extractTextContent(msg);\n if (!firstMessage && msg.role === \"user\") firstMessage = text;\n }\n\n return {\n path: filePath,\n id,\n cwd,\n name,\n created,\n modified: stats.mtime.toISOString(),\n messageCount,\n firstMessage: firstMessage || \"(no messages)\",\n parentSessionId,\n };\n } catch {\n return null;\n }\n}\n\nexport async function listAllSessions(): Promise<SessionInfo[]> {\n const sessionsDir = getSessionsDir();\n const sessions: SessionInfo[] = [];\n if (!existsSync(sessionsDir)) return sessions;\n\n try {\n const dirs = readdirSync(sessionsDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(sessionsDir, e.name));\n\n for (const dir of dirs) {\n try {\n const files = readdirSync(dir)\n .filter((f) => f.endsWith(\".jsonl\"))\n .map((f) => join(dir, f));\n for (const file of files) {\n const info = buildSessionInfo(file);\n if (info) sessions.push(info);\n }\n } catch {\n // skip unreadable dir\n }\n }\n } catch {\n // skip\n }\n\n sessions.sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());\n return sessions;\n}\n\nexport function getSessionEntries(filePath: string): SessionEntry[] {\n const entries = parseSessionFile(filePath);\n return entries.filter((e): e is SessionEntry => e.type !== \"session\");\n}\n\nexport function buildTree(entries: SessionEntry[]): SessionTreeNode[] {\n const labelsById = new Map<string, string>();\n for (const entry of entries) {\n if (entry.type === \"label\") {\n const l = entry as LabelEntry;\n if (l.label) labelsById.set(l.targetId, l.label);\n else labelsById.delete(l.targetId);\n }\n }\n\n const nodeMap = new Map<string, SessionTreeNode>();\n const roots: SessionTreeNode[] = [];\n\n for (const entry of entries) {\n nodeMap.set(entry.id, { entry, children: [], label: labelsById.get(entry.id) });\n }\n\n for (const entry of entries) {\n const node = nodeMap.get(entry.id)!;\n if (!entry.parentId) {\n roots.push(node);\n } else {\n const parent = nodeMap.get(entry.parentId);\n if (parent) {\n parent.children.push(node);\n } else {\n roots.push(node);\n }\n }\n }\n\n // sort children by timestamp\n const stack = [...roots];\n while (stack.length > 0) {\n const node = stack.pop()!;\n node.children.sort(\n (a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime()\n );\n stack.push(...node.children);\n }\n\n return roots;\n}\n\n\n\nexport function buildSessionContext(\n entries: SessionEntry[],\n leafId?: string | null\n): SessionContext {\n const byId = new Map<string, SessionEntry>();\n for (const entry of entries) {\n byId.set(entry.id, entry);\n }\n\n let leaf: SessionEntry | undefined;\n if (leafId === null) {\n return { messages: [], entryIds: [], thinkingLevel: \"off\", model: null };\n }\n if (leafId) {\n leaf = byId.get(leafId);\n }\n if (!leaf) {\n leaf = entries[entries.length - 1];\n }\n if (!leaf) {\n return { messages: [], entryIds: [], thinkingLevel: \"off\", model: null };\n }\n\n // walk from leaf to root\n const path: SessionEntry[] = [];\n let current: SessionEntry | undefined = leaf;\n while (current) {\n path.unshift(current);\n current = current.parentId ? byId.get(current.parentId) : undefined;\n }\n\n let thinkingLevel = \"off\";\n let model: { provider: string; modelId: string } | null = null;\n let compaction: CompactionEntry | null = null;\n\n for (const entry of path) {\n if (entry.type === \"thinking_level_change\") {\n thinkingLevel = entry.thinkingLevel;\n } else if (entry.type === \"model_change\") {\n model = { provider: entry.provider, modelId: entry.modelId };\n } else if (entry.type === \"message\" && (entry as SessionMessageEntry).message.role === \"assistant\") {\n const msg = (entry as SessionMessageEntry).message as { provider: string; model: string };\n model = { provider: msg.provider, modelId: msg.model };\n } else if (entry.type === \"compaction\") {\n compaction = entry as CompactionEntry;\n }\n }\n\n const messages: AgentMessage[] = [];\n const entryIds: string[] = [];\n\n const appendMessage = (entry: SessionEntry) => {\n if (entry.type === \"message\") {\n messages.push(normalizeToolCalls((entry as SessionMessageEntry).message));\n entryIds.push(entry.id);\n }\n };\n\n if (compaction) {\n // Inject compaction summary as a virtual user message matching agent's format\n const summaryMsg: AgentMessage = {\n role: \"user\",\n content: `*The conversation history before this point was compacted into the following summary:*\\n\\n${compaction.summary}`,\n timestamp: new Date(compaction.timestamp).getTime(),\n };\n messages.push(summaryMsg);\n entryIds.push(compaction.id);\n\n const compactionIdx = path.findIndex(\n (e) => e.type === \"compaction\" && e.id === compaction!.id\n );\n // Find firstKeptEntryId before the compaction node; if not found, skip all pre-compaction entries\n const firstKeptIdx = path.findIndex(\n (e, i) => i < compactionIdx && e.id === compaction!.firstKeptEntryId\n );\n const startIdx = firstKeptIdx >= 0 ? firstKeptIdx : compactionIdx;\n for (let i = startIdx; i < compactionIdx; i++) {\n appendMessage(path[i]);\n }\n for (let i = compactionIdx + 1; i < path.length; i++) {\n appendMessage(path[i]);\n }\n } else {\n for (const entry of path) {\n appendMessage(entry);\n }\n }\n\n return { messages, entryIds, thinkingLevel, model };\n}\n\nexport function getLeafId(entries: SessionEntry[]): string | null {\n if (entries.length === 0) return null;\n return entries[entries.length - 1].id;\n}\n\n// ============================================================================\n// Session path cache: sessionId → absolute file path\n// Stored in globalThis for hot-reload safety (same as rpc-manager registry)\n// ============================================================================\ndeclare global {\n var __piSessionPathCache: Map<string, string> | undefined;\n}\n\nfunction getPathCache(): Map<string, string> {\n if (!globalThis.__piSessionPathCache) globalThis.__piSessionPathCache = new Map();\n return globalThis.__piSessionPathCache;\n}\n\nexport function invalidateSessionPathCache(sessionId: string): void {\n getPathCache().delete(sessionId);\n}\n\nexport function resolveSessionPath(sessionId: string): string | null {\n const cache = getPathCache();\n const cached = cache.get(sessionId);\n if (cached && existsSync(cached)) return cached;\n\n const sessionsDir = getSessionsDir();\n if (!existsSync(sessionsDir)) return null;\n try {\n const dirs = readdirSync(sessionsDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(sessionsDir, e.name));\n for (const dir of dirs) {\n try {\n const files = readdirSync(dir).filter((f) => f.endsWith(\".jsonl\"));\n for (const file of files) {\n const fullPath = join(dir, file);\n // Read only first line to check header id\n const firstLine = readFileSync(fullPath, \"utf8\").split(\"\\n\")[0];\n try {\n const header = JSON.parse(firstLine) as SessionHeader;\n if (header.type === \"session\" && header.id === sessionId) {\n cache.set(sessionId, fullPath);\n return fullPath;\n }\n } catch { /* skip malformed */ }\n }\n } catch {\n // skip\n }\n }\n } catch {\n // skip\n }\n return null;\n}\n","import type { AgentMessage } from \"./types\";\n\n/**\n * Pi stores toolCall blocks as {id, name, arguments} but our types use\n * {toolCallId, toolName, input}. Normalize both file-read and streaming paths.\n */\nexport function normalizeToolCalls(msg: AgentMessage): AgentMessage {\n if (msg.role !== \"assistant\") return msg;\n const raw = msg as unknown as { content?: unknown[] };\n if (!Array.isArray(raw.content)) return msg;\n const normalized = raw.content.map((block) => {\n const b = block as Record<string, unknown>;\n if (b.type !== \"toolCall\") return b;\n return {\n type: \"toolCall\",\n toolCallId: b.toolCallId ?? b.id,\n toolName: b.toolName ?? b.name,\n input: b.input ?? b.arguments,\n };\n });\n return { ...(msg as object), content: normalized } as unknown as AgentMessage;\n}\n","/**\n * System prompt used when tools are disabled (preset: off).\n * Edit this file to customize what the agent is told in no-tool mode.\n */\n\nexport function buildNoToolsSystemPrompt(_cwd: string): string {\n return `You are a reliable, direct, and practical assistant.\n`;\n}\n","import { createAgentSession, type ResourceLoader } from \"@mariozechner/pi-coding-agent\";\nimport { join } from \"path\";\nimport { homedir } from \"os\";\nimport { buildNoToolsSystemPrompt } from \"./system-prompt-off\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface AgentEvent {\n type: string;\n [key: string]: unknown;\n}\n\ntype EventListener = (event: AgentEvent) => void;\n\n// ============================================================================\n// AgentSessionWrapper\n// Wraps AgentSession with the same interface the rest of the app expects\n// ============================================================================\n\nexport class AgentSessionWrapper {\n private listeners: EventListener[] = [];\n private unsubscribe: (() => void) | null = null;\n private idleTimer: ReturnType<typeof setTimeout> | null = null;\n private onDestroyCallback: (() => void) | null = null;\n private _alive = true;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n constructor(public readonly inner: any) {}\n\n get sessionId(): string {\n return this.inner.sessionId;\n }\n\n get sessionFile(): string {\n return this.inner.sessionFile ?? \"\";\n }\n\n isAlive(): boolean {\n return this._alive;\n }\n\n start(): void {\n this.unsubscribe = this.inner.subscribe((event: AgentEvent) => {\n this.resetIdleTimer();\n for (const l of this.listeners) l(event);\n });\n this.resetIdleTimer();\n }\n\n private resetIdleTimer(): void {\n if (this.idleTimer) clearTimeout(this.idleTimer);\n this.idleTimer = setTimeout(() => this.destroy(), 10 * 60 * 1000);\n }\n\n onEvent(listener: EventListener): () => void {\n this.listeners.push(listener);\n return () => {\n const i = this.listeners.indexOf(listener);\n if (i !== -1) this.listeners.splice(i, 1);\n };\n }\n\n onDestroy(cb: () => void): void {\n this.onDestroyCallback = cb;\n }\n\n async send(command: Record<string, unknown>): Promise<unknown> {\n this.resetIdleTimer();\n const type = command.type as string;\n\n switch (type) {\n case \"prompt\":\n // Fire and forget — events come via subscribe\n this.inner.prompt(command.message as string).catch(() => {});\n return null;\n\n case \"abort\":\n await this.inner.abort();\n return null;\n\n case \"get_state\": {\n const model = this.inner.model;\n return {\n sessionId: this.inner.sessionId,\n sessionFile: this.inner.sessionFile ?? \"\",\n isStreaming: this.inner.isStreaming,\n isCompacting: this.inner.isCompacting ?? false,\n thinkingLevel: this.inner.thinkingLevel ?? \"off\",\n autoCompactionEnabled: this.inner.autoCompactionEnabled ?? false,\n autoRetryEnabled: this.inner.autoRetryEnabled ?? false,\n model: model ? { id: model.id, provider: model.provider } : undefined,\n messageCount: 0,\n pendingMessageCount: 0,\n };\n }\n\n case \"set_model\": {\n const { provider, modelId } = command as { provider: string; modelId: string };\n const registry = this.inner.modelRegistry;\n const model = registry?.find(provider, modelId);\n if (!model) throw new Error(`Model not found: ${provider}/${modelId}`);\n await this.inner.setModel(model);\n return model;\n }\n\n case \"fork\": {\n const result = await this.inner.fork(command.entryId as string);\n if (result.cancelled) return { cancelled: true };\n // After fork, inner.sessionId is the new session's id.\n // Capture it before destroy() clears state.\n const newSessionId = this.inner.sessionId as string;\n // Destroy this wrapper immediately so the next request for the\n // original session reloads a clean AgentSession from its file.\n this.destroy();\n return { cancelled: false, newSessionId };\n }\n\n case \"navigate_tree\": {\n const result = await this.inner.navigateTree(command.targetId as string, {});\n return { cancelled: result.cancelled };\n }\n\n case \"set_thinking_level\": {\n this.inner.setThinkingLevel(command.level as string);\n return null;\n }\n\n case \"compact\": {\n const settings = this.inner.settingsManager.getCompactionSettings();\n const keepRecentTokens: number = settings?.keepRecentTokens ?? 20000;\n const usage = this.inner.getContextUsage();\n const currentTokens: number | null = usage?.tokens ?? null;\n if (currentTokens !== null && currentTokens < keepRecentTokens) {\n throw new Error(\"Conversation too short to compact\");\n }\n const result = await this.inner.compact(command.customInstructions as string | undefined);\n return result;\n }\n\n case \"set_auto_compaction\": {\n this.inner.setAutoCompactionEnabled(command.enabled as boolean);\n return null;\n }\n\n case \"steer\": {\n await this.inner.steer(command.message as string);\n return null;\n }\n\n case \"follow_up\": {\n await this.inner.followUp(command.message as string);\n return null;\n }\n\n case \"get_tools\": {\n const all = this.inner.getAllTools() as Array<{ name: string; description: string }>;\n const active = new Set<string>(this.inner.getActiveToolNames() as string[]);\n return all.map((t: { name: string; description: string }) => ({\n name: t.name,\n description: t.description,\n active: active.has(t.name),\n }));\n }\n\n case \"set_tools\": {\n this.inner.setActiveToolsByName(command.toolNames as string[]);\n return null;\n }\n\n case \"abort_compaction\": {\n this.inner.abortCompaction();\n return null;\n }\n\n case \"set_auto_retry\": {\n this.inner.setAutoRetryEnabled(command.enabled as boolean);\n return null;\n }\n\n default:\n throw new Error(`Unsupported command: ${type}`);\n }\n }\n\n destroy(): void {\n if (!this._alive) return;\n this._alive = false;\n if (this.idleTimer) clearTimeout(this.idleTimer);\n this.unsubscribe?.();\n this.onDestroyCallback?.();\n }\n}\n\n// ============================================================================\n// Session registry\n// ============================================================================\n\ndeclare global {\n var __piSessions: Map<string, AgentSessionWrapper> | undefined;\n var __piStartLocks: Map<string, Promise<{ session: AgentSessionWrapper; realSessionId: string }>> | undefined;\n}\n\nfunction getRegistry(): Map<string, AgentSessionWrapper> {\n if (!globalThis.__piSessions) {\n globalThis.__piSessions = new Map();\n const cleanup = () => globalThis.__piSessions?.forEach((s) => s.destroy());\n process.once(\"exit\", cleanup);\n process.once(\"SIGINT\", cleanup);\n process.once(\"SIGTERM\", cleanup);\n }\n return globalThis.__piSessions;\n}\n\nfunction getLocks(): Map<string, Promise<{ session: AgentSessionWrapper; realSessionId: string }>> {\n if (!globalThis.__piStartLocks) globalThis.__piStartLocks = new Map();\n return globalThis.__piStartLocks;\n}\n\nfunction getAgentDir(): string {\n const env = process.env.PI_CODING_AGENT_DIR;\n if (env) {\n if (env === \"~\") return homedir();\n if (env.startsWith(\"~/\")) return homedir() + env.slice(1);\n return env;\n }\n return join(homedir(), \".pi\", \"agent\");\n}\n\nexport function getRpcSession(sessionId: string): AgentSessionWrapper | undefined {\n return getRegistry().get(sessionId);\n}\n\n\n/**\n * Get or create an AgentSession for the given session.\n * For new sessions (sessionFile === \"\"), pi generates its own id.\n * Pass toolNames to pre-configure active tools (empty array = off).\n */\nexport async function startRpcSession(\n sessionId: string,\n sessionFile: string,\n cwd: string,\n toolNames?: string[]\n): Promise<{ session: AgentSessionWrapper; realSessionId: string }> {\n const registry = getRegistry();\n const locks = getLocks();\n\n const existing = registry.get(sessionId);\n if (existing?.isAlive()) return { session: existing, realSessionId: sessionId };\n\n const inflight = locks.get(sessionId);\n if (inflight) return inflight;\n\n const starting = (async () => {\n const agentDir = getAgentDir();\n\n const { SessionManager } = await import(\"@mariozechner/pi-coding-agent\");\n // Pass undefined for sessionDir so pi derives it from cwd (new) or file path (existing)\n const sessionManager = sessionFile\n ? SessionManager.open(sessionFile, undefined)\n : SessionManager.create(cwd, undefined);\n\n // When tools are explicitly disabled, use a minimal system prompt\n let resourceLoader: ResourceLoader | undefined;\n if (toolNames !== undefined && toolNames.length === 0) {\n const { DefaultResourceLoader } = await import(\"@mariozechner/pi-coding-agent\");\n const prompt = buildNoToolsSystemPrompt(cwd);\n const loader = new DefaultResourceLoader({ cwd, agentDir, systemPromptOverride: () => prompt });\n await loader.reload();\n resourceLoader = loader as ResourceLoader;\n }\n\n // Build tools array from names when caller specifies toolNames\n let toolsOption: unknown[] | undefined;\n if (toolNames !== undefined) {\n const { createReadTool, createBashTool, createEditTool, createWriteTool, createGrepTool, createFindTool, createLsTool } =\n await import(\"@mariozechner/pi-coding-agent\");\n const toolFactories: Record<string, () => unknown> = {\n read: () => createReadTool(cwd),\n bash: () => createBashTool(cwd),\n edit: () => createEditTool(cwd),\n write: () => createWriteTool(cwd),\n grep: () => createGrepTool(cwd),\n find: () => createFindTool(cwd),\n ls: () => createLsTool(cwd),\n };\n toolsOption = toolNames.map((n) => toolFactories[n]?.()).filter(Boolean);\n }\n\n const { session: inner } = await createAgentSession({\n cwd,\n agentDir,\n sessionManager,\n ...(resourceLoader ? { resourceLoader } : {}),\n ...(toolsOption !== undefined ? { tools: toolsOption as never[] } : {}),\n });\n const wrapper = new AgentSessionWrapper(inner);\n wrapper.start();\n\n const realSessionId = inner.sessionId as string;\n\n wrapper.onDestroy(() => registry.delete(realSessionId));\n registry.set(realSessionId, wrapper);\n\n return { session: wrapper, realSessionId };\n })().finally(() => locks.delete(sessionId));\n\n locks.set(sessionId, starting);\n return starting;\n}\n","import { resolveSessionPath, buildSessionInfo } from \"@/lib/session-reader\";\nimport { getRpcSession, startRpcSession } from \"@/lib/rpc-manager\";\n\nexport const dynamic = \"force-dynamic\";\n\n// GET /api/agent/[id]/events - SSE stream of agent events\nexport async function GET(\n req: Request,\n { params }: { params: Promise<{ id: string }> }\n) {\n const { id } = await params;\n\n // Fast path: already-running session\n let session = getRpcSession(id);\n if (!session || !session.isAlive()) {\n const filePath = resolveSessionPath(id);\n if (!filePath) {\n return new Response(\"Session not found\", { status: 404 });\n }\n const info = buildSessionInfo(filePath);\n const cwd = info?.cwd ?? process.cwd();\n try {\n ({ session } = await startRpcSession(id, filePath, cwd));\n } catch (error) {\n return new Response(`Failed to start agent: ${error}`, { status: 500 });\n }\n }\n\n const stream = new ReadableStream({\n start(controller) {\n const encode = (data: unknown) => {\n const text = `data: ${JSON.stringify(data)}\\n\\n`;\n controller.enqueue(new TextEncoder().encode(text));\n };\n\n // Send initial connected event\n encode({ type: \"connected\", sessionId: id });\n\n const unsubscribe = session.onEvent((event) => {\n encode(event);\n });\n\n // Cleanup when client disconnects\n const cleanup = () => {\n unsubscribe();\n controller.close();\n };\n\n // Detect client disconnect via abort signal\n req.signal?.addEventListener(\"abort\", cleanup);\n },\n });\n\n return new Response(stream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n","import {\n AppRouteRouteModule,\n type AppRouteRouteHandlerContext,\n type AppRouteRouteModuleOptions,\n} from '../../server/route-modules/app-route/module.compiled'\nimport { RouteKind } from '../../server/route-kind'\nimport { patchFetch as _patchFetch } from '../../server/lib/patch-fetch'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport {\n addRequestMeta,\n getRequestMeta,\n setRequestMeta,\n type RequestMeta,\n} from '../../server/request-meta'\nimport { getTracer, type Span, SpanKind } from '../../server/lib/trace/tracer'\nimport { setManifestsSingleton } from '../../server/app-render/manifests-singleton'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'\nimport {\n NextRequestAdapter,\n signalFromNodeResponse,\n} from '../../server/web/spec-extension/adapters/next-request'\nimport { BaseServerSpan } from '../../server/lib/trace/constants'\nimport { getRevalidateReason } from '../../server/instrumentation/utils'\nimport { sendResponse } from '../../server/send-response'\nimport {\n fromNodeOutgoingHttpHeaders,\n toNodeOutgoingHttpHeaders,\n} from '../../server/web/utils'\nimport { getCacheControlHeader } from '../../server/lib/cache-control'\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants'\nimport { NoFallbackError } from '../../shared/lib/no-fallback-error.external'\nimport {\n CachedRouteKind,\n type ResponseCacheEntry,\n type ResponseGenerator,\n} from '../../server/response-cache'\n\nimport * as userland from 'VAR_USERLAND'\n\n// These are injected by the loader afterwards. This is injected as a variable\n// instead of a replacement because this could also be `undefined` instead of\n// an empty string.\ndeclare const nextConfigOutput: AppRouteRouteModuleOptions['nextConfigOutput']\n\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\n// INJECT:nextConfigOutput\n\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: 'VAR_DEFINITION_PAGE',\n pathname: 'VAR_DEFINITION_PATHNAME',\n filename: 'VAR_DEFINITION_FILENAME',\n bundlePath: 'VAR_DEFINITION_BUNDLE_PATH',\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: 'VAR_RESOLVED_PAGE_PATH',\n nextConfigOutput,\n userland,\n})\n\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule\n\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage,\n })\n}\n\nexport {\n routeModule,\n workAsyncStorage,\n workUnitAsyncStorage,\n serverHooks,\n patchFetch,\n}\n\nexport async function handler(\n req: IncomingMessage,\n res: ServerResponse,\n ctx: {\n waitUntil?: (prom: Promise<void>) => void\n requestMeta?: RequestMeta\n }\n) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta)\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint())\n }\n let srcPage = 'VAR_DEFINITION_PAGE'\n\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/'\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/'\n }\n const multiZoneDraftMode = process.env\n .__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean\n\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode,\n })\n\n if (!prepareResult) {\n res.statusCode = 400\n res.end('Bad Request')\n ctx.waitUntil?.(Promise.resolve())\n return null\n }\n\n const {\n buildId,\n params,\n nextConfig,\n parsedUrl,\n isDraftMode,\n prerenderManifest,\n routerServerContext,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n resolvedPathname,\n clientReferenceManifest,\n serverActionsManifest,\n } = prepareResult\n\n const normalizedSrcPage = normalizeAppPath(srcPage)\n\n let isIsr = Boolean(\n prerenderManifest.dynamicRoutes[normalizedSrcPage] ||\n prerenderManifest.routes[resolvedPathname]\n )\n\n const render404 = async () => {\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext?.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false)\n } else {\n res.end('This page could not be found')\n }\n return null\n }\n\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname])\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage]\n\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404()\n }\n throw new NoFallbackError()\n }\n }\n }\n\n let cacheKey: string | null = null\n\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey\n }\n\n const supportsDynamicResponse: boolean =\n // If we're in development, we always support dynamic HTML\n routeModule.isDev === true ||\n // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr\n\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse\n\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest,\n })\n }\n\n const method = req.method || 'GET'\n const tracer = getTracer()\n const activeSpan = tracer.getActiveScopeSpan()\n const isWrappedByNextServer = Boolean(\n routerServerContext?.isWrappedByNextServer\n )\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'))\n\n const incrementalCache =\n getRequestMeta(req, 'incrementalCache') ||\n (await routeModule.getIncrementalCache(\n req,\n nextConfig,\n prerenderManifest,\n isMinimalMode\n ))\n\n incrementalCache?.resetRequestCache()\n ;(globalThis as any).__incrementalCache = incrementalCache\n\n const context: AppRouteRouteHandlerContext = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts),\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb) => {\n res.on('close', cb)\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (\n error,\n _request,\n errorContext,\n silenceLog\n ) =>\n routeModule.onRequestError(\n req,\n error,\n errorContext,\n silenceLog,\n routerServerContext\n ),\n },\n sharedContext: {\n buildId,\n },\n }\n const nodeNextReq = new NodeNextRequest(req)\n const nodeNextRes = new NodeNextResponse(res)\n\n const nextReq = NextRequestAdapter.fromNodeNextRequest(\n nodeNextReq,\n signalFromNodeResponse(res)\n )\n\n try {\n let parentSpan: Span | undefined\n const invokeRouteModule = async (span?: Span) => {\n return routeModule.handle(nextReq, context).finally(() => {\n if (!span) return\n\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false,\n })\n\n const rootSpanAttributes = tracer.getRootSpanAttributes()\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return\n }\n\n if (\n rootSpanAttributes.get('next.span_type') !==\n BaseServerSpan.handleRequest\n ) {\n console.warn(\n `Unexpected root span type '${rootSpanAttributes.get(\n 'next.span_type'\n )}'. Please report this Next.js issue https://github.com/vercel/next.js`\n )\n return\n }\n\n const route = rootSpanAttributes.get('next.route')\n if (route) {\n const name = `${method} ${route}`\n\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name,\n })\n span.updateName(name)\n\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route)\n parentSpan.updateName(name)\n }\n } else {\n span.updateName(`${method} ${srcPage}`)\n }\n })\n }\n\n const handleResponse = async (currentSpan?: Span) => {\n const responseGenerator: ResponseGenerator = async ({\n previousCacheEntry,\n }) => {\n try {\n if (\n !isMinimalMode &&\n isOnDemandRevalidate &&\n revalidateOnlyGenerated &&\n !previousCacheEntry\n ) {\n res.statusCode = 404\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED')\n res.end('This page could not be found')\n return null\n }\n\n const response = await invokeRouteModule(currentSpan)\n\n ;(req as any).fetchMetrics = (context.renderOpts as any).fetchMetrics\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil\n\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil)\n pendingWaitUntil = undefined\n }\n }\n const cacheTags = context.renderOpts.collectedTags\n\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob()\n\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers)\n\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags\n }\n\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type\n }\n\n const revalidate =\n typeof context.renderOpts.collectedRevalidate === 'undefined' ||\n context.renderOpts.collectedRevalidate >= INFINITE_CACHE\n ? false\n : context.renderOpts.collectedRevalidate\n\n const expire =\n typeof context.renderOpts.collectedExpire === 'undefined' ||\n context.renderOpts.collectedExpire >= INFINITE_CACHE\n ? undefined\n : context.renderOpts.collectedExpire\n\n // Create the cache entry for the response.\n const cacheEntry: ResponseCacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers,\n },\n cacheControl: { revalidate, expire },\n }\n\n return cacheEntry\n } else {\n // send response without caching if not ISR\n await sendResponse(\n nodeNextReq,\n nodeNextRes,\n response,\n context.renderOpts.pendingWaitUntil\n )\n return null\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry?.isStale) {\n const silenceLog = false\n await routeModule.onRequestError(\n req,\n err,\n {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate,\n }),\n },\n silenceLog,\n routerServerContext\n )\n }\n throw err\n }\n }\n\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode,\n })\n\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null\n }\n\n if (cacheEntry?.value?.kind !== CachedRouteKind.APP_ROUTE) {\n throw new Error(\n `Invariant: app-route received invalid cache entry ${cacheEntry?.value?.kind}`\n )\n }\n\n if (!isMinimalMode) {\n res.setHeader(\n 'x-nextjs-cache',\n isOnDemandRevalidate\n ? 'REVALIDATED'\n : cacheEntry.isMiss\n ? 'MISS'\n : cacheEntry.isStale\n ? 'STALE'\n : 'HIT'\n )\n }\n\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader(\n 'Cache-Control',\n 'private, no-cache, no-store, max-age=0, must-revalidate'\n )\n }\n\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers)\n\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER)\n }\n\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (\n cacheEntry.cacheControl &&\n !res.getHeader('Cache-Control') &&\n !headers.get('Cache-Control')\n ) {\n headers.set(\n 'Cache-Control',\n getCacheControlHeader(cacheEntry.cacheControl)\n )\n }\n\n await sendResponse(\n nodeNextReq,\n nodeNextRes,\n // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200,\n })\n )\n return null\n }\n\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan)\n } else {\n parentSpan = tracer.getActiveScopeSpan()\n await tracer.withPropagatedContext(\n req.headers,\n () =>\n tracer.trace(\n BaseServerSpan.handleRequest,\n {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url,\n },\n },\n handleResponse\n ),\n undefined,\n !isWrappedByNextServer\n )\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false\n await routeModule.onRequestError(\n req,\n err,\n {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate,\n }),\n },\n silenceLog,\n routerServerContext\n )\n }\n\n // rethrow so that we can handle serving error page\n\n // If this is during static generation, throw the error again.\n if (isIsr) throw err\n\n // Otherwise, send a 500 response.\n await sendResponse(\n nodeNextReq,\n nodeNextRes,\n new Response(null, { status: 500 })\n )\n return null\n }\n}\n"],"names":["normalizeToolCalls","msg","role","raw","Array","isArray","content","normalized","map","block","b","type","toolCallId","id","toolName","name","input","arguments","buildNoToolsSystemPrompt","_cwd","AgentSessionWrapper","listeners","unsubscribe","idleTimer","onDestroyCallback","_alive","inner","sessionId","sessionFile","isAlive","start","subscribe","event","resetIdleTimer","l","clearTimeout","setTimeout","destroy","onEvent","listener","push","i","indexOf","splice","onDestroy","cb","send","command","prompt","message","catch","abort","model","isStreaming","isCompacting","thinkingLevel","autoCompactionEnabled","autoRetryEnabled","provider","undefined","messageCount","pendingMessageCount","modelId","registry","modelRegistry","find","Error","setModel","result","fork","entryId","cancelled","newSessionId","navigateTree","targetId","setThinkingLevel","level","settings","settingsManager","getCompactionSettings","keepRecentTokens","usage","getContextUsage","currentTokens","tokens","compact","customInstructions","setAutoCompactionEnabled","enabled","steer","followUp","all","getAllTools","active","Set","getActiveToolNames","t","description","has","setActiveToolsByName","toolNames","abortCompaction","setAutoRetryEnabled","getRegistry","globalThis","__piSessions","Map","cleanup","forEach","s","process","once","getLocks","__piStartLocks","getAgentDir","env","PI_CODING_AGENT_DIR","startsWith","slice","getRpcSession","get","startRpcSession","cwd","locks","existing","session","realSessionId","inflight","starting","agentDir","SessionManager","sessionManager","open","create","resourceLoader","length","DefaultResourceLoader","loader","systemPromptOverride","reload","toolsOption","createReadTool","createBashTool","createEditTool","createWriteTool","createGrepTool","createFindTool","createLsTool","toolFactories","read","bash","edit","write","grep","ls","n","filter","Boolean","tools","wrapper","delete","set","finally","dynamic","GET","req","params","filePath","Response","status","info","error","stream","ReadableStream","controller","encode","data","text","JSON","stringify","enqueue","TextEncoder","close","signal","addEventListener","headers","Connection","AppRouteRouteModule","RouteKind","patchFetch","_patchFetch","addRequestMeta","getRequestMeta","setRequestMeta","getTracer","SpanKind","setManifestsSingleton","normalizeAppPath","NodeNextRequest","NodeNextResponse","NextRequestAdapter","signalFromNodeResponse","BaseServerSpan","getRevalidateReason","sendResponse","fromNodeOutgoingHttpHeaders","toNodeOutgoingHttpHeaders","getCacheControlHeader","INFINITE_CACHE","NEXT_CACHE_TAGS_HEADER","NoFallbackError","CachedRouteKind","userland","routeModule","definition","kind","APP_ROUTE","page","pathname","filename","bundlePath","distDir","__NEXT_RELATIVE_DIST_DIR","relativeProjectDir","__NEXT_RELATIVE_PROJECT_DIR","resolvedPagePath","nextConfigOutput","workAsyncStorage","workUnitAsyncStorage","serverHooks","handler","res","ctx","requestMeta","isDev","hrtime","bigint","srcPage","TURBOPACK","replace","multiZoneDraftMode","__NEXT_MULTI_ZONE_DRAFT_MODE","prepareResult","prepare","statusCode","end","waitUntil","Promise","resolve","buildId","nextConfig","parsedUrl","isDraftMode","prerenderManifest","routerServerContext","isOnDemandRevalidate","revalidateOnlyGenerated","resolvedPathname","clientReferenceManifest","serverActionsManifest","normalizedSrcPage","isIsr","dynamicRoutes","routes","render404","isPrerendered","prerenderInfo","fallback","adapterPath","cacheKey","supportsDynamicResponse","isStaticGeneration","method","tracer","activeSpan","getActiveScopeSpan","isWrappedByNextServer","isMinimalMode","incrementalCache","getIncrementalCache","resetRequestCache","__incrementalCache","context","previewProps","preview","renderOpts","experimental","authInterrupts","cacheComponents","cacheLifeProfiles","cacheLife","onClose","on","onAfterTaskError","onInstrumentationRequestError","_request","errorContext","silenceLog","onRequestError","sharedContext","nodeNextReq","nodeNextRes","nextReq","fromNodeNextRequest","parentSpan","invokeRouteModule","span","handle","setAttributes","rootSpanAttributes","getRootSpanAttributes","handleRequest","console","warn","route","updateName","setAttribute","handleResponse","currentSpan","cacheEntry","responseGenerator","previousCacheEntry","setHeader","response","fetchMetrics","pendingWaitUntil","cacheTags","collectedTags","blob","revalidate","collectedRevalidate","expire","collectedExpire","value","body","Buffer","from","arrayBuffer","cacheControl","err","isStale","routerKind","routePath","routeType","revalidateReason","routeKind","isFallback","isRoutePPREnabled","isMiss","getHeader","withPropagatedContext","trace","spanName","SERVER","attributes","url"],"mappings":"w+BAAA,IAAA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OAiBA,SAAS,IACP,IAAM,EAAS,QAAQ,GAAG,CAAC,mBAAmB,QAC9C,AAAI,EACa,AAAf,KAAoB,CADV,AACN,EAAuB,CAAA,EAAA,EAAA,OAAA,AAAO,IAC9B,EAAO,UAAU,CAAC,MAAc,CAAP,AAAO,EAAA,EAAA,OAAA,AAAO,IAAK,EAAO,KAAK,CAAC,GACtD,EAEF,CAAA,EAAA,EAAA,IAAA,AAAI,EAAC,CAAA,EAAA,EAAA,OAAA,AAAO,IAAI,MAAO,QAChC,CAEOU,SAAS,IACd,MAAO,CAAA,EAAA,EAAA,IAAA,AAAI,EAAC,IAAe,WAC7B,CASA,IAAI,EAA6C,KACjD,SAAS,IACP,GAAI,EAAa,OAAO,EACxB,EAAc,IAAI,IAClB,IAAM,EAAO,CAAA,EAAA,EAAA,IAAA,AAAI,EAAC,IAAe,eACjC,GAAI,CAAC,CAAA,EAAA,EAAA,UAAA,AAAU,EAAC,GAAO,OAAO,EAC9B,GAAI,CACF,IAAM,EAAO,KAAK,KAAK,CAAC,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAM,SAG3C,IAAK,GAAM,CAAC,EAAU,EAAa,GAAI,OAAO,OAAO,CAAC,EAAK,SAAS,EAAI,CAAC,GAAI,AAC3E,IAAK,IAAM,KAAS,EAAa,MAAM,EAAI,E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Y,CACV,cAAelF,EACf,cAAe3G,EAAI8L,GAAG,AACxB,CACF,EACAtC,GAEJlQ,OACA,CAACyN,GAGP,CAAE,MAAO+D,EAAK,CAuBZ,GAtBMA,aAAejI,EAAAA,eAAc,EAEjC,CAFqC,KAE/BG,EAAYqF,cAAc,CAC9BrI,EACA8K,EACA,CACEE,WAAY,aACZC,UAAWlF,EACXmF,UAAW,QACXC,iBAAAA,CAAAA,EAAkB7I,EAAAA,mBAAAA,EAAoB,oBACpCoE,EACAhB,sBACF,EACF,GACA0C,AAbiB,EAcjB3C,GAOAO,EAAO,MAAM8E,EAQjB,OALA,MAAA,CAAA,EAAMvI,EAAAA,YAAAA,EACJgG,EACAC,EACA,IAAIrI,SAAS,KAAM,CAAEC,OAAQ,GAAI,IAE5B,IACT,CACF,mCA3eA,SAASoB,EACP,MAAA,CAAA,EAAOC,EAAAA,UAAAA,EAAY,kBACjBqC,uBACAC,CACF,EACF","ignoreList":[5]}
@@ -0,0 +1,5 @@
1
+ module.exports=[24725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},18622,(e,t,r)=>{t.exports=e.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},56704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},70406,(e,t,r)=>{t.exports=e.x("next/dist/compiled/@opentelemetry/api",()=>require("next/dist/compiled/@opentelemetry/api"))},14747,(e,t,r)=>{t.exports=e.x("path",()=>require("path"))},93695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},22734,(e,t,r)=>{t.exports=e.x("fs",()=>require("fs"))},46786,(e,t,r)=>{t.exports=e.x("os",()=>require("os"))},9890,e=>{"use strict";var t=e.i(22734),r=e.i(14747),n=e.i(46786);function s(){let e=process.env.PI_CODING_AGENT_DIR;return e?"~"===e?(0,n.homedir)():e.startsWith("~/")?(0,n.homedir)()+e.slice(1):e:(0,r.join)((0,n.homedir)(),".pi","agent")}function i(){return(0,r.join)(s(),"sessions")}let o=null;function a(){if(o)return o;o=new Map;let e=(0,r.join)(s(),"models.json");if(!(0,t.existsSync)(e))return o;try{let r=JSON.parse((0,t.readFileSync)(e,"utf8"));for(let[e,t]of Object.entries(r.providers??{}))for(let r of t.models??[])r.id&&r.name&&o.set(`${e}:${r.id}`,{id:r.id,name:r.name,provider:e})}catch{}return o}function l(e){if(!(0,t.existsSync)(e))return[];let r=(0,t.readFileSync)(e,"utf8"),n=[];for(let e of r.trim().split("\n"))if(e.trim())try{n.push(JSON.parse(e))}catch{}return n}function d(e){try{let r,n,s=l(e);if(0===s.length)return null;let i=s[0];if("session"!==i.type)return null;let o=(0,t.statSync)(e),a=i.id,d=i.cwd??"",u=i.timestamp,p=i.parentSession?(n=(i.parentSession.replace(/\\/g,"/").split("/").pop()??"").match(/_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i),n?.[1]):void 0,c=0,f="";for(let e of s){if("session_info"===e.type&&e.name&&(r=e.name.trim()),"message"!==e.type)continue;c++;let t=e.message;if("user"!==t.role&&"assistant"!==t.role)continue;let n=function(e){let t=e.content;return"string"==typeof t?t:Array.isArray(t)?t.filter(e=>"text"===e.type).map(e=>e.text).join(" "):""}(t);f||"user"!==t.role||(f=n)}return{path:e,id:a,cwd:d,name:r,created:u,modified:o.mtime.toISOString(),messageCount:c,firstMessage:f||"(no messages)",parentSessionId:p}}catch{return null}}async function u(){let e=i(),n=[];if(!(0,t.existsSync)(e))return n;try{for(let s of(0,t.readdirSync)(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(t=>(0,r.join)(e,t.name)))try{for(let e of(0,t.readdirSync)(s).filter(e=>e.endsWith(".jsonl")).map(e=>(0,r.join)(s,e))){let t=d(e);t&&n.push(t)}}catch{}}catch{}return n.sort((e,t)=>new Date(t.modified).getTime()-new Date(e.modified).getTime()),n}function p(){return globalThis.__piSessionPathCache||(globalThis.__piSessionPathCache=new Map),globalThis.__piSessionPathCache}e.s(["buildSessionContext",0,function(e,t){let r,n=new Map;for(let t of e)n.set(t.id,t);if(null===t||(t&&(r=n.get(t)),r||(r=e[e.length-1]),!r))return{messages:[],entryIds:[],thinkingLevel:"off",model:null};let s=[],i=r;for(;i;)s.unshift(i),i=i.parentId?n.get(i.parentId):void 0;let o="off",a=null,l=null;for(let e of s)if("thinking_level_change"===e.type)o=e.thinkingLevel;else if("model_change"===e.type)a={provider:e.provider,modelId:e.modelId};else if("message"===e.type&&"assistant"===e.message.role){let t=e.message;a={provider:t.provider,modelId:t.model}}else"compaction"===e.type&&(l=e);let d=[],u=[],p=e=>{"message"===e.type&&(d.push(function(e){if("assistant"!==e.role||!Array.isArray(e.content))return e;let t=e.content.map(e=>"toolCall"!==e.type?e:{type:"toolCall",toolCallId:e.toolCallId??e.id,toolName:e.toolName??e.name,input:e.input??e.arguments});return{...e,content:t}}(e.message)),u.push(e.id))};if(l){let e={role:"user",content:`*The conversation history before this point was compacted into the following summary:*
2
+
3
+ ${l.summary}`,timestamp:new Date(l.timestamp).getTime()};d.push(e),u.push(l.id);let t=s.findIndex(e=>"compaction"===e.type&&e.id===l.id),r=s.findIndex((e,r)=>r<t&&e.id===l.firstKeptEntryId),n=r>=0?r:t;for(let e=n;e<t;e++)p(s[e]);for(let e=t+1;e<s.length;e++)p(s[e])}else for(let e of s)p(e);return{messages:d,entryIds:u,thinkingLevel:o,model:a}},"buildSessionInfo",0,d,"buildTree",0,function(e){let t=new Map;for(let r of e)"label"===r.type&&(r.label?t.set(r.targetId,r.label):t.delete(r.targetId));let r=new Map,n=[];for(let n of e)r.set(n.id,{entry:n,children:[],label:t.get(n.id)});for(let t of e){let e=r.get(t.id);if(t.parentId){let s=r.get(t.parentId);s?s.children.push(e):n.push(e)}else n.push(e)}let s=[...n];for(;s.length>0;){let e=s.pop();e.children.sort((e,t)=>new Date(e.entry.timestamp).getTime()-new Date(t.entry.timestamp).getTime()),s.push(...e.children)}return n},"getDefaultModel",0,function(){let e=(0,r.join)(s(),"settings.json");if(!(0,t.existsSync)(e))return null;try{let r=JSON.parse((0,t.readFileSync)(e,"utf8"));if(!r.defaultProvider)return null;if(r.defaultModel)return{provider:r.defaultProvider,modelId:r.defaultModel};let n=Array.from(a().values()).find(e=>e.provider===r.defaultProvider);if(n)return{provider:n.provider,modelId:n.id}}catch{}return null},"getLeafId",0,function(e){return 0===e.length?null:e[e.length-1].id},"getModelList",0,function(){return Array.from(a().values())},"getModelNameMap",0,function(){let e=new Map;for(let t of a().values())e.set(t.id,t.name);return e},"getSessionEntries",0,function(e){return l(e).filter(e=>"session"!==e.type)},"invalidateModelCache",0,function(){o=null},"invalidateSessionPathCache",0,function(e){p().delete(e)},"listAllSessions",0,u,"resolveSessionPath",0,function(e){let n=p(),s=n.get(e);if(s&&(0,t.existsSync)(s))return s;let o=i();if(!(0,t.existsSync)(o))return null;try{for(let s of(0,t.readdirSync)(o,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>(0,r.join)(o,e.name)))try{for(let i of(0,t.readdirSync)(s).filter(e=>e.endsWith(".jsonl"))){let o=(0,r.join)(s,i),a=(0,t.readFileSync)(o,"utf8").split("\n")[0];try{let t=JSON.parse(a);if("session"===t.type&&t.id===e)return n.set(e,o),o}catch{}}}catch{}}catch{}return null}],9890)},54799,(e,t,r)=>{t.exports=e.x("crypto",()=>require("crypto"))},93371,e=>{"use strict";var t=e.i(47909),r=e.i(74017),n=e.i(96250),s=e.i(59756),i=e.i(61916),o=e.i(74677),a=e.i(69741),l=e.i(16795),d=e.i(87718),u=e.i(95169),p=e.i(47587),c=e.i(66012),f=e.i(70101),h=e.i(74838),m=e.i(10372),y=e.i(93695);e.i(52474);var g=e.i(220),x=e.i(89171),v=e.i(22734),S=e.i(54799),R=e.i(14747),w=e.i(9890);async function C(e,{params:t}){let{id:r}=await t;try{let e=(0,w.resolveSessionPath)(r);if(!e)return x.NextResponse.json({error:"Session not found"},{status:404});let t=(0,w.getSessionEntries)(e),n=(0,w.buildTree)(t),s=(0,w.getLeafId)(t),i=(0,w.buildSessionContext)(t,s),o=(0,w.buildSessionInfo)(e);return x.NextResponse.json({sessionId:r,filePath:e,info:o,tree:n,leafId:s,context:i})}catch(e){return x.NextResponse.json({error:String(e)},{status:500})}}async function E(e,{params:t}){let{id:r}=await t;try{let{name:t}=await e.json();if("string"!=typeof t)return x.NextResponse.json({error:"name is required"},{status:400});let n=(0,w.resolveSessionPath)(r);if(!n)return x.NextResponse.json({error:"Session not found"},{status:404});let s=(0,w.getSessionEntries)(n),i=(0,w.getLeafId)(s),o={type:"session_info",id:(0,S.randomUUID)(),parentId:i,timestamp:new Date().toISOString(),name:t.trim()};return(0,v.appendFileSync)(n,JSON.stringify(o)+"\n"),x.NextResponse.json({ok:!0})}catch(e){return x.NextResponse.json({error:String(e)},{status:500})}}async function j(e,{params:t}){let{id:r}=await t;try{let e,t=(0,w.resolveSessionPath)(r);if(!t)return x.NextResponse.json({error:"Session not found"},{status:404});let n=(0,v.readFileSync)(t,"utf8").split("\n")[0];try{let t=JSON.parse(n);"session"===t.type&&(e=t.parentSession)}catch{}let s=t.replace(/\\/g,"/").split("/").slice(0,-1).join("/");try{for(let r of(0,v.readdirSync)(s).filter(e=>e.endsWith(".jsonl")&&(0,R.join)(s,e)!==t)){let n=(0,R.join)(s,r);try{let r=(0,v.readFileSync)(n,"utf8").split("\n"),s=JSON.parse(r[0]);"session"===s.type&&s.parentSession===t&&(s.parentSession=e,r[0]=JSON.stringify(s),(0,v.writeFileSync)(n,r.join("\n")))}catch{}}}catch{}return(0,v.unlinkSync)(t),(0,w.invalidateSessionPathCache)(r),x.NextResponse.json({ok:!0})}catch(e){return x.NextResponse.json({error:String(e)},{status:500})}}e.s(["DELETE",0,j,"GET",0,C,"PATCH",0,E],40784);var N=e.i(40784);let I=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/sessions/[id]/route",pathname:"/api/sessions/[id]",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/sessions/[id]/route.ts",nextConfigOutput:"",userland:N}),{workAsyncStorage:b,workUnitAsyncStorage:T,serverHooks:A}=I;async function P(e,t,n){n.requestMeta&&(0,s.setRequestMeta)(e,n.requestMeta),I.isDev&&(0,s.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let x="/api/sessions/[id]/route";x=x.replace(/\/index$/,"")||"/";let v=await I.prepare(e,t,{srcPage:x,multiZoneDraftMode:!1});if(!v)return t.statusCode=400,t.end("Bad Request"),null==n.waitUntil||n.waitUntil.call(n,Promise.resolve()),null;let{buildId:S,params:R,nextConfig:w,parsedUrl:C,isDraftMode:E,prerenderManifest:j,routerServerContext:N,isOnDemandRevalidate:b,revalidateOnlyGenerated:T,resolvedPathname:A,clientReferenceManifest:P,serverActionsManifest:_}=v,O=(0,a.normalizeAppPath)(x),q=!!(j.dynamicRoutes[O]||j.routes[A]),M=async()=>((null==N?void 0:N.render404)?await N.render404(e,t,C,!1):t.end("This page could not be found"),null);if(q&&!E){let e=!!j.routes[A],t=j.dynamicRoutes[O];if(t&&!1===t.fallback&&!e){if(w.adapterPath)return await M();throw new y.NoFallbackError}}let k=null;!q||I.isDev||E||(k="/index"===(k=A)?"/":k);let D=!0===I.isDev||!q,F=q&&!D;_&&P&&(0,o.setManifestsSingleton)({page:x,clientReferenceManifest:P,serverActionsManifest:_});let H=e.method||"GET",U=(0,i.getTracer)(),$=U.getActiveScopeSpan(),L=!!(null==N?void 0:N.isWrappedByNextServer),K=!!(0,s.getRequestMeta)(e,"minimalMode"),J=(0,s.getRequestMeta)(e,"incrementalCache")||await I.getIncrementalCache(e,w,j,K);null==J||J.resetRequestCache(),globalThis.__incrementalCache=J;let W={params:R,previewProps:j.preview,renderOpts:{experimental:{authInterrupts:!!w.experimental.authInterrupts},cacheComponents:!!w.cacheComponents,supportsDynamicResponse:D,incrementalCache:J,cacheLifeProfiles:w.cacheLife,waitUntil:n.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,n,s)=>I.onRequestError(e,t,n,s,N)},sharedContext:{buildId:S}},B=new l.NodeNextRequest(e),G=new l.NodeNextResponse(t),V=d.NextRequestAdapter.fromNodeNextRequest(B,(0,d.signalFromNodeResponse)(t));try{let s,o=async e=>I.handle(V,W).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=U.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==u.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=r.get("next.route");if(n){let t=`${H} ${n}`;e.setAttributes({"next.route":n,"http.route":n,"next.span_name":t}),e.updateName(t),s&&s!==e&&(s.setAttribute("http.route",n),s.updateName(t))}else e.updateName(`${H} ${x}`)}),a=async s=>{var i,a;let l=async({previousCacheEntry:r})=>{try{if(!K&&b&&T&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let i=await o(s);e.fetchMetrics=W.renderOpts.fetchMetrics;let a=W.renderOpts.pendingWaitUntil;a&&n.waitUntil&&(n.waitUntil(a),a=void 0);let l=W.renderOpts.collectedTags;if(!q)return await (0,c.sendResponse)(B,G,i,W.renderOpts.pendingWaitUntil),null;{let e=await i.blob(),t=(0,f.toNodeOutgoingHttpHeaders)(i.headers);l&&(t[m.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==W.renderOpts.collectedRevalidate&&!(W.renderOpts.collectedRevalidate>=m.INFINITE_CACHE)&&W.renderOpts.collectedRevalidate,n=void 0===W.renderOpts.collectedExpire||W.renderOpts.collectedExpire>=m.INFINITE_CACHE?void 0:W.renderOpts.collectedExpire;return{value:{kind:g.CachedRouteKind.APP_ROUTE,status:i.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:n}}}}catch(t){throw(null==r?void 0:r.isStale)&&await I.onRequestError(e,t,{routerKind:"App Router",routePath:x,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:F,isOnDemandRevalidate:b})},!1,N),t}},d=await I.handleResponse({req:e,nextConfig:w,cacheKey:k,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:j,isRoutePPREnabled:!1,isOnDemandRevalidate:b,revalidateOnlyGenerated:T,responseGenerator:l,waitUntil:n.waitUntil,isMinimalMode:K});if(!q)return null;if((null==d||null==(i=d.value)?void 0:i.kind)!==g.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==d||null==(a=d.value)?void 0:a.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});K||t.setHeader("x-nextjs-cache",b?"REVALIDATED":d.isMiss?"MISS":d.isStale?"STALE":"HIT"),E&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let u=(0,f.fromNodeOutgoingHttpHeaders)(d.value.headers);return K&&q||u.delete(m.NEXT_CACHE_TAGS_HEADER),!d.cacheControl||t.getHeader("Cache-Control")||u.get("Cache-Control")||u.set("Cache-Control",(0,h.getCacheControlHeader)(d.cacheControl)),await (0,c.sendResponse)(B,G,new Response(d.value.body,{headers:u,status:d.value.status||200})),null};L&&$?await a($):(s=U.getActiveScopeSpan(),await U.withPropagatedContext(e.headers,()=>U.trace(u.BaseServerSpan.handleRequest,{spanName:`${H} ${x}`,kind:i.SpanKind.SERVER,attributes:{"http.method":H,"http.target":e.url}},a),void 0,!L))}catch(t){if(t instanceof y.NoFallbackError||await I.onRequestError(e,t,{routerKind:"App Router",routePath:O,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:F,isOnDemandRevalidate:b})},!1,N),q)throw t;return await (0,c.sendResponse)(B,G,new Response(null,{status:500})),null}}e.s(["handler",0,P,"patchFetch",0,function(){return(0,n.patchFetch)({workAsyncStorage:b,workUnitAsyncStorage:T})},"routeModule",0,I,"serverHooks",0,A,"workAsyncStorage",0,b,"workUnitAsyncStorage",0,T],93371)}];
4
+
5
+ //# sourceMappingURL=%5Broot-of-the-server%5D__0cw6f~v._.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../lib/session-reader.ts","../../../lib/normalize.ts","../../../node_modules/next/dist/esm/build/templates/app-route.js","../../../app/api/sessions/%5Bid%5D/route.ts"],"sourcesContent":["import { readFileSync, readdirSync, statSync, existsSync } from \"fs\";\nimport { join } from \"path\";\nimport { homedir } from \"os\";\nimport type {\n FileEntry,\n SessionEntry,\n SessionHeader,\n SessionInfo,\n SessionTreeNode,\n SessionMessageEntry,\n SessionInfoEntry,\n LabelEntry,\n AgentMessage,\n SessionContext,\n CompactionEntry,\n TextContent,\n} from \"./types\";\nimport { normalizeToolCalls } from \"./normalize\";\n\nfunction getAgentDir(): string {\n const envDir = process.env.PI_CODING_AGENT_DIR;\n if (envDir) {\n if (envDir === \"~\") return homedir();\n if (envDir.startsWith(\"~/\")) return homedir() + envDir.slice(1);\n return envDir;\n }\n return join(homedir(), \".pi\", \"agent\");\n}\n\nexport function getSessionsDir(): string {\n return join(getAgentDir(), \"sessions\");\n}\n\nexport interface ModelInfo {\n id: string;\n name: string;\n provider: string;\n}\n\n// Build a map of \"provider:modelId\" -> ModelInfo from ~/.pi/agent/models.json\nlet _modelCache: Map<string, ModelInfo> | null = null;\nfunction getModelCache(): Map<string, ModelInfo> {\n if (_modelCache) return _modelCache;\n _modelCache = new Map();\n const path = join(getAgentDir(), \"models.json\");\n if (!existsSync(path)) return _modelCache;\n try {\n const data = JSON.parse(readFileSync(path, \"utf8\")) as {\n providers?: Record<string, { models?: { id: string; name?: string }[] }>;\n };\n for (const [provider, providerData] of Object.entries(data.providers ?? {})) {\n for (const model of providerData.models ?? []) {\n if (model.id && model.name) {\n _modelCache.set(`${provider}:${model.id}`, { id: model.id, name: model.name, provider });\n }\n }\n }\n } catch { /* ignore */ }\n return _modelCache;\n}\n\nexport function getModelNameMap(): Map<string, string> {\n const result = new Map<string, string>();\n for (const info of getModelCache().values()) result.set(info.id, info.name);\n return result;\n}\n\nexport function getModelList(): ModelInfo[] {\n return Array.from(getModelCache().values());\n}\n\nexport function invalidateModelCache(): void {\n _modelCache = null;\n}\n\nexport function getDefaultModel(): { provider: string; modelId: string } | null {\n const path = join(getAgentDir(), \"settings.json\");\n if (!existsSync(path)) return null;\n try {\n const data = JSON.parse(readFileSync(path, \"utf8\")) as {\n defaultProvider?: string;\n defaultModel?: string;\n };\n if (!data.defaultProvider) return null;\n if (data.defaultModel) {\n return { provider: data.defaultProvider, modelId: data.defaultModel };\n }\n // Only provider saved — pick the first model from that provider in models.json\n const first = Array.from(getModelCache().values()).find((m) => m.provider === data.defaultProvider);\n if (first) return { provider: first.provider, modelId: first.id };\n } catch { /* ignore */ }\n return null;\n}\n\nexport function parseSessionFile(filePath: string): FileEntry[] {\n if (!existsSync(filePath)) return [];\n const content = readFileSync(filePath, \"utf8\");\n const entries: FileEntry[] = [];\n for (const line of content.trim().split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n entries.push(JSON.parse(line) as FileEntry);\n } catch {\n // skip malformed lines\n }\n }\n return entries;\n}\n\nfunction extractTextContent(message: AgentMessage): string {\n const content = (message as { content: unknown }).content;\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .filter((b): b is TextContent => b.type === \"text\")\n .map((b) => b.text)\n .join(\" \");\n}\n\n// Extract session UUID from a session file path like \".../2026-03-18T12-11-02-213Z_20a1e7e5-991f-4b91-856d-14dd2d256f20.jsonl\"\nfunction extractSessionIdFromPath(filePath: string): string | undefined {\n const base = filePath.replace(/\\\\/g, \"/\").split(\"/\").pop() ?? \"\";\n // format: <timestamp>_<uuid>.jsonl\n const match = base.match(/_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\.jsonl$/i);\n return match?.[1];\n}\n\nexport function buildSessionInfo(filePath: string): SessionInfo | null {\n try {\n const entries = parseSessionFile(filePath);\n if (entries.length === 0) return null;\n\n // Skip files without a valid session header (incomplete fork artifacts)\n const maybeHeader = entries[0] as SessionHeader;\n if (maybeHeader.type !== \"session\") return null;\n\n const stats = statSync(filePath);\n const id = maybeHeader.id;\n const cwd = maybeHeader.cwd ?? \"\";\n const created = maybeHeader.timestamp;\n const parentSessionId = maybeHeader.parentSession\n ? extractSessionIdFromPath(maybeHeader.parentSession)\n : undefined;\n\n let messageCount = 0;\n let firstMessage = \"\";\n let name: string | undefined;\n\n for (const entry of entries) {\n if (entry.type === \"session_info\") {\n const e = entry as SessionInfoEntry;\n if (e.name) name = e.name.trim();\n }\n if (entry.type !== \"message\") continue;\n messageCount++;\n const msg = (entry as SessionMessageEntry).message;\n if (msg.role !== \"user\" && msg.role !== \"assistant\") continue;\n const text = extractTextContent(msg);\n if (!firstMessage && msg.role === \"user\") firstMessage = text;\n }\n\n return {\n path: filePath,\n id,\n cwd,\n name,\n created,\n modified: stats.mtime.toISOString(),\n messageCount,\n firstMessage: firstMessage || \"(no messages)\",\n parentSessionId,\n };\n } catch {\n return null;\n }\n}\n\nexport async function listAllSessions(): Promise<SessionInfo[]> {\n const sessionsDir = getSessionsDir();\n const sessions: SessionInfo[] = [];\n if (!existsSync(sessionsDir)) return sessions;\n\n try {\n const dirs = readdirSync(sessionsDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(sessionsDir, e.name));\n\n for (const dir of dirs) {\n try {\n const files = readdirSync(dir)\n .filter((f) => f.endsWith(\".jsonl\"))\n .map((f) => join(dir, f));\n for (const file of files) {\n const info = buildSessionInfo(file);\n if (info) sessions.push(info);\n }\n } catch {\n // skip unreadable dir\n }\n }\n } catch {\n // skip\n }\n\n sessions.sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());\n return sessions;\n}\n\nexport function getSessionEntries(filePath: string): SessionEntry[] {\n const entries = parseSessionFile(filePath);\n return entries.filter((e): e is SessionEntry => e.type !== \"session\");\n}\n\nexport function buildTree(entries: SessionEntry[]): SessionTreeNode[] {\n const labelsById = new Map<string, string>();\n for (const entry of entries) {\n if (entry.type === \"label\") {\n const l = entry as LabelEntry;\n if (l.label) labelsById.set(l.targetId, l.label);\n else labelsById.delete(l.targetId);\n }\n }\n\n const nodeMap = new Map<string, SessionTreeNode>();\n const roots: SessionTreeNode[] = [];\n\n for (const entry of entries) {\n nodeMap.set(entry.id, { entry, children: [], label: labelsById.get(entry.id) });\n }\n\n for (const entry of entries) {\n const node = nodeMap.get(entry.id)!;\n if (!entry.parentId) {\n roots.push(node);\n } else {\n const parent = nodeMap.get(entry.parentId);\n if (parent) {\n parent.children.push(node);\n } else {\n roots.push(node);\n }\n }\n }\n\n // sort children by timestamp\n const stack = [...roots];\n while (stack.length > 0) {\n const node = stack.pop()!;\n node.children.sort(\n (a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime()\n );\n stack.push(...node.children);\n }\n\n return roots;\n}\n\n\n\nexport function buildSessionContext(\n entries: SessionEntry[],\n leafId?: string | null\n): SessionContext {\n const byId = new Map<string, SessionEntry>();\n for (const entry of entries) {\n byId.set(entry.id, entry);\n }\n\n let leaf: SessionEntry | undefined;\n if (leafId === null) {\n return { messages: [], entryIds: [], thinkingLevel: \"off\", model: null };\n }\n if (leafId) {\n leaf = byId.get(leafId);\n }\n if (!leaf) {\n leaf = entries[entries.length - 1];\n }\n if (!leaf) {\n return { messages: [], entryIds: [], thinkingLevel: \"off\", model: null };\n }\n\n // walk from leaf to root\n const path: SessionEntry[] = [];\n let current: SessionEntry | undefined = leaf;\n while (current) {\n path.unshift(current);\n current = current.parentId ? byId.get(current.parentId) : undefined;\n }\n\n let thinkingLevel = \"off\";\n let model: { provider: string; modelId: string } | null = null;\n let compaction: CompactionEntry | null = null;\n\n for (const entry of path) {\n if (entry.type === \"thinking_level_change\") {\n thinkingLevel = entry.thinkingLevel;\n } else if (entry.type === \"model_change\") {\n model = { provider: entry.provider, modelId: entry.modelId };\n } else if (entry.type === \"message\" && (entry as SessionMessageEntry).message.role === \"assistant\") {\n const msg = (entry as SessionMessageEntry).message as { provider: string; model: string };\n model = { provider: msg.provider, modelId: msg.model };\n } else if (entry.type === \"compaction\") {\n compaction = entry as CompactionEntry;\n }\n }\n\n const messages: AgentMessage[] = [];\n const entryIds: string[] = [];\n\n const appendMessage = (entry: SessionEntry) => {\n if (entry.type === \"message\") {\n messages.push(normalizeToolCalls((entry as SessionMessageEntry).message));\n entryIds.push(entry.id);\n }\n };\n\n if (compaction) {\n // Inject compaction summary as a virtual user message matching agent's format\n const summaryMsg: AgentMessage = {\n role: \"user\",\n content: `*The conversation history before this point was compacted into the following summary:*\\n\\n${compaction.summary}`,\n timestamp: new Date(compaction.timestamp).getTime(),\n };\n messages.push(summaryMsg);\n entryIds.push(compaction.id);\n\n const compactionIdx = path.findIndex(\n (e) => e.type === \"compaction\" && e.id === compaction!.id\n );\n // Find firstKeptEntryId before the compaction node; if not found, skip all pre-compaction entries\n const firstKeptIdx = path.findIndex(\n (e, i) => i < compactionIdx && e.id === compaction!.firstKeptEntryId\n );\n const startIdx = firstKeptIdx >= 0 ? firstKeptIdx : compactionIdx;\n for (let i = startIdx; i < compactionIdx; i++) {\n appendMessage(path[i]);\n }\n for (let i = compactionIdx + 1; i < path.length; i++) {\n appendMessage(path[i]);\n }\n } else {\n for (const entry of path) {\n appendMessage(entry);\n }\n }\n\n return { messages, entryIds, thinkingLevel, model };\n}\n\nexport function getLeafId(entries: SessionEntry[]): string | null {\n if (entries.length === 0) return null;\n return entries[entries.length - 1].id;\n}\n\n// ============================================================================\n// Session path cache: sessionId → absolute file path\n// Stored in globalThis for hot-reload safety (same as rpc-manager registry)\n// ============================================================================\ndeclare global {\n var __piSessionPathCache: Map<string, string> | undefined;\n}\n\nfunction getPathCache(): Map<string, string> {\n if (!globalThis.__piSessionPathCache) globalThis.__piSessionPathCache = new Map();\n return globalThis.__piSessionPathCache;\n}\n\nexport function invalidateSessionPathCache(sessionId: string): void {\n getPathCache().delete(sessionId);\n}\n\nexport function resolveSessionPath(sessionId: string): string | null {\n const cache = getPathCache();\n const cached = cache.get(sessionId);\n if (cached && existsSync(cached)) return cached;\n\n const sessionsDir = getSessionsDir();\n if (!existsSync(sessionsDir)) return null;\n try {\n const dirs = readdirSync(sessionsDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(sessionsDir, e.name));\n for (const dir of dirs) {\n try {\n const files = readdirSync(dir).filter((f) => f.endsWith(\".jsonl\"));\n for (const file of files) {\n const fullPath = join(dir, file);\n // Read only first line to check header id\n const firstLine = readFileSync(fullPath, \"utf8\").split(\"\\n\")[0];\n try {\n const header = JSON.parse(firstLine) as SessionHeader;\n if (header.type === \"session\" && header.id === sessionId) {\n cache.set(sessionId, fullPath);\n return fullPath;\n }\n } catch { /* skip malformed */ }\n }\n } catch {\n // skip\n }\n }\n } catch {\n // skip\n }\n return null;\n}\n","import type { AgentMessage } from \"./types\";\n\n/**\n * Pi stores toolCall blocks as {id, name, arguments} but our types use\n * {toolCallId, toolName, input}. Normalize both file-read and streaming paths.\n */\nexport function normalizeToolCalls(msg: AgentMessage): AgentMessage {\n if (msg.role !== \"assistant\") return msg;\n const raw = msg as unknown as { content?: unknown[] };\n if (!Array.isArray(raw.content)) return msg;\n const normalized = raw.content.map((block) => {\n const b = block as Record<string, unknown>;\n if (b.type !== \"toolCall\") return b;\n return {\n type: \"toolCall\",\n toolCallId: b.toolCallId ?? b.id,\n toolName: b.toolName ?? b.name,\n input: b.input ?? b.arguments,\n };\n });\n return { ...(msg as object), content: normalized } as unknown as AgentMessage;\n}\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/esm/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/sessions/[id]/route\",\n pathname: \"/api/sessions/[id]\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/app/api/sessions/[id]/route.ts\",\n nextConfigOutput,\n userland\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/sessions/[id]/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","import { NextResponse } from \"next/server\";\nimport { appendFileSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from \"fs\";\nimport { randomUUID } from \"crypto\";\nimport { join } from \"path\";\nimport {\n resolveSessionPath,\n invalidateSessionPathCache,\n getSessionEntries,\n buildTree,\n buildSessionContext,\n getLeafId,\n buildSessionInfo,\n} from \"@/lib/session-reader\";\n\nexport async function GET(\n _req: Request,\n { params }: { params: Promise<{ id: string }> }\n) {\n const { id } = await params;\n try {\n const filePath = resolveSessionPath(id);\n if (!filePath) {\n return NextResponse.json({ error: \"Session not found\" }, { status: 404 });\n }\n\n const entries = getSessionEntries(filePath);\n const tree = buildTree(entries);\n const leafId = getLeafId(entries);\n const context = buildSessionContext(entries, leafId);\n const info = buildSessionInfo(filePath);\n\n return NextResponse.json({\n sessionId: id,\n filePath,\n info,\n tree,\n leafId,\n context,\n });\n } catch (error) {\n return NextResponse.json({ error: String(error) }, { status: 500 });\n }\n}\n\n// PATCH /api/sessions/[id] body: { name: string }\nexport async function PATCH(\n req: Request,\n { params }: { params: Promise<{ id: string }> }\n) {\n const { id } = await params;\n try {\n const { name } = await req.json() as { name?: string };\n if (typeof name !== \"string\") {\n return NextResponse.json({ error: \"name is required\" }, { status: 400 });\n }\n const filePath = resolveSessionPath(id);\n if (!filePath) {\n return NextResponse.json({ error: \"Session not found\" }, { status: 404 });\n }\n const entries = getSessionEntries(filePath);\n const leafId = getLeafId(entries);\n const entry = {\n type: \"session_info\",\n id: randomUUID(),\n parentId: leafId,\n timestamp: new Date().toISOString(),\n name: name.trim(),\n };\n appendFileSync(filePath, JSON.stringify(entry) + \"\\n\");\n return NextResponse.json({ ok: true });\n } catch (error) {\n return NextResponse.json({ error: String(error) }, { status: 500 });\n }\n}\n\n// DELETE /api/sessions/[id]\nexport async function DELETE(\n _req: Request,\n { params }: { params: Promise<{ id: string }> }\n) {\n const { id } = await params;\n try {\n const filePath = resolveSessionPath(id);\n if (!filePath) {\n return NextResponse.json({ error: \"Session not found\" }, { status: 404 });\n }\n\n // Read header before deleting to get parentSession path\n const firstLine = readFileSync(filePath, \"utf8\").split(\"\\n\")[0];\n let parentSessionPath: string | undefined;\n try {\n const header = JSON.parse(firstLine) as { type?: string; parentSession?: string };\n if (header.type === \"session\") parentSessionPath = header.parentSession;\n } catch { /* ignore */ }\n\n // Re-attach all direct children to this session's parent (cascade re-parent)\n // Scan sibling files in the same directory\n const dir = filePath.replace(/\\\\/g, \"/\").split(\"/\").slice(0, -1).join(\"/\");\n try {\n const files = readdirSync(dir).filter((f) => f.endsWith(\".jsonl\") && join(dir, f) !== filePath);\n for (const file of files) {\n const childPath = join(dir, file);\n try {\n const content = readFileSync(childPath, \"utf8\");\n const lines = content.split(\"\\n\");\n const header = JSON.parse(lines[0]) as { type?: string; parentSession?: string };\n if (header.type === \"session\" && header.parentSession === filePath) {\n // Rewrite header with new parentSession\n header.parentSession = parentSessionPath;\n lines[0] = JSON.stringify(header);\n writeFileSync(childPath, lines.join(\"\\n\"));\n }\n } catch { /* skip malformed */ }\n }\n } catch { /* skip if dir unreadable */ }\n\n unlinkSync(filePath);\n invalidateSessionPathCache(id);\n return NextResponse.json({ ok: true });\n } catch (error) {\n return NextResponse.json({ error: String(error) }, { status: 500 });\n }\n}\n"],"names":["normalizeToolCalls","msg","role","raw","Array","isArray","content","normalized","map","block","b","type","toolCallId","id","toolName","name","input","arguments","context","GET","_req","params","filePath","json","error","status","entries","tree","leafId","info","sessionId","String","PATCH","req","dir","entry","parentId","timestamp","Date","toISOString","trim","JSON","stringify","ok","parentSessionPath","DELETE","firstLine","split","header","parse","parentSession","replace","slice","join","files","filter","f","endsWith","file","childPath","lines"],"mappings":"2pCAAA,IAAA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OAiBA,SAAS,IACP,IAAM,EAAS,QAAQ,GAAG,CAAC,mBAAmB,QAC9C,AAAI,EACF,AAAe,KAAK,CADV,AACN,EAAuB,CAAA,EAAA,EAAA,OAAA,AAAO,IAC9B,EAAO,UAAU,CAAC,MAAc,CAAP,AAAO,EAAA,EAAA,OAAO,AAAP,IAAY,EAAO,KAAK,CAAC,GACtD,EAEF,CAAA,EAAA,EAAA,IAAA,AAAI,EAAC,CAAA,EAAA,EAAA,OAAA,AAAO,IAAI,MAAO,QAChC,CAEOU,SAAS,IACd,MAAO,CAAA,EAAA,EAAA,IAAA,AAAI,EAAC,IAAe,WAC7B,CASA,IAAI,EAA6C,KACjD,SAAS,IACP,GAAI,EAAa,OAAO,EACxB,EAAc,IAAI,IAClB,IAAM,EAAO,CAAA,EAAA,EAAA,IAAA,AAAI,EAAC,IAAe,eACjC,GAAI,CAAC,CAAA,EAAA,EAAA,UAAA,AAAU,EAAC,GAAO,OAAO,EAC9B,GAAI,CACF,IAAM,EAAO,KAAK,KAAK,CAAC,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAM,SAG3C,IAAK,GAAM,CAAC,EAAU,EAAa,GAAI,OAAO,OAAO,CAAC,EAAK,SAAS,EAAI,CAAC,GACvE,AAD2E,IACtE,IAAM,KAAS,EAAa,MAAM,EAAI,EAAE,CAAE,AACzC,EAAM,EAAE,EAAI,EAAM,IAAI,EAAE,AAC1B,E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,MAAM,EAKjB,OAHA,MAAM,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAa,EAAa,IAAI,SAAS,KAAM,CAC5D,OAAQ,GACZ,IACO,IACX,CACJ,mCA3TA,SAAS,EACL,MAAO,CAAA,EAAA,EAAA,UAAW,AAAX,EAAY,kBACf,uBACA,CACJ,EACJ","ignoreList":[2]}
@@ -0,0 +1,5 @@
1
+ module.exports=[24725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},18622,(e,t,r)=>{t.exports=e.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},56704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},32319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},70406,(e,t,r)=>{t.exports=e.x("next/dist/compiled/@opentelemetry/api",()=>require("next/dist/compiled/@opentelemetry/api"))},14747,(e,t,r)=>{t.exports=e.x("path",()=>require("path"))},93695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},22734,(e,t,r)=>{t.exports=e.x("fs",()=>require("fs"))},46786,(e,t,r)=>{t.exports=e.x("os",()=>require("os"))},9890,e=>{"use strict";var t=e.i(22734),r=e.i(14747),n=e.i(46786);function s(){let e=process.env.PI_CODING_AGENT_DIR;return e?"~"===e?(0,n.homedir)():e.startsWith("~/")?(0,n.homedir)()+e.slice(1):e:(0,r.join)((0,n.homedir)(),".pi","agent")}function i(){return(0,r.join)(s(),"sessions")}let a=null;function o(){if(a)return a;a=new Map;let e=(0,r.join)(s(),"models.json");if(!(0,t.existsSync)(e))return a;try{let r=JSON.parse((0,t.readFileSync)(e,"utf8"));for(let[e,t]of Object.entries(r.providers??{}))for(let r of t.models??[])r.id&&r.name&&a.set(`${e}:${r.id}`,{id:r.id,name:r.name,provider:e})}catch{}return a}function l(e){if(!(0,t.existsSync)(e))return[];let r=(0,t.readFileSync)(e,"utf8"),n=[];for(let e of r.trim().split("\n"))if(e.trim())try{n.push(JSON.parse(e))}catch{}return n}function d(e){try{let r,n,s=l(e);if(0===s.length)return null;let i=s[0];if("session"!==i.type)return null;let a=(0,t.statSync)(e),o=i.id,d=i.cwd??"",u=i.timestamp,p=i.parentSession?(n=(i.parentSession.replace(/\\/g,"/").split("/").pop()??"").match(/_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i),n?.[1]):void 0,c=0,f="";for(let e of s){if("session_info"===e.type&&e.name&&(r=e.name.trim()),"message"!==e.type)continue;c++;let t=e.message;if("user"!==t.role&&"assistant"!==t.role)continue;let n=function(e){let t=e.content;return"string"==typeof t?t:Array.isArray(t)?t.filter(e=>"text"===e.type).map(e=>e.text).join(" "):""}(t);f||"user"!==t.role||(f=n)}return{path:e,id:o,cwd:d,name:r,created:u,modified:a.mtime.toISOString(),messageCount:c,firstMessage:f||"(no messages)",parentSessionId:p}}catch{return null}}async function u(){let e=i(),n=[];if(!(0,t.existsSync)(e))return n;try{for(let s of(0,t.readdirSync)(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(t=>(0,r.join)(e,t.name)))try{for(let e of(0,t.readdirSync)(s).filter(e=>e.endsWith(".jsonl")).map(e=>(0,r.join)(s,e))){let t=d(e);t&&n.push(t)}}catch{}}catch{}return n.sort((e,t)=>new Date(t.modified).getTime()-new Date(e.modified).getTime()),n}function p(){return globalThis.__piSessionPathCache||(globalThis.__piSessionPathCache=new Map),globalThis.__piSessionPathCache}e.s(["buildSessionContext",0,function(e,t){let r,n=new Map;for(let t of e)n.set(t.id,t);if(null===t||(t&&(r=n.get(t)),r||(r=e[e.length-1]),!r))return{messages:[],entryIds:[],thinkingLevel:"off",model:null};let s=[],i=r;for(;i;)s.unshift(i),i=i.parentId?n.get(i.parentId):void 0;let a="off",o=null,l=null;for(let e of s)if("thinking_level_change"===e.type)a=e.thinkingLevel;else if("model_change"===e.type)o={provider:e.provider,modelId:e.modelId};else if("message"===e.type&&"assistant"===e.message.role){let t=e.message;o={provider:t.provider,modelId:t.model}}else"compaction"===e.type&&(l=e);let d=[],u=[],p=e=>{"message"===e.type&&(d.push(function(e){if("assistant"!==e.role||!Array.isArray(e.content))return e;let t=e.content.map(e=>"toolCall"!==e.type?e:{type:"toolCall",toolCallId:e.toolCallId??e.id,toolName:e.toolName??e.name,input:e.input??e.arguments});return{...e,content:t}}(e.message)),u.push(e.id))};if(l){let e={role:"user",content:`*The conversation history before this point was compacted into the following summary:*
2
+
3
+ ${l.summary}`,timestamp:new Date(l.timestamp).getTime()};d.push(e),u.push(l.id);let t=s.findIndex(e=>"compaction"===e.type&&e.id===l.id),r=s.findIndex((e,r)=>r<t&&e.id===l.firstKeptEntryId),n=r>=0?r:t;for(let e=n;e<t;e++)p(s[e]);for(let e=t+1;e<s.length;e++)p(s[e])}else for(let e of s)p(e);return{messages:d,entryIds:u,thinkingLevel:a,model:o}},"buildSessionInfo",0,d,"buildTree",0,function(e){let t=new Map;for(let r of e)"label"===r.type&&(r.label?t.set(r.targetId,r.label):t.delete(r.targetId));let r=new Map,n=[];for(let n of e)r.set(n.id,{entry:n,children:[],label:t.get(n.id)});for(let t of e){let e=r.get(t.id);if(t.parentId){let s=r.get(t.parentId);s?s.children.push(e):n.push(e)}else n.push(e)}let s=[...n];for(;s.length>0;){let e=s.pop();e.children.sort((e,t)=>new Date(e.entry.timestamp).getTime()-new Date(t.entry.timestamp).getTime()),s.push(...e.children)}return n},"getDefaultModel",0,function(){let e=(0,r.join)(s(),"settings.json");if(!(0,t.existsSync)(e))return null;try{let r=JSON.parse((0,t.readFileSync)(e,"utf8"));if(!r.defaultProvider)return null;if(r.defaultModel)return{provider:r.defaultProvider,modelId:r.defaultModel};let n=Array.from(o().values()).find(e=>e.provider===r.defaultProvider);if(n)return{provider:n.provider,modelId:n.id}}catch{}return null},"getLeafId",0,function(e){return 0===e.length?null:e[e.length-1].id},"getModelList",0,function(){return Array.from(o().values())},"getModelNameMap",0,function(){let e=new Map;for(let t of o().values())e.set(t.id,t.name);return e},"getSessionEntries",0,function(e){return l(e).filter(e=>"session"!==e.type)},"invalidateModelCache",0,function(){a=null},"invalidateSessionPathCache",0,function(e){p().delete(e)},"listAllSessions",0,u,"resolveSessionPath",0,function(e){let n=p(),s=n.get(e);if(s&&(0,t.existsSync)(s))return s;let a=i();if(!(0,t.existsSync)(a))return null;try{for(let s of(0,t.readdirSync)(a,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>(0,r.join)(a,e.name)))try{for(let i of(0,t.readdirSync)(s).filter(e=>e.endsWith(".jsonl"))){let a=(0,r.join)(s,i),o=(0,t.readFileSync)(a,"utf8").split("\n")[0];try{let t=JSON.parse(o);if("session"===t.type&&t.id===e)return n.set(e,a),a}catch{}}}catch{}}catch{}return null}],9890)},28966,e=>{"use strict";var t=e.i(47909),r=e.i(74017),n=e.i(96250),s=e.i(59756),i=e.i(61916),a=e.i(74677),o=e.i(69741),l=e.i(16795),d=e.i(87718),u=e.i(95169),p=e.i(47587),c=e.i(66012),f=e.i(70101),h=e.i(74838),m=e.i(10372),y=e.i(93695);e.i(52474);var g=e.i(220),x=e.i(89171),v=e.i(22734),w=e.i(14747),R=e.i(9890);let S=new Set(["node_modules",".git",".next","dist","build","__pycache__",".turbo",".cache","coverage",".pytest_cache",".mypy_cache","target","vendor",".DS_Store",".git"]),j=[".pyc"],b={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",h:"c",hpp:"cpp",cs:"csharp",html:"html",htm:"html",css:"css",scss:"css",less:"css",json:"json",jsonl:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",mdx:"markdown",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",sql:"sql",graphql:"graphql",gql:"graphql",dockerfile:"dockerfile",tf:"hcl",hcl:"hcl",env:"bash",gitignore:"bash",txt:"text"};async function C(){let e=await (0,R.listAllSessions)(),t=new Set;for(let r of e)r.cwd&&t.add(r.cwd);return t}async function E(e,{params:t}){try{let r,{path:n}=await t,s="/"+n.join("/"),i=e.nextUrl.searchParams.get("type")??"list",a=await C();if(!function(e,t){let r=w.default.resolve(e);for(let e of t){let t=w.default.resolve(e);if(r===t||r.startsWith(t+w.default.sep))return!0}return!1}(s,a))return x.NextResponse.json({error:"Access denied"},{status:403});try{r=v.default.statSync(s)}catch{return x.NextResponse.json({error:"Not found"},{status:404})}if("read"===i){let e;if(!r.isFile())return x.NextResponse.json({error:"Not a file"},{status:400});if(r.size>2097152)return x.NextResponse.json({error:"File too large (>2MB)"},{status:413});let t=v.default.readFileSync(s,"utf-8"),n=(e=w.default.basename(s).toLowerCase(),"dockerfile"===e||e.startsWith("dockerfile.")?"dockerfile":".env"===e||e.startsWith(".env.")?"bash":"makefile"===e||"gnumakefile"===e?"makefile":b[e.split(".").pop()??""]??"text");return x.NextResponse.json({content:t,language:n,size:r.size})}if(!r.isDirectory())return x.NextResponse.json({error:"Not a directory"},{status:400});let o=v.default.readdirSync(s).filter(e=>!S.has(e)&&!j.some(t=>e.endsWith(t))).map(e=>{let t=w.default.join(s,e);try{let r=v.default.statSync(t);return{name:e,isDir:r.isDirectory(),size:r.isFile()?r.size:0,modified:r.mtime.toISOString()}}catch{return null}}).filter(Boolean).sort((e,t)=>e.isDir!==t.isDir?e.isDir?-1:1:e.name.localeCompare(t.name));return x.NextResponse.json({entries:o,path:s})}catch(e){return x.NextResponse.json({error:String(e)},{status:500})}}e.s(["GET",0,E],34735);var N=e.i(34735);let _=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/files/[...path]/route",pathname:"/api/files/[...path]",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/files/[...path]/route.ts",nextConfigOutput:"",userland:N}),{workAsyncStorage:A,workUnitAsyncStorage:I,serverHooks:T}=_;async function k(e,t,n){n.requestMeta&&(0,s.setRequestMeta)(e,n.requestMeta),_.isDev&&(0,s.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let x="/api/files/[...path]/route";x=x.replace(/\/index$/,"")||"/";let v=await _.prepare(e,t,{srcPage:x,multiZoneDraftMode:!1});if(!v)return t.statusCode=400,t.end("Bad Request"),null==n.waitUntil||n.waitUntil.call(n,Promise.resolve()),null;let{buildId:w,params:R,nextConfig:S,parsedUrl:j,isDraftMode:b,prerenderManifest:C,routerServerContext:E,isOnDemandRevalidate:N,revalidateOnlyGenerated:A,resolvedPathname:I,clientReferenceManifest:T,serverActionsManifest:k}=v,P=(0,o.normalizeAppPath)(x),q=!!(C.dynamicRoutes[P]||C.routes[I]),D=async()=>((null==E?void 0:E.render404)?await E.render404(e,t,j,!1):t.end("This page could not be found"),null);if(q&&!b){let e=!!C.routes[I],t=C.dynamicRoutes[P];if(t&&!1===t.fallback&&!e){if(S.adapterPath)return await D();throw new y.NoFallbackError}}let M=null;!q||_.isDev||b||(M="/index"===(M=I)?"/":M);let O=!0===_.isDev||!q,F=q&&!O;k&&T&&(0,a.setManifestsSingleton)({page:x,clientReferenceManifest:T,serverActionsManifest:k});let H=e.method||"GET",U=(0,i.getTracer)(),$=U.getActiveScopeSpan(),L=!!(null==E?void 0:E.isWrappedByNextServer),W=!!(0,s.getRequestMeta)(e,"minimalMode"),K=(0,s.getRequestMeta)(e,"incrementalCache")||await _.getIncrementalCache(e,S,C,W);null==K||K.resetRequestCache(),globalThis.__incrementalCache=K;let B={params:R,previewProps:C.preview,renderOpts:{experimental:{authInterrupts:!!S.experimental.authInterrupts},cacheComponents:!!S.cacheComponents,supportsDynamicResponse:O,incrementalCache:K,cacheLifeProfiles:S.cacheLife,waitUntil:n.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,n,s)=>_.onRequestError(e,t,n,s,E)},sharedContext:{buildId:w}},z=new l.NodeNextRequest(e),G=new l.NodeNextResponse(t),J=d.NextRequestAdapter.fromNodeNextRequest(z,(0,d.signalFromNodeResponse)(t));try{let s,a=async e=>_.handle(J,B).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=U.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==u.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=r.get("next.route");if(n){let t=`${H} ${n}`;e.setAttributes({"next.route":n,"http.route":n,"next.span_name":t}),e.updateName(t),s&&s!==e&&(s.setAttribute("http.route",n),s.updateName(t))}else e.updateName(`${H} ${x}`)}),o=async s=>{var i,o;let l=async({previousCacheEntry:r})=>{try{if(!W&&N&&A&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let i=await a(s);e.fetchMetrics=B.renderOpts.fetchMetrics;let o=B.renderOpts.pendingWaitUntil;o&&n.waitUntil&&(n.waitUntil(o),o=void 0);let l=B.renderOpts.collectedTags;if(!q)return await (0,c.sendResponse)(z,G,i,B.renderOpts.pendingWaitUntil),null;{let e=await i.blob(),t=(0,f.toNodeOutgoingHttpHeaders)(i.headers);l&&(t[m.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==B.renderOpts.collectedRevalidate&&!(B.renderOpts.collectedRevalidate>=m.INFINITE_CACHE)&&B.renderOpts.collectedRevalidate,n=void 0===B.renderOpts.collectedExpire||B.renderOpts.collectedExpire>=m.INFINITE_CACHE?void 0:B.renderOpts.collectedExpire;return{value:{kind:g.CachedRouteKind.APP_ROUTE,status:i.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:n}}}}catch(t){throw(null==r?void 0:r.isStale)&&await _.onRequestError(e,t,{routerKind:"App Router",routePath:x,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:F,isOnDemandRevalidate:N})},!1,E),t}},d=await _.handleResponse({req:e,nextConfig:S,cacheKey:M,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:C,isRoutePPREnabled:!1,isOnDemandRevalidate:N,revalidateOnlyGenerated:A,responseGenerator:l,waitUntil:n.waitUntil,isMinimalMode:W});if(!q)return null;if((null==d||null==(i=d.value)?void 0:i.kind)!==g.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==d||null==(o=d.value)?void 0:o.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});W||t.setHeader("x-nextjs-cache",N?"REVALIDATED":d.isMiss?"MISS":d.isStale?"STALE":"HIT"),b&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let u=(0,f.fromNodeOutgoingHttpHeaders)(d.value.headers);return W&&q||u.delete(m.NEXT_CACHE_TAGS_HEADER),!d.cacheControl||t.getHeader("Cache-Control")||u.get("Cache-Control")||u.set("Cache-Control",(0,h.getCacheControlHeader)(d.cacheControl)),await (0,c.sendResponse)(z,G,new Response(d.value.body,{headers:u,status:d.value.status||200})),null};L&&$?await o($):(s=U.getActiveScopeSpan(),await U.withPropagatedContext(e.headers,()=>U.trace(u.BaseServerSpan.handleRequest,{spanName:`${H} ${x}`,kind:i.SpanKind.SERVER,attributes:{"http.method":H,"http.target":e.url}},o),void 0,!L))}catch(t){if(t instanceof y.NoFallbackError||await _.onRequestError(e,t,{routerKind:"App Router",routePath:P,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:F,isOnDemandRevalidate:N})},!1,E),q)throw t;return await (0,c.sendResponse)(z,G,new Response(null,{status:500})),null}}e.s(["handler",0,k,"patchFetch",0,function(){return(0,n.patchFetch)({workAsyncStorage:A,workUnitAsyncStorage:I})},"routeModule",0,_,"serverHooks",0,T,"workAsyncStorage",0,A,"workUnitAsyncStorage",0,I],28966)}];
4
+
5
+ //# sourceMappingURL=%5Broot-of-the-server%5D__0llo_uy._.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../lib/session-reader.ts","../../../lib/normalize.ts","../../../app/api/files/%5B...path%5D/route.ts","../../../node_modules/next/dist/esm/build/templates/app-route.js"],"sourcesContent":["import { readFileSync, readdirSync, statSync, existsSync } from \"fs\";\nimport { join } from \"path\";\nimport { homedir } from \"os\";\nimport type {\n FileEntry,\n SessionEntry,\n SessionHeader,\n SessionInfo,\n SessionTreeNode,\n SessionMessageEntry,\n SessionInfoEntry,\n LabelEntry,\n AgentMessage,\n SessionContext,\n CompactionEntry,\n TextContent,\n} from \"./types\";\nimport { normalizeToolCalls } from \"./normalize\";\n\nfunction getAgentDir(): string {\n const envDir = process.env.PI_CODING_AGENT_DIR;\n if (envDir) {\n if (envDir === \"~\") return homedir();\n if (envDir.startsWith(\"~/\")) return homedir() + envDir.slice(1);\n return envDir;\n }\n return join(homedir(), \".pi\", \"agent\");\n}\n\nexport function getSessionsDir(): string {\n return join(getAgentDir(), \"sessions\");\n}\n\nexport interface ModelInfo {\n id: string;\n name: string;\n provider: string;\n}\n\n// Build a map of \"provider:modelId\" -> ModelInfo from ~/.pi/agent/models.json\nlet _modelCache: Map<string, ModelInfo> | null = null;\nfunction getModelCache(): Map<string, ModelInfo> {\n if (_modelCache) return _modelCache;\n _modelCache = new Map();\n const path = join(getAgentDir(), \"models.json\");\n if (!existsSync(path)) return _modelCache;\n try {\n const data = JSON.parse(readFileSync(path, \"utf8\")) as {\n providers?: Record<string, { models?: { id: string; name?: string }[] }>;\n };\n for (const [provider, providerData] of Object.entries(data.providers ?? {})) {\n for (const model of providerData.models ?? []) {\n if (model.id && model.name) {\n _modelCache.set(`${provider}:${model.id}`, { id: model.id, name: model.name, provider });\n }\n }\n }\n } catch { /* ignore */ }\n return _modelCache;\n}\n\nexport function getModelNameMap(): Map<string, string> {\n const result = new Map<string, string>();\n for (const info of getModelCache().values()) result.set(info.id, info.name);\n return result;\n}\n\nexport function getModelList(): ModelInfo[] {\n return Array.from(getModelCache().values());\n}\n\nexport function invalidateModelCache(): void {\n _modelCache = null;\n}\n\nexport function getDefaultModel(): { provider: string; modelId: string } | null {\n const path = join(getAgentDir(), \"settings.json\");\n if (!existsSync(path)) return null;\n try {\n const data = JSON.parse(readFileSync(path, \"utf8\")) as {\n defaultProvider?: string;\n defaultModel?: string;\n };\n if (!data.defaultProvider) return null;\n if (data.defaultModel) {\n return { provider: data.defaultProvider, modelId: data.defaultModel };\n }\n // Only provider saved — pick the first model from that provider in models.json\n const first = Array.from(getModelCache().values()).find((m) => m.provider === data.defaultProvider);\n if (first) return { provider: first.provider, modelId: first.id };\n } catch { /* ignore */ }\n return null;\n}\n\nexport function parseSessionFile(filePath: string): FileEntry[] {\n if (!existsSync(filePath)) return [];\n const content = readFileSync(filePath, \"utf8\");\n const entries: FileEntry[] = [];\n for (const line of content.trim().split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n entries.push(JSON.parse(line) as FileEntry);\n } catch {\n // skip malformed lines\n }\n }\n return entries;\n}\n\nfunction extractTextContent(message: AgentMessage): string {\n const content = (message as { content: unknown }).content;\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .filter((b): b is TextContent => b.type === \"text\")\n .map((b) => b.text)\n .join(\" \");\n}\n\n// Extract session UUID from a session file path like \".../2026-03-18T12-11-02-213Z_20a1e7e5-991f-4b91-856d-14dd2d256f20.jsonl\"\nfunction extractSessionIdFromPath(filePath: string): string | undefined {\n const base = filePath.replace(/\\\\/g, \"/\").split(\"/\").pop() ?? \"\";\n // format: <timestamp>_<uuid>.jsonl\n const match = base.match(/_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\.jsonl$/i);\n return match?.[1];\n}\n\nexport function buildSessionInfo(filePath: string): SessionInfo | null {\n try {\n const entries = parseSessionFile(filePath);\n if (entries.length === 0) return null;\n\n // Skip files without a valid session header (incomplete fork artifacts)\n const maybeHeader = entries[0] as SessionHeader;\n if (maybeHeader.type !== \"session\") return null;\n\n const stats = statSync(filePath);\n const id = maybeHeader.id;\n const cwd = maybeHeader.cwd ?? \"\";\n const created = maybeHeader.timestamp;\n const parentSessionId = maybeHeader.parentSession\n ? extractSessionIdFromPath(maybeHeader.parentSession)\n : undefined;\n\n let messageCount = 0;\n let firstMessage = \"\";\n let name: string | undefined;\n\n for (const entry of entries) {\n if (entry.type === \"session_info\") {\n const e = entry as SessionInfoEntry;\n if (e.name) name = e.name.trim();\n }\n if (entry.type !== \"message\") continue;\n messageCount++;\n const msg = (entry as SessionMessageEntry).message;\n if (msg.role !== \"user\" && msg.role !== \"assistant\") continue;\n const text = extractTextContent(msg);\n if (!firstMessage && msg.role === \"user\") firstMessage = text;\n }\n\n return {\n path: filePath,\n id,\n cwd,\n name,\n created,\n modified: stats.mtime.toISOString(),\n messageCount,\n firstMessage: firstMessage || \"(no messages)\",\n parentSessionId,\n };\n } catch {\n return null;\n }\n}\n\nexport async function listAllSessions(): Promise<SessionInfo[]> {\n const sessionsDir = getSessionsDir();\n const sessions: SessionInfo[] = [];\n if (!existsSync(sessionsDir)) return sessions;\n\n try {\n const dirs = readdirSync(sessionsDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(sessionsDir, e.name));\n\n for (const dir of dirs) {\n try {\n const files = readdirSync(dir)\n .filter((f) => f.endsWith(\".jsonl\"))\n .map((f) => join(dir, f));\n for (const file of files) {\n const info = buildSessionInfo(file);\n if (info) sessions.push(info);\n }\n } catch {\n // skip unreadable dir\n }\n }\n } catch {\n // skip\n }\n\n sessions.sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());\n return sessions;\n}\n\nexport function getSessionEntries(filePath: string): SessionEntry[] {\n const entries = parseSessionFile(filePath);\n return entries.filter((e): e is SessionEntry => e.type !== \"session\");\n}\n\nexport function buildTree(entries: SessionEntry[]): SessionTreeNode[] {\n const labelsById = new Map<string, string>();\n for (const entry of entries) {\n if (entry.type === \"label\") {\n const l = entry as LabelEntry;\n if (l.label) labelsById.set(l.targetId, l.label);\n else labelsById.delete(l.targetId);\n }\n }\n\n const nodeMap = new Map<string, SessionTreeNode>();\n const roots: SessionTreeNode[] = [];\n\n for (const entry of entries) {\n nodeMap.set(entry.id, { entry, children: [], label: labelsById.get(entry.id) });\n }\n\n for (const entry of entries) {\n const node = nodeMap.get(entry.id)!;\n if (!entry.parentId) {\n roots.push(node);\n } else {\n const parent = nodeMap.get(entry.parentId);\n if (parent) {\n parent.children.push(node);\n } else {\n roots.push(node);\n }\n }\n }\n\n // sort children by timestamp\n const stack = [...roots];\n while (stack.length > 0) {\n const node = stack.pop()!;\n node.children.sort(\n (a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime()\n );\n stack.push(...node.children);\n }\n\n return roots;\n}\n\n\n\nexport function buildSessionContext(\n entries: SessionEntry[],\n leafId?: string | null\n): SessionContext {\n const byId = new Map<string, SessionEntry>();\n for (const entry of entries) {\n byId.set(entry.id, entry);\n }\n\n let leaf: SessionEntry | undefined;\n if (leafId === null) {\n return { messages: [], entryIds: [], thinkingLevel: \"off\", model: null };\n }\n if (leafId) {\n leaf = byId.get(leafId);\n }\n if (!leaf) {\n leaf = entries[entries.length - 1];\n }\n if (!leaf) {\n return { messages: [], entryIds: [], thinkingLevel: \"off\", model: null };\n }\n\n // walk from leaf to root\n const path: SessionEntry[] = [];\n let current: SessionEntry | undefined = leaf;\n while (current) {\n path.unshift(current);\n current = current.parentId ? byId.get(current.parentId) : undefined;\n }\n\n let thinkingLevel = \"off\";\n let model: { provider: string; modelId: string } | null = null;\n let compaction: CompactionEntry | null = null;\n\n for (const entry of path) {\n if (entry.type === \"thinking_level_change\") {\n thinkingLevel = entry.thinkingLevel;\n } else if (entry.type === \"model_change\") {\n model = { provider: entry.provider, modelId: entry.modelId };\n } else if (entry.type === \"message\" && (entry as SessionMessageEntry).message.role === \"assistant\") {\n const msg = (entry as SessionMessageEntry).message as { provider: string; model: string };\n model = { provider: msg.provider, modelId: msg.model };\n } else if (entry.type === \"compaction\") {\n compaction = entry as CompactionEntry;\n }\n }\n\n const messages: AgentMessage[] = [];\n const entryIds: string[] = [];\n\n const appendMessage = (entry: SessionEntry) => {\n if (entry.type === \"message\") {\n messages.push(normalizeToolCalls((entry as SessionMessageEntry).message));\n entryIds.push(entry.id);\n }\n };\n\n if (compaction) {\n // Inject compaction summary as a virtual user message matching agent's format\n const summaryMsg: AgentMessage = {\n role: \"user\",\n content: `*The conversation history before this point was compacted into the following summary:*\\n\\n${compaction.summary}`,\n timestamp: new Date(compaction.timestamp).getTime(),\n };\n messages.push(summaryMsg);\n entryIds.push(compaction.id);\n\n const compactionIdx = path.findIndex(\n (e) => e.type === \"compaction\" && e.id === compaction!.id\n );\n // Find firstKeptEntryId before the compaction node; if not found, skip all pre-compaction entries\n const firstKeptIdx = path.findIndex(\n (e, i) => i < compactionIdx && e.id === compaction!.firstKeptEntryId\n );\n const startIdx = firstKeptIdx >= 0 ? firstKeptIdx : compactionIdx;\n for (let i = startIdx; i < compactionIdx; i++) {\n appendMessage(path[i]);\n }\n for (let i = compactionIdx + 1; i < path.length; i++) {\n appendMessage(path[i]);\n }\n } else {\n for (const entry of path) {\n appendMessage(entry);\n }\n }\n\n return { messages, entryIds, thinkingLevel, model };\n}\n\nexport function getLeafId(entries: SessionEntry[]): string | null {\n if (entries.length === 0) return null;\n return entries[entries.length - 1].id;\n}\n\n// ============================================================================\n// Session path cache: sessionId → absolute file path\n// Stored in globalThis for hot-reload safety (same as rpc-manager registry)\n// ============================================================================\ndeclare global {\n var __piSessionPathCache: Map<string, string> | undefined;\n}\n\nfunction getPathCache(): Map<string, string> {\n if (!globalThis.__piSessionPathCache) globalThis.__piSessionPathCache = new Map();\n return globalThis.__piSessionPathCache;\n}\n\nexport function invalidateSessionPathCache(sessionId: string): void {\n getPathCache().delete(sessionId);\n}\n\nexport function resolveSessionPath(sessionId: string): string | null {\n const cache = getPathCache();\n const cached = cache.get(sessionId);\n if (cached && existsSync(cached)) return cached;\n\n const sessionsDir = getSessionsDir();\n if (!existsSync(sessionsDir)) return null;\n try {\n const dirs = readdirSync(sessionsDir, { withFileTypes: true })\n .filter((e) => e.isDirectory())\n .map((e) => join(sessionsDir, e.name));\n for (const dir of dirs) {\n try {\n const files = readdirSync(dir).filter((f) => f.endsWith(\".jsonl\"));\n for (const file of files) {\n const fullPath = join(dir, file);\n // Read only first line to check header id\n const firstLine = readFileSync(fullPath, \"utf8\").split(\"\\n\")[0];\n try {\n const header = JSON.parse(firstLine) as SessionHeader;\n if (header.type === \"session\" && header.id === sessionId) {\n cache.set(sessionId, fullPath);\n return fullPath;\n }\n } catch { /* skip malformed */ }\n }\n } catch {\n // skip\n }\n }\n } catch {\n // skip\n }\n return null;\n}\n","import type { AgentMessage } from \"./types\";\n\n/**\n * Pi stores toolCall blocks as {id, name, arguments} but our types use\n * {toolCallId, toolName, input}. Normalize both file-read and streaming paths.\n */\nexport function normalizeToolCalls(msg: AgentMessage): AgentMessage {\n if (msg.role !== \"assistant\") return msg;\n const raw = msg as unknown as { content?: unknown[] };\n if (!Array.isArray(raw.content)) return msg;\n const normalized = raw.content.map((block) => {\n const b = block as Record<string, unknown>;\n if (b.type !== \"toolCall\") return b;\n return {\n type: \"toolCall\",\n toolCallId: b.toolCallId ?? b.id,\n toolName: b.toolName ?? b.name,\n input: b.input ?? b.arguments,\n };\n });\n return { ...(msg as object), content: normalized } as unknown as AgentMessage;\n}\n","import { NextRequest, NextResponse } from \"next/server\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { listAllSessions } from \"@/lib/session-reader\";\n\nconst IGNORED_NAMES = new Set([\n \"node_modules\", \".git\", \".next\", \"dist\", \"build\", \"__pycache__\",\n \".turbo\", \".cache\", \"coverage\", \".pytest_cache\", \".mypy_cache\",\n \"target\", \"vendor\", \".DS_Store\", \".git\",\n]);\n\nconst IGNORED_SUFFIXES = [\".pyc\"];\n\nconst EXT_TO_LANGUAGE: Record<string, string> = {\n ts: \"typescript\", tsx: \"typescript\", js: \"javascript\", jsx: \"javascript\",\n mjs: \"javascript\", cjs: \"javascript\", py: \"python\", rb: \"ruby\",\n go: \"go\", rs: \"rust\", java: \"java\", kt: \"kotlin\", swift: \"swift\",\n c: \"c\", cpp: \"cpp\", h: \"c\", hpp: \"cpp\", cs: \"csharp\",\n html: \"html\", htm: \"html\", css: \"css\", scss: \"css\", less: \"css\",\n json: \"json\", jsonl: \"json\", yaml: \"yaml\", yml: \"yaml\",\n toml: \"toml\", xml: \"xml\", md: \"markdown\", mdx: \"markdown\",\n sh: \"bash\", bash: \"bash\", zsh: \"bash\", fish: \"bash\",\n sql: \"sql\", graphql: \"graphql\", gql: \"graphql\",\n dockerfile: \"dockerfile\", tf: \"hcl\", hcl: \"hcl\",\n env: \"bash\", gitignore: \"bash\", txt: \"text\",\n};\n\nfunction getLanguage(filePath: string): string {\n const base = path.basename(filePath).toLowerCase();\n // Special full-name matches\n if (base === \"dockerfile\" || base.startsWith(\"dockerfile.\")) return \"dockerfile\";\n if (base === \".env\" || base.startsWith(\".env.\")) return \"bash\";\n if (base === \"makefile\" || base === \"gnumakefile\") return \"makefile\";\n const ext = base.split(\".\").pop() ?? \"\";\n return EXT_TO_LANGUAGE[ext] ?? \"text\";\n}\n\nasync function getAllowedRoots(): Promise<Set<string>> {\n const sessions = await listAllSessions();\n const roots = new Set<string>();\n for (const s of sessions) {\n if (s.cwd) roots.add(s.cwd);\n }\n return roots;\n}\n\nfunction isPathAllowed(target: string, allowedRoots: Set<string>): boolean {\n const normalized = path.resolve(target);\n for (const root of allowedRoots) {\n const normalizedRoot = path.resolve(root);\n if (normalized === normalizedRoot || normalized.startsWith(normalizedRoot + path.sep)) {\n return true;\n }\n }\n return false;\n}\n\nexport async function GET(\n request: NextRequest,\n { params }: { params: Promise<{ path: string[] }> }\n) {\n try {\n const { path: segments } = await params;\n const filePath = \"/\" + segments.join(\"/\");\n const type = request.nextUrl.searchParams.get(\"type\") ?? \"list\";\n\n const allowedRoots = await getAllowedRoots();\n if (!isPathAllowed(filePath, allowedRoots)) {\n return NextResponse.json({ error: \"Access denied\" }, { status: 403 });\n }\n\n let stat: fs.Stats;\n try {\n stat = fs.statSync(filePath);\n } catch {\n return NextResponse.json({ error: \"Not found\" }, { status: 404 });\n }\n\n if (type === \"read\") {\n if (!stat.isFile()) {\n return NextResponse.json({ error: \"Not a file\" }, { status: 400 });\n }\n // Limit file size to 2MB\n if (stat.size > 2 * 1024 * 1024) {\n return NextResponse.json({ error: \"File too large (>2MB)\" }, { status: 413 });\n }\n const content = fs.readFileSync(filePath, \"utf-8\");\n const language = getLanguage(filePath);\n return NextResponse.json({ content, language, size: stat.size });\n }\n\n // type === \"list\"\n if (!stat.isDirectory()) {\n return NextResponse.json({ error: \"Not a directory\" }, { status: 400 });\n }\n\n const names = fs.readdirSync(filePath);\n const entries = names\n .filter((name) => !IGNORED_NAMES.has(name) && !IGNORED_SUFFIXES.some((s) => name.endsWith(s)))\n .map((name) => {\n const full = path.join(filePath, name);\n try {\n const s = fs.statSync(full);\n return {\n name,\n isDir: s.isDirectory(),\n size: s.isFile() ? s.size : 0,\n modified: s.mtime.toISOString(),\n };\n } catch {\n return null;\n }\n })\n .filter(Boolean)\n .sort((a, b) => {\n // Dirs first, then files, both alphabetically\n if (a!.isDir !== b!.isDir) return a!.isDir ? -1 : 1;\n return a!.name.localeCompare(b!.name);\n });\n\n return NextResponse.json({ entries, path: filePath });\n } catch (error) {\n return NextResponse.json({ error: String(error) }, { status: 500 });\n }\n}\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/esm/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/files/[...path]/route\",\n pathname: \"/api/files/[...path]\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/app/api/files/[...path]/route.ts\",\n nextConfigOutput,\n userland\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/files/[...path]/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n"],"names":["normalizeToolCalls","msg","role","raw","Array","isArray","content","normalized","map","block","b","type","toolCallId","id","toolName","name","input","arguments","IGNORED_NAMES","Set","IGNORED_SUFFIXES","filePath","EXT_TO_LANGUAGE","ts","tsx","js","jsx","mjs","cjs","py","rb","go","rs","java","kt","swift","c","cpp","h","hpp","cs","html","htm","css","scss","less","json","jsonl","yaml","yml","toml","xml","md","mdx","sh","bash","zsh","fish","sql","graphql","gql","dockerfile","s","tf","hcl","env","gitignore","txt","getLanguage","base","basename","toLowerCase","startsWith","ext","split","pop","getAllowedRoots","sessions","roots","cwd","add","isPathAllowed","target","allowedRoots","resolve","root","normalizedRoot","sep","stat","GET","request","params","path","segments","join","nextUrl","searchParams","get","error","status","statSync","isDir","sort","isFile","size","readFileSync","language","isDirectory","names","readdirSync","entries","filter","has","some","endsWith","full","modified","mtime","toISOString","Boolean","a","localeCompare","String"],"mappings":"2pCAAA,IAAA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,OAiBA,SAAS,IACP,IAAM,EAAS,QAAQ,GAAG,CAAC,mBAAmB,QAC9C,AAAI,EACF,AAAe,KAAK,CADV,AACN,EAAuB,CAAA,EAAA,EAAA,OAAA,AAAO,IAC9B,EAAO,UAAU,CAAC,MAAc,CAAP,AAAO,EAAA,EAAA,OAAO,AAAP,IAAY,EAAO,KAAK,CAAC,GACtD,EAEF,CAAA,EAAA,EAAA,IAAA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