@henlii/pidance 0.2.33 → 0.2.34

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 (268) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +14 -15
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.json +1 -1
  6. package/.next/routes-manifest.json +0 -6
  7. package/.next/server/app/_global-error/page.js +3 -3
  8. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  9. package/.next/server/app/_global-error.html +1 -1
  10. package/.next/server/app/_global-error.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  16. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  17. package/.next/server/app/_not-found/page.js +2 -2
  18. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  19. package/.next/server/app/_not-found.html +1 -1
  20. package/.next/server/app/_not-found.rsc +3 -3
  21. package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  22. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  23. package/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
  24. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  25. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  26. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  27. package/.next/server/app/api/about/route.js +1 -1
  28. package/.next/server/app/api/agent/[id]/bash-output/route.js +1 -1
  29. package/.next/server/app/api/agent/[id]/events/route.js +2 -2
  30. package/.next/server/app/api/agent/[id]/route.js +1 -1
  31. package/.next/server/app/api/agent/new/route.js +1 -1
  32. package/.next/server/app/api/agent/running/events/route.js +2 -2
  33. package/.next/server/app/api/agent/running/route.js +1 -1
  34. package/.next/server/app/api/agent/submissions/[submissionId]/route.js +1 -1
  35. package/.next/server/app/api/agent-settings/route.js +2 -2
  36. package/.next/server/app/api/attachments/route.js +1 -1
  37. package/.next/server/app/api/auth/all-providers/route.js +1 -1
  38. package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
  39. package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
  40. package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
  41. package/.next/server/app/api/auth/providers/route.js +1 -1
  42. package/.next/server/app/api/auth/ui-session/route.js +1 -1
  43. package/.next/server/app/api/auth/ui-sessions/[id]/route.js +1 -1
  44. package/.next/server/app/api/auth/ui-sessions/route.js +1 -1
  45. package/.next/server/app/api/cwd/browse/route.js +1 -1
  46. package/.next/server/app/api/cwd/create/route.js +1 -1
  47. package/.next/server/app/api/cwd/validate/route.js +1 -1
  48. package/.next/server/app/api/default-cwd/route.js +1 -1
  49. package/.next/server/app/api/file-index/route.js +1 -1
  50. package/.next/server/app/api/files/[...path]/route.js +2 -2
  51. package/.next/server/app/api/git/diff/route.js +1 -1
  52. package/.next/server/app/api/git/status/route.js +1 -1
  53. package/.next/server/app/api/home/route.js +1 -1
  54. package/.next/server/app/api/message-media/route.js +1 -1
  55. package/.next/server/app/api/models/route.js +1 -1
  56. package/.next/server/app/api/models-config/raw/route.js +1 -1
  57. package/.next/server/app/api/models-config/route.js +1 -1
  58. package/.next/server/app/api/models-config/test/route.js +1 -1
  59. package/.next/server/app/api/plugins/route.js +1 -1
  60. package/.next/server/app/api/plugins/search/route.js +1 -1
  61. package/.next/server/app/api/plugins/updates/route.js +1 -1
  62. package/.next/server/app/api/preferences/route.js +1 -1
  63. package/.next/server/app/api/project-assets/route.js +2 -2
  64. package/.next/server/app/api/prompts/route.js +1 -1
  65. package/.next/server/app/api/pty/route.js +1 -1
  66. package/.next/server/app/api/sessions/[id]/archive/route.js +1 -1
  67. package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
  68. package/.next/server/app/api/sessions/[id]/command-entry/route.js +1 -1
  69. package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
  70. package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
  71. package/.next/server/app/api/sessions/[id]/export/route.js +1 -1
  72. package/.next/server/app/api/sessions/[id]/info/route.js +1 -1
  73. package/.next/server/app/api/sessions/[id]/outline/route.js +1 -1
  74. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  75. package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
  76. package/.next/server/app/api/sessions/[id]/tool-results/[toolCallId]/route.js +1 -1
  77. package/.next/server/app/api/sessions/route.js +1 -1
  78. package/.next/server/app/api/sessions/search/route.js +1 -1
  79. package/.next/server/app/api/settings/raw/route.js +2 -2
  80. package/.next/server/app/api/settings/remote/route.js +1 -1
  81. package/.next/server/app/api/skills/check/route.js +1 -1
  82. package/.next/server/app/api/skills/install/route.js +1 -1
  83. package/.next/server/app/api/skills/route.js +2 -2
  84. package/.next/server/app/api/skills/search/route.js +1 -1
  85. package/.next/server/app/api/skills/update/route.js +1 -1
  86. package/.next/server/app/api/subagent-runs/route.js +1 -1
  87. package/.next/server/app/api/update/apply/route.js +2 -2
  88. package/.next/server/app/api/update/check/route.js +1 -1
  89. package/.next/server/app/icon.png/route.js +1 -1
  90. package/.next/server/app/index.html +1 -1
  91. package/.next/server/app/index.rsc +5 -5
  92. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  93. package/.next/server/app/index.segments/_full.segment.rsc +5 -5
  94. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  95. package/.next/server/app/index.segments/_index.segment.rsc +3 -3
  96. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  97. package/.next/server/app/page.js +14 -15
  98. package/.next/server/app/page_client-reference-manifest.js +1 -1
  99. package/.next/server/app-paths-manifest.json +14 -15
  100. package/.next/server/chunks/1707.js +1 -1
  101. package/.next/server/chunks/188.js +1 -1
  102. package/.next/server/chunks/2871.js +1 -1
  103. package/.next/server/chunks/3379.js +1 -1
  104. package/.next/server/chunks/5274.js +1 -1
  105. package/.next/server/chunks/5304.js +1 -1
  106. package/.next/server/chunks/5726.js +1 -0
  107. package/.next/server/chunks/6192.js +1 -1
  108. package/.next/server/chunks/6509.js +1 -1
  109. package/.next/server/chunks/7181.js +1 -1
  110. package/.next/server/chunks/7594.js +1 -1
  111. package/.next/server/chunks/9169.js +1 -1
  112. package/.next/server/chunks/9280.js +2 -2
  113. package/.next/server/chunks/9935.js +1 -1
  114. package/.next/server/instrumentation.js +1 -1
  115. package/.next/server/middleware-build-manifest.js +1 -1
  116. package/.next/server/pages/404.html +1 -1
  117. package/.next/server/pages/500.html +1 -1
  118. package/.next/server/server-reference-manifest.json +1 -1
  119. package/.next/static/Xz9XxhYAztXJctQiqfonK/_buildManifest.js +1 -0
  120. package/.next/static/chunks/9780-10c5b784a91324f0.js +1 -0
  121. package/.next/static/chunks/app/_global-error/page-b2c38d3e76d6c6b5.js +1 -0
  122. package/.next/static/chunks/app/api/about/route-b2c38d3e76d6c6b5.js +1 -0
  123. package/.next/static/chunks/app/api/agent/[id]/bash-output/route-b2c38d3e76d6c6b5.js +1 -0
  124. package/.next/static/chunks/app/api/agent/[id]/events/route-b2c38d3e76d6c6b5.js +1 -0
  125. package/.next/static/chunks/app/api/agent/[id]/route-b2c38d3e76d6c6b5.js +1 -0
  126. package/.next/static/chunks/app/api/agent/new/route-b2c38d3e76d6c6b5.js +1 -0
  127. package/.next/static/chunks/app/api/agent/running/events/route-b2c38d3e76d6c6b5.js +1 -0
  128. package/.next/static/chunks/app/api/agent/running/route-b2c38d3e76d6c6b5.js +1 -0
  129. package/.next/static/chunks/app/api/agent/submissions/[submissionId]/route-b2c38d3e76d6c6b5.js +1 -0
  130. package/.next/static/chunks/app/api/agent-settings/route-b2c38d3e76d6c6b5.js +1 -0
  131. package/.next/static/chunks/app/api/attachments/route-b2c38d3e76d6c6b5.js +1 -0
  132. package/.next/static/chunks/app/api/auth/all-providers/route-b2c38d3e76d6c6b5.js +1 -0
  133. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-b2c38d3e76d6c6b5.js +1 -0
  134. package/.next/static/chunks/app/api/auth/login/[provider]/route-b2c38d3e76d6c6b5.js +1 -0
  135. package/.next/static/chunks/app/api/auth/logout/[provider]/route-b2c38d3e76d6c6b5.js +1 -0
  136. package/.next/static/chunks/app/api/auth/providers/route-b2c38d3e76d6c6b5.js +1 -0
  137. package/.next/static/chunks/app/api/auth/ui-session/route-b2c38d3e76d6c6b5.js +1 -0
  138. package/.next/static/chunks/app/api/auth/ui-sessions/[id]/route-b2c38d3e76d6c6b5.js +1 -0
  139. package/.next/static/chunks/app/api/auth/ui-sessions/route-b2c38d3e76d6c6b5.js +1 -0
  140. package/.next/static/chunks/app/api/cwd/browse/route-b2c38d3e76d6c6b5.js +1 -0
  141. package/.next/static/chunks/app/api/cwd/create/route-b2c38d3e76d6c6b5.js +1 -0
  142. package/.next/static/chunks/app/api/cwd/validate/route-b2c38d3e76d6c6b5.js +1 -0
  143. package/.next/static/chunks/app/api/default-cwd/route-b2c38d3e76d6c6b5.js +1 -0
  144. package/.next/static/chunks/app/api/file-index/route-b2c38d3e76d6c6b5.js +1 -0
  145. package/.next/static/chunks/app/api/files/[...path]/route-b2c38d3e76d6c6b5.js +1 -0
  146. package/.next/static/chunks/app/api/git/diff/route-b2c38d3e76d6c6b5.js +1 -0
  147. package/.next/static/chunks/app/api/git/status/route-b2c38d3e76d6c6b5.js +1 -0
  148. package/.next/static/chunks/app/api/home/route-b2c38d3e76d6c6b5.js +1 -0
  149. package/.next/static/chunks/app/api/message-media/route-b2c38d3e76d6c6b5.js +1 -0
  150. package/.next/static/chunks/app/api/models/route-b2c38d3e76d6c6b5.js +1 -0
  151. package/.next/static/chunks/app/api/models-config/raw/route-b2c38d3e76d6c6b5.js +1 -0
  152. package/.next/static/chunks/app/api/models-config/route-b2c38d3e76d6c6b5.js +1 -0
  153. package/.next/static/chunks/app/api/models-config/test/route-b2c38d3e76d6c6b5.js +1 -0
  154. package/.next/static/chunks/app/api/plugins/route-b2c38d3e76d6c6b5.js +1 -0
  155. package/.next/static/chunks/app/api/plugins/search/route-b2c38d3e76d6c6b5.js +1 -0
  156. package/.next/static/chunks/app/api/plugins/updates/route-b2c38d3e76d6c6b5.js +1 -0
  157. package/.next/static/chunks/app/api/preferences/route-b2c38d3e76d6c6b5.js +1 -0
  158. package/.next/static/chunks/app/api/project-assets/route-b2c38d3e76d6c6b5.js +1 -0
  159. package/.next/static/chunks/app/api/prompts/route-b2c38d3e76d6c6b5.js +1 -0
  160. package/.next/static/chunks/app/api/pty/route-b2c38d3e76d6c6b5.js +1 -0
  161. package/.next/static/chunks/app/api/sessions/[id]/archive/route-b2c38d3e76d6c6b5.js +1 -0
  162. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-b2c38d3e76d6c6b5.js +1 -0
  163. package/.next/static/chunks/app/api/sessions/[id]/command-entry/route-b2c38d3e76d6c6b5.js +1 -0
  164. package/.next/static/chunks/app/api/sessions/[id]/context/route-b2c38d3e76d6c6b5.js +1 -0
  165. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-b2c38d3e76d6c6b5.js +1 -0
  166. package/.next/static/chunks/app/api/sessions/[id]/export/route-b2c38d3e76d6c6b5.js +1 -0
  167. package/.next/static/chunks/app/api/sessions/[id]/info/route-b2c38d3e76d6c6b5.js +1 -0
  168. package/.next/static/chunks/app/api/sessions/[id]/outline/route-b2c38d3e76d6c6b5.js +1 -0
  169. package/.next/static/chunks/app/api/sessions/[id]/route-b2c38d3e76d6c6b5.js +1 -0
  170. package/.next/static/chunks/app/api/sessions/[id]/state/route-b2c38d3e76d6c6b5.js +1 -0
  171. package/.next/static/chunks/app/api/sessions/[id]/tool-results/[toolCallId]/route-b2c38d3e76d6c6b5.js +1 -0
  172. package/.next/static/chunks/app/api/sessions/route-b2c38d3e76d6c6b5.js +1 -0
  173. package/.next/static/chunks/app/api/sessions/search/route-b2c38d3e76d6c6b5.js +1 -0
  174. package/.next/static/chunks/app/api/settings/raw/route-b2c38d3e76d6c6b5.js +1 -0
  175. package/.next/static/chunks/app/api/settings/remote/route-b2c38d3e76d6c6b5.js +1 -0
  176. package/.next/static/chunks/app/api/skills/check/route-b2c38d3e76d6c6b5.js +1 -0
  177. package/.next/static/chunks/app/api/skills/install/route-b2c38d3e76d6c6b5.js +1 -0
  178. package/.next/static/chunks/app/api/skills/route-b2c38d3e76d6c6b5.js +1 -0
  179. package/.next/static/chunks/app/api/skills/search/route-b2c38d3e76d6c6b5.js +1 -0
  180. package/.next/static/chunks/app/api/skills/update/route-b2c38d3e76d6c6b5.js +1 -0
  181. package/.next/static/chunks/app/api/subagent-runs/route-b2c38d3e76d6c6b5.js +1 -0
  182. package/.next/static/chunks/app/api/update/apply/route-b2c38d3e76d6c6b5.js +1 -0
  183. package/.next/static/chunks/app/api/update/check/route-b2c38d3e76d6c6b5.js +1 -0
  184. package/.next/static/chunks/app/page-61e09e843c0fdee8.js +24 -0
  185. package/.next/static/chunks/next/dist/client/components/builtin/app-error-b2c38d3e76d6c6b5.js +1 -0
  186. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-b2c38d3e76d6c6b5.js +1 -0
  187. package/.next/static/chunks/next/dist/client/components/builtin/not-found-b2c38d3e76d6c6b5.js +1 -0
  188. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-b2c38d3e76d6c6b5.js +1 -0
  189. package/.next/static/css/{a2bef6e707e10928.css → 2c5193dd12bf5ffb.css} +1 -1
  190. package/README.en.md +5 -6
  191. package/README.md +3 -4
  192. package/README.zh-CN.md +0 -1
  193. package/package.json +1 -1
  194. package/.next/server/app/api/worktrees/route.js +0 -1
  195. package/.next/server/app/api/worktrees/route_client-reference-manifest.js +0 -1
  196. package/.next/server/chunks/5582.js +0 -1
  197. package/.next/static/0jTCyAHZ1cMAQtbthkA6a/_buildManifest.js +0 -1
  198. package/.next/static/chunks/9780-b283d1d0384d11b4.js +0 -1
  199. package/.next/static/chunks/app/_global-error/page-fb11d0d31328bf72.js +0 -1
  200. package/.next/static/chunks/app/api/about/route-fb11d0d31328bf72.js +0 -1
  201. package/.next/static/chunks/app/api/agent/[id]/bash-output/route-fb11d0d31328bf72.js +0 -1
  202. package/.next/static/chunks/app/api/agent/[id]/events/route-fb11d0d31328bf72.js +0 -1
  203. package/.next/static/chunks/app/api/agent/[id]/route-fb11d0d31328bf72.js +0 -1
  204. package/.next/static/chunks/app/api/agent/new/route-fb11d0d31328bf72.js +0 -1
  205. package/.next/static/chunks/app/api/agent/running/events/route-fb11d0d31328bf72.js +0 -1
  206. package/.next/static/chunks/app/api/agent/running/route-fb11d0d31328bf72.js +0 -1
  207. package/.next/static/chunks/app/api/agent/submissions/[submissionId]/route-fb11d0d31328bf72.js +0 -1
  208. package/.next/static/chunks/app/api/agent-settings/route-fb11d0d31328bf72.js +0 -1
  209. package/.next/static/chunks/app/api/attachments/route-fb11d0d31328bf72.js +0 -1
  210. package/.next/static/chunks/app/api/auth/all-providers/route-fb11d0d31328bf72.js +0 -1
  211. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-fb11d0d31328bf72.js +0 -1
  212. package/.next/static/chunks/app/api/auth/login/[provider]/route-fb11d0d31328bf72.js +0 -1
  213. package/.next/static/chunks/app/api/auth/logout/[provider]/route-fb11d0d31328bf72.js +0 -1
  214. package/.next/static/chunks/app/api/auth/providers/route-fb11d0d31328bf72.js +0 -1
  215. package/.next/static/chunks/app/api/auth/ui-session/route-fb11d0d31328bf72.js +0 -1
  216. package/.next/static/chunks/app/api/auth/ui-sessions/[id]/route-fb11d0d31328bf72.js +0 -1
  217. package/.next/static/chunks/app/api/auth/ui-sessions/route-fb11d0d31328bf72.js +0 -1
  218. package/.next/static/chunks/app/api/cwd/browse/route-fb11d0d31328bf72.js +0 -1
  219. package/.next/static/chunks/app/api/cwd/create/route-fb11d0d31328bf72.js +0 -1
  220. package/.next/static/chunks/app/api/cwd/validate/route-fb11d0d31328bf72.js +0 -1
  221. package/.next/static/chunks/app/api/default-cwd/route-fb11d0d31328bf72.js +0 -1
  222. package/.next/static/chunks/app/api/file-index/route-fb11d0d31328bf72.js +0 -1
  223. package/.next/static/chunks/app/api/files/[...path]/route-fb11d0d31328bf72.js +0 -1
  224. package/.next/static/chunks/app/api/git/diff/route-fb11d0d31328bf72.js +0 -1
  225. package/.next/static/chunks/app/api/git/status/route-fb11d0d31328bf72.js +0 -1
  226. package/.next/static/chunks/app/api/home/route-fb11d0d31328bf72.js +0 -1
  227. package/.next/static/chunks/app/api/message-media/route-fb11d0d31328bf72.js +0 -1
  228. package/.next/static/chunks/app/api/models/route-fb11d0d31328bf72.js +0 -1
  229. package/.next/static/chunks/app/api/models-config/raw/route-fb11d0d31328bf72.js +0 -1
  230. package/.next/static/chunks/app/api/models-config/route-fb11d0d31328bf72.js +0 -1
  231. package/.next/static/chunks/app/api/models-config/test/route-fb11d0d31328bf72.js +0 -1
  232. package/.next/static/chunks/app/api/plugins/route-fb11d0d31328bf72.js +0 -1
  233. package/.next/static/chunks/app/api/plugins/search/route-fb11d0d31328bf72.js +0 -1
  234. package/.next/static/chunks/app/api/plugins/updates/route-fb11d0d31328bf72.js +0 -1
  235. package/.next/static/chunks/app/api/preferences/route-fb11d0d31328bf72.js +0 -1
  236. package/.next/static/chunks/app/api/project-assets/route-fb11d0d31328bf72.js +0 -1
  237. package/.next/static/chunks/app/api/prompts/route-fb11d0d31328bf72.js +0 -1
  238. package/.next/static/chunks/app/api/pty/route-fb11d0d31328bf72.js +0 -1
  239. package/.next/static/chunks/app/api/sessions/[id]/archive/route-fb11d0d31328bf72.js +0 -1
  240. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-fb11d0d31328bf72.js +0 -1
  241. package/.next/static/chunks/app/api/sessions/[id]/command-entry/route-fb11d0d31328bf72.js +0 -1
  242. package/.next/static/chunks/app/api/sessions/[id]/context/route-fb11d0d31328bf72.js +0 -1
  243. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-fb11d0d31328bf72.js +0 -1
  244. package/.next/static/chunks/app/api/sessions/[id]/export/route-fb11d0d31328bf72.js +0 -1
  245. package/.next/static/chunks/app/api/sessions/[id]/info/route-fb11d0d31328bf72.js +0 -1
  246. package/.next/static/chunks/app/api/sessions/[id]/outline/route-fb11d0d31328bf72.js +0 -1
  247. package/.next/static/chunks/app/api/sessions/[id]/route-fb11d0d31328bf72.js +0 -1
  248. package/.next/static/chunks/app/api/sessions/[id]/state/route-fb11d0d31328bf72.js +0 -1
  249. package/.next/static/chunks/app/api/sessions/[id]/tool-results/[toolCallId]/route-fb11d0d31328bf72.js +0 -1
  250. package/.next/static/chunks/app/api/sessions/route-fb11d0d31328bf72.js +0 -1
  251. package/.next/static/chunks/app/api/sessions/search/route-fb11d0d31328bf72.js +0 -1
  252. package/.next/static/chunks/app/api/settings/raw/route-fb11d0d31328bf72.js +0 -1
  253. package/.next/static/chunks/app/api/settings/remote/route-fb11d0d31328bf72.js +0 -1
  254. package/.next/static/chunks/app/api/skills/check/route-fb11d0d31328bf72.js +0 -1
  255. package/.next/static/chunks/app/api/skills/install/route-fb11d0d31328bf72.js +0 -1
  256. package/.next/static/chunks/app/api/skills/route-fb11d0d31328bf72.js +0 -1
  257. package/.next/static/chunks/app/api/skills/search/route-fb11d0d31328bf72.js +0 -1
  258. package/.next/static/chunks/app/api/skills/update/route-fb11d0d31328bf72.js +0 -1
  259. package/.next/static/chunks/app/api/subagent-runs/route-fb11d0d31328bf72.js +0 -1
  260. package/.next/static/chunks/app/api/update/apply/route-fb11d0d31328bf72.js +0 -1
  261. package/.next/static/chunks/app/api/update/check/route-fb11d0d31328bf72.js +0 -1
  262. package/.next/static/chunks/app/api/worktrees/route-fb11d0d31328bf72.js +0 -1
  263. package/.next/static/chunks/app/page-f29f2997141a81c4.js +0 -25
  264. package/.next/static/chunks/next/dist/client/components/builtin/app-error-fb11d0d31328bf72.js +0 -1
  265. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-fb11d0d31328bf72.js +0 -1
  266. package/.next/static/chunks/next/dist/client/components/builtin/not-found-fb11d0d31328bf72.js +0 -1
  267. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-fb11d0d31328bf72.js +0 -1
  268. /package/.next/static/{0jTCyAHZ1cMAQtbthkA6a → Xz9XxhYAztXJctQiqfonK}/_ssgManifest.js +0 -0
@@ -1,2 +1,2 @@
1
- exports.id=5274,exports.ids=[5274],exports.modules={10433:(a,b,c)=>{"use strict";c.d(b,{H7:()=>g,cS:()=>h});var d=c(89477),e=c(86697);let f="win32"===process.platform?"npm.cmd":"npm";function g(a=process.env,b=process.execPath){let c=a.npm_execpath?.trim();if(c&&(0,d.existsSync)(c))return c;let h=(0,e.join)((0,e.dirname)(b),f);return(0,d.existsSync)(h)?h:f}function h(a=process.env,b=g(a),c=process.execPath){let d=(0,e.dirname)(b===f?c:b);return{...a,PATH:`${d}${e.delimiter}${a.PATH??""}`}}},31974:(a,b,c)=>{"use strict";c.d(b,{ex:()=>z,i7:()=>A});var d=c(95398),e=c(89477),f=c(86697),g=c(37418),h=c(10433);let i=(0,g.promisify)(d.execFile),j="@henlii/pidance",k="https://registry.npmjs.org/",l="pidance.service";function m(a,b){return 0===b||"active"===a.trim()}function n(a){if(a.restartOk||a.laterActive)return{restarted:!0};let b=a.restartError?.trim();return{restarted:!1,message:b?`重启 ${l} 失败:${b}`:`重启 ${l} 失败`}}function o(a){if(a&&"object"==typeof a&&"stdout"in a){let b=a.stdout;if("string"==typeof b)return b;if(Buffer.isBuffer(b))return b.toString("utf8")}return""}function p(a){if(a&&"object"==typeof a&&"code"in a){let b=a.code;if("number"==typeof b&&Number.isFinite(b))return b}return null}function q(a,b){return b?["--user",a,l]:[a,l]}async function r(a,b){if("0"===b.PIDANCE_SYSTEMCTL_USER)return!1;if("1"===b.PIDANCE_SYSTEMCTL_USER)return!0;if(!b.XDG_RUNTIME_DIR&&!b.DBUS_SESSION_BUS_ADDRESS)return!1;try{let c=await a("systemctl",q("is-active",!0),{timeout:1e4,env:b});return m(String(c.stdout??""),0)}catch(a){return m(o(a),p(a))}}async function s(a,b,c){try{let d=await a("systemctl",q("is-active",c),{timeout:1e4,env:b});return m(String(d.stdout??""),0)}catch(a){return m(o(a),p(a))}}async function t(a){let b=a.execFileImpl??i,c=a.env??process.env,d=a.sleepImpl??(a=>new Promise(b=>{setTimeout(b,a)})),e=a.now??Date.now,f=await r(b,c);try{return await b("systemctl",q("restart",f),{timeout:21e4,env:c}),n({restartOk:!0,laterActive:!1})}catch(h){let a=h instanceof Error?h.message:String(h),g=e();if(await s(b,c,f))return n({restartOk:!1,restartError:a,laterActive:!0});for(;e()-g<6e4;)if(await d(1500),await s(b,c,f))return n({restartOk:!1,restartError:a,laterActive:!0});return n({restartOk:!1,restartError:a,laterActive:!1})}}function u(a=process.env){let b=(a.PIDANCE_NPM_REGISTRY||a.npm_config_registry||k).trim();return b?b.endsWith("/")?b:`${b}/`:k}function v(a,b){let c=w(a),d=w(b);if(!c||!d)return 0;for(let a=0;a<3;a++){if(c.core[a]>d.core[a])return 1;if(c.core[a]<d.core[a])return -1}return null===c.pre&&null===d.pre?0:null===c.pre?1:null===d.pre||c.pre<d.pre?-1:+(c.pre>d.pre)}function w(a){let b=a.trim().replace(/^v/i,""),c=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(b);return c?{core:[Number(c[1]),Number(c[2]),Number(c[3])],pre:c[4]??null}:null}async function x(a=u(),b=globalThis.fetch.bind(globalThis)){let c=new URL("@henlii%2Fpidance/latest",a.endsWith("/")?a:`${a}/`).toString();try{let a=await b(c,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(12e3)});if(!a.ok)return null;let d=await a.json();return"string"==typeof d.version&&d.version.trim()?d.version.trim():null}catch{return null}}async function y(a=u(),b=Date.now(),c=globalThis.fetch.bind(globalThis),d=!1){let e=globalThis.__piPidanceLatestCache;if(!d&&e&&b-e.ts<18e5&&e.latest)return e.latest;let f=await x(a,c);return f&&(globalThis.__piPidanceLatestCache={latest:f,ts:b}),f}async function z(a){let b,c=a?.cwd??process.cwd(),d=a?.env??process.env,g=u(d),h=function(a=process.cwd()){for(let b of[(0,f.join)(a,"package.json"),(0,f.join)(a,"node_modules","@henlii","pidance","package.json")])try{if(!(0,e.existsSync)(b))continue;let a=JSON.parse((0,e.readFileSync)(b,"utf8"));if(a.name===j&&"string"==typeof a.version&&a.version.trim())return a.version.trim();let c=a.dependencies?.[j];if("string"==typeof c&&c.trim()&&!c.startsWith("file:"))return c.trim().replace(/^[\^~>=<\s]+/,"")}catch{}let b="0.2.33".trim();return b&&"unknown"!==b?b:"0.0.0"}(c),{mode:i,installRoot:k}=function(a=process.cwd(),b=process.env){let c=function(a,b=process.env){let c=b.PIDANCE_INSTALL_ROOT?.trim();if(c)try{return(0,f.resolve)(c)}catch{return null}let d=a;try{d=(0,e.realpathSync)(a)}catch{d=(0,f.resolve)(a)}let g=d.replace(/\\/g,"/"),h=/^(.*)\/releases\/[^/]+\/node_modules\/@henlii\/pidance$/.exec(g);if(h)return(0,f.resolve)(h[1]);let i=/^(.*)\/releases\/[^/]+$/.exec(g);return i?(0,f.resolve)(i[1]):null}(a,b);if(c)return{mode:"formal-install",installRoot:c};try{let b=(0,f.join)(a,"package.json");if((0,e.existsSync)(b)&&JSON.parse((0,e.readFileSync)(b,"utf8")).name===j)return{mode:"workspace",installRoot:null}}catch{}return{mode:"unknown",installRoot:null}}(c,d),l=await y(g,a?.now,a?.fetchImpl,a?.forceRefresh===!0),m=null!=l&&v(l,h)>0,n=function(a=process.env){return"0"!==a.PIDANCE_ALLOW_SELF_UPGRADE}(d),o=n&&"formal-install"===i&&null!=k;return b=l?m?o?`可升级到 ${l}`:"workspace"===i?"当前为工作区/测试部署,仅提示有新版本;请在正式安装位(31415)一键升级":n?"未检测到正式安装目录,无法一键升级":"已禁用自升级(PIDANCE_ALLOW_SELF_UPGRADE=0)":"已是最新版本":"无法从 npm registry 获取最新版本",{currentVersion:h,latestVersion:l,updateAvailable:m,upgradeSupported:o,upgradeMode:i,installRoot:k,packageName:j,registry:g,reason:b,checkedAt:new Date(a?.now??Date.now()).toISOString()}}async function A(a){let b=a?.cwd??process.cwd(),c=a?.env??process.env,d=a?.execFileImpl??i,g=(b,c,d)=>{try{a?.onProgress?.({phase:b,percent:c,message:d})}catch{}};g("preparing",5,"准备升级…");let k=await z({cwd:b,env:c,fetchImpl:a?.fetchImpl});if(!k.upgradeSupported||!k.installRoot)return g("error",100,k.reason),{ok:!1,status:"not_supported",currentVersion:k.currentVersion,targetVersion:k.latestVersion,message:k.reason};let m=(a?.targetVersion?.trim()||k.latestVersion||"").trim();if(!m)return{ok:!1,status:"error",currentVersion:k.currentVersion,targetVersion:null,message:"无目标版本"};if(0>=v(m,k.currentVersion)&&!a?.targetVersion)return g("done",100,"已是最新版本"),{ok:!0,status:"already_latest",currentVersion:k.currentVersion,targetVersion:m,message:"已是最新版本"};if(!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(m))return{ok:!1,status:"error",currentVersion:k.currentVersion,targetVersion:m,message:"非法版本号"};let n=k.installRoot,o=(0,f.join)(n,"releases",m),p=k.registry;try{g("preparing",12,`创建发布目录 ${m}…`),(0,e.mkdirSync)(o,{recursive:!0});let b={name:`pidance-${m}`,version:"1.0.0",private:!0,dependencies:{[j]:m}};(0,e.writeFileSync)((0,f.join)(o,"package.json"),`${JSON.stringify(b,null,2)}
1
+ exports.id=5274,exports.ids=[5274],exports.modules={10433:(a,b,c)=>{"use strict";c.d(b,{H7:()=>g,cS:()=>h});var d=c(89477),e=c(86697);let f="win32"===process.platform?"npm.cmd":"npm";function g(a=process.env,b=process.execPath){let c=a.npm_execpath?.trim();if(c&&(0,d.existsSync)(c))return c;let h=(0,e.join)((0,e.dirname)(b),f);return(0,d.existsSync)(h)?h:f}function h(a=process.env,b=g(a),c=process.execPath){let d=(0,e.dirname)(b===f?c:b);return{...a,PATH:`${d}${e.delimiter}${a.PATH??""}`}}},31974:(a,b,c)=>{"use strict";c.d(b,{ex:()=>z,i7:()=>A});var d=c(95398),e=c(89477),f=c(86697),g=c(37418),h=c(10433);let i=(0,g.promisify)(d.execFile),j="@henlii/pidance",k="https://registry.npmjs.org/",l="pidance.service";function m(a,b){return 0===b||"active"===a.trim()}function n(a){if(a.restartOk||a.laterActive)return{restarted:!0};let b=a.restartError?.trim();return{restarted:!1,message:b?`重启 ${l} 失败:${b}`:`重启 ${l} 失败`}}function o(a){if(a&&"object"==typeof a&&"stdout"in a){let b=a.stdout;if("string"==typeof b)return b;if(Buffer.isBuffer(b))return b.toString("utf8")}return""}function p(a){if(a&&"object"==typeof a&&"code"in a){let b=a.code;if("number"==typeof b&&Number.isFinite(b))return b}return null}function q(a,b){return b?["--user",a,l]:[a,l]}async function r(a,b){if("0"===b.PIDANCE_SYSTEMCTL_USER)return!1;if("1"===b.PIDANCE_SYSTEMCTL_USER)return!0;if(!b.XDG_RUNTIME_DIR&&!b.DBUS_SESSION_BUS_ADDRESS)return!1;try{let c=await a("systemctl",q("is-active",!0),{timeout:1e4,env:b});return m(String(c.stdout??""),0)}catch(a){return m(o(a),p(a))}}async function s(a,b,c){try{let d=await a("systemctl",q("is-active",c),{timeout:1e4,env:b});return m(String(d.stdout??""),0)}catch(a){return m(o(a),p(a))}}async function t(a){let b=a.execFileImpl??i,c=a.env??process.env,d=a.sleepImpl??(a=>new Promise(b=>{setTimeout(b,a)})),e=a.now??Date.now,f=await r(b,c);try{return await b("systemctl",q("restart",f),{timeout:21e4,env:c}),n({restartOk:!0,laterActive:!1})}catch(h){let a=h instanceof Error?h.message:String(h),g=e();if(await s(b,c,f))return n({restartOk:!1,restartError:a,laterActive:!0});for(;e()-g<6e4;)if(await d(1500),await s(b,c,f))return n({restartOk:!1,restartError:a,laterActive:!0});return n({restartOk:!1,restartError:a,laterActive:!1})}}function u(a=process.env){let b=(a.PIDANCE_NPM_REGISTRY||a.npm_config_registry||k).trim();return b?b.endsWith("/")?b:`${b}/`:k}function v(a,b){let c=w(a),d=w(b);if(!c||!d)return 0;for(let a=0;a<3;a++){if(c.core[a]>d.core[a])return 1;if(c.core[a]<d.core[a])return -1}return null===c.pre&&null===d.pre?0:null===c.pre?1:null===d.pre||c.pre<d.pre?-1:+(c.pre>d.pre)}function w(a){let b=a.trim().replace(/^v/i,""),c=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(b);return c?{core:[Number(c[1]),Number(c[2]),Number(c[3])],pre:c[4]??null}:null}async function x(a=u(),b=globalThis.fetch.bind(globalThis)){let c=new URL("@henlii%2Fpidance/latest",a.endsWith("/")?a:`${a}/`).toString();try{let a=await b(c,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(12e3)});if(!a.ok)return null;let d=await a.json();return"string"==typeof d.version&&d.version.trim()?d.version.trim():null}catch{return null}}async function y(a=u(),b=Date.now(),c=globalThis.fetch.bind(globalThis),d=!1){let e=globalThis.__piPidanceLatestCache;if(!d&&e&&b-e.ts<18e5&&e.latest)return e.latest;let f=await x(a,c);return f&&(globalThis.__piPidanceLatestCache={latest:f,ts:b}),f}async function z(a){let b,c=a?.cwd??process.cwd(),d=a?.env??process.env,g=u(d),h=function(a=process.cwd()){for(let b of[(0,f.join)(a,"package.json"),(0,f.join)(a,"node_modules","@henlii","pidance","package.json")])try{if(!(0,e.existsSync)(b))continue;let a=JSON.parse((0,e.readFileSync)(b,"utf8"));if(a.name===j&&"string"==typeof a.version&&a.version.trim())return a.version.trim();let c=a.dependencies?.[j];if("string"==typeof c&&c.trim()&&!c.startsWith("file:"))return c.trim().replace(/^[\^~>=<\s]+/,"")}catch{}let b="0.2.34".trim();return b&&"unknown"!==b?b:"0.0.0"}(c),{mode:i,installRoot:k}=function(a=process.cwd(),b=process.env){let c=function(a,b=process.env){let c=b.PIDANCE_INSTALL_ROOT?.trim();if(c)try{return(0,f.resolve)(c)}catch{return null}let d=a;try{d=(0,e.realpathSync)(a)}catch{d=(0,f.resolve)(a)}let g=d.replace(/\\/g,"/"),h=/^(.*)\/releases\/[^/]+\/node_modules\/@henlii\/pidance$/.exec(g);if(h)return(0,f.resolve)(h[1]);let i=/^(.*)\/releases\/[^/]+$/.exec(g);return i?(0,f.resolve)(i[1]):null}(a,b);if(c)return{mode:"formal-install",installRoot:c};try{let b=(0,f.join)(a,"package.json");if((0,e.existsSync)(b)&&JSON.parse((0,e.readFileSync)(b,"utf8")).name===j)return{mode:"workspace",installRoot:null}}catch{}return{mode:"unknown",installRoot:null}}(c,d),l=await y(g,a?.now,a?.fetchImpl,a?.forceRefresh===!0),m=null!=l&&v(l,h)>0,n=function(a=process.env){return"0"!==a.PIDANCE_ALLOW_SELF_UPGRADE}(d),o=n&&"formal-install"===i&&null!=k;return b=l?m?o?`可升级到 ${l}`:"workspace"===i?"当前为工作区/测试部署,仅提示有新版本;请在正式安装位(31415)一键升级":n?"未检测到正式安装目录,无法一键升级":"已禁用自升级(PIDANCE_ALLOW_SELF_UPGRADE=0)":"已是最新版本":"无法从 npm registry 获取最新版本",{currentVersion:h,latestVersion:l,updateAvailable:m,upgradeSupported:o,upgradeMode:i,installRoot:k,packageName:j,registry:g,reason:b,checkedAt:new Date(a?.now??Date.now()).toISOString()}}async function A(a){let b=a?.cwd??process.cwd(),c=a?.env??process.env,d=a?.execFileImpl??i,g=(b,c,d)=>{try{a?.onProgress?.({phase:b,percent:c,message:d})}catch{}};g("preparing",5,"准备升级…");let k=await z({cwd:b,env:c,fetchImpl:a?.fetchImpl});if(!k.upgradeSupported||!k.installRoot)return g("error",100,k.reason),{ok:!1,status:"not_supported",currentVersion:k.currentVersion,targetVersion:k.latestVersion,message:k.reason};let m=(a?.targetVersion?.trim()||k.latestVersion||"").trim();if(!m)return{ok:!1,status:"error",currentVersion:k.currentVersion,targetVersion:null,message:"无目标版本"};if(0>=v(m,k.currentVersion)&&!a?.targetVersion)return g("done",100,"已是最新版本"),{ok:!0,status:"already_latest",currentVersion:k.currentVersion,targetVersion:m,message:"已是最新版本"};if(!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(m))return{ok:!1,status:"error",currentVersion:k.currentVersion,targetVersion:m,message:"非法版本号"};let n=k.installRoot,o=(0,f.join)(n,"releases",m),p=k.registry;try{g("preparing",12,`创建发布目录 ${m}…`),(0,e.mkdirSync)(o,{recursive:!0});let b={name:`pidance-${m}`,version:"1.0.0",private:!0,dependencies:{[j]:m}};(0,e.writeFileSync)((0,f.join)(o,"package.json"),`${JSON.stringify(b,null,2)}
2
2
  `,"utf8"),g("downloading",20,"正在从 npm 下载包…");let i=(0,h.H7)(c);await d(i,["install","--omit=dev",`--registry=${p}`,"--no-fund","--no-audit"],{cwd:o,env:{...(0,h.cS)(c,i),npm_config_registry:p},timeout:6e5,maxBuffer:8388608}),g("installing",82,"校验安装结果…");let q=(0,f.join)(o,"node_modules","@henlii","pidance","package.json");if(!(0,e.existsSync)(q))throw Error("安装后未找到 @henlii/pidance 包");let r=JSON.parse((0,e.readFileSync)(q,"utf8"));if(r.version!==m)throw Error(`安装版本不符:期望 ${m},实际 ${r.version??"?"}`);g("linking",88,"切换 current 符号链接…");let s=(0,f.join)(n,"current"),u=(0,f.join)(n,`.current-tmp-${process.pid}`);try{(0,e.existsSync)(u)&&(0,e.rmSync)(u,{force:!0,recursive:!0})}catch{}(0,e.symlinkSync)(o,u),(0,e.renameSync)(u,s);try{!function(a,b){let c=(0,f.join)(a,"releases");if(!(0,e.existsSync)(c))return;let d=new Set(b.map(a=>a.trim()).filter(Boolean));try{let b=(0,e.realpathSync)((0,f.join)(a,"current")),c=/\/releases\/([^/]+)$/.exec(b.replace(/\\/g,"/"));c&&d.add(c[1])}catch{}let g=c;try{g=(0,e.realpathSync)(c)}catch{return[]}let h=[];for(let a of(0,e.readdirSync)(c,{withFileTypes:!0})){let b;if(!a.isDirectory()||a.isSymbolicLink()||"."===a.name||".."===a.name||a.name.includes("/")||a.name.includes("\\")||d.has(a.name))continue;let i=(0,f.join)(c,a.name);try{b=(0,e.realpathSync)(i)}catch{continue}let j=g.endsWith("/")?g:`${g}/`;(b===g||b.startsWith(j))&&((0,e.rmSync)(i,{recursive:!0,force:!0}),h.push(a.name))}}(n,[m,k.currentVersion])}catch{}let v=!1;if(a?.restartService!==!1&&"1"!==c.PIDANCE_SKIP_SERVICE_RESTART){g("restarting",94,"正在重启服务…");let a=await t({execFileImpl:d,env:c});if(v=a.restarted,!a.restarted){let b={ok:!0,status:"upgraded",currentVersion:k.currentVersion,targetVersion:m,message:`已切换到 ${m},但${a.message??`重启 ${l} 失败`}`,restarted:!1};return g("done",100,b.message),b}}let w={ok:!0,status:"upgraded",currentVersion:k.currentVersion,targetVersion:m,message:v?`已升级到 ${m} 并重启服务`:`已升级到 ${m}(未重启服务)`,restarted:v};return g("done",100,w.message),w}catch(b){let a=b instanceof Error?b.message:String(b);return g("error",100,`升级失败:${a}`),{ok:!1,status:"error",currentVersion:k.currentVersion,targetVersion:m,message:`升级失败:${a}`}}}},78335:()=>{},96487:()=>{}};
@@ -1,2 +1,2 @@
1
- "use strict";exports.id=5304,exports.ids=[5304],exports.modules={10611:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>z});var e=c(75430),f=c(92783),g=c(84127),h=c(82356),i=c(68642),j=c(93686),k=c(40673),l=c(99595),m=c(89358),n=c(31360),o=c(75377),p=c(63480),q=c(33727),r=c(31119),s=c(11955),t=c(35948),u=c(58732),v=c(19228),w=c(36315),x=a([e,j,n,u,v]);function y(a){return"string"==typeof a&&a?a:void 0}[e,j,n,u,v]=x.then?(await x)():x;class A{static{this.PARTIAL_RENDER_MIN_INTERVAL_MS=100}constructor(a){this.options=a,this.listeners=[],this.runtime=null,this.unsubscribe=null,this.extensionUi=null,this.idleTimer=null,this.startupHoldTimer=null,this.startupHold=!0,this.activeCommandCount=0,this.destroyCallbacks=new Set,this.pendingDestroys=new Map,this._alive=!0,this.promptRunning=!1,this.streamRunSeq=0,this.lastStopReason=null,this.followUpQueue=[],this.followUpQueueRevision=0,this.followUpQueueHydrated=!1,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,this.internalPromptTicket=Symbol("pidance internal follow-up prompt"),this.followUpFlushBlocked=!1,this.dispatchingFollowUpQueue=!1,this.commandReceipts=new Map,this.bashRunning=!1,this.bashCommand=null,this.localQueue={steering:[],followUp:[]},this.turnMetrics={startedAt:0,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},this.promptReceipts=new Map,this.promptInFlight=new Map,this.steerFlights=new Map,this.pendingBinaryBatches=[],this.destroyPromise=null,this.hasQueueSnapshot=!1,this.renderBridgeTheme=(0,w.Lm)(),this.toolRenderStates=new Map,this.followUpAdmittedAttemptIds=[],this.realSessionId=a.sessionId,this.realSessionFile=a.sessionFile,this.idleTimeoutMs=a.idleTimeoutMs??3e4,this.destroyWaitMs=a.destroyWaitMs??5e3,this.agentDir=a.agentDir??(0,f.$M)(),this.activeToolNames=a.toolNames}get sessionId(){return this.realSessionId}get sessionFile(){return this.realSessionFile}listPendingExtensionRequests(){return Array.from(this.extensionUi?.pendingSnapshot.values()??[])}get inner(){let a=this.runtime?.session;if(a)return{sessionManager:a.sessionManager}}isAlive(){return this._alive&&null!==this.runtime}isRunning(){if(!this._alive||!this.runtime)return!1;let a=this.runtime.session;return this.promptRunning||this.bashRunning||a.isStreaming||a.isCompacting}async runSteerCommand(a){let b=this.session;if(this.bashRunning){let b=this.reject(a.submissionId,"bash");return this.commandReceipts.set(a.submissionId,b),b}if(b.isCompacting&&!b.isStreaming&&!this.promptRunning){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"compacting");return this.commandReceipts.set(a.submissionId,c),c}let c=this.resolvePromptImages(a.images);if(c.missing.length){console.error("[pidance] steer image missing on disk:",c.missing);let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}if(!this.isRunning()&&!this.flushingFollowUp){let b=await this.send({type:"prompt",message:a.message,images:a.images,streamingBehavior:"steer"}),c={...b,submissionId:a.submissionId,action:"accepted"===b.status?"prompt":"queued"};return this.commandReceipts.set(a.submissionId,c),c}if(!b.isStreaming){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"busy");return this.commandReceipts.set(a.submissionId,c),c}await b.steer(a.message,c.images);let d={submissionId:a.submissionId,sessionId:this.realSessionId,status:"accepted",action:"steer"};return this.commandReceipts.set(a.submissionId,d),d}onDestroy(a){return this.destroyCallbacks.add(a),()=>{this.destroyCallbacks.delete(a)}}onEvent(a){let b=0===this.listeners.length;return this.listeners.push(a),b&&this.resetIdleTimer(),()=>{let b=this.listeners.length>0;this.listeners=this.listeners.filter(b=>b!==a),b&&0===this.listeners.length&&this.resetIdleTimer()}}beginExtensionBinding(){}async waitForExtensionsBound(){}emit(a){for(let b of this.listeners)try{b(a)}catch(a){console.error("[pidance] sdk host listener error:",a)}}notifyRunning(){this.options.onRunningChange?.()}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!this._alive||!this.runtime||this.startupHold||this.isRunning()||this.flushingFollowUp)return;if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(this.listeners.length>0)return;let a=this.idleTimeoutMs;this.idleTimer=setTimeout(()=>{this.idleTimer=null,this.isRunning()||this.flushingFollowUp||(this.hasWaitingFollowUp()&&!this.isFollowUpHeld()?this.scheduleFollowUpFlush():this.listeners.length>0||this.destroyAsync().catch(()=>{}))},a)}releaseStartupHold(){this.startupHold&&(this.startupHold=!1,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null)}isSettled(){return!!this.runtime&&!!this._alive&&!this.isRunning()}isFollowUpHeld(){let a=(0,g.readPidancePrefs)(this.agentDir);return!0===(0,g.ql)(a,`sessionQueueHold.${this.realSessionId}`)}setFollowUpHeld(a){try{(0,g.xP)(`sessionQueueHold.${this.realSessionId}`,!!a||null,this.agentDir)}catch(b){console.error("[pidance] failed to persist follow-up hold:",b),this.emit({type:"follow_up_flush_error",errorMessage:a?"failed to persist follow-up hold; the queue may flush automatically":"failed to clear follow-up hold; the queue may stay held",...this.queueReceiptBase()})}}hydrateFollowUpQueue(){if(this.followUpQueueHydrated)return;this.followUpQueueHydrated=!0;let a=(0,g.readPidancePrefs)(this.agentDir),b=(0,g.ql)(a,`sessionQueue.${this.realSessionId}`),c=(0,k.jG)(b);this.followUpQueue=c.items.map(a=>"claimed"===a.state?{...a,state:"unknown"}:a),this.followUpQueueRevision=c.revision,this.followUpAdmittedAttemptIds=c.admittedAttemptIds,this.followUpQueue=this.followUpQueue.map(a=>{if(!a.media?.length)return a;let b=a.media.filter(a=>this.isQueueMediaRefAlive(a));return b.length===a.media.length?a:{...b.length?{...a,media:b}:{text:a.text,id:a.id,state:a.state},state:"unknown"}})}waitingFollowUp(){return this.followUpQueue.filter(a=>"waiting"===a.state)}hasWaitingFollowUp(){return this.followUpQueue.some(a=>"waiting"===a.state)}visibleFollowUp(){return this.followUpQueue.filter(a=>"claimed"!==a.state)}inFlightFollowUpTexts(){return this.followUpQueue.filter(a=>"claimed"===a.state).map(a=>a.text)}commitFollowUpQueue(a,b,c=[]){for(let c of a)if((c.media?.length??0)>k.ym)return console.error(`[pidance] refusing to persist follow-up queue (${b}): item media exceeds ${k.ym}`),!1;let d=this.followUpQueueRevision+1,e=(0,k.S1)(this.followUpAdmittedAttemptIds,c);try{(0,g.xP)(`sessionQueue.${this.realSessionId}`,(0,k.EP)({items:a,revision:d,admittedAttemptIds:e}),this.agentDir)}catch(a){return console.error(`[pidance] failed to persist follow-up queue (${b}):`,a),!1}return this.followUpQueue=a,this.followUpQueueRevision=d,this.followUpAdmittedAttemptIds=e,this.followUpFlushBlocked=!1,!0}discardDeliveredModelMedia(a){let b=new Set((0,k.Ot)(this.followUpQueue).map(a=>a.path));for(let c of a)"model"!==c.role||b.has(c.path)||(0,j.fm)(c.path,this.agentDir)}withFollowUpState(a,b){let c=new Set(a);return this.followUpQueue.map(a=>c.has(a.id)?{...a,state:b}:a)}queueReceiptBase(){return{revision:this.followUpQueueRevision,items:this.visibleFollowUp(),inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}reject(a,b){return{submissionId:a,sessionId:this.realSessionId,status:"rejected",reason:b}}isQueueMediaRefAlive(a){let b="model"===a.role?8388608:j.Md,c=(0,j.vy)(a.path,this.agentDir);return null!==c&&c<=b}validateQueueMedia(a){if(!a?.length)return!0;if(a.length>k.ym)return!1;let b=0;for(let c of a){let a=(0,j.vy)(c.path,this.agentDir);if(null===a)return!1;let d="model"===c.role?8388608:j.Md;if(a>d||(b+=a,c.previewPath&&null===(0,j.vy)(c.previewPath,this.agentDir)))return!1}return b<=j.Lj}readQueueModelImages(a){let b=[],c=[];for(let d of(0,k.Ot)(a)){if("model"!==d.role)continue;let a=(0,j.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b,missing:c}}queueBinaryBlocks(a){return(0,k.Ot)(a).filter(a=>"original"===a.role).map(a=>({path:a.path,name:a.name,mimeType:a.mimeType,size:a.size,...a.previewPath?{previewPath:a.previewPath}:{}}))}writeFollowUpQueue(a,b){if(null!==b&&b!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};for(let b of a)if(!this.validateQueueMedia(b.media))return{ok:!1,persist:!0,...this.queueReceiptBase()};let c=this.followUpQueue.filter(a=>"claimed"===a.state),d=this.followUpQueue.filter(a=>"claimed"!==a.state),e=[...c,...(0,k.Pt)(d,a,{inFlightIds:c.map(a=>a.id)})];return this.commitFollowUpQueue(e,"set",a.map(a=>a.attemptId))?{ok:!0,...this.queueReceiptBase()}:{ok:!1,persist:!0,...this.queueReceiptBase()}}recallFollowUpQueue(a){let b=[],c=[];for(let d of a){let a=this.followUpQueue.find(a=>a.id===d);if(!a){c.push({id:d,reason:"missing"});continue}if("claimed"===a.state){c.push({id:d,reason:"claimed"});continue}b.push(a)}if(!b.length)return{ok:!0,...this.queueReceiptBase(),recalled:[],skipped:c};let d=new Set(b.map(a=>a.id)),e=this.followUpQueue.filter(a=>!d.has(a.id));return this.commitFollowUpQueue(e,"recall")?(this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,...this.queueReceiptBase(),recalled:b,skipped:c}):{ok:!1,persist:!0,...this.queueReceiptBase(),recalled:[],skipped:c}}enqueuePayloads(a,b,c){let d=this.writeFollowUpQueue([...this.visibleFollowUp().map(a=>({text:a.text})),...b],null);return d.ok?(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer(),{submissionId:a,sessionId:this.realSessionId,status:"queued",action:"queued",...c?{reason:c}:{},queue:{items:d.items,inFlight:d.inFlight,revision:d.revision,admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}):this.reject(a,"error")}queueMediaFromPromptImages(a){if(!a?.length)return{media:void 0,ok:!0};let b=[];for(let[c,d]of a.entries()){let a;if("ref"===d.type){let a=(0,j.vy)(d.path,this.agentDir);if(null===a||a>8388608)return{media:void 0,ok:!1};b.push({role:"model",path:d.path,name:d.path.split(/[\\/]/).pop()??`image-${c}`,mimeType:d.mimeType,size:a});continue}try{a=(0,j.ki)(`prompt-image-${c}.${function(a){let b=a.split(";")[0].trim().toLowerCase();return"image/jpeg"===b?"jpg":"image/svg+xml"===b?"svg":b.startsWith("image/")?b.slice(6).replace(/[^a-z0-9]/g,"")||"png":"bin"}(d.mimeType)}`,Buffer.from(d.data,"base64"),this.agentDir)}catch(a){return console.error("[pidance] inline prompt image could not be stored:",a),{media:void 0,ok:!1}}b.push({role:"model",path:a.path,name:a.name,mimeType:d.mimeType,size:a.size})}return{media:b,ok:!0}}resolvePromptImages(a){if(!a?.length)return{images:void 0,missing:[]};let b=[],c=[];for(let d of a){if("ref"!==d.type){b.push(d);continue}let a=(0,j.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b.length?b:void 0,missing:c}}async dispatchFollowUpQueue(a){if(this.bashRunning)return{ok:!1,status:"rejected",reason:"bash",...this.queueReceiptBase()};if(this.session.isCompacting)return{ok:!1,status:"rejected",reason:"compacting",...this.queueReceiptBase()};if(this.flushingFollowUp||this.dispatchingFollowUpQueue)return{ok:!1,conflict:!0,reason:"in-flight",...this.queueReceiptBase()};if(null!==a.expectedRevision&&a.expectedRevision!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};let b=this.waitingFollowUp(),c=a.extra?.trim();if(0===b.length&&!c)return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};let{text:d}=(0,k.X_)(b,c),e=this.readQueueModelImages(b);if(e.missing.length)return console.error("[pidance] queued media missing, dispatch rejected:",e.missing),{ok:!1,status:"rejected",reason:"media",...this.queueReceiptBase()};let f=this.queueBinaryBlocks(b),g=b.map(a=>a.media?.length?(0,k.ko)(a.text,"claimed",a.media):(0,k.ko)(a.text,"claimed"));c&&g.push((0,k.ko)(c,"claimed"));let h=g.map(a=>a.id),i=new Set(h),j=[...this.followUpQueue.filter(a=>"waiting"!==a.state),...g];if(!this.commitFollowUpQueue(j,"dispatch-claim",[a.extraAttemptId]))return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};this.dispatchingFollowUpQueue=!0,this.emitQueueChanged();let l=e.images.length?e.images:void 0,m="prompt";try{if(this.session.isStreaming)m="steer",await this.session.steer(d,l);else{let a=await this.send({type:"prompt",message:d,...l?.length?{images:l}:{},...f.length?{binaryBlocks:f}:{},streamingBehavior:"steer"},this.internalPromptTicket);if(a?.status==="queued")return m="queued",this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-queued"),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:m,...this.queueReceiptBase()};if(a?.status!=="accepted")return this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release"),this.emitQueueChanged(),{ok:!1,status:"rejected",reason:a?.reason??"error",...this.queueReceiptBase()}}}catch(b){let a=this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release");return this.emitQueueChanged(),a||this.emit({type:"follow_up_flush_error",errorMessage:"dispatch rejected and the claim could not be released; it stays claimed for the user to inspect",...this.queueReceiptBase()}),{ok:!1,status:"rejected",reason:(0,s.K2)(b),...this.queueReceiptBase()}}finally{this.dispatchingFollowUpQueue=!1}let n=(0,k.Ot)(g);return this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-deliver")&&this.discardDeliveredModelMedia(n),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:m,...this.queueReceiptBase()}}scheduleFollowUpFlush(){if(!this._alive||!this.runtime||this.flushingFollowUp||this.followUpFlushBlocked||this.isFollowUpHeld()||this.dispatchingFollowUpQueue||!this.isSettled())return;let a=this.waitingFollowUp();if(0===a.length)return;let b=!0===(0,g.readPidancePrefs)(this.agentDir).queueFlushAsOne;this.flushingFollowUp=!0,this.followUpFlushUnits=b?[{ids:a.map(a=>a.id)}]:a.map(a=>({ids:[a.id]})),this.followUpFlushCursor=0,this.sendNextFollowUp()}emitQueueChanged(){let a=this.queueReceiptBase();this.emit({type:"follow_up_queue_changed",sessionId:this.realSessionId,items:a.items,revision:a.revision,inFlight:a.inFlight,admittedAttemptIds:a.admittedAttemptIds})}async sendNextFollowUp(){if(this.followUpSending||!this.flushingFollowUp)return;if(this.isFollowUpHeld())return void this.abortFollowUpFlush();let a=this.followUpFlushUnits[this.followUpFlushCursor];if(void 0===a)return void this.finishFollowUpFlush();if(!this.isSettled())return void setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushUnits[this.followUpFlushCursor]===a&&this.sendNextFollowUp()},80);this.followUpSending=!0;try{await this.deliverFollowUpUnit(a)}finally{this.followUpSending=!1}this.flushingFollowUp&&(this.followUpFlushCursor+=1,this.followUpFlushCursor>=this.followUpFlushUnits.length?this.finishFollowUpFlush():this.sendNextFollowUp())}async deliverFollowUpUnit(a){let b=new Set(a.ids),c=this.followUpQueue.filter(a=>b.has(a.id)&&"waiting"===a.state);if(0===c.length)return void this.emitQueueChanged();let d=c.map(a=>a.id),e=(0,k.X_)(c).text,{images:f,missing:g}=this.readQueueModelImages(c),h=this.queueBinaryBlocks(c);if(g.length){console.error("[pidance] queued image missing, delivery blocked:",g),this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"queued image is missing; delivery blocked",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}let i=f.length?f:void 0;if(this.session.isCompacting||this.bashRunning){this.emit({type:"follow_up_flush_error",errorMessage:this.session.isCompacting?"follow-up delivery deferred while compaction is running":"follow-up delivery deferred while a shell command is running",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}if(!this.commitFollowUpQueue(this.withFollowUpState(d,"claimed"),"claim")){this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"failed to persist follow-up queue before delivery",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}this.emitQueueChanged();let j=null;try{j=await this.send({type:"prompt",message:e,...i?{images:i}:{},...h.length?{binaryBlocks:h}:{}},this.internalPromptTicket)}catch(c){let a=c instanceof Error?c.message:String(c),b=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:a,...this.queueReceiptBase()}),this.abortFollowUpFlush(),b&&this.emitQueueChanged();return}if(j?.status==="queued"){this.commitFollowUpQueue(this.followUpQueue.filter(a=>!new Set(d).has(a.id)),"deliver-queued"),this.emitQueueChanged(),this.abortFollowUpFlush();return}if(j&&"accepted"!==j.status){let a=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:`follow-up prompt rejected: ${j.reason??"unknown"}`,...this.queueReceiptBase()}),this.abortFollowUpFlush(),a&&this.emitQueueChanged();return}let l=new Set(d),m=(0,k.Ot)(c),n=this.commitFollowUpQueue(this.followUpQueue.filter(a=>!l.has(a.id)),"deliver");n&&this.discardDeliveredModelMedia(m),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:e,...this.queueReceiptBase()}),n||this.emit({type:"follow_up_flush_error",errorMessage:"follow-up delivered but queue removal was not persisted",...this.queueReceiptBase()}),this.emitQueueChanged()}abortFollowUpFlush(){this.flushingFollowUp&&(this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer())}finishFollowUpFlush(){this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.scheduleFollowUpFlush()}get session(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.session}get services(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.services}syncIdentityFromSession(){let a=this.session,b=a.sessionId||this.realSessionId,c=a.sessionFile||this.realSessionFile,d=this.realSessionId;this.realSessionId=b,this.realSessionFile=c,c&&this.options.cacheSessionPath?.(b,c),d!==b&&this.options.onSessionRekeyed?.(d,b,this)}async rebindSession(){let a=this.session;this.extensionUi?.dispose(),this.extensionUi=(0,o.t)(a=>{this.trackExtensionSideEffects(a),this.emit(a)}),await a.bindExtensions({uiContext:this.extensionUi.uiContext,mode:"rpc",commandContextActions:{waitForIdle:()=>a.waitForIdle(),newSession:async a=>{let b=await this.runtime.newSession(a);return b.cancelled||await this.rebindSession(),b},fork:async(a,b)=>{let c=await this.runtime.fork(a,b);return c.cancelled||await this.rebindSession(),{cancelled:c.cancelled}},navigateTree:async(b,c)=>({cancelled:(await a.navigateTree(b,{summarize:c?.summarize,customInstructions:c?.customInstructions,replaceInstructions:c?.replaceInstructions,label:c?.label})).cancelled}),switchSession:async(a,b)=>{let c=await this.runtime.switchSession(a,b);return c.cancelled||await this.rebindSession(),c},reload:async()=>{await a.reload()}},onError:a=>{this.setFollowUpHeld(!0),this.emit({type:"extension_error",extensionPath:a.extensionPath,event:a.event,error:a.error})}}),this.unsubscribe?.(),this.unsubscribe=a.subscribe(a=>{this.resetIdleTimer(),this.handleSessionEvent(a)}),this.syncIdentityFromSession()}trackExtensionSideEffects(a){if("extension_ui_request"!==a.type)return;let b=y(a.method);if("setStatus"===b){let b=y(a.statusKey)??y(a.key)??"default",c=y(a.statusText)??y(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=y(a.widgetKey)??y(a.key)??"default",c=a.widgetLines??a.content;null==c?this.extensionUi?.widgets.delete(b):this.extensionUi?.widgets.set(b,{lines:c,placement:a.widgetPlacement})}this.notifyRunning()}maybeAutoNameSession(){try{let a=this.session?.sessionManager;if(!a||a.getSessionName())return;let b=(a.buildSessionContext().messages??[]).find(a=>"user"===a.role),c=function(a){let b="";"string"==typeof a?b=a:Array.isArray(a)&&(b=a.filter(a=>"object"==typeof a&&null!==a&&"text"===a.type&&"string"==typeof a.text).map(a=>a.text).join("\n"));let c=b.replace(/\s+/g," ").trim();if(c)return c.length>60?`${c.slice(0,60)}…`:c}(b?.content);c&&a.appendSessionInfo(c)}catch{}}readStopReasonFromAgentEnd(a){let b=a.messages;if(!Array.isArray(b))return null;for(let a=b.length-1;a>=0;a--){let c=b[a],d=c?.message?.stopReason??c?.stopReason;if("string"==typeof d){if("aborted"===d)return"aborted";if("error"===d||"prompt_error"===d)return"error";return"completed"}}return null}removePendingBinaryBatch(a){this.pendingBinaryBatches=this.pendingBinaryBatches.filter(b=>b.submissionId!==a)}persistPendingBinaryBlocks(a){if(0!==a.length)try{let b=this.session.sessionManager;(0,n.kb)(b);let c=b.getEntries(),d=[...c].reverse().find(a=>"message"===a.type&&a.message?.role==="user"&&"string"==typeof a.id)?.id||b.getLeafId()||void 0;for(let c of a){let a=d?{...c,messageEntryId:d}:c,e=b.appendCustomEntry(t.uG,a);this.emit({type:"message_end",entryId:e,message:(0,t.FH)(a,Date.now())})}(0,n.kb)(b),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] persist binary message failed:",a)}}static hasRenderableContent(a){if(!a)return!1;let b=a.content;return"string"==typeof b?b.length>0:Array.isArray(b)&&b.length>0}static outputTokensOf(a){let b=a?.usage?.output;return"number"==typeof b&&Number.isFinite(b)&&b>=0?b:null}accumulateTurnMetrics(a){let b=Date.now();if("agent_start"===a.type)return this.turnMetrics={startedAt:b,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},!0;if("message_start"===a.type||"message_update"===a.type){let c=a.message;if(c?.role==="user")return!1;if(null===this.turnMetrics.firstTokenAt&&A.hasRenderableContent(c)){this.turnMetrics.firstTokenAt=b;let a=null===this.turnMetrics.ttftMs;return a&&this.turnMetrics.startedAt>0&&b>=this.turnMetrics.startedAt&&(this.turnMetrics.ttftMs=b-this.turnMetrics.startedAt),a}return!1}if("message_end"===a.type){let c=a.message;if(c?.role!=="assistant")return!1;let d=null===this.turnMetrics.firstTokenAt?null:Math.max(0,b-this.turnMetrics.firstTokenAt);this.turnMetrics.firstTokenAt=null;let e=A.outputTokensOf(c);if(null!==d&&null!==e)return this.turnMetrics.decodeMs+=d,this.turnMetrics.outputTokens+=e,this.turnMetrics.sampled=!0,!0}return!1}projectTurnMetrics(){let a={};return null!==this.turnMetrics.ttftMs&&this.turnMetrics.startedAt>0&&(a.ttftMs=this.turnMetrics.ttftMs),this.turnMetrics.sampled&&this.turnMetrics.decodeMs>0&&(a.tokensPerSecond=this.turnMetrics.outputTokens/(this.turnMetrics.decodeMs/1e3)),a}handleSessionEvent(a){let b=this.accumulateTurnMetrics(a),c="agent_start"===a.type?++this.streamRunSeq:this.streamRunSeq;switch(a.type){case"agent_start":this.promptRunning=!0,(0,i.NK)(this.realSessionId,Date.now()),this.notifyRunning();break;case"agent_end":this.promptRunning=!1,this.lastStopReason=this.readStopReasonFromAgentEnd(a)??this.lastStopReason??"completed",("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.setFollowUpHeld(!0),(0,i.PI)(this.realSessionId),this.options.onSessionListInvalidate?.(),this.realSessionFile&&(0,m.$9)(this.realSessionFile),this.maybeAutoNameSession(),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});break;case"agent_settled":this.promptRunning=!1,this.notifyRunning(),"completed"===this.lastStopReason?this.flushingFollowUp?this.sendNextFollowUp():this.scheduleFollowUpFlush():this.flushingFollowUp&&("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.abortFollowUpFlush();let d="agent_settled"===a.type&&!this.flushingFollowUp&&(!this.hasWaitingFollowUp()||this.isFollowUpHeld());this.resetIdleTimer(),d&&this.destroyAsync().catch(()=>{});break;case"compaction_start":case"auto_compaction_start":this.notifyRunning();break;case"compaction_end":case"auto_compaction_end":this.notifyRunning(),!0!==a.aborted&&!a.errorMessage&&this.isSettled()&&this.scheduleFollowUpFlush(),this.resetIdleTimer();break;case"message_end":{let b=a.message;if(b?.role==="user"){let a=this.pendingBinaryBatches.shift();setImmediate(()=>{try{(0,n.kb)(this.session.sessionManager),this.syncIdentityFromSession(),this.persistPendingBinaryBlocks(a?.blocks??[]),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] materialize after user message failed:",a)}})}break}case"queue_update":{let b=Array.isArray(a.steering)?a.steering.filter(a=>"string"==typeof a):[],c=Array.isArray(a.followUp)?a.followUp.filter(a=>"string"==typeof a):[];this.localQueue={steering:b,followUp:c},this.hasQueueSnapshot=!0}}let e=c>0?{...a,streamRunSeq:c}:a;if(b){let a=this.projectTurnMetrics();(void 0!==a.ttftMs||void 0!==a.tokensPerSecond)&&(e={...e,turnMetrics:a})}let f="message_end"===a.type&&a.message?.role==="assistant";if("agent_end"===a.type||f){let a=this.contextUsageSnapshot();a&&(e={...e,contextUsage:a})}this.emit(this.withRenderedToolLines(e))}contextUsageSnapshot(){try{let a=this.session.getContextUsage();if(a&&"number"==typeof a.contextWindow&&a.contextWindow>0)return{contextWindow:a.contextWindow,percent:"number"==typeof a.percent?a.percent:null,tokens:"number"==typeof a.tokens?a.tokens:null}}catch{}}withRenderedToolLines(a){try{if(!this.renderBridgeTheme)return a;switch(a.type){case"tool_execution_update":{if(!this.shouldRenderPartialUpdate(a.toolCallId))return a;let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.args??a.input,{isPartial:!0,expanded:!0,isError:!0===a.isError,resultSlot:!0});if(!c)return a;let d=(0,w.t_)(b,a.partialResult,{expanded:!0,isPartial:!0},c,b=>this.updateToolRenderLastComponent(a.toolCallId,!0,b));return d?{...a,renderedLines:d}:a}case"tool_call":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.input,{isPartial:!1,expanded:!0,isError:!1,resultSlot:!1});if(!c)return a;let d=(0,w.GD)(b,a.input,c,b=>this.updateToolRenderLastComponent(a.toolCallId,!1,b));return d?{...a,renderedCallLines:d}:a}case"tool_result":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.args??a.input,{isPartial:!1,expanded:!0,isError:!0===a.isError,resultSlot:!0});if(!c)return a;let d=(0,w.t_)(b,{content:a.content,details:a.details,isError:!0===a.isError,...void 0!==a.usage?{usage:a.usage}:{}},{expanded:!0,isPartial:!1},c,b=>this.updateToolRenderLastComponent(a.toolCallId,!0,b));return d?{...a,renderedResultLines:d}:a}case"message_start":case"message_end":{let b=a.message;if(b?.role!=="custom"||"string"!=typeof b.customType||""===b.customType)return a;let c=this.session.extensionRunner,d="function"==typeof c?.getMessageRenderer?c.getMessageRenderer(b.customType):void 0,e=(0,w.Mf)(d,a.message,this.renderBridgeTheme);return e?{...a,renderedLines:e}:a}default:return a}}catch{return a}}getToolRenderDefinition(a){if("string"==typeof a&&""!==a)try{return this.session.getToolDefinition(a)}catch{return}}buildToolRenderContext(a,b,c){let d=this.getOrCreateToolRenderState(a);return d?{args:b,toolCallId:a,invalidate:()=>{},lastComponent:c.resultSlot?d.lastResultComponent:d.lastCallComponent,state:d.state,cwd:this.realCwd,executionStarted:!0,argsComplete:!0,isPartial:c.isPartial,expanded:c.expanded,showImages:!1,isError:c.isError}:null}getOrCreateToolRenderState(a){if("string"!=typeof a||""===a)return null;let b=this.toolRenderStates.get(a);return b||(b={state:{},lastCallComponent:void 0,lastResultComponent:void 0,lastPartialRenderAt:void 0},this.toolRenderStates.set(a,b)),b}updateToolRenderLastComponent(a,b,c){if("string"!=typeof a||""===a)return;let d=this.toolRenderStates.get(a);d&&(b?d.lastResultComponent=c:d.lastCallComponent=c)}shouldRenderPartialUpdate(a){if("string"!=typeof a||""===a)return!0;let b=Date.now(),c=this.getOrCreateToolRenderState(a);return!c||(void 0===c.lastPartialRenderAt||!(b-c.lastPartialRenderAt<A.PARTIAL_RENDER_MIN_INTERVAL_MS))&&(c.lastPartialRenderAt=b,!0)}get realCwd(){try{return this.session.sessionManager.getHeader()?.cwd||this.options.cwd}catch{return this.options.cwd}}async start(){try{var a,b;let c=(a=this.realSessionFile,b=this.options.cwd,a?(0,n.G1)(a):(0,n.Qu)(b)),d=c.getCwd()||this.options.cwd,f=this.agentDir,g=this.activeToolNames,h=async({cwd:a,agentDir:b,sessionManager:c,sessionStartEvent:d})=>{let f=(0,v._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:v.Jv,label:"Send file to user",description:"Publish an agent-created project file as a user-visible attachment with preview/download support.",promptSnippet:"deliver a generated file to the user as a downloadable attachment",promptGuidelines:["When the user needs a generated file, call send_file_to_user; do not only print a local path or paste Base64.","Only report a file as delivered after send_file_to_user returns successfully."],parameters:v.Tv,async execute(a,b,c){let d=await f(b,c);return{content:[{type:"text",text:`Delivered ${d.name} to the user (entry ${d.entryId}).`}],details:d}}},i=await (0,e.createAgentSessionServices)({cwd:a,agentDir:b,resourceLoaderOptions:{appendSystemPromptOverride:v.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,r.yu)(a);return{...await (0,e.createAgentSessionFromServices)({services:i,sessionManager:c,sessionStartEvent:d,tools:g&&g.length>0?g:void 0,noTools:g&&0===g.length?"all":void 0}),services:i,diagnostics:i.diagnostics}};this.runtime=await (0,e.createAgentSessionRuntime)(h,{cwd:d,agentDir:f,sessionManager:c}),this.runtime.setRebindSession(async()=>{await this.rebindSession()}),this.runtime.setBeforeSessionInvalidate(()=>{this.extensionUi?.dispose(),this.unsubscribe?.(),this.unsubscribe=null}),await this.rebindSession(),this.syncIdentityFromSession(),this.hydrateFollowUpQueue(),this.startupHoldTimer=setTimeout(()=>{this.startupHoldTimer=null,this.startupHold=!1,this.resetIdleTimer()},15e3),this.startupHoldTimer.unref?.(),this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.isSettled()&&this.scheduleFollowUpFlush()}catch(a){throw await this.destroyAsync(),a}}projectState(){let a=this.session,b=a.model,c={stateSources:{rpcGetState:!1,sdkSession:!0,sessionStats:!0,localQueue:!0,localExtensionUi:!0},sessionId:this.realSessionId,sessionFile:this.realSessionFile,sessionName:a.sessionName,isStreaming:a.isStreaming,isCompacting:a.isCompacting,isPromptRunning:this.promptRunning,lastStopReason:this.lastStopReason,isBashRunning:this.bashRunning,turnMetrics:this.projectTurnMetrics(),pendingBash:this.bashCommand,autoCompactionEnabled:a.autoCompactionEnabled,steeringMode:a.steeringMode,followUpMode:a.followUpMode,thinkingLevel:a.thinkingLevel,systemPrompt:a.systemPrompt??"",model:b?{id:b.id,provider:b.provider,modelId:b.id}:void 0,messageCount:a.messages.length,pendingMessageCount:a.pendingMessageCount,extensionStatuses:Array.from(this.extensionUi?.statuses.entries()??[],([a,b])=>({key:a,text:b})),extensionWidgets:Array.from(this.extensionUi?.widgets.entries()??[],([a,b])=>({key:a,lines:Array.isArray(b?.lines)?b.lines:[],placement:b?.placement==="belowEditor"?"belowEditor":"aboveEditor"})),pendingExtensionRequests:Array.from(this.extensionUi?.pendingSnapshot.values()??[]),activeCustomUi:this.extensionUi?.customSnapshot??null};c.queuedMessages={steering:this.hasQueueSnapshot?[...this.localQueue.steering]:[],followUp:(0,k.gC)(this.visibleFollowUp()),followUpItems:this.visibleFollowUp(),followUpRevision:this.followUpQueueRevision,inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]};try{let b=a.getContextUsage();b&&"number"==typeof b.contextWindow&&b.contextWindow>0&&(c.contextUsage={contextWindow:b.contextWindow,percent:"number"==typeof b.percent?b.percent:null,tokens:"number"==typeof b.tokens?b.tokens:null})}catch{}return c}appendActivity(a){if(!this.runtime)throw Error("Cannot append activity: session not alive");let b=a&&"object"==typeof a&&"type"in a&&"append_activity"===a.type?(0,l.qF)(a):(0,l.l$)(a),c=this.session.sessionManager.appendCustomEntry(l.cP,b);return this.options.onSessionListInvalidate?.(),{entryId:c,activity:b}}appendBinary(a,b){if(!this._alive||!this.runtime||this.destroyPromise)throw Error("Cannot append binary message: session not alive");let c=this.session.sessionManager;if(b&&c!==b)throw Error("Cannot publish file after the session changed");let d=a&&"object"==typeof a&&!Array.isArray(a)?a:{},e="append_binary"===d.type?d.binaryBlock:a,f=(0,u.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(t.uG,f);try{this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] binary message list notification failed:",a)}try{this.emit({type:"message_end",entryId:g,message:(0,t.FH)(f,Date.now())})}catch(a){console.error("[pidance] binary message event notification failed:",a)}return{entryId:g,binary:f}}async send(a,b){if(!this.runtime)throw Error("SDK session is not alive");let c=a.type;"get_state"!==c&&"ensure_session"!==c&&this.releaseStartupHold(),this.activeCommandCount+=1,this.resetIdleTimer();let d=this.session;try{switch(c){case"prompt":{let c=(0,s.JT)(a),e=this.promptReceipts.get(c.submissionId);if(e)return e;let f=c.submissionId,g=this.promptInFlight.get(f);if(g)return g;let j=(0,u.Nu)(c.binaryBlocks,this.agentDir),k=c.images??a.images,l=this.resolvePromptImages(k);if(l.missing.length){console.error("[pidance] prompt image missing on disk:",l.missing);let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}if(this.bashRunning&&!(0,q.D)(c.message)){let a=this.reject(c.submissionId,"bash");return this.promptReceipts.set(c.submissionId,a),a}if(d.isCompacting&&!(0,q.D)(c.message)){let a=this.queueMediaFromPromptImages(k);if(!a.ok){let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}let b=this.enqueuePayloads(c.submissionId,[{text:c.message,...a.media?.length?{media:a.media}:{}}],"compacting");return this.promptReceipts.set(c.submissionId,b),this.options.onSessionListInvalidate?.(),b}if(this.flushingFollowUp&&b!==this.internalPromptTicket&&!(0,q.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}if((this.promptRunning||d.isStreaming)&&"steer"!==a.streamingBehavior){if(!(0,q.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}try{await d.prompt(c.message,{images:l.images,source:"rpc"});let a={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(c.submissionId,a),a}catch{let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}}if(!(0,h.kP)(this.realSessionId))throw Error(h.GT);this.promptRunning=!0,this.lastStopReason=null,(0,i.NK)(this.realSessionId,Date.now()),this.notifyRunning();let m=(async()=>{try{await new Promise((b,e)=>{let g=!1,h=()=>{d.isStreaming||d.isCompacting||this.bashRunning||this.promptRunning&&(this.promptRunning=!1,"aborted"!==this.lastStopReason&&"error"!==this.lastStopReason&&(this.lastStopReason="completed"),(0,i.PI)(this.realSessionId),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq}),this.resetIdleTimer())};d.prompt(c.message,{images:l.images,streamingBehavior:a.streamingBehavior,source:"rpc",preflightResult:a=>{a&&(g=!0,j.length>0&&this.pendingBinaryBatches.push({submissionId:f,blocks:j}),this.syncIdentityFromSession(),this.setFollowUpHeld(!1),this.options.onSessionListInvalidate?.(),b())}}).then(()=>{if(!g){g=!0;try{(0,n.kb)(d.sessionManager)}catch(a){console.error("[pidance] materialize after prompt failed:",a)}this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.(),b()}h()}).catch(a=>{"aborted"!==this.lastStopReason&&(this.lastStopReason="error"),this.setFollowUpHeld(!0),h(),g||(g=!0,e(a))})});let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(f,b),b}catch(g){this.removePendingBinaryBatch(f);let a=(0,s.K2)(g);if(d.isStreaming&&(0,s.in)(a)){let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected",reason:a};return this.promptReceipts.set(f,b),b}this.promptRunning=!1,this.lastStopReason="aborted"===this.lastStopReason?"aborted":"error",this.setFollowUpHeld(!0),(0,i.PI)(this.realSessionId),this.notifyRunning();let b=g instanceof Error?g.message:String(g);this.emit({type:"prompt_error",errorMessage:b}),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});let e={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected"};throw this.promptReceipts.set(f,e),g}finally{this.promptInFlight.delete(f)}})();return this.promptInFlight.set(f,m),m}case"abort":return this.lastStopReason="aborted",this.setFollowUpHeld(!0),this.promptRunning=!1,this.notifyRunning(),await d.abort(),this.notifyRunning(),null;case"get_state":return this.projectState();case"set_model":{let b=String(a.provider??""),c=String(a.modelId??""),e=(0,p.E)(d.modelRuntime,b,c);if(!e)try{e=(await d.modelRuntime.getAvailable()).find(a=>a.provider===b&&a.id===c)}catch{e=void 0}if(!e)throw Error(`Model not found: ${b}/${c}`);return await d.setModel((0,r.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return d.model&&(0,r.yu)(d.model),d.setThinkingLevel(a.level),this.options.onSessionListInvalidate?.(),null;case"compact":{let b=await d.compact("string"==typeof a.customInstructions?a.customInstructions:void 0);return this.options.onSessionListInvalidate?.(),this.notifyRunning(),this.resetIdleTimer(),b}case"steer":{let b=(0,s._3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.steerFlights.get(b.submissionId);if(d)return d;let e=this.runSteerCommand(b);this.steerFlights.set(b.submissionId,e);try{return await e}finally{this.steerFlights.get(b.submissionId)===e&&this.steerFlights.delete(b.submissionId)}}case"dispatch_follow_up_queue":{let b=(0,s.s)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=await this.dispatchFollowUpQueue(b);return this.commandReceipts.set(b.submissionId,d),d}case"recall_follow_up_queue":{let b=(0,s.TJ)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.recallFollowUpQueue(b.itemIds);return this.commandReceipts.set(b.submissionId,d),d}case"set_follow_up_queue":{let b=(0,s.QT)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.writeFollowUpQueue(b.items,b.expectedRevision);return this.commandReceipts.set(b.submissionId,d),d.ok&&(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer()),d}case"follow_up":{let b=(0,s.$3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.queueMediaFromPromptImages(b.images),e=this.bashRunning?this.reject(b.submissionId,"bash"):d.ok?b.message.trim()||d.media?.length?this.enqueuePayloads(b.submissionId,[{text:b.message,...d.media?.length?{media:d.media}:{}}]):this.reject(b.submissionId,"error"):this.reject(b.submissionId,"media");return this.commandReceipts.set(b.submissionId,e),e}case"set_session_name":{let b=String(a.name??"").trim();if(!b)throw Error("Session name cannot be empty");return d.setSessionName(b),this.options.onSessionListInvalidate?.(),null}case"set_auto_compaction":return d.setAutoCompactionEnabled(!!a.enabled),null;case"set_auto_retry":return d.setAutoRetryEnabled(!!a.enabled),null;case"clear_queue":return d.clearQueue();case"get_tools":{let a=d.getAllTools(),b=new Set(d.getActiveToolNames());return{source:"sdk",tools:a.map(a=>({name:a.name,description:a.description??"",active:b.has(a.name)}))}}case"set_tools":{let b=Array.isArray(a.tools)?a.tools.filter(a=>"string"==typeof a):[];return d.setActiveToolsByName(b),this.activeToolNames=b,null}case"get_commands":{let a=[];for(let b of d.extensionRunner.getRegisteredCommands())a.push({name:b.invocationName,description:b.description,source:"extension",sourceInfo:b.sourceInfo});for(let b of d.promptTemplates)a.push({name:b.name,description:b.description,source:"prompt_template"});try{let b=d.resourceLoader?.getSkills?.();for(let c of b?.skills??[])a.push({name:`skill:${c.name}`,description:c.description,source:"skill",sourceInfo:c.sourceInfo})}catch{}return{commands:a}}case"get_session_stats":return d.getSessionStats();case"bash":if(d.isStreaming)throw Error("Cannot run bash while agent is streaming");this.bashRunning=!0,this.bashCommand={command:String(a.command??""),excludeFromContext:!!a.excludeFromContext,startedAt:Date.now()},this.notifyRunning();try{return await d.executeBash(String(a.command??""),void 0,{excludeFromContext:!!a.excludeFromContext})}finally{this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),this.resetIdleTimer()}case"abort_bash":return d.abortBash(),this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),null;case"abort_compaction":return d.abortCompaction(),null;case"extension_ui_response":{let b=y(a.id);if(!b)throw Error("extension_ui_response requires id");let c={...a};return delete c.type,delete c.id,!this.extensionUi?.respond(b,c),this.notifyRunning(),null}case"extension_ui_input":{let b=y(a.id),c="string"==typeof a.data?a.data:"";return b&&this.extensionUi?.inputCustom(b,c),null}case"append_activity":return this.appendActivity(a);case"append_binary":return this.appendBinary(a);case"fork":{if(this.bashRunning)throw Error("Cannot fork while a shell command is running");let b=String(a.entryId??"");if(!b)throw Error("entryId is required");let c=await this.runtime.fork(b);return c.cancelled||(await this.rebindSession(),this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.()),{cancelled:c.cancelled,newSessionId:c.cancelled?void 0:this.realSessionId,text:c.selectedText}}case"navigate_tree":{if(this.bashRunning)throw Error("Cannot navigate while a shell command is running");let b=y(a.targetId);if(!b)throw Error("targetId is required");let c=await d.navigateTree(b,{summarize:a.summarize,customInstructions:y(a.customInstructions)});if(!c.cancelled&&this.realSessionFile){d.sessionManager.getLeafId();let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries(),c=b.at(-1)?.id;a&&c&&a!==c?(0,m.R3)(this.realSessionFile,a):this.realSessionFile&&(0,m.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:c.cancelled}}case"select_leaf_exact":{let b=y(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.selectLeafExact(this.sessionId,b,a)}let e=await d.navigateTree(b,{summarize:!1});if(!e.cancelled&&this.realSessionFile){let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries().at(-1)?.id;a&&b&&a!==b?(0,m.R3)(this.realSessionFile,a):(0,m.$9)(this.realSessionFile)}return{cancelled:e.cancelled}}case"branch_from_assistant":{let b=y(a.assistantEntryId);if(!b)throw Error("assistantEntryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.branchFromAssistant(this.sessionId,b,a)}throw Error("branch_from_assistant is unavailable")}case"create_session_from_leaf":{let b=y(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.createSessionFromLeaf(this.sessionId,b,a)}throw Error("create_session_from_leaf is unavailable")}case"set_branch_label":{let b=y(a.targetId);if(!b)throw Error("targetId is required");let c=void 0===a.label||null===a.label?void 0:String(a.label);return d.sessionManager.appendLabelChange(b,c),this.options.onSessionListInvalidate?.(),null}case"reload":return await d.reload(),await this.rebindSession(),null;case"get_last_assistant_text":return{text:d.getLastAssistantText()};case"ensure_session":return null;default:throw Error(`Unsupported command: ${c}`)}}finally{this.activeCommandCount=Math.max(0,this.activeCommandCount-1),0===this.activeCommandCount&&this.resetIdleTimer()}}destroy(){this.destroyAsync().catch(()=>{})}async destroyAsync(){return this.destroyExcluding(0)}destroyExcluding(a){if(this.destroyPromise)return this.destroyPromise;if(!this._alive&&!this.runtime)return Promise.resolve();if(this.activeCommandCount-a>0){let b=this.pendingDestroys.get(a);return b||(b=this.destroyWhenCommandsSettle(a),this.pendingDestroys.set(a,b)),b}return this.beginDispose()}destroyWhenCommandsSettle(a){let b=(async()=>{let b=Date.now()+this.destroyWaitMs;for(;this.activeCommandCount-a>0;){if(Date.now()>=b)throw Error("Session writer is busy: a command is still in flight");await new Promise(a=>{let b=setTimeout(a,25);b.unref?.()})}return this.beginDispose()})().finally(()=>{this.pendingDestroys.get(a)===b&&this.pendingDestroys.delete(a)});return b}beginDispose(){return this.destroyPromise||(this._alive=!1,this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null,this.startupHold=!1,this.destroyPromise=(async()=>{this.unsubscribe?.(),this.unsubscribe=null,this.extensionUi?.dispose(),this.extensionUi=null;let a=this.runtime;if(this.runtime=null,a)try{await a.dispose()}catch(a){console.error("[pidance] sdk runtime dispose error:",a)}for(let a of(this.promptRunning=!1,this.bashRunning=!1,this.bashCommand=null,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,(0,i.PI)(this.realSessionId),[...this.destroyCallbacks]))try{a()}catch(a){console.error("[pidance] sdk host destroy listener error:",a)}this.destroyCallbacks.clear(),this.notifyRunning()})()),this.destroyPromise}}async function z(a){let b=new A(a);return await b.start(),b}d()}catch(a){d(a)}})},11955:(a,b,c)=>{c.d(b,{$3:()=>o,JT:()=>k,K2:()=>g,QT:()=>p,TJ:()=>r,_3:()=>n,in:()=>f,s:()=>q});var d=c(35948),e=c(40673);function f(a){return"busy"===a||"compacting"===a||"bash"===a}function g(a){let b=a instanceof Error?a.message:String(a);return/already processing|already running|streamingBehavior/i.test(b)?"busy":/shell command is running/i.test(b)?"bash":/compaction/i.test(b)?"compacting":/cannot be queued|Extension command/i.test(b)?"extension":/no (valid )?model|model not found|未选择模型/i.test(b)?"model":/401|403|unauthor|api key|authentication|permission denied/i.test(b)?"auth":/running lease|locked by another|another process/i.test(b)?"locked":"error"}function h(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`sub-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function i(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("images must be an array");let b=[];for(let c of a){if(!c||"object"!=typeof c)throw Error("invalid image");if("ref"===c.type){let a="string"==typeof c.path?c.path.trim():"",e=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!a||!e?.startsWith("image/"))throw Error("invalid image");b.push({type:"ref",path:a,mimeType:e});continue}let a="string"==typeof c.data?c.data:void 0,e="string"==typeof c.mimeType?c.mimeType:"string"==typeof c.mime_type?c.mime_type:void 0,f=(0,d.Ln)(e);if(!a||!f?.startsWith("image/"))throw Error("invalid image");if(a.length>4194304)throw Error("invalid image: payload too large");b.push({type:"image",data:a,mimeType:f})}return b}function j(a){if("string"!=typeof a.message)throw Error("message is required");return a.message}function k(a,b=h){return{type:"prompt",message:j(a),submissionId:"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b(),images:i(a.images),binaryBlocks:function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("binaryBlocks must be an array");if(a.length>32)throw Error("too many binary blocks");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid binary block");let a="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.name?c.name.trim():"",f=(0,d.Ln)(c.mimeType),g=c.size,h=void 0===c.previewPath?void 0:"string"==typeof c.previewPath?c.previewPath.trim():null;if(!a||!e||!f||!Number.isSafeInteger(g)||g<0||null===h)throw Error("invalid binary block");b.push({path:a,name:e,mimeType:f,size:g,...h?{previewPath:h}:{}})}return b}(a.binaryBlocks)}}function l(a,b){return"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b()}function m(a){if(null==a)return null;if("number"!=typeof a||!Number.isFinite(a)||a<0)throw Error("expectedRevision must be a non-negative number");return a}function n(a,b=h){return{type:"steer",message:j(a),submissionId:l(a,b),images:i(a.images)}}function o(a,b=h){return{type:"follow_up",message:j(a),submissionId:l(a,b),images:i(a.images)}}function p(a,b=h){if(void 0!==a.items&&!Array.isArray(a.items))throw Error("items must be an array");let c=[];for(let b of Array.isArray(a.items)?a.items:[]){let a,f;if("string"==typeof b){if(!b.trim())throw Error("items must not contain empty text");c.push({text:b});continue}if(!b||"object"!=typeof b||Array.isArray(b)||"string"!=typeof b.text)throw Error("items must be strings or { text, media? } objects");let g=function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("invalid queue media");if(0===a.length)return;if(a.length>e.ym)throw Error("invalid queue media: too many refs");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid queue media");let a="model"===c.role||"original"===c.role?c.role:null,e="string"==typeof c.path?c.path.trim():"";if(!a||!e)throw Error("invalid queue media");let f=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!f||"model"===a&&!f.startsWith("image/"))throw Error("invalid queue media");let g="string"==typeof c.name&&c.name.trim()?c.name.trim():"",h=c.size;if(!g||"number"!=typeof h||!Number.isSafeInteger(h)||h<0)throw Error("invalid queue media");let i="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(void 0!==c.previewPath&&!i)throw Error("invalid queue media");b.push({role:a,path:e,name:g,mimeType:f,size:h,...i&&i!==e?{previewPath:i}:{}})}return b.length?b:void 0}(b.media);if(!b.text.trim()&&!g?.length)throw Error("items must not be empty");if(void 0!==b.attemptId&&!(a=(0,e.Kk)(b.attemptId)??void 0))throw Error("invalid item attemptId");if(void 0!==b.id&&!(f=(0,e.mv)(b.id)??void 0))throw Error("invalid item id");c.push({text:b.text,...g?{media:g}:{},...a?{attemptId:a}:{},...f?{id:f}:{}})}return{type:"set_follow_up_queue",items:c,expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function q(a,b=h){let c,d="string"==typeof a.extra?a.extra:void 0;if(void 0!==a.extraAttemptId&&!(c=(0,e.Kk)(a.extraAttemptId)??void 0))throw Error("invalid extraAttemptId");return{type:"dispatch_follow_up_queue",...void 0!==d?{extra:d}:{},...c?{extraAttemptId:c}:{},expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function r(a,b=h){if(!Array.isArray(a.itemIds))throw Error("itemIds must be an array");if(0===a.itemIds.length)throw Error("itemIds must not be empty");if(a.itemIds.length>256)throw Error("too many itemIds");let c=[];for(let b of a.itemIds){let a="string"==typeof b?b.trim():"";if(!a)throw Error("invalid itemId");c.includes(a)||c.push(a)}return{type:"recall_follow_up_queue",itemIds:c,submissionId:l(a,b)}}},19228:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Jv:()=>r,Tv:()=>t,_D:()=>q,n3:()=>n});var e=c(89477),f=c(42524),g=c(86697),h=c(26238),i=c(93686),j=c(87390),k=c(69271),l=c(58732),m=a([i,j,l]);[i,j,l]=m.then?(await m)():m;let r="send_file_to_user",s="## Pidance file delivery\nWhen the `send_file_to_user` tool is available and you create a file that the user needs to view, download, or play, call it instead of only printing a local path or embedding Base64. The tool publishes a user-visible attachment message: images keep the original for preview and download, audio/video follow the UI playback size policy, and other files get a download card. Only claim that a file was sent after the tool returns success.";function n(a){return a.some(a=>a===s)?a:[...a,s]}let t={type:"object",additionalProperties:!1,properties:{path:{type:"string",description:"Absolute or current-project-relative path of the file to deliver."},name:{type:"string",description:"Optional filename shown to the user; the source basename is used by default."}},required:["path"]};function o(a){if(a?.aborted)throw a.reason instanceof Error?a.reason:Error("file delivery aborted")}async function p(a,b){let c,d;if("string"!=typeof a||!a.trim())throw Error("path is required");let f=(0,g.resolve)(b,a.trim()),h=(0,j.bk)()?null:await (0,j.mc)();if(h&&!(0,j.A$)(f,h))throw Error("file path is not allowed");try{c=(0,e.lstatSync)(f)}catch{throw Error("file not found")}if(c.isSymbolicLink())throw Error("symbolic-link sources are not allowed");if(!c.isFile())throw Error("path must be a regular file");try{d=(0,e.realpathSync)(f)}catch{throw Error("file path could not be resolved")}if(h&&!(0,j.A$)(d,h))throw Error("file path is not allowed");return{path:d,stat:c}}function q(a){return async function(b,c){let d;o(c);let j=await p(b.path,a.cwd),m=j.path,n="string"==typeof b.name&&b.name.trim()?b.name.trim():(0,g.basename)(m),q="number"==typeof e.constants.O_NOFOLLOW?e.constants.O_NOFOLLOW:0,r="number"==typeof e.constants.O_NONBLOCK?e.constants.O_NONBLOCK:0,s=await (0,f.open)(m,e.constants.O_RDONLY|q|r);try{let b=await s.stat();if(!b.isFile())throw Error("path must be a regular file");if(0!==j.stat.dev&&0!==j.stat.ino&&(b.dev!==j.stat.dev||b.ino!==j.stat.ino))throw Error("file changed during open");if(b.size>i.Gt)throw Error(`file exceeds ${i.Gt} bytes`);o(c);let f=(0,e.createReadStream)("",{fd:s.fd,autoClose:!1,signal:c});d=await (0,i.xd)(n,h.Readable.toWeb(f),a.agentDir,i.Gt),o(c);let g=(0,l.iU)({path:d.path,name:d.name,mimeType:(0,k.cV)(m)??(0,k.X)(m)??(0,k.k2)(m)??(0,k.oC)(m)??({txt:"text/plain",md:"text/markdown",json:"application/json",csv:"text/csv",html:"text/html",xml:"application/xml",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar"})[(0,k.GO)(m)]??"application/octet-stream",size:d.size},a.agentDir),{entryId:p}=a.appendBinary(g);return d=void 0,{entryId:p,name:g.name,size:g.size}}finally{if(await s.close().catch(()=>{}),d)try{(0,e.unlinkSync)(d.path)}catch{}}}}d()}catch(a){d(a)}})},31119:(a,b,c)=>{function d(a){if(!a.reasoning)return a;let b=a.thinkingLevelMap,c={...b??{}},d=!1;for(let a of["xhigh","max"])Object.prototype.hasOwnProperty.call(c,a)&&void 0!==c[a]||(c[a]=a,d=!0);return!d&&b?a:{...a,thinkingLevelMap:c}}function e(a){let b=d(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}c.d(b,{eU:()=>d,yu:()=>e})},33727:(a,b,c)=>{c.d(b,{D:()=>d});function d(a){return a.trim().startsWith("/")}},35304:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{recoverFollowUpQueues:()=>q});var e=c(69453),f=c(31360),g=c(84127),h=c(40673),i=c(10611),j=c(82356),k=a([e,f,i]);function l(){if(!globalThis.__piSessions){globalThis.__piSessions=new Map;let a=()=>{globalThis.__piSessions?.forEach(a=>a.destroy())};process.once("exit",a),process.once("SIGINT",a),process.once("SIGTERM",a)}return globalThis.__piSessions}function m(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function n(){return[...m().keys()]}[e,f,i]=k.then?(await k)():k;let s="",t=new Set,u=null;function o(){!function a(){let b=new Set(function(){let a=new Set(n());for(let[b,c]of l())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,j.AZ)(a),t.add(a);for(let a of[...t])b.has(a)||((0,j.Hl)(a),t.delete(a));if(0===b.size){u&&(clearInterval(u),u=null);return}u||(u=setInterval(()=>{a()},8e3),u.unref?.())}();let a=function(){let a=new Set(n());for(let[b,c]of l())c.isRunning()&&a.add(c.sessionId||b);return[...a]}(),b=function(){let a=[];for(let[b,c]of l()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c!==s)for(let b of(s=c,globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners))try{b(a)}catch{}}async function p(a,b,c,d,e){return r(a,b,c,d,e)}async function q(){let a=(0,g.readPidancePrefs)();for(let b of function(a){let b=new Set,c=a.sessionQueue;if("object"==typeof c&&null!==c&&!Array.isArray(c))for(let[a,d]of Object.entries(c))a&&(0,h.aL)(d)&&b.add(a);for(let[c,d]of Object.entries(a)){if(!c.startsWith("sessionQueue.")||!(0,h.aL)(d))continue;let a=c.slice(13);a&&b.add(a)}return[...b].filter(b=>!0!==(0,g.ql)(a,`sessionQueueHold.${b}`)&&!0!==a[`sessionQueueHold.${b}`]).sort()}(a)){let a=l().get(b);if(a?.isAlive()||(0,j.wy)(b))continue;let c=await (0,e.os)(b);if(!c)continue;let d=process.cwd();try{d=(0,f.kW)(c).getHeader()?.cwd||process.cwd()}catch{}try{await p(b,c,d)}catch(a){console.error(`[pidance] recover follow-up queue failed for ${b}:`,a)}}}async function r(a,b,c,d,f){let g=l(),h=m(),k=g.get(a);if(k?.isAlive())return{session:k,realSessionId:a};let n=h.get(a);if(n)return n;if(!(0,j.kP)(a))throw Error(j.GT);o();let p=(async()=>{try{let h=await (0,i.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>o(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=l(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,j.kP)(b),(0,j.Hl)(a))}}),k=h.sessionId,m=h.sessionFile;return m&&(0,e.O8)(k,m),k!==a&&(0,j.kP)(k),h.onDestroy(()=>{g.get(k)===h&&g.delete(k),a!==k&&g.get(a)===h&&g.delete(a),(0,j.Hl)(k),a!==k&&(0,j.Hl)(a),o()}),g.set(k,h),h.beginExtensionBinding(),{session:h,realSessionId:k}}catch(b){throw(0,j.Hl)(a),o(),b}})().finally(()=>{h.delete(a),o()});return h.set(a,p),p}d()}catch(a){d(a)}})},35948:(a,b,c)=>{c.d(b,{FH:()=>g,Ln:()=>f,PB:()=>h,uG:()=>d});let d="pidance.binary",e=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function f(a){if("string"!=typeof a)return null;let b=a.trim().toLowerCase();return e.test(b)?b:null}function g(a,b){let c={role:"custom",customType:d,content:a.name,display:!0,details:a};return void 0!==b&&(c.timestamp=b),c}function h(a,b){let c,d=f(a.mimeType)??"application/octet-stream",e=function(a){if("string"!=typeof a)return null;let b=a.replace(/[\\/\0]/g,"_").trim();return!b||b.length>180?null:b}(a.name)??"file",g=a.path.trim(),h=Number.isSafeInteger(a.size)&&a.size>=0?a.size:0,i=a.previewPath?.trim()||void 0;return{type:"binary",version:1,kind:(c=d.toLowerCase()).startsWith("image/")?"image":c.startsWith("audio/")?"audio":c.startsWith("video/")?"video":"file",path:g,name:e,mimeType:d,size:h,...i?{previewPath:i}:{},...b?{messageEntryId:b}:{}}}},36315:(a,b,c)=>{let d;c.d(b,{Lm:()=>i,Mf:()=>n,GD:()=>l,t_:()=>k,tU:()=>m});let e=JSON.parse('{"$schema":"https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json","name":"dark","vars":{"cyan":"#00d7ff","blue":"#5f87ff","green":"#b5bd68","red":"#cc6666","yellow":"#ffff00","text":"#d4d4d4","gray":"#808080","dimGray":"#666666","darkGray":"#505050","accent":"#8abeb7","selectedBg":"#3a3a4a","userMsgBg":"#343541","toolPendingBg":"#282832","toolSuccessBg":"#283228","toolErrorBg":"#3c2828","customMsgBg":"#2d2838"},"colors":{"accent":"accent","border":"blue","borderAccent":"cyan","borderMuted":"darkGray","success":"green","error":"red","warning":"yellow","muted":"gray","dim":"dimGray","text":"text","thinkingText":"gray","selectedBg":"selectedBg","userMessageBg":"userMsgBg","userMessageText":"text","customMessageBg":"customMsgBg","customMessageText":"text","customMessageLabel":"#9575cd","toolPendingBg":"toolPendingBg","toolSuccessBg":"toolSuccessBg","toolErrorBg":"toolErrorBg","toolTitle":"text","toolOutput":"gray","mdHeading":"#f0c674","mdLink":"#81a2be","mdLinkUrl":"dimGray","mdCode":"accent","mdCodeBlock":"green","mdCodeBlockBorder":"gray","mdQuote":"gray","mdQuoteBorder":"gray","mdHr":"gray","mdListBullet":"accent","toolDiffAdded":"green","toolDiffRemoved":"red","toolDiffContext":"gray","syntaxComment":"#6A9955","syntaxKeyword":"#569CD6","syntaxFunction":"#DCDCAA","syntaxVariable":"#9CDCFE","syntaxString":"#CE9178","syntaxNumber":"#B5CEA8","syntaxType":"#4EC9B0","syntaxOperator":"#D4D4D4","syntaxPunctuation":"#D4D4D4","thinkingOff":"darkGray","thinkingMinimal":"#6e6e6e","thinkingLow":"#5f87af","thinkingMedium":"#81a2be","thinkingHigh":"#b294bb","thinkingXhigh":"#d183e8","thinkingMax":"#ff5fff","bashMode":"green"},"export":{"pageBg":"#18181e","cardBg":"#1e1e24","infoBg":"#3c3728"}}');function f(a){let b=a.replace("#",""),c=Number.parseInt(3===b.length?b.split("").map(a=>a+a).join(""):b,16);return{r:c>>16&255,g:c>>8&255,b:255&c}}class g{constructor(a,b,c="truecolor",d){for(const[b,e]of(this.fgAnsiMap=new Map,this.bgAnsiMap=new Map,this.mode=c,this.name=d?.name,Object.entries({...a,thinkingMax:a.thinkingMax??a.thinkingXhigh})))this.fgAnsiMap.set(b,function(a,b){if(""===a)return"\x1b[39m";if("number"==typeof a)return`\x1b[38;5;${a}m`;if("string"==typeof a&&a.startsWith("#")){if("truecolor"===b){let{r:b,g:c,b:d}=f(a);return`\x1b[38;2;${b};${c};${d}m`}return"\x1b[38;5;7m"}throw Error(`Invalid color value: ${String(a)}`)}(e,c));for(const[a,d]of Object.entries(b))this.bgAnsiMap.set(a,function(a,b){if(""===a)return"\x1b[49m";if("number"==typeof a)return`\x1b[48;5;${a}m`;if("string"==typeof a&&a.startsWith("#")){if("truecolor"===b){let{r:b,g:c,b:d}=f(a);return`\x1b[48;2;${b};${c};${d}m`}return"\x1b[48;5;0m"}throw Error(`Invalid color value: ${String(a)}`)}(d,c))}fg(a,b){let c=this.fgAnsiMap.get(a);if(!c)throw Error(`Unknown theme color: ${a}`);return`${c}${b}\x1b[39m`}bg(a,b){let c=this.bgAnsiMap.get(a);if(!c)throw Error(`Unknown theme background color: ${a}`);return`${c}${b}\x1b[49m`}bold(a){return`\x1b[1m${a}\x1b[22m`}italic(a){return`\x1b[3m${a}\x1b[23m`}underline(a){return`\x1b[4m${a}\x1b[24m`}inverse(a){return`\x1b[7m${a}\x1b[27m`}strikethrough(a){return`\x1b[9m${a}\x1b[29m`}getFgAnsi(a){let b=this.fgAnsiMap.get(a);if(!b)throw Error(`Unknown theme color: ${a}`);return b}getBgAnsi(a){let b=this.bgAnsiMap.get(a);if(!b)throw Error(`Unknown theme background color: ${a}`);return b}getColorMode(){return this.mode}getThinkingBorderColor(a){let b={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"}[a]??"thinkingOff";return a=>this.fg(b,a)}getBashModeBorderColor(){return a=>this.fg("bashMode",a)}}let h=new Set(["selectedBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]);function i(){if(void 0!==d)return d;try{d=function(a){let b={...a.colors,thinkingMax:a.colors.thinkingMax??a.colors.thinkingXhigh},c=a.vars??{},d={},e={};for(let[a,f]of Object.entries(b)){let b=function a(b,c,d=new Set){if("number"==typeof b||""===b||b.startsWith("#"))return b;if(d.has(b))throw Error(`Circular variable reference detected: ${b}`);if(!(b in c))throw Error(`Variable reference not found: ${b}`);return d.add(b),a(c[b],c,d)}(f,c);h.has(a)?e[a]=b:d[a]=b}return new g(d,e,"truecolor",{name:a.name})}(e)}catch{d=null}return d}function j(a,b=100){if(!a||"object"!=typeof a||"function"!=typeof a.render)return null;try{let c=a.render(b);if(!function(a){if(!Array.isArray(a)||0===a.length||!a.every(a=>"string"==typeof a)||a.length>500)return!1;let b=0;for(let c of a)if(c.length>4e3||(b+=c.length)>204800)return!1;return!0}(c))return null;return c}catch{return null}}function k(a,b,c,d,e){let f=function(a){if(!a||"object"!=typeof a)return;let b=a.renderResult??a.ln;return"function"==typeof b?b:void 0}(a);if(!f)return null;let g=i();if(!g)return null;try{let a=f(b,c,g,d);return a&&"object"==typeof a&&e?.(a),j(a)}catch{return null}}function l(a,b,c,d){let e=function(a){if(!a||"object"!=typeof a)return;let b=a.renderCall;return"function"==typeof b?b:void 0}(a);if(!e)return null;let f=i();if(!f)return null;try{let a=e(b,f,c);return a&&"object"==typeof a&&d?.(a),j(a)}catch{return null}}function m(a,b,c=100){if("function"!=typeof a||!b)return null;try{let d=a(void 0,b);return j(d,c)}catch{return null}}function n(a,b,c,d=100){if("function"!=typeof a||!c)return null;try{let e=a(b,{expanded:!0},c);return j(e,d)}catch{return null}}},40673:(a,b,c)=>{function d(a){if("string"!=typeof a)return null;let b=a.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(b)?b:null}function e(a){return d(a)}function f(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){let a=d(c);a&&!b.includes(a)&&b.push(a)}return b.length>128?b.slice(b.length-128):b}function g(a,b){let c=[...a];for(let a of b)!a||c.includes(a)||c.push(a);return c.length>128?c.slice(c.length-128):c}c.d(b,{EP:()=>l,Kk:()=>d,Ot:()=>q,Pt:()=>o,S1:()=>g,X_:()=>p,aL:()=>m,gC:()=>n,jG:()=>k,ko:()=>i,mv:()=>e,ym:()=>h});let h=32;function i(a,b="waiting",c){let d,e={id:(d=globalThis.crypto)&&"function"==typeof d.randomUUID?d.randomUUID():`q-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,text:a,state:b};return c?.length&&(e.media=[...c]),e}function j(a,b){let c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=0x1000193*c>>>0;return`legacy-${a}-${c.toString(36)}`}function k(a){let b=Array.isArray(a)?a:a&&"object"==typeof a?a.items:void 0,c=a&&"object"==typeof a&&!Array.isArray(a)&&"number"==typeof a.revision&&Number.isFinite(a.revision)?a.revision:0,d=f(a&&"object"==typeof a&&!Array.isArray(a)?a.admittedAttemptIds:void 0);if(!Array.isArray(b))return{items:[],revision:c,admittedAttemptIds:d};let e=[];for(let a=0;a<b.length;a++){let c=function(a,b){var c;if("string"==typeof a){let c=a.trim();return c?{id:j(b,a),text:c,state:"waiting"}:null}if(!a||"object"!=typeof a||Array.isArray(a)||"string"!=typeof a.text)return null;let d=function(a){if(void 0===a)return[];if(!Array.isArray(a)||a.length>h)return null;let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))return null;let a="model"===c.role||"original"===c.role?c.role:null,d="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.mimeType?c.mimeType.trim():"",f="string"==typeof c.name?c.name.trim():"",g=c.size,h="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(!a||!d||!e||!f||"number"!=typeof g||!Number.isSafeInteger(g)||g<0||void 0!==c.previewPath&&!h)return null;b.push({role:a,path:d,name:f,mimeType:e,size:g,...h&&h!==d?{previewPath:h}:{}})}return b}(a.media);return null!==d&&(a.text.trim()||0!==d.length)?{id:"string"==typeof a.id&&a.id.trim()?a.id:j(b,a.text),text:a.text,state:"claimed"===(c=a.state)||"unknown"===c?c:"waiting",...d.length?{media:d}:{}}:null}(b[a],a);c&&e.push(c)}return{items:e,revision:c,admittedAttemptIds:d}}function l(a){let b=f(a.admittedAttemptIds);return{items:a.items.map(a=>({id:a.id,text:a.text,state:a.state,...a.media?.length?{media:a.media.map(a=>({...a}))}:{}})),revision:a.revision,...b.length?{admittedAttemptIds:b}:{}}}function m(a){return k(a).items.length>0}function n(a){return a.map(a=>a.text)}function o(a,b,c){let d=new Set(c?.inFlightIds??[]),e=Array(a.length).fill(!1),f=new Map;a.forEach((a,b)=>{f.has(a.id)||f.set(a.id,b)});let g=[];for(let c of b){if(void 0!==c.id&&d.has(c.id))continue;let b=void 0===c.id?void 0:f.get(c.id);if(void 0!==b&&!e[b]){e[b]=!0;let d=a[b],f=c.media?.length?c.media:d.media;g.push({id:d.id,text:c.text,state:d.state,...f?.length?{media:[...f]}:{}});continue}let h=-1;for(let b=0;b<a.length;b++){let d=a[b];if(!e[b]&&d.text===c.text){if(function(a,b){let c=a??[],d=b??[];return c.length===d.length&&c.every((a,b)=>a.path===d[b].path)}(d.media,c.media)){h=b;break}h<0&&(h=b)}}if(h>=0){e[h]=!0;let b=a[h],d=c.media?.length?c.media:b.media;g.push({id:b.id,text:c.text,state:b.state,...d?.length?{media:[...d]}:{}});continue}g.push(c.media?.length?i(c.text,"waiting",c.media):i(c.text,"waiting"))}return g}function p(a,b){return{text:[...n(a),...b?.trim()?[b.trim()]:[]].map(a=>a.trim()).filter(a=>a.length>0).join("\n"),media:q(a)}}function q(a){return a.flatMap(a=>a.media??[])}},58732:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Nu:()=>m,iU:()=>l});var e=c(89477),f=c(86697),g=c(92783),h=c(93686),i=c(35948),j=a([h]);h=(j.then?(await j)():j)[0];class n extends Error{constructor(a){super(a),this.name="BinaryMessageError"}}function k(a,b){let c,d,g=(0,e.realpathSync)((0,h.eq)(b));try{c=(0,e.realpathSync)((0,f.resolve)(a))}catch{throw new n("binary media file not found")}let i=(0,f.relative)(g,c);if(!i||".."===i||i.startsWith(`..${f.sep}`)||(0,f.isAbsolute)(i))throw new n("binary media path is not allowed");try{d=(0,e.statSync)(c)}catch{throw new n("binary media file not found")}if(!d.isFile())throw new n("binary media must be a file");return{path:c.replace(/\\/g,"/"),size:d.size}}function l(a,b=(0,g.$M)(),c){if(!a||"object"!=typeof a||"string"!=typeof a.name||!a.name.trim()||"string"!=typeof a.path||!a.path.trim())throw new n("invalid binary block");let d=(0,i.Ln)(a.mimeType);if(!d)throw new n("invalid binary MIME type");let e=(0,h.uF)(a.name);if(!e)throw new n("binary file name is required");let f=k(a.path,b),j=a.previewPath?k(a.previewPath,b):void 0;return(0,i.PB)({path:f.path,name:e,mimeType:d,size:f.size,...j?{previewPath:j.path}:{}},c)}function m(a,b=(0,g.$M)()){if(!a||0===a.length)return[];if(a.length>32)throw new n("too many binary blocks");return a.map(a=>l(a,b))}d()}catch(a){d(a)}})},63480:(a,b,c)=>{c.d(b,{E:()=>d});function d(a,b,c){let d=a.getModel?.(b,c);return d||a.getAvailableSnapshot?.().find(a=>a.provider===b&&a.id===c)}},68642:(a,b,c)=>{c.d(b,{NK:()=>f,PI:()=>g});let d="__piRunningStartedAt";function e(){let a=globalThis;return d in a&&a[d]instanceof Map||(a[d]=new Map),a[d]}function f(a,b){let c=e();c.has(a)||c.set(a,b)}function g(a){e().delete(a)}},69271:(a,b,c)=>{c.d(b,{GO:()=>h,X:()=>j,cV:()=>i,k2:()=>k,oC:()=>l});let d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},e={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},f={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},g={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function h(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function i(a){return d[h(a)]??null}function j(a){return e[h(a)]??null}function k(a){return f[h(a)]??null}function l(a){return g[h(a)]??null}},75377:(a,b,c)=>{c.d(b,{t:()=>g});var d=c(716),e=c(36315);function f(a,b,c,e,f,g,h){let i=(0,d.randomUUID)();return new Promise((d,j)=>{let k,l=!1,m=()=>{a.delete(i),b.delete(i),k&&clearTimeout(k),e?.signal?.removeEventListener("abort",o)},n=a=>{l||(l=!0,m(),d(a))},o=()=>n(f);e?.signal?.addEventListener("abort",o,{once:!0}),e?.timeout&&(k=setTimeout(()=>n(f),e.timeout)),a.set(i,{resolve:a=>{try{n(h(a))}catch(a){if(l)return;l=!0,m(),j(a instanceof Error?a:Error(String(a)))}},reject:a=>{l||(l=!0,m(),j(a))}});let p={type:"extension_ui_request",id:i,...g};b.set(i,p),c(p)})}function g(a){let b=new Map,c=new Map,g=new Map,h=new Map,i=new Map,j=null,k={select:(d,e,g)=>f(b,c,a,g,void 0,{method:"select",title:d,options:e,timeout:g?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),confirm:(d,e,g)=>f(b,c,a,g,!1,{method:"confirm",title:d,message:e,timeout:g?.timeout},a=>(!("cancelled"in a)||!a.cancelled)&&"confirmed"in a&&!!a.confirmed),input:(d,e,g)=>f(b,c,a,g,void 0,{method:"input",title:d,placeholder:e,timeout:g?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),notify(b,c){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"notify",message:b,notifyType:c})},onTerminalInput:()=>()=>{},setStatus(b,c){c?g.set(b,c):g.delete(b),a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setStatus",statusKey:b,statusText:c})},setWorkingMessage(){},setWorkingVisible(){},setWorkingIndicator(){},setHiddenThinkingLabel(){},setWidget(b,c,f){if("function"==typeof c){let a=(0,e.tU)(c,(0,e.Lm)());if(null===a)return;c=a}(void 0===c||Array.isArray(c))&&(null==c?h.delete(b):h.set(b,{lines:c,placement:f?.placement}),a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:c,widgetPlacement:f?.placement}))},setFooter(){},setHeader(){},setTitle(b){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setTitle",title:b})},async custom(b){let c=(0,d.randomUUID)();return new Promise(d=>{let f,g=!1,h=b=>{g||(g=!0,i.delete(c),j?.id===c&&(j=null),a({type:"extension_ui_request",id:c,method:"custom",closed:!0,lines:[]}),d(b))},l=()=>{if(g)return;let b=[];try{let a=f?.render?.(92);Array.isArray(a)&&(b=a.filter(a=>"string"==typeof a))}catch(a){console.error("[pidance] custom UI render failed:",a)}a({type:"extension_ui_request",id:c,method:"custom",lines:b}),j={id:c,lines:[...b]}};i.set(c,{handleInput:a=>{if("\x03"===a)return void h(void 0);try{f?.handleInput?.(a)}catch(a){console.error("[pidance] custom UI input failed:",a)}},done:h});let m=function(a,b=92,c=40){return Object.freeze({terminal:Object.freeze({columns:b,rows:c,kittyProtocolActive:!1}),requestRender:a})}(()=>{l()},92,40),n=(0,e.Lm)()??k.theme;Promise.resolve().then(()=>b(m,n,{},h)).then(a=>{g||(f=a,l())}).catch(a=>{console.error("[pidance] custom UI factory failed:",a),h(void 0)})})},pasteToEditor(a){this.setEditorText(a)},setEditorText(b){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"set_editor_text",text:b})},getEditorText:()=>"",editor:async(d,e)=>f(b,c,a,void 0,void 0,{method:"editor",title:d,prefill:e},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){let a=a=>String(a??""),b=(a,b)=>void 0===b?"":String(b);return new Proxy({fg:b,bg:b,bold:a,dim:a,italic:a},{get:(b,c)=>c in b?b[c]:"then"!==c?a:void 0})},getAllThemes:()=>[],getTheme(){},setTheme:()=>({success:!1,error:"Theme switching not supported in Web mode"}),getToolsExpanded:()=>!1,setToolsExpanded(){}};return{uiContext:k,pending:b,statuses:g,widgets:h,pendingSnapshot:c,get customSnapshot(){return j},respond(a,c){let d=b.get(a);return!!d&&(d.resolve(c),!0)},inputCustom(a,b){let c=i.get(a);return!!c&&(c.handleInput(b),!0)},dispose(){for(let[a,d]of b)b.delete(a),c.delete(a),d.reject(Error("Extension UI disposed"));for(let a of i.values())a.done(void 0);i.clear(),j=null,g.clear(),h.clear()}}}},82356:(a,b,c)=>{c.d(b,{AZ:()=>u,GT:()=>h,Hl:()=>v,kP:()=>t,sweepStaleRunningLeases:()=>s,wy:()=>w});var d=c(716),e=c(89477),f=c(86697),g=c(92783);let h="Session is locked by another Pidance process (writable host ownership)",i="Timed out acquiring Pidance running-lease lock";function j(a){return(0,f.join)(a,"pidance-running-leases")}function k(a,b){let c=b.replace(/[^a-zA-Z0-9._-]+/g,"_").slice(0,180);return(0,f.join)(j(a),`${c}.json`)}function l(a){if(!Number.isFinite(a)||a<=0)return!1;try{return process.kill(a,0),!0}catch(a){return"EPERM"===a.code}}function m(a){try{let b=JSON.parse((0,e.readFileSync)(a,"utf8"));if("number"!=typeof b.pid||"string"!=typeof b.sessionId||"number"!=typeof b.heartbeatAt)return null;return{pid:b.pid,sessionId:b.sessionId,heartbeatAt:b.heartbeatAt,startedAt:"number"==typeof b.startedAt?b.startedAt:b.heartbeatAt}}catch{return null}}function n(a){try{let b=JSON.parse((0,e.readFileSync)(a,"utf8"));if("number"!=typeof b.pid||"string"!=typeof b.token)return null;return{pid:b.pid,token:b.token}}catch{return null}}function o(a,b){let c=j(a);(0,e.existsSync)(c)||(0,e.mkdirSync)(c,{recursive:!0,mode:448});let g=(0,f.join)(c,".lease-lock"),h=(0,d.randomBytes)(8).toString("hex"),k=Date.now()+3e3,m=!1;for(;!m;){let a=`${g}.${process.pid}.${h}.tmp`;try{(0,e.writeFileSync)(a,JSON.stringify({pid:process.pid,token:h}),{mode:384}),(0,e.linkSync)(a,g),m=!0}catch(b){if("EEXIST"!==b.code){try{(0,e.unlinkSync)(a)}catch{}throw b}}try{(0,e.unlinkSync)(a)}catch{}if(m)break;let b=n(g);if(b&&!l(b.pid)){try{n(g)?.token===b.token&&(0,e.unlinkSync)(g)}catch{}continue}if(!b)try{Date.now()-(0,e.statSync)(g).mtimeMs>1e4&&(0,e.unlinkSync)(g)}catch{}if(Date.now()>=k)throw Error(i);!function(){let a=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(a,0,0,5)}()}try{return b()}finally{try{n(g)?.token===h&&(0,e.unlinkSync)(g)}catch{}}}function p(a){return a instanceof Error&&a.message===i}function q(a,b){let c=`${a}.${process.pid}.tmp`;(0,e.writeFileSync)(c,`${JSON.stringify(b)}
1
+ "use strict";exports.id=5304,exports.ids=[5304],exports.modules={10611:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>A});var e=c(75430),f=c(92783),g=c(66323),h=c(84127),i=c(82356),j=c(68642),k=c(93686),l=c(40673),m=c(99595),n=c(89358),o=c(31360),p=c(75377),q=c(63480),r=c(33727),s=c(31119),t=c(11955),u=c(35948),v=c(58732),w=c(19228),x=c(36315),y=a([e,k,o,v,w]);function z(a){return"string"==typeof a&&a?a:void 0}[e,k,o,v,w]=y.then?(await y)():y;class B{static{this.PARTIAL_RENDER_MIN_INTERVAL_MS=100}constructor(a){this.options=a,this.listeners=[],this.runtime=null,this.unsubscribe=null,this.extensionUi=null,this.idleTimer=null,this.startupHoldTimer=null,this.startupHold=!0,this.activeCommandCount=0,this.destroyCallbacks=new Set,this.pendingDestroys=new Map,this._alive=!0,this.promptRunning=!1,this.streamRunSeq=0,this.lastStopReason=null,this.followUpQueue=[],this.followUpQueueRevision=0,this.followUpQueueHydrated=!1,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,this.internalPromptTicket=Symbol("pidance internal follow-up prompt"),this.followUpFlushBlocked=!1,this.dispatchingFollowUpQueue=!1,this.commandReceipts=new Map,this.bashRunning=!1,this.bashCommand=null,this.localQueue={steering:[],followUp:[]},this.turnMetrics={startedAt:0,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},this.promptReceipts=new Map,this.promptInFlight=new Map,this.steerFlights=new Map,this.pendingBinaryBatches=[],this.destroyPromise=null,this.hasQueueSnapshot=!1,this.renderBridgeTheme=(0,x.Lm)(),this.toolRenderStates=new Map,this.followUpAdmittedAttemptIds=[],this.realSessionId=a.sessionId,this.realSessionFile=a.sessionFile,this.idleTimeoutMs=a.idleTimeoutMs??3e4,this.destroyWaitMs=a.destroyWaitMs??5e3,this.agentDir=a.agentDir??(0,f.$M)(),this.activeToolNames=a.toolNames}get sessionId(){return this.realSessionId}get sessionFile(){return this.realSessionFile}listPendingExtensionRequests(){return Array.from(this.extensionUi?.pendingSnapshot.values()??[])}get inner(){let a=this.runtime?.session;if(a)return{sessionManager:a.sessionManager}}isAlive(){return this._alive&&null!==this.runtime}isRunning(){if(!this._alive||!this.runtime)return!1;let a=this.runtime.session;return this.promptRunning||this.bashRunning||a.isStreaming||a.isCompacting}async runSteerCommand(a){let b=this.session;if(this.bashRunning){let b=this.reject(a.submissionId,"bash");return this.commandReceipts.set(a.submissionId,b),b}if(b.isCompacting&&!b.isStreaming&&!this.promptRunning){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"compacting");return this.commandReceipts.set(a.submissionId,c),c}let c=this.resolvePromptImages(a.images);if(c.missing.length){console.error("[pidance] steer image missing on disk:",c.missing);let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}if(!this.isRunning()&&!this.flushingFollowUp){let b=await this.send({type:"prompt",message:a.message,images:a.images,streamingBehavior:"steer"}),c={...b,submissionId:a.submissionId,action:"accepted"===b.status?"prompt":"queued"};return this.commandReceipts.set(a.submissionId,c),c}if(!b.isStreaming){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"busy");return this.commandReceipts.set(a.submissionId,c),c}await b.steer(a.message,c.images);let d={submissionId:a.submissionId,sessionId:this.realSessionId,status:"accepted",action:"steer"};return this.commandReceipts.set(a.submissionId,d),d}onDestroy(a){return this.destroyCallbacks.add(a),()=>{this.destroyCallbacks.delete(a)}}onEvent(a){let b=0===this.listeners.length;return this.listeners.push(a),b&&this.resetIdleTimer(),()=>{let b=this.listeners.length>0;this.listeners=this.listeners.filter(b=>b!==a),b&&0===this.listeners.length&&this.resetIdleTimer()}}beginExtensionBinding(){}async waitForExtensionsBound(){}emit(a){for(let b of this.listeners)try{b(a)}catch(a){console.error("[pidance] sdk host listener error:",a)}}notifyRunning(){this.options.onRunningChange?.()}hasActiveSubagentRun(){let a=this.realSessionFile;if(!a)return!1;try{let{runs:b}=(0,g._2)({limit:50});return(0,g.EE)(b,a)}catch{return!1}}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!this._alive||!this.runtime||this.startupHold||this.isRunning()||this.flushingFollowUp)return;if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(this.listeners.length>0)return;let a=this.idleTimeoutMs;this.idleTimer=setTimeout(()=>{if(this.idleTimer=null,!this.isRunning()&&!this.flushingFollowUp){if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(!(this.listeners.length>0)){if(this.hasActiveSubagentRun())return void this.resetIdleTimer();this.destroyAsync().catch(()=>{})}}},a)}releaseStartupHold(){this.startupHold&&(this.startupHold=!1,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null)}isSettled(){return!!this.runtime&&!!this._alive&&!this.isRunning()}isFollowUpHeld(){let a=(0,h.readPidancePrefs)(this.agentDir);return!0===(0,h.ql)(a,`sessionQueueHold.${this.realSessionId}`)}setFollowUpHeld(a){try{(0,h.xP)(`sessionQueueHold.${this.realSessionId}`,!!a||null,this.agentDir)}catch(b){console.error("[pidance] failed to persist follow-up hold:",b),this.emit({type:"follow_up_flush_error",errorMessage:a?"failed to persist follow-up hold; the queue may flush automatically":"failed to clear follow-up hold; the queue may stay held",...this.queueReceiptBase()})}}hydrateFollowUpQueue(){if(this.followUpQueueHydrated)return;this.followUpQueueHydrated=!0;let a=(0,h.readPidancePrefs)(this.agentDir),b=(0,h.ql)(a,`sessionQueue.${this.realSessionId}`),c=(0,l.jG)(b);this.followUpQueue=c.items.map(a=>"claimed"===a.state?{...a,state:"unknown"}:a),this.followUpQueueRevision=c.revision,this.followUpAdmittedAttemptIds=c.admittedAttemptIds,this.followUpQueue=this.followUpQueue.map(a=>{if(!a.media?.length)return a;let b=a.media.filter(a=>this.isQueueMediaRefAlive(a));return b.length===a.media.length?a:{...b.length?{...a,media:b}:{text:a.text,id:a.id,state:a.state},state:"unknown"}})}waitingFollowUp(){return this.followUpQueue.filter(a=>"waiting"===a.state)}hasWaitingFollowUp(){return this.followUpQueue.some(a=>"waiting"===a.state)}visibleFollowUp(){return this.followUpQueue.filter(a=>"claimed"!==a.state)}inFlightFollowUpTexts(){return this.followUpQueue.filter(a=>"claimed"===a.state).map(a=>a.text)}commitFollowUpQueue(a,b,c=[]){for(let c of a)if((c.media?.length??0)>l.ym)return console.error(`[pidance] refusing to persist follow-up queue (${b}): item media exceeds ${l.ym}`),!1;let d=this.followUpQueueRevision+1,e=(0,l.S1)(this.followUpAdmittedAttemptIds,c);try{(0,h.xP)(`sessionQueue.${this.realSessionId}`,(0,l.EP)({items:a,revision:d,admittedAttemptIds:e}),this.agentDir)}catch(a){return console.error(`[pidance] failed to persist follow-up queue (${b}):`,a),!1}return this.followUpQueue=a,this.followUpQueueRevision=d,this.followUpAdmittedAttemptIds=e,this.followUpFlushBlocked=!1,!0}discardDeliveredModelMedia(a){let b=new Set((0,l.Ot)(this.followUpQueue).map(a=>a.path));for(let c of a)"model"!==c.role||b.has(c.path)||(0,k.fm)(c.path,this.agentDir)}withFollowUpState(a,b){let c=new Set(a);return this.followUpQueue.map(a=>c.has(a.id)?{...a,state:b}:a)}queueReceiptBase(){return{revision:this.followUpQueueRevision,items:this.visibleFollowUp(),inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}reject(a,b){return{submissionId:a,sessionId:this.realSessionId,status:"rejected",reason:b}}isQueueMediaRefAlive(a){let b="model"===a.role?8388608:k.Md,c=(0,k.vy)(a.path,this.agentDir);return null!==c&&c<=b}validateQueueMedia(a){if(!a?.length)return!0;if(a.length>l.ym)return!1;let b=0;for(let c of a){let a=(0,k.vy)(c.path,this.agentDir);if(null===a)return!1;let d="model"===c.role?8388608:k.Md;if(a>d||(b+=a,c.previewPath&&null===(0,k.vy)(c.previewPath,this.agentDir)))return!1}return b<=k.Lj}readQueueModelImages(a){let b=[],c=[];for(let d of(0,l.Ot)(a)){if("model"!==d.role)continue;let a=(0,k.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b,missing:c}}queueBinaryBlocks(a){return(0,l.Ot)(a).filter(a=>"original"===a.role).map(a=>({path:a.path,name:a.name,mimeType:a.mimeType,size:a.size,...a.previewPath?{previewPath:a.previewPath}:{}}))}writeFollowUpQueue(a,b){if(null!==b&&b!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};for(let b of a)if(!this.validateQueueMedia(b.media))return{ok:!1,persist:!0,...this.queueReceiptBase()};let c=this.followUpQueue.filter(a=>"claimed"===a.state),d=this.followUpQueue.filter(a=>"claimed"!==a.state),e=[...c,...(0,l.Pt)(d,a,{inFlightIds:c.map(a=>a.id)})];return this.commitFollowUpQueue(e,"set",a.map(a=>a.attemptId))?{ok:!0,...this.queueReceiptBase()}:{ok:!1,persist:!0,...this.queueReceiptBase()}}recallFollowUpQueue(a){let b=[],c=[];for(let d of a){let a=this.followUpQueue.find(a=>a.id===d);if(!a){c.push({id:d,reason:"missing"});continue}if("claimed"===a.state){c.push({id:d,reason:"claimed"});continue}b.push(a)}if(!b.length)return{ok:!0,...this.queueReceiptBase(),recalled:[],skipped:c};let d=new Set(b.map(a=>a.id)),e=this.followUpQueue.filter(a=>!d.has(a.id));return this.commitFollowUpQueue(e,"recall")?(this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,...this.queueReceiptBase(),recalled:b,skipped:c}):{ok:!1,persist:!0,...this.queueReceiptBase(),recalled:[],skipped:c}}enqueuePayloads(a,b,c){let d=this.writeFollowUpQueue([...this.visibleFollowUp().map(a=>({text:a.text})),...b],null);return d.ok?(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer(),{submissionId:a,sessionId:this.realSessionId,status:"queued",action:"queued",...c?{reason:c}:{},queue:{items:d.items,inFlight:d.inFlight,revision:d.revision,admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}):this.reject(a,"error")}queueMediaFromPromptImages(a){if(!a?.length)return{media:void 0,ok:!0};let b=[];for(let[c,d]of a.entries()){let a;if("ref"===d.type){let a=(0,k.vy)(d.path,this.agentDir);if(null===a||a>8388608)return{media:void 0,ok:!1};b.push({role:"model",path:d.path,name:d.path.split(/[\\/]/).pop()??`image-${c}`,mimeType:d.mimeType,size:a});continue}try{a=(0,k.ki)(`prompt-image-${c}.${function(a){let b=a.split(";")[0].trim().toLowerCase();return"image/jpeg"===b?"jpg":"image/svg+xml"===b?"svg":b.startsWith("image/")?b.slice(6).replace(/[^a-z0-9]/g,"")||"png":"bin"}(d.mimeType)}`,Buffer.from(d.data,"base64"),this.agentDir)}catch(a){return console.error("[pidance] inline prompt image could not be stored:",a),{media:void 0,ok:!1}}b.push({role:"model",path:a.path,name:a.name,mimeType:d.mimeType,size:a.size})}return{media:b,ok:!0}}resolvePromptImages(a){if(!a?.length)return{images:void 0,missing:[]};let b=[],c=[];for(let d of a){if("ref"!==d.type){b.push(d);continue}let a=(0,k.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b.length?b:void 0,missing:c}}async dispatchFollowUpQueue(a){if(this.bashRunning)return{ok:!1,status:"rejected",reason:"bash",...this.queueReceiptBase()};if(this.session.isCompacting)return{ok:!1,status:"rejected",reason:"compacting",...this.queueReceiptBase()};if(this.flushingFollowUp||this.dispatchingFollowUpQueue)return{ok:!1,conflict:!0,reason:"in-flight",...this.queueReceiptBase()};if(null!==a.expectedRevision&&a.expectedRevision!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};let b=this.waitingFollowUp(),c=a.extra?.trim();if(0===b.length&&!c)return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};let{text:d}=(0,l.X_)(b,c),e=this.readQueueModelImages(b);if(e.missing.length)return console.error("[pidance] queued media missing, dispatch rejected:",e.missing),{ok:!1,status:"rejected",reason:"media",...this.queueReceiptBase()};let f=this.queueBinaryBlocks(b),g=b.map(a=>a.media?.length?(0,l.ko)(a.text,"claimed",a.media):(0,l.ko)(a.text,"claimed"));c&&g.push((0,l.ko)(c,"claimed"));let h=g.map(a=>a.id),i=new Set(h),j=[...this.followUpQueue.filter(a=>"waiting"!==a.state),...g];if(!this.commitFollowUpQueue(j,"dispatch-claim",[a.extraAttemptId]))return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};this.dispatchingFollowUpQueue=!0,this.emitQueueChanged();let k=e.images.length?e.images:void 0,m="prompt";try{if(this.session.isStreaming)m="steer",await this.session.steer(d,k);else{let a=await this.send({type:"prompt",message:d,...k?.length?{images:k}:{},...f.length?{binaryBlocks:f}:{},streamingBehavior:"steer"},this.internalPromptTicket);if(a?.status==="queued")return m="queued",this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-queued"),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:m,...this.queueReceiptBase()};if(a?.status!=="accepted")return this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release"),this.emitQueueChanged(),{ok:!1,status:"rejected",reason:a?.reason??"error",...this.queueReceiptBase()}}}catch(b){let a=this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release");return this.emitQueueChanged(),a||this.emit({type:"follow_up_flush_error",errorMessage:"dispatch rejected and the claim could not be released; it stays claimed for the user to inspect",...this.queueReceiptBase()}),{ok:!1,status:"rejected",reason:(0,t.K2)(b),...this.queueReceiptBase()}}finally{this.dispatchingFollowUpQueue=!1}let n=(0,l.Ot)(g);return this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-deliver")&&this.discardDeliveredModelMedia(n),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:m,...this.queueReceiptBase()}}scheduleFollowUpFlush(){if(!this._alive||!this.runtime||this.flushingFollowUp||this.followUpFlushBlocked||this.isFollowUpHeld()||this.dispatchingFollowUpQueue||!this.isSettled())return;let a=this.waitingFollowUp();if(0===a.length)return;let b=!0===(0,h.readPidancePrefs)(this.agentDir).queueFlushAsOne;this.flushingFollowUp=!0,this.followUpFlushUnits=b?[{ids:a.map(a=>a.id)}]:a.map(a=>({ids:[a.id]})),this.followUpFlushCursor=0,this.sendNextFollowUp()}emitQueueChanged(){let a=this.queueReceiptBase();this.emit({type:"follow_up_queue_changed",sessionId:this.realSessionId,items:a.items,revision:a.revision,inFlight:a.inFlight,admittedAttemptIds:a.admittedAttemptIds})}async sendNextFollowUp(){if(this.followUpSending||!this.flushingFollowUp)return;if(this.isFollowUpHeld())return void this.abortFollowUpFlush();let a=this.followUpFlushUnits[this.followUpFlushCursor];if(void 0===a)return void this.finishFollowUpFlush();if(!this.isSettled())return void setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushUnits[this.followUpFlushCursor]===a&&this.sendNextFollowUp()},80);this.followUpSending=!0;try{await this.deliverFollowUpUnit(a)}finally{this.followUpSending=!1}this.flushingFollowUp&&(this.followUpFlushCursor+=1,this.followUpFlushCursor>=this.followUpFlushUnits.length?this.finishFollowUpFlush():this.sendNextFollowUp())}async deliverFollowUpUnit(a){let b=new Set(a.ids),c=this.followUpQueue.filter(a=>b.has(a.id)&&"waiting"===a.state);if(0===c.length)return void this.emitQueueChanged();let d=c.map(a=>a.id),e=(0,l.X_)(c).text,{images:f,missing:g}=this.readQueueModelImages(c),h=this.queueBinaryBlocks(c);if(g.length){console.error("[pidance] queued image missing, delivery blocked:",g),this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"queued image is missing; delivery blocked",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}let i=f.length?f:void 0;if(this.session.isCompacting||this.bashRunning){this.emit({type:"follow_up_flush_error",errorMessage:this.session.isCompacting?"follow-up delivery deferred while compaction is running":"follow-up delivery deferred while a shell command is running",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}if(!this.commitFollowUpQueue(this.withFollowUpState(d,"claimed"),"claim")){this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"failed to persist follow-up queue before delivery",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}this.emitQueueChanged();let j=null;try{j=await this.send({type:"prompt",message:e,...i?{images:i}:{},...h.length?{binaryBlocks:h}:{}},this.internalPromptTicket)}catch(c){let a=c instanceof Error?c.message:String(c),b=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:a,...this.queueReceiptBase()}),this.abortFollowUpFlush(),b&&this.emitQueueChanged();return}if(j?.status==="queued"){this.commitFollowUpQueue(this.followUpQueue.filter(a=>!new Set(d).has(a.id)),"deliver-queued"),this.emitQueueChanged(),this.abortFollowUpFlush();return}if(j&&"accepted"!==j.status){let a=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:`follow-up prompt rejected: ${j.reason??"unknown"}`,...this.queueReceiptBase()}),this.abortFollowUpFlush(),a&&this.emitQueueChanged();return}let k=new Set(d),m=(0,l.Ot)(c),n=this.commitFollowUpQueue(this.followUpQueue.filter(a=>!k.has(a.id)),"deliver");n&&this.discardDeliveredModelMedia(m),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:e,...this.queueReceiptBase()}),n||this.emit({type:"follow_up_flush_error",errorMessage:"follow-up delivered but queue removal was not persisted",...this.queueReceiptBase()}),this.emitQueueChanged()}abortFollowUpFlush(){this.flushingFollowUp&&(this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer())}finishFollowUpFlush(){this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.scheduleFollowUpFlush()}get session(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.session}get services(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.services}syncIdentityFromSession(){let a=this.session,b=a.sessionId||this.realSessionId,c=a.sessionFile||this.realSessionFile,d=this.realSessionId;this.realSessionId=b,this.realSessionFile=c,c&&this.options.cacheSessionPath?.(b,c),d!==b&&this.options.onSessionRekeyed?.(d,b,this)}async rebindSession(){let a=this.session;this.extensionUi?.dispose(),this.extensionUi=(0,p.t)(a=>{this.trackExtensionSideEffects(a),this.emit(a)}),await a.bindExtensions({uiContext:this.extensionUi.uiContext,mode:"rpc",commandContextActions:{waitForIdle:()=>a.waitForIdle(),newSession:async a=>{let b=await this.runtime.newSession(a);return b.cancelled||await this.rebindSession(),b},fork:async(a,b)=>{let c=await this.runtime.fork(a,b);return c.cancelled||await this.rebindSession(),{cancelled:c.cancelled}},navigateTree:async(b,c)=>({cancelled:(await a.navigateTree(b,{summarize:c?.summarize,customInstructions:c?.customInstructions,replaceInstructions:c?.replaceInstructions,label:c?.label})).cancelled}),switchSession:async(a,b)=>{let c=await this.runtime.switchSession(a,b);return c.cancelled||await this.rebindSession(),c},reload:async()=>{await a.reload()}},onError:a=>{this.setFollowUpHeld(!0),this.emit({type:"extension_error",extensionPath:a.extensionPath,event:a.event,error:a.error})}}),this.unsubscribe?.(),this.unsubscribe=a.subscribe(a=>{this.resetIdleTimer(),this.handleSessionEvent(a)}),this.syncIdentityFromSession()}trackExtensionSideEffects(a){if("extension_ui_request"!==a.type)return;let b=z(a.method);if("setStatus"===b){let b=z(a.statusKey)??z(a.key)??"default",c=z(a.statusText)??z(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=z(a.widgetKey)??z(a.key)??"default",c=a.widgetLines??a.content;null==c?this.extensionUi?.widgets.delete(b):this.extensionUi?.widgets.set(b,{lines:c,placement:a.widgetPlacement})}this.notifyRunning()}maybeAutoNameSession(){try{let a=this.session?.sessionManager;if(!a||a.getSessionName())return;let b=(a.buildSessionContext().messages??[]).find(a=>"user"===a.role),c=function(a){let b="";"string"==typeof a?b=a:Array.isArray(a)&&(b=a.filter(a=>"object"==typeof a&&null!==a&&"text"===a.type&&"string"==typeof a.text).map(a=>a.text).join("\n"));let c=b.replace(/\s+/g," ").trim();if(c)return c.length>60?`${c.slice(0,60)}…`:c}(b?.content);c&&a.appendSessionInfo(c)}catch{}}readStopReasonFromAgentEnd(a){let b=a.messages;if(!Array.isArray(b))return null;for(let a=b.length-1;a>=0;a--){let c=b[a],d=c?.message?.stopReason??c?.stopReason;if("string"==typeof d){if("aborted"===d)return"aborted";if("error"===d||"prompt_error"===d)return"error";return"completed"}}return null}removePendingBinaryBatch(a){this.pendingBinaryBatches=this.pendingBinaryBatches.filter(b=>b.submissionId!==a)}persistPendingBinaryBlocks(a){if(0!==a.length)try{let b=this.session.sessionManager;(0,o.kb)(b);let c=b.getEntries(),d=[...c].reverse().find(a=>"message"===a.type&&a.message?.role==="user"&&"string"==typeof a.id)?.id||b.getLeafId()||void 0;for(let c of a){let a=d?{...c,messageEntryId:d}:c,e=b.appendCustomEntry(u.uG,a);this.emit({type:"message_end",entryId:e,message:(0,u.FH)(a,Date.now())})}(0,o.kb)(b),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] persist binary message failed:",a)}}static hasRenderableContent(a){if(!a)return!1;let b=a.content;return"string"==typeof b?b.length>0:Array.isArray(b)&&b.length>0}static outputTokensOf(a){let b=a?.usage?.output;return"number"==typeof b&&Number.isFinite(b)&&b>=0?b:null}accumulateTurnMetrics(a){let b=Date.now();if("agent_start"===a.type)return this.turnMetrics={startedAt:b,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},!0;if("message_start"===a.type||"message_update"===a.type){let c=a.message;if(c?.role==="user")return!1;if(null===this.turnMetrics.firstTokenAt&&B.hasRenderableContent(c)){this.turnMetrics.firstTokenAt=b;let a=null===this.turnMetrics.ttftMs;return a&&this.turnMetrics.startedAt>0&&b>=this.turnMetrics.startedAt&&(this.turnMetrics.ttftMs=b-this.turnMetrics.startedAt),a}return!1}if("message_end"===a.type){let c=a.message;if(c?.role!=="assistant")return!1;let d=null===this.turnMetrics.firstTokenAt?null:Math.max(0,b-this.turnMetrics.firstTokenAt);this.turnMetrics.firstTokenAt=null;let e=B.outputTokensOf(c);if(null!==d&&null!==e)return this.turnMetrics.decodeMs+=d,this.turnMetrics.outputTokens+=e,this.turnMetrics.sampled=!0,!0}return!1}projectTurnMetrics(){let a={};return null!==this.turnMetrics.ttftMs&&this.turnMetrics.startedAt>0&&(a.ttftMs=this.turnMetrics.ttftMs),this.turnMetrics.sampled&&this.turnMetrics.decodeMs>0&&(a.tokensPerSecond=this.turnMetrics.outputTokens/(this.turnMetrics.decodeMs/1e3)),a}handleSessionEvent(a){let b=this.accumulateTurnMetrics(a),c="agent_start"===a.type?++this.streamRunSeq:this.streamRunSeq;switch(a.type){case"agent_start":this.promptRunning=!0,(0,j.NK)(this.realSessionId,Date.now()),this.notifyRunning();break;case"agent_end":this.promptRunning=!1,this.lastStopReason=this.readStopReasonFromAgentEnd(a)??this.lastStopReason??"completed",("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.setFollowUpHeld(!0),(0,j.PI)(this.realSessionId),this.options.onSessionListInvalidate?.(),this.realSessionFile&&(0,n.$9)(this.realSessionFile),this.maybeAutoNameSession(),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});break;case"agent_settled":this.promptRunning=!1,this.notifyRunning(),"completed"===this.lastStopReason?this.flushingFollowUp?this.sendNextFollowUp():this.scheduleFollowUpFlush():this.flushingFollowUp&&("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.abortFollowUpFlush();let d="agent_settled"===a.type&&!this.flushingFollowUp&&(!this.hasWaitingFollowUp()||this.isFollowUpHeld())&&!this.hasActiveSubagentRun();this.resetIdleTimer(),d&&this.destroyAsync().catch(()=>{});break;case"compaction_start":case"auto_compaction_start":this.notifyRunning();break;case"compaction_end":case"auto_compaction_end":this.notifyRunning(),!0!==a.aborted&&!a.errorMessage&&this.isSettled()&&this.scheduleFollowUpFlush(),this.resetIdleTimer();break;case"message_end":{let b=a.message;if(b?.role==="user"){let a=this.pendingBinaryBatches.shift();setImmediate(()=>{try{(0,o.kb)(this.session.sessionManager),this.syncIdentityFromSession(),this.persistPendingBinaryBlocks(a?.blocks??[]),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] materialize after user message failed:",a)}})}break}case"queue_update":{let b=Array.isArray(a.steering)?a.steering.filter(a=>"string"==typeof a):[],c=Array.isArray(a.followUp)?a.followUp.filter(a=>"string"==typeof a):[];this.localQueue={steering:b,followUp:c},this.hasQueueSnapshot=!0}}let e=c>0?{...a,streamRunSeq:c}:a;if(b){let a=this.projectTurnMetrics();(void 0!==a.ttftMs||void 0!==a.tokensPerSecond)&&(e={...e,turnMetrics:a})}let f="message_end"===a.type&&a.message?.role==="assistant";if("agent_end"===a.type||f){let a=this.contextUsageSnapshot();a&&(e={...e,contextUsage:a})}this.emit(this.withRenderedToolLines(e))}contextUsageSnapshot(){try{let a=this.session.getContextUsage();if(a&&"number"==typeof a.contextWindow&&a.contextWindow>0)return{contextWindow:a.contextWindow,percent:"number"==typeof a.percent?a.percent:null,tokens:"number"==typeof a.tokens?a.tokens:null}}catch{}}withRenderedToolLines(a){try{if(!this.renderBridgeTheme)return a;switch(a.type){case"tool_execution_update":{if(!this.shouldRenderPartialUpdate(a.toolCallId))return a;let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.args??a.input,{isPartial:!0,expanded:!0,isError:!0===a.isError,resultSlot:!0});if(!c)return a;let d=(0,x.t_)(b,a.partialResult,{expanded:!0,isPartial:!0},c,b=>this.updateToolRenderLastComponent(a.toolCallId,!0,b));return d?{...a,renderedLines:d}:a}case"tool_call":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.input,{isPartial:!1,expanded:!0,isError:!1,resultSlot:!1});if(!c)return a;let d=(0,x.GD)(b,a.input,c,b=>this.updateToolRenderLastComponent(a.toolCallId,!1,b));return d?{...a,renderedCallLines:d}:a}case"tool_result":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.args??a.input,{isPartial:!1,expanded:!0,isError:!0===a.isError,resultSlot:!0});if(!c)return a;let d=(0,x.t_)(b,{content:a.content,details:a.details,isError:!0===a.isError,...void 0!==a.usage?{usage:a.usage}:{}},{expanded:!0,isPartial:!1},c,b=>this.updateToolRenderLastComponent(a.toolCallId,!0,b));return d?{...a,renderedResultLines:d}:a}case"message_start":case"message_end":{let b=a.message;if(b?.role!=="custom"||"string"!=typeof b.customType||""===b.customType)return a;let c=this.session.extensionRunner,d="function"==typeof c?.getMessageRenderer?c.getMessageRenderer(b.customType):void 0,e=(0,x.Mf)(d,a.message,this.renderBridgeTheme);return e?{...a,renderedLines:e}:a}default:return a}}catch{return a}}getToolRenderDefinition(a){if("string"==typeof a&&""!==a)try{return this.session.getToolDefinition(a)}catch{return}}buildToolRenderContext(a,b,c){let d=this.getOrCreateToolRenderState(a);return d?{args:b,toolCallId:a,invalidate:()=>{},lastComponent:c.resultSlot?d.lastResultComponent:d.lastCallComponent,state:d.state,cwd:this.realCwd,executionStarted:!0,argsComplete:!0,isPartial:c.isPartial,expanded:c.expanded,showImages:!1,isError:c.isError}:null}getOrCreateToolRenderState(a){if("string"!=typeof a||""===a)return null;let b=this.toolRenderStates.get(a);return b||(b={state:{},lastCallComponent:void 0,lastResultComponent:void 0,lastPartialRenderAt:void 0},this.toolRenderStates.set(a,b)),b}updateToolRenderLastComponent(a,b,c){if("string"!=typeof a||""===a)return;let d=this.toolRenderStates.get(a);d&&(b?d.lastResultComponent=c:d.lastCallComponent=c)}shouldRenderPartialUpdate(a){if("string"!=typeof a||""===a)return!0;let b=Date.now(),c=this.getOrCreateToolRenderState(a);return!c||(void 0===c.lastPartialRenderAt||!(b-c.lastPartialRenderAt<B.PARTIAL_RENDER_MIN_INTERVAL_MS))&&(c.lastPartialRenderAt=b,!0)}get realCwd(){try{return this.session.sessionManager.getHeader()?.cwd||this.options.cwd}catch{return this.options.cwd}}async start(){try{var a,b;let c=(a=this.realSessionFile,b=this.options.cwd,a?(0,o.G1)(a):(0,o.Qu)(b)),d=c.getCwd()||this.options.cwd,f=this.agentDir,g=this.activeToolNames,h=async({cwd:a,agentDir:b,sessionManager:c,sessionStartEvent:d})=>{let f=(0,w._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:w.Jv,label:"Send file to user",description:"Publish an agent-created project file as a user-visible attachment with preview/download support.",promptSnippet:"deliver a generated file to the user as a downloadable attachment",promptGuidelines:["When the user needs a generated file, call send_file_to_user; do not only print a local path or paste Base64.","Only report a file as delivered after send_file_to_user returns successfully."],parameters:w.Tv,async execute(a,b,c){let d=await f(b,c);return{content:[{type:"text",text:`Delivered ${d.name} to the user (entry ${d.entryId}).`}],details:d}}},i=await (0,e.createAgentSessionServices)({cwd:a,agentDir:b,resourceLoaderOptions:{appendSystemPromptOverride:w.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,s.yu)(a);return{...await (0,e.createAgentSessionFromServices)({services:i,sessionManager:c,sessionStartEvent:d,tools:g&&g.length>0?g:void 0,noTools:g&&0===g.length?"all":void 0}),services:i,diagnostics:i.diagnostics}};this.runtime=await (0,e.createAgentSessionRuntime)(h,{cwd:d,agentDir:f,sessionManager:c}),this.runtime.setRebindSession(async()=>{await this.rebindSession()}),this.runtime.setBeforeSessionInvalidate(()=>{this.extensionUi?.dispose(),this.unsubscribe?.(),this.unsubscribe=null}),await this.rebindSession(),this.syncIdentityFromSession(),this.hydrateFollowUpQueue(),this.startupHoldTimer=setTimeout(()=>{this.startupHoldTimer=null,this.startupHold=!1,this.resetIdleTimer()},15e3),this.startupHoldTimer.unref?.(),this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.isSettled()&&this.scheduleFollowUpFlush()}catch(a){throw await this.destroyAsync(),a}}projectState(){let a=this.session,b=a.model,c={stateSources:{rpcGetState:!1,sdkSession:!0,sessionStats:!0,localQueue:!0,localExtensionUi:!0},sessionId:this.realSessionId,sessionFile:this.realSessionFile,sessionName:a.sessionName,isStreaming:a.isStreaming,isCompacting:a.isCompacting,isPromptRunning:this.promptRunning,lastStopReason:this.lastStopReason,isBashRunning:this.bashRunning,turnMetrics:this.projectTurnMetrics(),pendingBash:this.bashCommand,autoCompactionEnabled:a.autoCompactionEnabled,steeringMode:a.steeringMode,followUpMode:a.followUpMode,thinkingLevel:a.thinkingLevel,systemPrompt:a.systemPrompt??"",model:b?{id:b.id,provider:b.provider,modelId:b.id}:void 0,messageCount:a.messages.length,pendingMessageCount:a.pendingMessageCount,extensionStatuses:Array.from(this.extensionUi?.statuses.entries()??[],([a,b])=>({key:a,text:b})),extensionWidgets:Array.from(this.extensionUi?.widgets.entries()??[],([a,b])=>({key:a,lines:Array.isArray(b?.lines)?b.lines:[],placement:b?.placement==="belowEditor"?"belowEditor":"aboveEditor"})),pendingExtensionRequests:Array.from(this.extensionUi?.pendingSnapshot.values()??[]),activeCustomUi:this.extensionUi?.customSnapshot??null};c.queuedMessages={steering:this.hasQueueSnapshot?[...this.localQueue.steering]:[],followUp:(0,l.gC)(this.visibleFollowUp()),followUpItems:this.visibleFollowUp(),followUpRevision:this.followUpQueueRevision,inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]};try{let b=a.getContextUsage();b&&"number"==typeof b.contextWindow&&b.contextWindow>0&&(c.contextUsage={contextWindow:b.contextWindow,percent:"number"==typeof b.percent?b.percent:null,tokens:"number"==typeof b.tokens?b.tokens:null})}catch{}return c}appendActivity(a){if(!this.runtime)throw Error("Cannot append activity: session not alive");let b=a&&"object"==typeof a&&"type"in a&&"append_activity"===a.type?(0,m.qF)(a):(0,m.l$)(a),c=this.session.sessionManager.appendCustomEntry(m.cP,b);return this.options.onSessionListInvalidate?.(),{entryId:c,activity:b}}appendBinary(a,b){if(!this._alive||!this.runtime||this.destroyPromise)throw Error("Cannot append binary message: session not alive");let c=this.session.sessionManager;if(b&&c!==b)throw Error("Cannot publish file after the session changed");let d=a&&"object"==typeof a&&!Array.isArray(a)?a:{},e="append_binary"===d.type?d.binaryBlock:a,f=(0,v.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(u.uG,f);try{this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] binary message list notification failed:",a)}try{this.emit({type:"message_end",entryId:g,message:(0,u.FH)(f,Date.now())})}catch(a){console.error("[pidance] binary message event notification failed:",a)}return{entryId:g,binary:f}}async send(a,b){if(!this.runtime)throw Error("SDK session is not alive");let c=a.type;"get_state"!==c&&"ensure_session"!==c&&this.releaseStartupHold(),this.activeCommandCount+=1,this.resetIdleTimer();let d=this.session;try{switch(c){case"prompt":{let c=(0,t.JT)(a),e=this.promptReceipts.get(c.submissionId);if(e)return e;let f=c.submissionId,g=this.promptInFlight.get(f);if(g)return g;let h=(0,v.Nu)(c.binaryBlocks,this.agentDir),k=c.images??a.images,l=this.resolvePromptImages(k);if(l.missing.length){console.error("[pidance] prompt image missing on disk:",l.missing);let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}if(this.bashRunning&&!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"bash");return this.promptReceipts.set(c.submissionId,a),a}if(d.isCompacting&&!(0,r.D)(c.message)){let a=this.queueMediaFromPromptImages(k);if(!a.ok){let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}let b=this.enqueuePayloads(c.submissionId,[{text:c.message,...a.media?.length?{media:a.media}:{}}],"compacting");return this.promptReceipts.set(c.submissionId,b),this.options.onSessionListInvalidate?.(),b}if(this.flushingFollowUp&&b!==this.internalPromptTicket&&!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}if((this.promptRunning||d.isStreaming)&&"steer"!==a.streamingBehavior){if(!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}try{await d.prompt(c.message,{images:l.images,source:"rpc"});let a={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(c.submissionId,a),a}catch{let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}}if(!(0,i.kP)(this.realSessionId))throw Error(i.GT);this.promptRunning=!0,this.lastStopReason=null,(0,j.NK)(this.realSessionId,Date.now()),this.notifyRunning();let m=(async()=>{try{await new Promise((b,e)=>{let g=!1,i=()=>{d.isStreaming||d.isCompacting||this.bashRunning||this.promptRunning&&(this.promptRunning=!1,"aborted"!==this.lastStopReason&&"error"!==this.lastStopReason&&(this.lastStopReason="completed"),(0,j.PI)(this.realSessionId),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq}),this.resetIdleTimer())};d.prompt(c.message,{images:l.images,streamingBehavior:a.streamingBehavior,source:"rpc",preflightResult:a=>{a&&(g=!0,h.length>0&&this.pendingBinaryBatches.push({submissionId:f,blocks:h}),this.syncIdentityFromSession(),this.setFollowUpHeld(!1),this.options.onSessionListInvalidate?.(),b())}}).then(()=>{if(!g){g=!0;try{(0,o.kb)(d.sessionManager)}catch(a){console.error("[pidance] materialize after prompt failed:",a)}this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.(),b()}i()}).catch(a=>{"aborted"!==this.lastStopReason&&(this.lastStopReason="error"),this.setFollowUpHeld(!0),i(),g||(g=!0,e(a))})});let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(f,b),b}catch(g){this.removePendingBinaryBatch(f);let a=(0,t.K2)(g);if(d.isStreaming&&(0,t.in)(a)){let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected",reason:a};return this.promptReceipts.set(f,b),b}this.promptRunning=!1,this.lastStopReason="aborted"===this.lastStopReason?"aborted":"error",this.setFollowUpHeld(!0),(0,j.PI)(this.realSessionId),this.notifyRunning();let b=g instanceof Error?g.message:String(g);this.emit({type:"prompt_error",errorMessage:b}),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});let e={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected"};throw this.promptReceipts.set(f,e),g}finally{this.promptInFlight.delete(f)}})();return this.promptInFlight.set(f,m),m}case"abort":return this.lastStopReason="aborted",this.setFollowUpHeld(!0),this.promptRunning=!1,this.notifyRunning(),await d.abort(),this.notifyRunning(),null;case"get_state":return this.projectState();case"set_model":{let b=String(a.provider??""),c=String(a.modelId??""),e=(0,q.E)(d.modelRuntime,b,c);if(!e)try{e=(await d.modelRuntime.getAvailable()).find(a=>a.provider===b&&a.id===c)}catch{e=void 0}if(!e)throw Error(`Model not found: ${b}/${c}`);return await d.setModel((0,s.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return d.model&&(0,s.yu)(d.model),d.setThinkingLevel(a.level),this.options.onSessionListInvalidate?.(),null;case"compact":{let b=await d.compact("string"==typeof a.customInstructions?a.customInstructions:void 0);return this.options.onSessionListInvalidate?.(),this.notifyRunning(),this.resetIdleTimer(),b}case"steer":{let b=(0,t._3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.steerFlights.get(b.submissionId);if(d)return d;let e=this.runSteerCommand(b);this.steerFlights.set(b.submissionId,e);try{return await e}finally{this.steerFlights.get(b.submissionId)===e&&this.steerFlights.delete(b.submissionId)}}case"dispatch_follow_up_queue":{let b=(0,t.s)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=await this.dispatchFollowUpQueue(b);return this.commandReceipts.set(b.submissionId,d),d}case"recall_follow_up_queue":{let b=(0,t.TJ)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.recallFollowUpQueue(b.itemIds);return this.commandReceipts.set(b.submissionId,d),d}case"set_follow_up_queue":{let b=(0,t.QT)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.writeFollowUpQueue(b.items,b.expectedRevision);return this.commandReceipts.set(b.submissionId,d),d.ok&&(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer()),d}case"follow_up":{let b=(0,t.$3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.queueMediaFromPromptImages(b.images),e=this.bashRunning?this.reject(b.submissionId,"bash"):d.ok?b.message.trim()||d.media?.length?this.enqueuePayloads(b.submissionId,[{text:b.message,...d.media?.length?{media:d.media}:{}}]):this.reject(b.submissionId,"error"):this.reject(b.submissionId,"media");return this.commandReceipts.set(b.submissionId,e),e}case"set_session_name":{let b=String(a.name??"").trim();if(!b)throw Error("Session name cannot be empty");return d.setSessionName(b),this.options.onSessionListInvalidate?.(),null}case"set_auto_compaction":return d.setAutoCompactionEnabled(!!a.enabled),null;case"set_auto_retry":return d.setAutoRetryEnabled(!!a.enabled),null;case"clear_queue":return d.clearQueue();case"get_tools":{let a=d.getAllTools(),b=new Set(d.getActiveToolNames());return{source:"sdk",tools:a.map(a=>({name:a.name,description:a.description??"",active:b.has(a.name)}))}}case"set_tools":{let b=Array.isArray(a.tools)?a.tools.filter(a=>"string"==typeof a):[];return d.setActiveToolsByName(b),this.activeToolNames=b,null}case"get_commands":{let a=[];for(let b of d.extensionRunner.getRegisteredCommands())a.push({name:b.invocationName,description:b.description,source:"extension",sourceInfo:b.sourceInfo});for(let b of d.promptTemplates)a.push({name:b.name,description:b.description,source:"prompt_template"});try{let b=d.resourceLoader?.getSkills?.();for(let c of b?.skills??[])a.push({name:`skill:${c.name}`,description:c.description,source:"skill",sourceInfo:c.sourceInfo})}catch{}return{commands:a}}case"get_session_stats":return d.getSessionStats();case"bash":if(d.isStreaming)throw Error("Cannot run bash while agent is streaming");this.bashRunning=!0,this.bashCommand={command:String(a.command??""),excludeFromContext:!!a.excludeFromContext,startedAt:Date.now()},this.notifyRunning();try{return await d.executeBash(String(a.command??""),void 0,{excludeFromContext:!!a.excludeFromContext})}finally{this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),this.resetIdleTimer()}case"abort_bash":return d.abortBash(),this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),null;case"abort_compaction":return d.abortCompaction(),null;case"extension_ui_response":{let b=z(a.id);if(!b)throw Error("extension_ui_response requires id");let c={...a};return delete c.type,delete c.id,!this.extensionUi?.respond(b,c),this.notifyRunning(),null}case"extension_ui_input":{let b=z(a.id),c="string"==typeof a.data?a.data:"";return b&&this.extensionUi?.inputCustom(b,c),null}case"append_activity":return this.appendActivity(a);case"append_binary":return this.appendBinary(a);case"fork":{if(this.bashRunning)throw Error("Cannot fork while a shell command is running");let b=String(a.entryId??"");if(!b)throw Error("entryId is required");let c=await this.runtime.fork(b);return c.cancelled||(await this.rebindSession(),this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.()),{cancelled:c.cancelled,newSessionId:c.cancelled?void 0:this.realSessionId,text:c.selectedText}}case"navigate_tree":{if(this.bashRunning)throw Error("Cannot navigate while a shell command is running");let b=z(a.targetId);if(!b)throw Error("targetId is required");let c=await d.navigateTree(b,{summarize:a.summarize,customInstructions:z(a.customInstructions)});if(!c.cancelled&&this.realSessionFile){d.sessionManager.getLeafId();let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries(),c=b.at(-1)?.id;a&&c&&a!==c?(0,n.R3)(this.realSessionFile,a):this.realSessionFile&&(0,n.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:c.cancelled}}case"select_leaf_exact":{let b=z(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.selectLeafExact(this.sessionId,b,a)}let e=await d.navigateTree(b,{summarize:!1});if(!e.cancelled&&this.realSessionFile){let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries().at(-1)?.id;a&&b&&a!==b?(0,n.R3)(this.realSessionFile,a):(0,n.$9)(this.realSessionFile)}return{cancelled:e.cancelled}}case"branch_from_assistant":{let b=z(a.assistantEntryId);if(!b)throw Error("assistantEntryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.branchFromAssistant(this.sessionId,b,a)}throw Error("branch_from_assistant is unavailable")}case"create_session_from_leaf":{let b=z(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.createSessionFromLeaf(this.sessionId,b,a)}throw Error("create_session_from_leaf is unavailable")}case"set_branch_label":{let b=z(a.targetId);if(!b)throw Error("targetId is required");let c=void 0===a.label||null===a.label?void 0:String(a.label);return d.sessionManager.appendLabelChange(b,c),this.options.onSessionListInvalidate?.(),null}case"reload":return await d.reload(),await this.rebindSession(),null;case"get_last_assistant_text":return{text:d.getLastAssistantText()};case"ensure_session":return null;default:throw Error(`Unsupported command: ${c}`)}}finally{this.activeCommandCount=Math.max(0,this.activeCommandCount-1),0===this.activeCommandCount&&this.resetIdleTimer()}}destroy(){this.destroyAsync().catch(()=>{})}async destroyAsync(){return this.destroyExcluding(0)}destroyExcluding(a){if(this.destroyPromise)return this.destroyPromise;if(!this._alive&&!this.runtime)return Promise.resolve();if(this.activeCommandCount-a>0){let b=this.pendingDestroys.get(a);return b||(b=this.destroyWhenCommandsSettle(a),this.pendingDestroys.set(a,b)),b}return this.beginDispose()}destroyWhenCommandsSettle(a){let b=(async()=>{let b=Date.now()+this.destroyWaitMs;for(;this.activeCommandCount-a>0;){if(Date.now()>=b)throw Error("Session writer is busy: a command is still in flight");await new Promise(a=>{let b=setTimeout(a,25);b.unref?.()})}return this.beginDispose()})().finally(()=>{this.pendingDestroys.get(a)===b&&this.pendingDestroys.delete(a)});return b}beginDispose(){return this.destroyPromise||(this._alive=!1,this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null,this.startupHold=!1,this.destroyPromise=(async()=>{this.unsubscribe?.(),this.unsubscribe=null,this.extensionUi?.dispose(),this.extensionUi=null;let a=this.runtime;if(this.runtime=null,a)try{await a.dispose()}catch(a){console.error("[pidance] sdk runtime dispose error:",a)}for(let a of(this.promptRunning=!1,this.bashRunning=!1,this.bashCommand=null,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,(0,j.PI)(this.realSessionId),[...this.destroyCallbacks]))try{a()}catch(a){console.error("[pidance] sdk host destroy listener error:",a)}this.destroyCallbacks.clear(),this.notifyRunning()})()),this.destroyPromise}}async function A(a){let b=new B(a);return await b.start(),b}d()}catch(a){d(a)}})},11955:(a,b,c)=>{c.d(b,{$3:()=>o,JT:()=>k,K2:()=>g,QT:()=>p,TJ:()=>r,_3:()=>n,in:()=>f,s:()=>q});var d=c(35948),e=c(40673);function f(a){return"busy"===a||"compacting"===a||"bash"===a}function g(a){let b=a instanceof Error?a.message:String(a);return/already processing|already running|streamingBehavior/i.test(b)?"busy":/shell command is running/i.test(b)?"bash":/compaction/i.test(b)?"compacting":/cannot be queued|Extension command/i.test(b)?"extension":/no (valid )?model|model not found|未选择模型/i.test(b)?"model":/401|403|unauthor|api key|authentication|permission denied/i.test(b)?"auth":/running lease|locked by another|another process/i.test(b)?"locked":"error"}function h(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`sub-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function i(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("images must be an array");let b=[];for(let c of a){if(!c||"object"!=typeof c)throw Error("invalid image");if("ref"===c.type){let a="string"==typeof c.path?c.path.trim():"",e=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!a||!e?.startsWith("image/"))throw Error("invalid image");b.push({type:"ref",path:a,mimeType:e});continue}let a="string"==typeof c.data?c.data:void 0,e="string"==typeof c.mimeType?c.mimeType:"string"==typeof c.mime_type?c.mime_type:void 0,f=(0,d.Ln)(e);if(!a||!f?.startsWith("image/"))throw Error("invalid image");if(a.length>4194304)throw Error("invalid image: payload too large");b.push({type:"image",data:a,mimeType:f})}return b}function j(a){if("string"!=typeof a.message)throw Error("message is required");return a.message}function k(a,b=h){return{type:"prompt",message:j(a),submissionId:"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b(),images:i(a.images),binaryBlocks:function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("binaryBlocks must be an array");if(a.length>32)throw Error("too many binary blocks");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid binary block");let a="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.name?c.name.trim():"",f=(0,d.Ln)(c.mimeType),g=c.size,h=void 0===c.previewPath?void 0:"string"==typeof c.previewPath?c.previewPath.trim():null;if(!a||!e||!f||!Number.isSafeInteger(g)||g<0||null===h)throw Error("invalid binary block");b.push({path:a,name:e,mimeType:f,size:g,...h?{previewPath:h}:{}})}return b}(a.binaryBlocks)}}function l(a,b){return"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b()}function m(a){if(null==a)return null;if("number"!=typeof a||!Number.isFinite(a)||a<0)throw Error("expectedRevision must be a non-negative number");return a}function n(a,b=h){return{type:"steer",message:j(a),submissionId:l(a,b),images:i(a.images)}}function o(a,b=h){return{type:"follow_up",message:j(a),submissionId:l(a,b),images:i(a.images)}}function p(a,b=h){if(void 0!==a.items&&!Array.isArray(a.items))throw Error("items must be an array");let c=[];for(let b of Array.isArray(a.items)?a.items:[]){let a,f;if("string"==typeof b){if(!b.trim())throw Error("items must not contain empty text");c.push({text:b});continue}if(!b||"object"!=typeof b||Array.isArray(b)||"string"!=typeof b.text)throw Error("items must be strings or { text, media? } objects");let g=function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("invalid queue media");if(0===a.length)return;if(a.length>e.ym)throw Error("invalid queue media: too many refs");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid queue media");let a="model"===c.role||"original"===c.role?c.role:null,e="string"==typeof c.path?c.path.trim():"";if(!a||!e)throw Error("invalid queue media");let f=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!f||"model"===a&&!f.startsWith("image/"))throw Error("invalid queue media");let g="string"==typeof c.name&&c.name.trim()?c.name.trim():"",h=c.size;if(!g||"number"!=typeof h||!Number.isSafeInteger(h)||h<0)throw Error("invalid queue media");let i="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(void 0!==c.previewPath&&!i)throw Error("invalid queue media");b.push({role:a,path:e,name:g,mimeType:f,size:h,...i&&i!==e?{previewPath:i}:{}})}return b.length?b:void 0}(b.media);if(!b.text.trim()&&!g?.length)throw Error("items must not be empty");if(void 0!==b.attemptId&&!(a=(0,e.Kk)(b.attemptId)??void 0))throw Error("invalid item attemptId");if(void 0!==b.id&&!(f=(0,e.mv)(b.id)??void 0))throw Error("invalid item id");c.push({text:b.text,...g?{media:g}:{},...a?{attemptId:a}:{},...f?{id:f}:{}})}return{type:"set_follow_up_queue",items:c,expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function q(a,b=h){let c,d="string"==typeof a.extra?a.extra:void 0;if(void 0!==a.extraAttemptId&&!(c=(0,e.Kk)(a.extraAttemptId)??void 0))throw Error("invalid extraAttemptId");return{type:"dispatch_follow_up_queue",...void 0!==d?{extra:d}:{},...c?{extraAttemptId:c}:{},expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function r(a,b=h){if(!Array.isArray(a.itemIds))throw Error("itemIds must be an array");if(0===a.itemIds.length)throw Error("itemIds must not be empty");if(a.itemIds.length>256)throw Error("too many itemIds");let c=[];for(let b of a.itemIds){let a="string"==typeof b?b.trim():"";if(!a)throw Error("invalid itemId");c.includes(a)||c.push(a)}return{type:"recall_follow_up_queue",itemIds:c,submissionId:l(a,b)}}},19228:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Jv:()=>r,Tv:()=>t,_D:()=>q,n3:()=>n});var e=c(89477),f=c(42524),g=c(86697),h=c(26238),i=c(93686),j=c(87390),k=c(69271),l=c(58732),m=a([i,j,l]);[i,j,l]=m.then?(await m)():m;let r="send_file_to_user",s="## Pidance file delivery\nWhen the `send_file_to_user` tool is available and you create a file that the user needs to view, download, or play, call it instead of only printing a local path or embedding Base64. The tool publishes a user-visible attachment message: images keep the original for preview and download, audio/video follow the UI playback size policy, and other files get a download card. Only claim that a file was sent after the tool returns success.";function n(a){return a.some(a=>a===s)?a:[...a,s]}let t={type:"object",additionalProperties:!1,properties:{path:{type:"string",description:"Absolute or current-project-relative path of the file to deliver."},name:{type:"string",description:"Optional filename shown to the user; the source basename is used by default."}},required:["path"]};function o(a){if(a?.aborted)throw a.reason instanceof Error?a.reason:Error("file delivery aborted")}async function p(a,b){let c,d;if("string"!=typeof a||!a.trim())throw Error("path is required");let f=(0,g.resolve)(b,a.trim()),h=(0,j.bk)()?null:await (0,j.mc)();if(h&&!(0,j.A$)(f,h))throw Error("file path is not allowed");try{c=(0,e.lstatSync)(f)}catch{throw Error("file not found")}if(c.isSymbolicLink())throw Error("symbolic-link sources are not allowed");if(!c.isFile())throw Error("path must be a regular file");try{d=(0,e.realpathSync)(f)}catch{throw Error("file path could not be resolved")}if(h&&!(0,j.A$)(d,h))throw Error("file path is not allowed");return{path:d,stat:c}}function q(a){return async function(b,c){let d;o(c);let j=await p(b.path,a.cwd),m=j.path,n="string"==typeof b.name&&b.name.trim()?b.name.trim():(0,g.basename)(m),q="number"==typeof e.constants.O_NOFOLLOW?e.constants.O_NOFOLLOW:0,r="number"==typeof e.constants.O_NONBLOCK?e.constants.O_NONBLOCK:0,s=await (0,f.open)(m,e.constants.O_RDONLY|q|r);try{let b=await s.stat();if(!b.isFile())throw Error("path must be a regular file");if(0!==j.stat.dev&&0!==j.stat.ino&&(b.dev!==j.stat.dev||b.ino!==j.stat.ino))throw Error("file changed during open");if(b.size>i.Gt)throw Error(`file exceeds ${i.Gt} bytes`);o(c);let f=(0,e.createReadStream)("",{fd:s.fd,autoClose:!1,signal:c});d=await (0,i.xd)(n,h.Readable.toWeb(f),a.agentDir,i.Gt),o(c);let g=(0,l.iU)({path:d.path,name:d.name,mimeType:(0,k.cV)(m)??(0,k.X)(m)??(0,k.k2)(m)??(0,k.oC)(m)??({txt:"text/plain",md:"text/markdown",json:"application/json",csv:"text/csv",html:"text/html",xml:"application/xml",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar"})[(0,k.GO)(m)]??"application/octet-stream",size:d.size},a.agentDir),{entryId:p}=a.appendBinary(g);return d=void 0,{entryId:p,name:g.name,size:g.size}}finally{if(await s.close().catch(()=>{}),d)try{(0,e.unlinkSync)(d.path)}catch{}}}}d()}catch(a){d(a)}})},31119:(a,b,c)=>{function d(a){if(!a.reasoning)return a;let b=a.thinkingLevelMap,c={...b??{}},d=!1;for(let a of["xhigh","max"])Object.prototype.hasOwnProperty.call(c,a)&&void 0!==c[a]||(c[a]=a,d=!0);return!d&&b?a:{...a,thinkingLevelMap:c}}function e(a){let b=d(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}c.d(b,{eU:()=>d,yu:()=>e})},33727:(a,b,c)=>{c.d(b,{D:()=>d});function d(a){return a.trim().startsWith("/")}},35304:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{recoverFollowUpQueues:()=>q});var e=c(69453),f=c(31360),g=c(84127),h=c(40673),i=c(10611),j=c(82356),k=a([e,f,i]);function l(){if(!globalThis.__piSessions){globalThis.__piSessions=new Map;let a=()=>{globalThis.__piSessions?.forEach(a=>a.destroy())};process.once("exit",a),process.once("SIGINT",a),process.once("SIGTERM",a)}return globalThis.__piSessions}function m(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function n(){return[...m().keys()]}[e,f,i]=k.then?(await k)():k;let s="",t=new Set,u=null;function o(){!function a(){let b=new Set(function(){let a=new Set(n());for(let[b,c]of l())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,j.AZ)(a),t.add(a);for(let a of[...t])b.has(a)||((0,j.Hl)(a),t.delete(a));if(0===b.size){u&&(clearInterval(u),u=null);return}u||(u=setInterval(()=>{a()},8e3),u.unref?.())}();let a=function(){let a=new Set(n());for(let[b,c]of l())c.isRunning()&&a.add(c.sessionId||b);return[...a]}(),b=function(){let a=[];for(let[b,c]of l()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c!==s)for(let b of(s=c,globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners))try{b(a)}catch{}}async function p(a,b,c,d,e){return r(a,b,c,d,e)}async function q(){let a=(0,g.readPidancePrefs)();for(let b of function(a){let b=new Set,c=a.sessionQueue;if("object"==typeof c&&null!==c&&!Array.isArray(c))for(let[a,d]of Object.entries(c))a&&(0,h.aL)(d)&&b.add(a);for(let[c,d]of Object.entries(a)){if(!c.startsWith("sessionQueue.")||!(0,h.aL)(d))continue;let a=c.slice(13);a&&b.add(a)}return[...b].filter(b=>!0!==(0,g.ql)(a,`sessionQueueHold.${b}`)&&!0!==a[`sessionQueueHold.${b}`]).sort()}(a)){let a=l().get(b);if(a?.isAlive()||(0,j.wy)(b))continue;let c=await (0,e.os)(b);if(!c)continue;let d=process.cwd();try{d=(0,f.kW)(c).getHeader()?.cwd||process.cwd()}catch{}try{await p(b,c,d)}catch(a){console.error(`[pidance] recover follow-up queue failed for ${b}:`,a)}}}async function r(a,b,c,d,f){let g=l(),h=m(),k=g.get(a);if(k?.isAlive())return{session:k,realSessionId:a};let n=h.get(a);if(n)return n;if(!(0,j.kP)(a))throw Error(j.GT);o();let p=(async()=>{try{let h=await (0,i.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>o(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=l(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,j.kP)(b),(0,j.Hl)(a))}}),k=h.sessionId,m=h.sessionFile;return m&&(0,e.O8)(k,m),k!==a&&(0,j.kP)(k),h.onDestroy(()=>{g.get(k)===h&&g.delete(k),a!==k&&g.get(a)===h&&g.delete(a),(0,j.Hl)(k),a!==k&&(0,j.Hl)(a),o()}),g.set(k,h),h.beginExtensionBinding(),{session:h,realSessionId:k}}catch(b){throw(0,j.Hl)(a),o(),b}})().finally(()=>{h.delete(a),o()});return h.set(a,p),p}d()}catch(a){d(a)}})},35948:(a,b,c)=>{c.d(b,{FH:()=>g,Ln:()=>f,PB:()=>h,uG:()=>d});let d="pidance.binary",e=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function f(a){if("string"!=typeof a)return null;let b=a.trim().toLowerCase();return e.test(b)?b:null}function g(a,b){let c={role:"custom",customType:d,content:a.name,display:!0,details:a};return void 0!==b&&(c.timestamp=b),c}function h(a,b){let c,d=f(a.mimeType)??"application/octet-stream",e=function(a){if("string"!=typeof a)return null;let b=a.replace(/[\\/\0]/g,"_").trim();return!b||b.length>180?null:b}(a.name)??"file",g=a.path.trim(),h=Number.isSafeInteger(a.size)&&a.size>=0?a.size:0,i=a.previewPath?.trim()||void 0;return{type:"binary",version:1,kind:(c=d.toLowerCase()).startsWith("image/")?"image":c.startsWith("audio/")?"audio":c.startsWith("video/")?"video":"file",path:g,name:e,mimeType:d,size:h,...i?{previewPath:i}:{},...b?{messageEntryId:b}:{}}}},36315:(a,b,c)=>{let d;c.d(b,{Lm:()=>i,Mf:()=>n,GD:()=>l,t_:()=>k,tU:()=>m});let e=JSON.parse('{"$schema":"https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json","name":"dark","vars":{"cyan":"#00d7ff","blue":"#5f87ff","green":"#b5bd68","red":"#cc6666","yellow":"#ffff00","text":"#d4d4d4","gray":"#808080","dimGray":"#666666","darkGray":"#505050","accent":"#8abeb7","selectedBg":"#3a3a4a","userMsgBg":"#343541","toolPendingBg":"#282832","toolSuccessBg":"#283228","toolErrorBg":"#3c2828","customMsgBg":"#2d2838"},"colors":{"accent":"accent","border":"blue","borderAccent":"cyan","borderMuted":"darkGray","success":"green","error":"red","warning":"yellow","muted":"gray","dim":"dimGray","text":"text","thinkingText":"gray","selectedBg":"selectedBg","userMessageBg":"userMsgBg","userMessageText":"text","customMessageBg":"customMsgBg","customMessageText":"text","customMessageLabel":"#9575cd","toolPendingBg":"toolPendingBg","toolSuccessBg":"toolSuccessBg","toolErrorBg":"toolErrorBg","toolTitle":"text","toolOutput":"gray","mdHeading":"#f0c674","mdLink":"#81a2be","mdLinkUrl":"dimGray","mdCode":"accent","mdCodeBlock":"green","mdCodeBlockBorder":"gray","mdQuote":"gray","mdQuoteBorder":"gray","mdHr":"gray","mdListBullet":"accent","toolDiffAdded":"green","toolDiffRemoved":"red","toolDiffContext":"gray","syntaxComment":"#6A9955","syntaxKeyword":"#569CD6","syntaxFunction":"#DCDCAA","syntaxVariable":"#9CDCFE","syntaxString":"#CE9178","syntaxNumber":"#B5CEA8","syntaxType":"#4EC9B0","syntaxOperator":"#D4D4D4","syntaxPunctuation":"#D4D4D4","thinkingOff":"darkGray","thinkingMinimal":"#6e6e6e","thinkingLow":"#5f87af","thinkingMedium":"#81a2be","thinkingHigh":"#b294bb","thinkingXhigh":"#d183e8","thinkingMax":"#ff5fff","bashMode":"green"},"export":{"pageBg":"#18181e","cardBg":"#1e1e24","infoBg":"#3c3728"}}');function f(a){let b=a.replace("#",""),c=Number.parseInt(3===b.length?b.split("").map(a=>a+a).join(""):b,16);return{r:c>>16&255,g:c>>8&255,b:255&c}}class g{constructor(a,b,c="truecolor",d){for(const[b,e]of(this.fgAnsiMap=new Map,this.bgAnsiMap=new Map,this.mode=c,this.name=d?.name,Object.entries({...a,thinkingMax:a.thinkingMax??a.thinkingXhigh})))this.fgAnsiMap.set(b,function(a,b){if(""===a)return"\x1b[39m";if("number"==typeof a)return`\x1b[38;5;${a}m`;if("string"==typeof a&&a.startsWith("#")){if("truecolor"===b){let{r:b,g:c,b:d}=f(a);return`\x1b[38;2;${b};${c};${d}m`}return"\x1b[38;5;7m"}throw Error(`Invalid color value: ${String(a)}`)}(e,c));for(const[a,d]of Object.entries(b))this.bgAnsiMap.set(a,function(a,b){if(""===a)return"\x1b[49m";if("number"==typeof a)return`\x1b[48;5;${a}m`;if("string"==typeof a&&a.startsWith("#")){if("truecolor"===b){let{r:b,g:c,b:d}=f(a);return`\x1b[48;2;${b};${c};${d}m`}return"\x1b[48;5;0m"}throw Error(`Invalid color value: ${String(a)}`)}(d,c))}fg(a,b){let c=this.fgAnsiMap.get(a);if(!c)throw Error(`Unknown theme color: ${a}`);return`${c}${b}\x1b[39m`}bg(a,b){let c=this.bgAnsiMap.get(a);if(!c)throw Error(`Unknown theme background color: ${a}`);return`${c}${b}\x1b[49m`}bold(a){return`\x1b[1m${a}\x1b[22m`}italic(a){return`\x1b[3m${a}\x1b[23m`}underline(a){return`\x1b[4m${a}\x1b[24m`}inverse(a){return`\x1b[7m${a}\x1b[27m`}strikethrough(a){return`\x1b[9m${a}\x1b[29m`}getFgAnsi(a){let b=this.fgAnsiMap.get(a);if(!b)throw Error(`Unknown theme color: ${a}`);return b}getBgAnsi(a){let b=this.bgAnsiMap.get(a);if(!b)throw Error(`Unknown theme background color: ${a}`);return b}getColorMode(){return this.mode}getThinkingBorderColor(a){let b={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"}[a]??"thinkingOff";return a=>this.fg(b,a)}getBashModeBorderColor(){return a=>this.fg("bashMode",a)}}let h=new Set(["selectedBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]);function i(){if(void 0!==d)return d;try{d=function(a){let b={...a.colors,thinkingMax:a.colors.thinkingMax??a.colors.thinkingXhigh},c=a.vars??{},d={},e={};for(let[a,f]of Object.entries(b)){let b=function a(b,c,d=new Set){if("number"==typeof b||""===b||b.startsWith("#"))return b;if(d.has(b))throw Error(`Circular variable reference detected: ${b}`);if(!(b in c))throw Error(`Variable reference not found: ${b}`);return d.add(b),a(c[b],c,d)}(f,c);h.has(a)?e[a]=b:d[a]=b}return new g(d,e,"truecolor",{name:a.name})}(e)}catch{d=null}return d}function j(a,b=100){if(!a||"object"!=typeof a||"function"!=typeof a.render)return null;try{let c=a.render(b);if(!function(a){if(!Array.isArray(a)||0===a.length||!a.every(a=>"string"==typeof a)||a.length>500)return!1;let b=0;for(let c of a)if(c.length>4e3||(b+=c.length)>204800)return!1;return!0}(c))return null;return c}catch{return null}}function k(a,b,c,d,e){let f=function(a){if(!a||"object"!=typeof a)return;let b=a.renderResult??a.ln;return"function"==typeof b?b:void 0}(a);if(!f)return null;let g=i();if(!g)return null;try{let a=f(b,c,g,d);return a&&"object"==typeof a&&e?.(a),j(a)}catch{return null}}function l(a,b,c,d){let e=function(a){if(!a||"object"!=typeof a)return;let b=a.renderCall;return"function"==typeof b?b:void 0}(a);if(!e)return null;let f=i();if(!f)return null;try{let a=e(b,f,c);return a&&"object"==typeof a&&d?.(a),j(a)}catch{return null}}function m(a,b,c=100){if("function"!=typeof a||!b)return null;try{let d=a(void 0,b);return j(d,c)}catch{return null}}function n(a,b,c,d=100){if("function"!=typeof a||!c)return null;try{let e=a(b,{expanded:!0},c);return j(e,d)}catch{return null}}},40673:(a,b,c)=>{function d(a){if("string"!=typeof a)return null;let b=a.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(b)?b:null}function e(a){return d(a)}function f(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){let a=d(c);a&&!b.includes(a)&&b.push(a)}return b.length>128?b.slice(b.length-128):b}function g(a,b){let c=[...a];for(let a of b)!a||c.includes(a)||c.push(a);return c.length>128?c.slice(c.length-128):c}c.d(b,{EP:()=>l,Kk:()=>d,Ot:()=>q,Pt:()=>o,S1:()=>g,X_:()=>p,aL:()=>m,gC:()=>n,jG:()=>k,ko:()=>i,mv:()=>e,ym:()=>h});let h=32;function i(a,b="waiting",c){let d,e={id:(d=globalThis.crypto)&&"function"==typeof d.randomUUID?d.randomUUID():`q-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,text:a,state:b};return c?.length&&(e.media=[...c]),e}function j(a,b){let c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=0x1000193*c>>>0;return`legacy-${a}-${c.toString(36)}`}function k(a){let b=Array.isArray(a)?a:a&&"object"==typeof a?a.items:void 0,c=a&&"object"==typeof a&&!Array.isArray(a)&&"number"==typeof a.revision&&Number.isFinite(a.revision)?a.revision:0,d=f(a&&"object"==typeof a&&!Array.isArray(a)?a.admittedAttemptIds:void 0);if(!Array.isArray(b))return{items:[],revision:c,admittedAttemptIds:d};let e=[];for(let a=0;a<b.length;a++){let c=function(a,b){var c;if("string"==typeof a){let c=a.trim();return c?{id:j(b,a),text:c,state:"waiting"}:null}if(!a||"object"!=typeof a||Array.isArray(a)||"string"!=typeof a.text)return null;let d=function(a){if(void 0===a)return[];if(!Array.isArray(a)||a.length>h)return null;let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))return null;let a="model"===c.role||"original"===c.role?c.role:null,d="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.mimeType?c.mimeType.trim():"",f="string"==typeof c.name?c.name.trim():"",g=c.size,h="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(!a||!d||!e||!f||"number"!=typeof g||!Number.isSafeInteger(g)||g<0||void 0!==c.previewPath&&!h)return null;b.push({role:a,path:d,name:f,mimeType:e,size:g,...h&&h!==d?{previewPath:h}:{}})}return b}(a.media);return null!==d&&(a.text.trim()||0!==d.length)?{id:"string"==typeof a.id&&a.id.trim()?a.id:j(b,a.text),text:a.text,state:"claimed"===(c=a.state)||"unknown"===c?c:"waiting",...d.length?{media:d}:{}}:null}(b[a],a);c&&e.push(c)}return{items:e,revision:c,admittedAttemptIds:d}}function l(a){let b=f(a.admittedAttemptIds);return{items:a.items.map(a=>({id:a.id,text:a.text,state:a.state,...a.media?.length?{media:a.media.map(a=>({...a}))}:{}})),revision:a.revision,...b.length?{admittedAttemptIds:b}:{}}}function m(a){return k(a).items.length>0}function n(a){return a.map(a=>a.text)}function o(a,b,c){let d=new Set(c?.inFlightIds??[]),e=Array(a.length).fill(!1),f=new Map;a.forEach((a,b)=>{f.has(a.id)||f.set(a.id,b)});let g=[];for(let c of b){if(void 0!==c.id&&d.has(c.id))continue;let b=void 0===c.id?void 0:f.get(c.id);if(void 0!==b&&!e[b]){e[b]=!0;let d=a[b],f=c.media?.length?c.media:d.media;g.push({id:d.id,text:c.text,state:d.state,...f?.length?{media:[...f]}:{}});continue}let h=-1;for(let b=0;b<a.length;b++){let d=a[b];if(!e[b]&&d.text===c.text){if(function(a,b){let c=a??[],d=b??[];return c.length===d.length&&c.every((a,b)=>a.path===d[b].path)}(d.media,c.media)){h=b;break}h<0&&(h=b)}}if(h>=0){e[h]=!0;let b=a[h],d=c.media?.length?c.media:b.media;g.push({id:b.id,text:c.text,state:b.state,...d?.length?{media:[...d]}:{}});continue}g.push(c.media?.length?i(c.text,"waiting",c.media):i(c.text,"waiting"))}return g}function p(a,b){return{text:[...n(a),...b?.trim()?[b.trim()]:[]].map(a=>a.trim()).filter(a=>a.length>0).join("\n"),media:q(a)}}function q(a){return a.flatMap(a=>a.media??[])}},58732:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Nu:()=>m,iU:()=>l});var e=c(89477),f=c(86697),g=c(92783),h=c(93686),i=c(35948),j=a([h]);h=(j.then?(await j)():j)[0];class n extends Error{constructor(a){super(a),this.name="BinaryMessageError"}}function k(a,b){let c,d,g=(0,e.realpathSync)((0,h.eq)(b));try{c=(0,e.realpathSync)((0,f.resolve)(a))}catch{throw new n("binary media file not found")}let i=(0,f.relative)(g,c);if(!i||".."===i||i.startsWith(`..${f.sep}`)||(0,f.isAbsolute)(i))throw new n("binary media path is not allowed");try{d=(0,e.statSync)(c)}catch{throw new n("binary media file not found")}if(!d.isFile())throw new n("binary media must be a file");return{path:c.replace(/\\/g,"/"),size:d.size}}function l(a,b=(0,g.$M)(),c){if(!a||"object"!=typeof a||"string"!=typeof a.name||!a.name.trim()||"string"!=typeof a.path||!a.path.trim())throw new n("invalid binary block");let d=(0,i.Ln)(a.mimeType);if(!d)throw new n("invalid binary MIME type");let e=(0,h.uF)(a.name);if(!e)throw new n("binary file name is required");let f=k(a.path,b),j=a.previewPath?k(a.previewPath,b):void 0;return(0,i.PB)({path:f.path,name:e,mimeType:d,size:f.size,...j?{previewPath:j.path}:{}},c)}function m(a,b=(0,g.$M)()){if(!a||0===a.length)return[];if(a.length>32)throw new n("too many binary blocks");return a.map(a=>l(a,b))}d()}catch(a){d(a)}})},63480:(a,b,c)=>{c.d(b,{E:()=>d});function d(a,b,c){let d=a.getModel?.(b,c);return d||a.getAvailableSnapshot?.().find(a=>a.provider===b&&a.id===c)}},66323:(a,b,c)=>{c.d(b,{EE:()=>r,_2:()=>s});var d=c(89477),e=c.n(d),f=c(62228),g=c.n(f),h=c(86697),i=c.n(h);let j=/^[A-Za-z0-9_-]{1,128}$/,k=/^output-\d+\.log$/,l=new Set(["queued","running","complete","failed","paused","stopped"]),m=new Set(["single","parallel","chain"]),n=new Set(["active_long_running","needs_attention"]),o={readdirSync:a=>e().readdirSync(a),lstatSync:a=>e().lstatSync(a),realpathSync:a=>e().realpathSync(a),readFileSync:(a,b)=>e().readFileSync(a,b),openSync:(a,b)=>e().openSync(a,b),readSync:(a,b,c,d,f)=>e().readSync(a,b,c,d,f),closeSync:a=>e().closeSync(a),fstatSync:a=>e().fstatSync(a),constants:e().constants};function p(a){return a.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}let q=new Set(["running","queued","paused"]);function r(a,b,c=Date.now(),d=9e5){let e="string"==typeof b?b:"";if(!e.endsWith(".jsonl"))return!1;let f=e.slice(0,-6),g=a=>{if("string"!=typeof a||!a||!a.startsWith(f))return!1;let b=a.charAt(f.length);return"/"===b||"\\"===b};for(let b of a??[]){if(!b||"object"!=typeof b||!q.has(b.state))continue;let a=b.lastUpdate??b.startedAt;if("number"!=typeof a||!(c-a>d)){for(let a of b.steps??[])if(g(a?.sessionFile))return!0}}return!1}function s(a={}){var b,c;let d,e,f,h,n=a.fs??o,q=a.limit??20,r=a.now?.()??Date.now(),C=a.root??(b=a.scope,h=b?.tmpdir?.()??g().tmpdir(),i().join(h,`pi-subagents-${function(a){let b=a?.env??process.env,c=a&&Object.hasOwn(a,"getuid")?a.getuid:process.getuid?.bind(process);if("function"==typeof c)return`uid-${c()}`;for(let a of["USERNAME","USER","LOGNAME"]){let c=b[a];if(c)return`user-${p(c)}`}let d=a&&Object.hasOwn(a,"userInfo")?a.userInfo:g().userInfo;try{let a=d?.().username;if(a)return`user-${p(a)}`}catch{}let e=b.USERPROFILE??b.HOME;if(e)return`home-${p(e)}`;let f=a&&Object.hasOwn(a,"homedir")?a.homedir:g().homedir;try{let a=f?.();if(a)return`home-${p(a)}`}catch{}return"shared"}(b)}`,"async-subagent-runs"));try{let a=n.lstatSync(C);if(a.isSymbolicLink()||!a.isDirectory())return t(r,!1);e=n.realpathSync(C)}catch(a){return u(a),t(r,!1)}try{f=n.readdirSync(C)}catch(a){return u(a),t(r,!1)}f.length>256&&(f=f.slice(0,256));let D=[];for(let a of f)if(j.test(a))try{let b=function(a,b,c,d){var e,f;let g,h,j,n,o=i().join(b,d);try{g=a.lstatSync(o)}catch{return null}if(g.isSymbolicLink()||!g.isDirectory())return null;try{h=a.realpathSync(o)}catch{return null}if(!v(h,c))return null;let p=function(a,b,c){let d=w(a,b,c);if(!d)return null;let{fd:e,size:f}=d;try{if(f<=0||f>2097152)return null;let b=Buffer.alloc(f),c=0;for(;c<f;){let d=a.readSync(e,b,c,f-c,c);if(0===d)break;c+=d}let d=b.subarray(0,c).toString("utf8"),g=JSON.parse(d);if(!g||"object"!=typeof g||Array.isArray(g))return null;return g}catch{return null}finally{try{a.closeSync(e)}catch{}}}(a,i().join(o,"status.json"),c);if(!p)return null;let q=(e=p.state,"string"==typeof e&&l.has(e)?e:void 0);if(!q)return null;let r=(f=p.mode,("string"==typeof f&&m.has(f)?f:void 0)??"single"),s=z(p.startedAt);if(void 0===s)return null;let t="string"==typeof p.runId&&p.runId.trim()?p.runId.trim():d,u=y(p.activityState),C=z(p.endedAt),D=z(p.lastUpdate),E="string"==typeof p.cwd?p.cwd:void 0,F="string"==typeof p.error?p.error:void 0,G=z(p.currentStep),H=z(p.chainStepCount),I=A(p.totalTokens),J=B(p.totalCost),K=function(a){if(!Array.isArray(a))return[];let b=[];for(let c=0;c<a.length;c+=1){let d=a[c];if(!d||"object"!=typeof d||Array.isArray(d)){b.push({index:c,agent:"unknown",status:"unknown"});continue}let e="string"==typeof d.agent&&d.agent?d.agent:"unknown",f={index:c,agent:e,status:"string"==typeof d.status&&d.status?d.status:"unknown"};"string"==typeof d.label&&(f.label=d.label),"string"==typeof d.model&&(f.model=d.model),"string"==typeof d.sessionFile&&(f.sessionFile=d.sessionFile),"string"==typeof d.error&&(f.error=d.error);let g=y(d.activityState);g&&(f.activityState=g),"string"==typeof d.currentTool&&(f.currentTool=d.currentTool);let h=A(d.tokens);h&&(f.tokens=h);let i=B(d.totalCost)??z(d.costUsd);void 0!==i&&(f.costUsd=i);let j=z(d.startedAt);void 0!==j&&(f.startedAt=j);let k=z(d.endedAt);void 0!==k&&(f.endedAt=k),Array.isArray(d.recentOutput)&&(f.recentOutput=function(a){let b=[];for(let c of a){if(b.length>=8)break;"string"==typeof c&&b.push(c.length>200?c.slice(0,200):c)}return b}(d.recentOutput)),b.push(f)}return b}(p.steps),L=function(a,b,c){let d=x(a,b,c,65536);if(!d||!d.text)return[];let e=d.text;if(d.truncated){let a=e.indexOf("\n");a>=0&&(e=e.slice(a+1))}let f=e.split(/\r?\n/).filter(a=>a.trim().length>0),g=[];for(let a=f.length-1;a>=0&&g.length<20;a-=1)try{let b=JSON.parse(f[a]);if(!b||"object"!=typeof b||Array.isArray(b))continue;let c="string"==typeof b.type?b.type:void 0;if(!c)continue;let d={type:c},e=z(b.timestamp)??z(b.ts)??z(b.time);void 0!==e&&(d.timestamp=e);let h="string"==typeof b.message?b.message:"string"==typeof b.error?b.error:void 0;void 0!==h&&(d.message=h.length>200?h.slice(0,200):h),g.push(d)}catch{}return g.reverse(),g}(a,i().join(o,"events.jsonl"),c),M=function(a,b){if("string"!=typeof a||!a.trim())return null;let c=i().basename(a.trim());return k.test(c)?{absPath:i().join(b,c)}:null}(p.outputFile,o);if(M){let b=x(a,M.absPath,c,32768);if(b){let a=b.text;if(b.truncated){let b=a.indexOf("\n");b>=0&&(a=a.slice(b+1))}j=a,n=b.truncated}}let N={id:t,state:q,mode:r,startedAt:s,steps:K,recentEvents:L};return u&&(N.activityState=u),void 0!==C&&(N.endedAt=C),void 0!==D&&(N.lastUpdate=D),void 0!==E&&(N.cwd=E),void 0!==F&&(N.error=F),void 0!==G&&(N.currentStep=G),void 0!==H&&(N.chainStepCount=H),I&&(N.totalTokens=I),void 0!==J&&(N.totalCostUsd=J),void 0!==j&&(N.outputTail=j),void 0!==n&&(N.outputTruncated=n),N}(n,C,e,a);b&&D.push(b)}catch{}return{runs:(c=D,d=a=>{switch(a){case"running":return 0;case"queued":return 1;case"failed":case"stopped":case"paused":return 2;case"complete":return 3;default:return 4}},[...c].sort((a,b)=>{let c=d(a.state)-d(b.state);if(0!==c)return c;let e=a.lastUpdate??a.endedAt??a.startedAt;return(b.lastUpdate??b.endedAt??b.startedAt)-e})).slice(0,Math.min(q,50)),generatedAt:r,rootAvailable:!0}}function t(a,b){return{runs:[],generatedAt:a,rootAvailable:b}}function u(a){return"object"==typeof a&&null!==a&&"code"in a&&"ENOENT"===a.code}function v(a,b){let c=i().resolve(a),d=b.endsWith(i().sep)?b:b+i().sep;return c===b||c.startsWith(d)}function w(a,b,c){try{let d=a.lstatSync(b);if(d.isSymbolicLink()||!d.isFile())return null;let e=a.realpathSync(b);if(!v(e,c))return null;let f="number"==typeof a.constants.O_NOFOLLOW?a.constants.O_NOFOLLOW:0,g=a.openSync(b,a.constants.O_RDONLY|f);try{let c=a.fstatSync?a.fstatSync(g):a.lstatSync(b);if(!c.isFile())return a.closeSync(g),null;return{fd:g,size:c.size}}catch{try{a.closeSync(g)}catch{}return null}}catch{return null}}function x(a,b,c,d){let e=w(a,b,c);if(!e)return null;let{fd:f,size:g}=e;try{if(0===g)return{text:"",truncated:!1,size:0};let b=Math.min(d,g),c=Math.max(0,g-b),e=Buffer.alloc(b),h=0;for(;h<b;){let d=a.readSync(f,e,h,b-h,c+h);if(0===d)break;h+=d}return{text:e.subarray(0,h).toString("utf8"),truncated:g>d,size:g}}finally{try{a.closeSync(f)}catch{}}}function y(a){return"string"==typeof a&&n.has(a)?a:void 0}function z(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function A(a){if(!a||"object"!=typeof a||Array.isArray(a))return;let b=z(a.input),c=z(a.output),d=z(a.total);if(void 0!==b&&void 0!==c&&void 0!==d)return{input:b,output:c,total:d}}function B(a){return"number"==typeof a&&Number.isFinite(a)?a:!a||"object"!=typeof a||Array.isArray(a)?void 0:z(a.costUsd)}},68642:(a,b,c)=>{c.d(b,{NK:()=>f,PI:()=>g});let d="__piRunningStartedAt";function e(){let a=globalThis;return d in a&&a[d]instanceof Map||(a[d]=new Map),a[d]}function f(a,b){let c=e();c.has(a)||c.set(a,b)}function g(a){e().delete(a)}},69271:(a,b,c)=>{c.d(b,{GO:()=>h,X:()=>j,cV:()=>i,k2:()=>k,oC:()=>l});let d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},e={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},f={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},g={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function h(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function i(a){return d[h(a)]??null}function j(a){return e[h(a)]??null}function k(a){return f[h(a)]??null}function l(a){return g[h(a)]??null}},75377:(a,b,c)=>{c.d(b,{t:()=>g});var d=c(716),e=c(36315);function f(a,b,c,e,f,g,h){let i=(0,d.randomUUID)();return new Promise((d,j)=>{let k,l=!1,m=()=>{a.delete(i),b.delete(i),k&&clearTimeout(k),e?.signal?.removeEventListener("abort",o)},n=a=>{l||(l=!0,m(),d(a))},o=()=>n(f);e?.signal?.addEventListener("abort",o,{once:!0}),e?.timeout&&(k=setTimeout(()=>n(f),e.timeout)),a.set(i,{resolve:a=>{try{n(h(a))}catch(a){if(l)return;l=!0,m(),j(a instanceof Error?a:Error(String(a)))}},reject:a=>{l||(l=!0,m(),j(a))}});let p={type:"extension_ui_request",id:i,...g};b.set(i,p),c(p)})}function g(a){let b=new Map,c=new Map,g=new Map,h=new Map,i=new Map,j=null,k={select:(d,e,g)=>f(b,c,a,g,void 0,{method:"select",title:d,options:e,timeout:g?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),confirm:(d,e,g)=>f(b,c,a,g,!1,{method:"confirm",title:d,message:e,timeout:g?.timeout},a=>(!("cancelled"in a)||!a.cancelled)&&"confirmed"in a&&!!a.confirmed),input:(d,e,g)=>f(b,c,a,g,void 0,{method:"input",title:d,placeholder:e,timeout:g?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),notify(b,c){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"notify",message:b,notifyType:c})},onTerminalInput:()=>()=>{},setStatus(b,c){c?g.set(b,c):g.delete(b),a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setStatus",statusKey:b,statusText:c})},setWorkingMessage(){},setWorkingVisible(){},setWorkingIndicator(){},setHiddenThinkingLabel(){},setWidget(b,c,f){if("function"==typeof c){let a=(0,e.tU)(c,(0,e.Lm)());if(null===a)return;c=a}(void 0===c||Array.isArray(c))&&(null==c?h.delete(b):h.set(b,{lines:c,placement:f?.placement}),a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:c,widgetPlacement:f?.placement}))},setFooter(){},setHeader(){},setTitle(b){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setTitle",title:b})},async custom(b){let c=(0,d.randomUUID)();return new Promise(d=>{let f,g=!1,h=b=>{g||(g=!0,i.delete(c),j?.id===c&&(j=null),a({type:"extension_ui_request",id:c,method:"custom",closed:!0,lines:[]}),d(b))},l=()=>{if(g)return;let b=[];try{let a=f?.render?.(92);Array.isArray(a)&&(b=a.filter(a=>"string"==typeof a))}catch(a){console.error("[pidance] custom UI render failed:",a)}a({type:"extension_ui_request",id:c,method:"custom",lines:b}),j={id:c,lines:[...b]}};i.set(c,{handleInput:a=>{if("\x03"===a)return void h(void 0);try{f?.handleInput?.(a)}catch(a){console.error("[pidance] custom UI input failed:",a)}},done:h});let m=function(a,b=92,c=40){return Object.freeze({terminal:Object.freeze({columns:b,rows:c,kittyProtocolActive:!1}),requestRender:a})}(()=>{l()},92,40),n=(0,e.Lm)()??k.theme;Promise.resolve().then(()=>b(m,n,{},h)).then(a=>{g||(f=a,l())}).catch(a=>{console.error("[pidance] custom UI factory failed:",a),h(void 0)})})},pasteToEditor(a){this.setEditorText(a)},setEditorText(b){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"set_editor_text",text:b})},getEditorText:()=>"",editor:async(d,e)=>f(b,c,a,void 0,void 0,{method:"editor",title:d,prefill:e},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){let a=a=>String(a??""),b=(a,b)=>void 0===b?"":String(b);return new Proxy({fg:b,bg:b,bold:a,dim:a,italic:a},{get:(b,c)=>c in b?b[c]:"then"!==c?a:void 0})},getAllThemes:()=>[],getTheme(){},setTheme:()=>({success:!1,error:"Theme switching not supported in Web mode"}),getToolsExpanded:()=>!1,setToolsExpanded(){}};return{uiContext:k,pending:b,statuses:g,widgets:h,pendingSnapshot:c,get customSnapshot(){return j},respond(a,c){let d=b.get(a);return!!d&&(d.resolve(c),!0)},inputCustom(a,b){let c=i.get(a);return!!c&&(c.handleInput(b),!0)},dispose(){for(let[a,d]of b)b.delete(a),c.delete(a),d.reject(Error("Extension UI disposed"));for(let a of i.values())a.done(void 0);i.clear(),j=null,g.clear(),h.clear()}}}},82356:(a,b,c)=>{c.d(b,{AZ:()=>u,GT:()=>h,Hl:()=>v,kP:()=>t,sweepStaleRunningLeases:()=>s,wy:()=>w});var d=c(716),e=c(89477),f=c(86697),g=c(92783);let h="Session is locked by another Pidance process (writable host ownership)",i="Timed out acquiring Pidance running-lease lock";function j(a){return(0,f.join)(a,"pidance-running-leases")}function k(a,b){let c=b.replace(/[^a-zA-Z0-9._-]+/g,"_").slice(0,180);return(0,f.join)(j(a),`${c}.json`)}function l(a){if(!Number.isFinite(a)||a<=0)return!1;try{return process.kill(a,0),!0}catch(a){return"EPERM"===a.code}}function m(a){try{let b=JSON.parse((0,e.readFileSync)(a,"utf8"));if("number"!=typeof b.pid||"string"!=typeof b.sessionId||"number"!=typeof b.heartbeatAt)return null;return{pid:b.pid,sessionId:b.sessionId,heartbeatAt:b.heartbeatAt,startedAt:"number"==typeof b.startedAt?b.startedAt:b.heartbeatAt}}catch{return null}}function n(a){try{let b=JSON.parse((0,e.readFileSync)(a,"utf8"));if("number"!=typeof b.pid||"string"!=typeof b.token)return null;return{pid:b.pid,token:b.token}}catch{return null}}function o(a,b){let c=j(a);(0,e.existsSync)(c)||(0,e.mkdirSync)(c,{recursive:!0,mode:448});let g=(0,f.join)(c,".lease-lock"),h=(0,d.randomBytes)(8).toString("hex"),k=Date.now()+3e3,m=!1;for(;!m;){let a=`${g}.${process.pid}.${h}.tmp`;try{(0,e.writeFileSync)(a,JSON.stringify({pid:process.pid,token:h}),{mode:384}),(0,e.linkSync)(a,g),m=!0}catch(b){if("EEXIST"!==b.code){try{(0,e.unlinkSync)(a)}catch{}throw b}}try{(0,e.unlinkSync)(a)}catch{}if(m)break;let b=n(g);if(b&&!l(b.pid)){try{n(g)?.token===b.token&&(0,e.unlinkSync)(g)}catch{}continue}if(!b)try{Date.now()-(0,e.statSync)(g).mtimeMs>1e4&&(0,e.unlinkSync)(g)}catch{}if(Date.now()>=k)throw Error(i);!function(){let a=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(a,0,0,5)}()}try{return b()}finally{try{n(g)?.token===h&&(0,e.unlinkSync)(g)}catch{}}}function p(a){return a instanceof Error&&a.message===i}function q(a,b){let c=`${a}.${process.pid}.tmp`;(0,e.writeFileSync)(c,`${JSON.stringify(b)}
2
2
  `,{mode:384}),(0,e.renameSync)(c,a)}function r(a){return!!(a&&l(a.pid))}function s(a=(0,g.$M)(),b=Date.now()){try{let c,{fresh:d,removed:g}=(c=j(a),(0,e.existsSync)(c)?o(a,()=>{let a=[],d=0;for(let g of(0,e.readdirSync)(c)){if(!g.endsWith(".json"))continue;let h=(0,f.join)(c,g),i=m(h);if(!r(i)){try{(0,e.unlinkSync)(h),d+=1}catch{}continue}b-i.heartbeatAt<=2e4&&l(i.pid)&&a.push(i)}return{fresh:a,removed:d}}):{fresh:[],removed:0});return{removed:g,active:d.length,skipped:!1}}catch(a){if(p(a))return{removed:0,active:0,skipped:!0};throw a}}function t(a,b=(0,g.$M)(),c=Date.now()){if(!a)return!1;try{return o(b,()=>{let d=k(b,a),f=(0,e.existsSync)(d)?m(d):null;return!(f&&f.pid!==process.pid&&r(f))&&(q(d,{pid:process.pid,sessionId:a,heartbeatAt:c,startedAt:f&&f.pid===process.pid?f.startedAt:c}),!0)})}catch(a){if(p(a))return!1;throw a}}function u(a,b=(0,g.$M)(),c=Date.now()){if(a)try{o(b,()=>{let d=k(b,a),f=(0,e.existsSync)(d)?m(d):null;f&&f.pid!==process.pid&&r(f)||q(d,{pid:process.pid,sessionId:a,heartbeatAt:c,startedAt:f&&f.pid===process.pid?f.startedAt:c})})}catch(a){if(!p(a))throw a}}function v(a,b=(0,g.$M)()){if(a)try{o(b,()=>{let c=k(b,a),d=(0,e.existsSync)(c)?m(c):null;if(!d||d.pid===process.pid)try{(0,e.unlinkSync)(c)}catch{}})}catch(a){if(!p(a))throw a}}function w(a,b=(0,g.$M)(),c=Date.now()){if(!a)return!1;let d=(0,e.existsSync)(k(b,a))?m(k(b,a)):null;return!!d&&d.pid!==process.pid&&r(d)}}};
@@ -0,0 +1 @@
1
+ exports.id=5726,exports.ids=[5726],exports.modules={12039:(a,b,c)=>{"use strict";c.d(b,{B:()=>f});var d=c(31514);function e(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function f(a){if("assistant"!==a.role)return a;let b=a.content;if(!Array.isArray(b))return a;let c=b.map(a=>{let b=function(a){if(!e(a)||"toolCall"!==a.type)return null;let b={type:"toolCall",toolCallId:"string"==typeof a.toolCallId?a.toolCallId:"string"==typeof a.id?a.id:"",toolName:"string"==typeof a.toolName?a.toolName:"string"==typeof a.name?a.name:"",input:"object"!=typeof a.input||null===a.input||Array.isArray(a.input)?"object"!=typeof a.arguments||null===a.arguments||Array.isArray(a.arguments)?{}:a.arguments:a.input};return Array.isArray(a.renderedCallLines)&&a.renderedCallLines.every(a=>"string"==typeof a)&&(b.renderedCallLines=[...a.renderedCallLines]),b}(a);return b||(e(a)&&(0,d.mv)(a.type)?(0,d.Xb)(a):a)});return{...a,content:c}}},13737:(a,b,c)=>{"use strict";c.d(b,{FH:()=>j,Ln:()=>g,PB:()=>k,QT:()=>i,uG:()=>d});let d="pidance.binary",e=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function f(a){let b=a.toLowerCase();return b.startsWith("image/")?"image":b.startsWith("audio/")?"audio":b.startsWith("video/")?"video":"file"}function g(a){if("string"!=typeof a)return null;let b=a.trim().toLowerCase();return e.test(b)?b:null}function h(a){if("string"!=typeof a)return null;let b=a.replace(/[\\/\0]/g,"_").trim();return!b||b.length>180?null:b}function i(a){if(!a||"object"!=typeof a||Array.isArray(a)||"binary"!==a.type||1!==a.version||"string"!=typeof a.path)return null;let b=a.path.trim();if(!b||b.length>4096)return null;let c=h(a.name),d=g(a.mimeType);if(!c||!d||"number"!=typeof a.size||!Number.isSafeInteger(a.size)||a.size<0)return null;let e=a.kind;if("image"!==e&&"audio"!==e&&"video"!==e&&"file"!==e||e!==f(d))return null;let i=void 0===a.previewPath?void 0:"string"==typeof a.previewPath&&a.previewPath.trim().length<=4096?a.previewPath.trim()||void 0:null;if(null===i)return null;let j=void 0===a.messageEntryId?void 0:"string"==typeof a.messageEntryId&&a.messageEntryId.trim()?a.messageEntryId.trim():null;return null===j?null:{type:"binary",version:1,kind:e,path:b,name:c,mimeType:d,size:a.size,...i?{previewPath:i}:{},...j?{messageEntryId:j}:{}}}function j(a,b){let c={role:"custom",customType:d,content:a.name,display:!0,details:a};return void 0!==b&&(c.timestamp=b),c}function k(a,b){let c=g(a.mimeType)??"application/octet-stream",d=h(a.name)??"file",e=a.path.trim(),i=Number.isSafeInteger(a.size)&&a.size>=0?a.size:0,j=a.previewPath?.trim()||void 0;return{type:"binary",version:1,kind:f(c),path:e,name:d,mimeType:c,size:i,...j?{previewPath:j}:{},...b?{messageEntryId:b}:{}}}},13995:(a,b,c)=>{"use strict";let d;c.d(b,{If:()=>o,Jz:()=>l,O:()=>q,iw:()=>m});var e=c(4984),f=c(29021),g=c(79748),h=c(33873),i=c(60396);function j(){return(0,h.join)((0,i.$M)(),"pidance-session-cache.json")}async function k(a){try{let b=await (0,g.stat)(a);return{path:a,mtimeMs:b.mtimeMs,size:b.size}}catch{return null}}async function l(a=(0,h.join)((0,i.$M)(),"sessions")){let b=[];try{b=(await (0,g.readdir)(a,{withFileTypes:!0})).filter(a=>a.isDirectory()).map(b=>(0,h.join)(a,b.name))}catch{return[]}let c=[],d=[];for(let a of b)d.push((async()=>{try{for(let b of(await (0,g.readdir)(a)))b.endsWith(".jsonl")&&c.push((0,h.join)(a,b))}catch{}})());return await Promise.all(d),(await Promise.all(c.map(a=>k(a)))).filter(a=>null!==a)}function m(a=j()){try{let b=(0,f.readFileSync)(a,"utf8"),c=JSON.parse(b);if(!c||2!==c.version||!c.sessions||"object"!=typeof c.sessions)return null;return{version:2,sessions:c.sessions,discovery:c.discovery&&"object"==typeof c.discovery?c.discovery:{}}}catch{return null}}let n=!1;function o(a,b,c=j()){n=!0,d||(d=setTimeout(()=>{if(d=void 0,!n)return;n=!1;let e={version:2,sessions:Object.fromEntries(a),discovery:Object.fromEntries(b)},g=`${c}.tmp`;try{(0,f.writeFileSync)(g,JSON.stringify(e),"utf8"),(0,f.renameSync)(g,c)}catch{try{(0,f.existsSync)(g)&&(0,f.renameSync)(g,c)}catch{}}},1500))}function p(a){return"object"==typeof a&&null!==a&&"string"==typeof a.role&&"content"in a}async function q(a,b){try{let c,d,g=(0,e.createInterface)({input:(0,f.createReadStream)(a,{encoding:"utf8"}),crlfDelay:1/0}),h=null,i=0,j="";for await(let a of g){let b;if(!a.trim())continue;try{b=JSON.parse(a)}catch{continue}if(!h){if("session"!==b.type)return null;h=b;continue}if("session_info"===b.type){let a=b.name;"string"==typeof a&&a.trim()&&(c=a.trim());continue}if("message"!==b.type)continue;i++;let e=function(a){let b=a.message;if(!p(b)||"user"!==b.role)return;let c=b.timestamp;if("number"==typeof c)return c;let d=new Date(a.timestamp??"").getTime();return Number.isNaN(d)?void 0:d}(b);"number"==typeof e&&(d=Math.max(d??0,e));let f=b.message;if(!p(f)||"user"!==f.role&&"assistant"!==f.role)continue;let g=function(a){let b=a.content;return"string"==typeof b?b:Array.isArray(b)?b.filter(a=>!!(a&&"text"===a.type&&"string"==typeof a.text)).map(a=>a.text).join(" "):""}(f);g&&(j||"user"!==f.role||(j=g))}if(!h)return null;let k="string"==typeof h.timestamp?new Date(h.timestamp).getTime():NaN,l=new Date("number"==typeof d&&d>0?d:Number.isNaN(k)?b.mtimeMs:k);return{id:"string"==typeof h.id?h.id:"",cwd:"string"==typeof h.cwd?h.cwd:"",name:c,created:h.timestamp,modified:l.toISOString(),messageCount:i,firstMessage:j||"(no messages)",parentSessionPath:"string"==typeof h.parentSession?h.parentSession:void 0}}catch{return null}}},15461:(a,b,c)=>{"use strict";c.d(b,{OE:()=>d,fc:()=>e,yz:()=>f});let d="pidance.command";function e(a){return{command:"string"==typeof a.command?a.command.trim():"",ok:!1!==a.ok,result:"string"==typeof a.result&&""!==a.result.trim()?a.result.trim():void 0,version:1}}function f(a){return a&&"object"==typeof a?1!==a.version||"string"!=typeof a.command||""===a.command.trim()?null:{command:a.command,ok:!1!==a.ok,result:"string"==typeof a.result?a.result:void 0,version:1}:null}},31514:(a,b,c)=>{"use strict";function d(a){for(let b of[a.thinking,a.text,a.reasoning])if("string"==typeof b&&b.length>0)return b;return""}function e(a){return"thinking"===a||"reasoning"===a||"redacted_thinking"===a}function f(a){let b={...a,type:"thinking",thinking:d(a)};return!0===a.deferred&&(b.deferred=!0),b}c.d(b,{Ux:()=>d,Xb:()=>f,mv:()=>e})},40402:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{BR:()=>x,CM:()=>C,DK:()=>z,O8:()=>w,Uv:()=>E,Zx:()=>A,dQ:()=>q,eP:()=>y,jK:()=>B,mD:()=>r,os:()=>u,tY:()=>D,u1:()=>v});var e=c(29021),f=c(33873),g=c(15461),h=c(13995),i=c(12039),j=c(85664),k=c(13737),l=c(50955);c(60396);var m=c(95237),n=c(31514),o=a([m]);async function p(){let a=await (0,h.Jz)(),b=(0,h.iw)(),c=new Map;if(b)for(let[a,d]of Object.entries(b.sessions))c.set(a,d);let d=a.filter(a=>{let b=c.get(a.path);return!b||b.m!==a.mtimeMs||b.s!==a.size}),g=d.length>0,i=new Map;for(let a of(await Promise.all(d.map(async a=>{let b=await (0,h.O)(a.path,a);b&&i.set(a.path,b)})),d)){let b=i.get(a.path);if(!b){c.delete(a.path);continue}c.set(a.path,{m:a.mtimeMs,s:a.size,i:b})}let j=new Set(a.map(a=>a.path)),k=0;for(let a of[...c.keys()])!j.has(a)&&(c.delete(a),k++);k>0&&(g=!0);let m=[...c.entries()].map(([a,b])=>({path:a,...b.i})).filter(a=>!!(a&&a.id)),n=new Map,o=new Map;for(let a of m){let b=(0,f.normalize)(a.path);n.has(b)||o.has(a.id)||(n.set(b,a.id),o.set(a.id,b))}let p=new Set,q=new Set,r=m.sort((a,b)=>a.modified<b.modified?1:a.modified>b.modified?-1:0).flatMap(a=>{let b=(0,f.normalize)(a.path);return p.has(b)||q.has(a.id)?[]:(p.add(b),q.add(a.id),w(a.id,a.path),[{path:a.path,id:a.id,cwd:a.cwd,name:a.name,created:a.created,modified:a.modified,messageCount:a.messageCount,firstMessage:a.firstMessage||"(no messages)",parentSessionId:a.parentSessionPath?n.get((0,f.normalize)(a.parentSessionPath)):void 0,projectRoot:a.cwd}])}),s=new Map(r.map(a=>[(0,f.normalize)(a.path),a])),t=new Map(r.map(a=>[a.id,a])),u=new Set,v=new Set,x=[],y=new Map;if(b)for(let[a,c]of Object.entries(b.discovery))y.set(a,c);let z=r.map(a=>({parent:a,depth:0}));for(;z.length&&v.size<256;){let a=z.shift();if(!(a.depth>=16))for(let b of function(a,b,c,d){try{let g=(0,e.statSync)(a),h=a.endsWith(".jsonl")?function a(b,c,d){let g;if(d.n<=0)return"";try{g=(0,e.statSync)(b)}catch{return""}if(d.n-=1,!g.isDirectory())return`${g.mtimeMs}:${g.size}`;let h=[];try{h=(0,e.readdirSync)(b)}catch{return`${g.mtimeMs}:${g.size}`}let i=[`${g.mtimeMs}:${g.size}`];if(c<=0){for(let a of h.slice(0,32))i.push(a);return i.join("|")}for(let e of h.slice(0,32))i.push(`${e}=${a((0,f.join)(b,e),c-1,d)}`);return i.join("|")}(a.slice(0,-6),2,{n:96}):"",i=c.get(a);if(i&&i.m===g.mtimeMs&&i.s===g.size&&i.d===h)return i.c;let j=d(a,b);return c.set(a,{m:g.mtimeMs,s:g.size,d:h,c:j}),j}catch{return c.delete(a),[]}}(a.parent.path,a.parent.id,y,(a,b)=>(g=!0,(0,l.ob)(a,b).map(a=>({path:a.path,id:a.header.id,cwd:a.header.cwd,timestamp:a.header.timestamp,parentSessionId:a.parentSessionId,runId:a.runId,runIndex:a.runIndex,...a.agent?{agent:a.agent}:{}}))))){let c=(0,f.normalize)(b.path);if(u.has(c)||v.has(b.id))continue;u.add(c),v.add(b.id);let d=s.get(c),e=t.get(b.id);if(d&&d.id!==b.id||e&&(0,f.normalize)(e.path)!==c)continue;let g=d??e;if(g){g.subagent={parentSessionId:b.parentSessionId,runId:b.runId,runIndex:b.runIndex,...b.agent?{agent:b.agent}:{}},g.readOnly=!0,z.push({parent:g,depth:a.depth+1});continue}p.has(c)||q.has(b.id)||(p.add(c),q.add(b.id),n.set(c,b.id),x.push({child:b}),z.push({parent:{path:b.path,id:b.id,cwd:b.cwd,created:b.timestamp,modified:b.timestamp,messageCount:0,firstMessage:"(no messages)",projectRoot:b.cwd},depth:a.depth+1}))}}let A=await Promise.all(x.map(async({child:a})=>{let b=a.timestamp;try{b=(0,e.statSync)(a.path).mtime.toISOString()}catch{}return w(a.id,a.path),{path:a.path,id:a.id,cwd:a.cwd,created:a.timestamp,modified:b,messageCount:0,firstMessage:"(no messages)",projectRoot:a.cwd,subagent:{parentSessionId:a.parentSessionId,runId:a.runId,runIndex:a.runIndex,...a.agent?{agent:a.agent}:{}},readOnly:!0}}));return g&&(0,h.If)(c,y),[...r,...A]}async function q(){let a=globalThis.__piSessionListGeneration??0;if(globalThis.__piSessionListCache&&Date.now()-globalThis.__piSessionListCache.ts<I)return globalThis.__piSessionListCache.data;if(globalThis.__piSessionListPromise&&globalThis.__piSessionListPromiseGeneration===a)return globalThis.__piSessionListPromise;let b=p().then(b=>((globalThis.__piSessionListGeneration??0)===a&&(globalThis.__piSessionListCache={data:b,ts:Date.now()}),b)).finally(()=>{globalThis.__piSessionListPromise===b&&(globalThis.__piSessionListPromise=void 0,globalThis.__piSessionListPromiseGeneration=void 0)});return globalThis.__piSessionListPromise=b,globalThis.__piSessionListPromiseGeneration=a,b}m=(o.then?(await o)():o)[0];let I=3e4;function r(){globalThis.__piSessionListGeneration=(globalThis.__piSessionListGeneration??0)+1,globalThis.__piSessionListCache=void 0}function s(){return globalThis.__piSessionPathCache||(globalThis.__piSessionPathCache=new Map),globalThis.__piSessionPathCache}function t(){return globalThis.__piPathToSessionIdCache||(globalThis.__piPathToSessionIdCache=new Map),globalThis.__piPathToSessionIdCache}async function u(a){let b=s().get(a);if(b){if((0,e.existsSync)(b))return b;x(a)}await q();let c=s().get(a)??null;return c&&!(0,e.existsSync)(c)?(x(a),null):c}async function v(a){let b=(0,f.normalize)(a),c=t().get(b);return c||(await q(),t().get(b))}function w(a,b){let c=(0,f.normalize)(b),d=s(),e=t(),g=d.get(a),h=e.get(c);g&&g!==c&&e.get(g)===a&&e.delete(g),h&&h!==a&&d.get(h)===c&&d.delete(h),d.set(a,c),e.set(c,a)}function x(a){let b=s(),c=t(),d=b.get(a);b.delete(a),d&&c.get(d)===a&&c.delete(d)}function y(a){let b=(0,e.openSync)(a,"r");try{let a=[],c=0,d=!1;for(;c<65536&&!d;){let f=Buffer.allocUnsafe(Math.min(4096,65536-c)),g=(0,e.readSync)(b,f,0,f.length,c);if(0===g)break;let h=f.subarray(0,g),i=h.indexOf(10);a.push(-1===i?h:h.subarray(0,i)),c+=g,d=-1!==i}if(!d&&c>=65536)return null;let f=Buffer.concat(a).toString("utf8").trimEnd();if(!f)return null;try{let a=JSON.parse(f);return"session"===a.type?a:null}catch{return null}}finally{(0,e.closeSync)(b)}}function z(a){return(0,m.kW)(a).getEntries()}function A(a){let b=a.liveSession;return b?.isAlive()&&b.inner?.sessionManager?b.inner.sessionManager:(a.openFromDisk??(a=>{let b=(0,m.kW)(a);return{getEntries:()=>b.getEntries(),getLeafId:()=>b.getLeafId(),getTree:()=>b.getTree(),getHeader:()=>b.getHeader(),getSessionName:()=>b.getSessionName()}}))(a.filePath)}function B(a,b={}){let c=a.getEntries(),d=C(c,a.getLeafId()),e=function(a){let b=new Set,c=new Set(a),d=new Set,e=[...a];for(;e.length>0;){let a=e.pop();if(!d.has(a))for(let f of(d.add(a),(c.has(a)||1!==a.children.length||"string"==typeof a.label&&a.label.length>0)&&b.add(a),a.children))e.push(f)}let f=(a,b)=>({...a,children:[],...b?.length?{compressedEntryIds:b}:{}}),g=a.map(a=>f(a)),h=a.map((a,b)=>({source:a,projected:g[b],depth:1})),i=(a,c)=>{let d=[{node:a,compressedEntryIds:[]}],e=new Set;for(;d.length>0;){let{node:a,compressedEntryIds:g}=d.pop();if(!e.has(a)){e.add(a),b.has(a)&&c.children.push(f(a,g));for(let c=a.children.length-1;c>=0;c--)d.push({node:a.children[c],compressedEntryIds:b.has(a)?[]:[...g,a.entry.id]})}}};for(;h.length>0;){let{source:a,projected:c,depth:d}=h.pop();for(let e of a.children){let a=e;if(d>=200){i(a,c);continue}let g=[];for(;!b.has(a)&&1===a.children.length;)g.push(a.entry.id),a=a.children[0];if(!b.has(a))continue;let j=f(a,g);c.children.push(j),h.push({source:a,projected:j,depth:d+1})}}return g}(function(a){let b=[],c=[];for(let d=a.length-1;d>=0;d--)c.push({node:a[d],out:b});for(;c.length>0;){let{node:a,out:b}=c.pop();if("label"===a.entry.type){for(let d=a.children.length-1;d>=0;d--)c.push({node:a.children[d],out:b});continue}let d=[];for(let b=a.children.length-1;b>=0;b--)c.push({node:a.children[b],out:d});b.push({...a,children:d})}return b}(a.getTree())),f=E(c,d,b);return{entries:c,leafId:d,tree:e,context:f,header:a.getHeader(),sessionName:a.getSessionName()}}function C(a,b){if(null==b)return null;let c=new Map(a.map(a=>[a.id,a])),d=c.get(b);if(!d)return b;for(;d?.type==="label";){if(!d.parentId)return null;d=c.get(d.parentId)}return d?.id??null}function D(a,b){if(null===b)return[];let c=new Map,d=null;for(let b of a)b?.id&&(c.set(b.id,b),d=b.id);let e=void 0!==b?b:d,f=[],g=new Set;for(;e&&!g.has(e);){g.add(e);let a=c.get(e);if(!a)break;f.unshift(a),e=a.parentId??null}return f}function E(a,b,c={}){let d=D(a,b),e=function(a){let b,c,d;for(let e of a)if("thinking_level_change"===e.type&&"string"==typeof e.thinkingLevel&&(b=e.thinkingLevel),"model_change"===e.type&&e.provider&&e.modelId&&(c={provider:e.provider,modelId:e.modelId,id:e.modelId}),"message"===e.type){let a=e.message;a?.role==="assistant"&&"string"==typeof a.provider&&a.provider&&"string"==typeof a.model&&a.model&&(d={provider:a.provider,modelId:a.model,id:a.model})}return{thinkingLevel:b,model:c??d}}(d),f=D(a,b),h=[],l=[],m=new Map,o="off";for(let a of d)"thinking_level_change"===a.type&&"string"==typeof a.thinkingLevel&&(o=a.thinkingLevel),m.set(a.id,o);for(let a of f){let b=function(a,b){switch(a.type){case"message":{let c=(0,i.B)(a.message);if(b.deferToolResultImages&&(c=function(a){if("toolResult"!==a.role)return a;let b=0,c=0,d=new Set,e=a.content.filter(a=>{let e=function(a){let b,c;if(!G(a)||"image"!==a.type||("string"==typeof a.data?(b=a.data,c="string"==typeof a.mimeType?a.mimeType:void 0):G(a.source)&&"base64"===a.source.type&&"string"==typeof a.source.data&&(b=a.source.data,c="string"==typeof a.source.media_type?a.source.media_type:void 0),!b))return null;let d=b.endsWith("==")?2:+!!b.endsWith("=");return{bytes:Math.max(0,Math.floor(3*b.length/4)-d),mime:c}}(a);return!e||(b+=1,c+=e.bytes,e.mime&&d.add(e.mime),!1)});if(0===b)return a;let f=d.size>0?`: ${[...d].join(", ")}`:"";return e.push({type:"text",text:`[${b} tool result image${1===b?"":"s"} omitted from initial history payload${f}, ~${c} bytes]`}),{...a,content:e}}(c),c=function(a){if("toolResult"!==a.role||!G(a.details))return a;let b=!1,c={};for(let[d,e]of Object.entries(a.details))if(d!==K){if(J.has(d)){b=!0;continue}c[d]=e}return b?{...a,details:{...c,[K]:!0}}:a}(c)),!b.deferThinking||"assistant"!==c.role)return c;return{...c,content:c.content.map(a=>(0,n.mv)(a.type)&&""!==(0,n.Ux)(a).trim()?{...a,thinking:"",deferred:!0}:a)}}case"compaction":return{role:"custom",customType:"compaction",content:a.summary,display:!0,details:{tokensBefore:a.tokensBefore,firstKeptEntryId:a.firstKeptEntryId},timestamp:F(a.timestamp)};case"branch_summary":if(!a.summary)return null;let c=a.usage;return{role:"custom",customType:"branch_summary",content:a.summary,display:!0,details:{fromId:a.fromId,details:a.details,usage:c,fromHook:a.fromHook},timestamp:F(a.timestamp)};case"custom_message":return{role:"custom",customType:a.customType,content:a.content,display:a.display,details:a.details,timestamp:F(a.timestamp)};case"custom":{if(a.customType===k.uG){let b=(0,k.QT)(a.data);if(!b)return null;return(0,k.FH)(b,F(a.timestamp))}if(a.customType===g.OE){let b=(0,g.yz)(a.data);if(!b)return null;return{role:"custom",customType:g.OE,content:b.command,display:!0,details:{ok:b.ok,result:b.result},timestamp:F(a.timestamp)}}if(a.customType!==j.cP)return null;let b=(0,j.p_)(a.data);if(!b)return null;return(0,j.iv)(b,F(a.timestamp))}default:return null}}(a,c);if(b?.role==="custom"&&b.customType===k.uG){let a=(0,k.QT)(b.details),c=a?.messageEntryId?l.indexOf(a.messageEntryId):-1,d=c>=0?h[c]:void 0;if(a&&d?.role==="user"){h[c]={...d,binaryBlocks:[...d.binaryBlocks??[],a]};continue}}b&&(h.push("assistant"===b.role?{...b,thinkingLevel:m.get(a.id)??o}:b),l.push(a.id))}return{messages:c.deferToolResultImages?h.map(H):h,entryIds:l,thinkingLevel:e.thinkingLevel??"off",model:e.model??null}}function F(a){let b=Date.parse(a);return Number.isNaN(b)?void 0:b}function G(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function H(a){return"user"===a.role&&Array.isArray(a.content)&&a.binaryBlocks?.some(a=>"image"===a.kind)?{...a,content:a.content.filter(a=>"image"!==a.type)}:a}let J=new Set(["diff","patch","diffData","readSeekValue"]),K="deferredHeavy";d()}catch(a){d(a)}})},50593:(a,b,c)=>{"use strict";function d(a){try{return decodeURIComponent(a)}catch{return a}}function e(a){return a.replace(/\\/g,"/")}c.d(b,{Nw:()=>e,ex:()=>d})},50955:(a,b,c)=>{"use strict";c.d(b,{ku:()=>p,ob:()=>o,uq:()=>m});var d=c(29021),e=c(33873);let f=/^(?:[0-9a-f]{8}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i,g=/^run-(\d+)$/,h="forks",i=/^async-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function j(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function k(a,b){try{let c=(0,d.lstatSync)(a);if(!c.isFile()||c.isSymbolicLink()||!a.endsWith(".jsonl"))return null;let f=(0,d.realpathSync)(a),g=(0,d.realpathSync)(b),h=(0,e.relative)(g,f);if(!h||h.startsWith("..")||h.includes("/../")||h.includes("\\..\\"))return null;let i=g;for(let a of h.split(/[\\/]/))if(i=(0,e.join)(i,a),(0,d.lstatSync)(i).isSymbolicLink())return null;return f}catch{return null}}function l(a){let b=-1;try{b=(0,d.openSync)(a,"r");let c=[],e=0,f=!1;for(;e<65536&&!f;){let a=Buffer.allocUnsafe(Math.min(4096,65536-e)),g=(0,d.readSync)(b,a,0,a.length,e);if(!g)break;let h=a.subarray(0,g),i=h.indexOf(10);c.push(i>=0?h.subarray(0,i):h),e+=g,f=i>=0}if(!f&&e>=65536)return null;let g=Buffer.concat(c).toString("utf8").replace(/\r$/,""),h=JSON.parse(g);if(!j(h)||"session"!==h.type||"string"!=typeof h.id||!h.id||"string"!=typeof h.cwd||"string"!=typeof h.timestamp)return null;return h}catch{return null}finally{b>=0&&(0,d.closeSync)(b)}}function m(a,b,c){let f=0;for(let g of[...a].sort((a,b)=>b.path.length-a.path.length))try{if(!function(a,b,c){try{return k(a,b)===(0,d.realpathSync)(a)&&l(a)?.id===c}catch{return!1}}(g.path,b,g.header.id)){f++;continue}let a=(0,d.realpathSync)(g.path),h=(0,d.realpathSync)(b),i=(0,e.relative)(h,a);if(!i||i.startsWith("..")||i.includes("/../")||i.includes("\\..\\")){f++;continue}(0,d.unlinkSync)(g.path),c(g.header.id);let j=(0,e.dirname)(g.path);for(let a=0;a<4;a++){try{let a=(0,d.lstatSync)(j);if(!a.isDirectory()||a.isSymbolicLink())break;(0,d.rmdirSync)(j)}catch{break}j=(0,e.dirname)(j)}}catch{f++}return f}function n(a,b,c){let d;try{d=JSON.parse(a)}catch{return}if(!j(d)||"message"!==d.type||!j(d.message)||"toolResult"!==d.message.role||"subagent"!==d.message.toolName||!j(d.message.details)||!Array.isArray(d.message.details.results))return;let e=d.message.details,f=e.results,g="string"==typeof e.runId?e.runId:void 0;for(let a of f){if(!j(a))continue;let d="string"==typeof a.agent?a.agent:"string"==typeof e.agent?e.agent:void 0;g&&d&&c.set(g,d),"string"==typeof a.sessionFile&&b.push({path:a.sessionFile,runId:g,agent:d})}}function o(a,b){let c=a.endsWith(".jsonl")?a.slice(0,-6):"";if(!c)return[];let j=new Set,m=new Set,o=[],p=function(a){let b=[],c=new Map,e=-1;try{e=(0,d.openSync)(a,"r");let f="",g=0;for(;g<2097152&&b.length<512;){let a=Buffer.allocUnsafe(Math.min(65536,2097152-g)),h=(0,d.readSync)(e,a,0,a.length,g);if(!h)break;g+=h;let i=(f+=a.subarray(0,h).toString("utf8")).split(/\r?\n/);for(let a of(f=i.pop()??"",i))if(!(a.length>131072)&&(n(a,b,c),b.length>=512))break}f.length<=131072&&b.length<512&&n(f,b,c)}catch{}finally{e>=0&&(0,d.closeSync)(e)}return{candidates:b,agents:c}}(a);for(let n of[...p.candidates,...(function(a){let b=a.endsWith(".jsonl")?a.slice(0,-6):"",c=[];if(!b)return c;try{for(let a of(0,d.readdirSync)(b,{withFileTypes:!0})){if(!a.isDirectory()||a.isSymbolicLink()||!f.test(a.name))continue;let h=(0,e.join)(b,a.name);for(let a of(0,d.readdirSync)(h,{withFileTypes:!0}))if(!(!a.isDirectory()||a.isSymbolicLink())&&g.test(a.name)&&(c.push((0,e.join)(h,a.name,"session.jsonl")),c.length>=2048))return c}for(let a of(0,d.readdirSync)(b,{withFileTypes:!0})){if(!a.isDirectory()||a.isSymbolicLink()||!i.test(a.name)&&a.name!==h)continue;let f=(0,e.join)(b,a.name);for(let a of(0,d.readdirSync)(f,{withFileTypes:!0}).filter(a=>a.isFile()&&!a.isSymbolicLink()&&a.name.endsWith(".jsonl")).map(a=>a.name).sort())if(c.push((0,e.join)(f,a)),c.length>=2048)return c}}catch{}return c})(a).map(a=>({path:a}))]){if(o.length>=256)break;let a=k((0,e.resolve)(n.path),c);if(!a||!function(a,b){let c=(0,e.relative)((0,e.resolve)(b),(0,e.resolve)(a)).split(/[\\/]/);return!!(3===c.length&&f.test(c[0])&&g.test(c[1])&&"session.jsonl"===c[2]||2===c.length&&i.test(c[0])&&c[1].endsWith(".jsonl"))||2===c.length&&c[0]===h&&c[1].endsWith(".jsonl")}(a,c)||j.has(a))continue;let d=(0,e.relative)((0,e.resolve)(c),(0,e.resolve)(a)).split(/[\\/]/),q=2===d.length&&i.test(d[0]),r=2===d.length&&d[0]===h,s=2===d.length&&(i.test(d[0])||d[0]===h)?0:function(a){let b=g.exec((0,e.basename)((0,e.dirname)(a)));return b?Number(b[1]):null}(a);if(null===s||s<0)continue;let t=l(a);if(!t||m.has(t.id)||t.id===b)continue;let u=q?d[0].slice(6):r?n.runId??(0,e.basename)(a).replace(/\.jsonl$/,""):n.runId??(0,e.basename)((0,e.dirname)((0,e.dirname)(a)));j.add(a),m.add(t.id),o.push({path:a,header:t,runIndex:s,parentSessionId:b,runId:u,agent:n.agent??p.agents.get(u)})}return o}function p(a,b){let c=[],d=new Set([(0,e.resolve)(a)]),f=new Set([b]),g=[{file:a,id:b,depth:0}];for(;g.length&&c.length<256;){let a=g.shift();if(!(a.depth>=16))for(let b of o(a.file,a.id))d.has(b.path)||f.has(b.header.id)||(d.add(b.path),f.add(b.header.id),c.push(b),g.push({file:b.path,id:b.header.id,depth:a.depth+1}))}return c}},60396:(a,b,c)=>{"use strict";c.d(b,{$M:()=>f,CZ:()=>h,Mc:()=>g,pA:()=>i});var d=c(62228),e=c(86697);function f(a=process.env){let b=a.PI_CODING_AGENT_DIR?.trim();if(b)return"~"===b?(0,d.homedir)():b.startsWith("~/")||b.startsWith("~\\")?(0,e.join)((0,d.homedir)(),b.slice(2)):b;return(0,e.join)((0,d.homedir)(),".pi","agent")}function g(a=process.env){return(0,e.join)(f(a),"models.json")}function h(a=process.env){return(0,e.join)(f(a),"auth.json")}function i(a=process.env){return(0,e.join)(f(a),"settings.json")}},65107:(a,b,c)=>{"use strict";c.d(b,{$9:()=>j,R3:()=>i,ek:()=>h});var d=c(89477),e=c(86697),f=c(716);function g(a){return`${a}.leaf.json`}function h(a){let b=g(a);if(!(0,d.existsSync)(b))return null;try{let a=JSON.parse((0,d.readFileSync)(b,"utf8"));if(!a||"object"!=typeof a)return null;let c=a.leafId;return"string"==typeof c&&c?c:null}catch{return null}}function i(a,b){let c=g(a),h=(0,e.dirname)(c);(0,d.existsSync)(h)||(0,d.mkdirSync)(h,{recursive:!0});let i=JSON.stringify({version:1,leafId:b},null,2),j=(0,e.join)(h,`.leaf-${process.pid}-${(0,f.randomUUID)()}.tmp`);try{(0,d.writeFileSync)(j,i,{encoding:"utf8",flag:"wx"}),(0,d.renameSync)(j,c)}catch(a){try{(0,d.existsSync)(j)&&(0,d.unlinkSync)(j)}catch{}throw a}}function j(a){try{let b=g(a);(0,d.existsSync)(b)&&(0,d.unlinkSync)(b)}catch{}}},78335:()=>{},85664:(a,b,c)=>{"use strict";c.d(b,{cP:()=>d,iv:()=>l,l$:()=>j,o7:()=>m,p_:()=>k,qF:()=>n});let d="pidance.activity",e=["result","warning","error","output"];class f extends Error{constructor(a){super(a),this.name="SessionActivityError"}}function g(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function h(a){return Buffer.byteLength(a,"utf8")}function i(a,b,c){if(void 0===a)return;if("string"!=typeof a)throw new f(`${b} must be a string`);let d=a.trim();if(""!==d){if(d.length>c)throw new f(`${b} exceeds maximum length ${c}`);return d}}function j(a){var b;let c,d;if(!g(a))throw new f("activity must be a plain object");let j=void 0===a.version?1:a.version;if(1!==j)throw new f(`unsupported activity version: ${String(j)}`);if(!("string"==typeof(b=a.kind)&&e.includes(b)))throw new f(`kind must be one of: ${e.join(", ")}`);if("string"!=typeof a.title)throw new f("title must be a string");let k=a.title.trim();if(""===k)throw new f("title is required");if(k.length>200)throw new f("title exceeds maximum length 200");if("string"!=typeof a.content)throw new f("content must be a string");let l=a.content.trim();if(l.length>32768)throw new f("content exceeds maximum length 32768");let m=i(a.source,"source",200),n=i(a.requestId,"requestId",200);if(void 0!==a.metadata){if(!g(a.metadata))throw new f("metadata must be a plain object");let b=function a(b,c,d){if(null===b)return null;if("string"==typeof b){if(h(b)>1024)throw new f("metadata string exceeds 1024 bytes");return b}if("number"==typeof b){if(!Number.isFinite(b))throw new f("metadata number must be finite");return b}if("boolean"==typeof b)return b;if("bigint"==typeof b||"function"==typeof b||"symbol"==typeof b||void 0===b||"object"!=typeof b)throw new f("metadata contains non-JSON value");if(d.has(b))throw new f("metadata contains circular reference");if(c>3)throw new f("metadata exceeds max depth 3");if(Array.isArray(b)){if(b.length>32)throw new f("metadata array exceeds 32 items");d.add(b);try{return b.map(b=>a(b,c+1,d))}finally{d.delete(b)}}let e=Object.getPrototypeOf(b);if(e!==Object.prototype&&null!==e)throw new f("metadata must be a plain JSON object or array");let g=Object.keys(b);if(g.length>20)throw new f("metadata exceeds 20 keys");d.add(b);try{let e=Object.create(null);for(let i of g){if("__proto__"===i||"constructor"===i||"prototype"===i)throw new f("metadata key is not allowed");if(h(i)>64)throw new f("metadata key exceeds 64 bytes");e[i]=a(b[i],c+1,d)}return e}finally{d.delete(b)}}(a.metadata,0,new WeakSet);if(!g(b)||Array.isArray(b))throw new f("metadata must be a plain object");0===Object.keys(c=b).length&&(c=void 0)}let o={version:1,kind:a.kind,title:k,content:l};void 0!==m&&(o.source=m),void 0!==n&&(o.requestId=n),void 0!==c&&(o.metadata=c);try{d=JSON.stringify(o)}catch{throw new f("activity is not JSON-serializable")}if(h(d)>48e3)throw new f("activity exceeds maximum serialized size 48000 bytes");return o}function k(a){try{return j(a)}catch{return null}}function l(a,b){let c={role:"custom",customType:d,content:a.title,display:!0,details:a};return void 0!==b&&(c.timestamp=b),c}function m(a){return"custom"===a.type&&a.customType===d&&null!==k(a.data)}function n(a){if("customType"in a&&void 0!==a.customType)throw new f("customType is not allowed on append_activity");let b=a.activity;if(void 0!==b){if(!g(b))throw new f("activity must be a plain object");if("customType"in b&&void 0!==b.customType)throw new f("customType is not allowed on append_activity");return j(b)}let c={...a};return delete c.type,j(c)}},95237:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{G1:()=>k,Qu:()=>l,i5:()=>n,iR:()=>e.CURRENT_SESSION_VERSION,kW:()=>m,kb:()=>j});var e=c(75430),f=c(89477),g=c(65107),h=a([e]);function i(a){let b="function"!=typeof a._rewriteFile?null:{rewriteFile:()=>a._rewriteFile.call(a),markFlushed:()=>{a.flushed=!0}};if(!b)throw Error("Pi SDK 未提供会话文件写入入口(_rewriteFile / flushed)。请检查 @earendil-works/pi-coding-agent 版本(当前基线 0.85.1)与 pi-session-io 适配层。");return b}function j(a){let b=a.getSessionFile();if(!b)return;let c=i(a);(0,f.existsSync)(b)||c.rewriteFile(),(0,f.existsSync)(b)&&c.markFlushed()}function k(a,b){let c=e.SessionManager.open(a,b),d=(0,g.ek)(a);if(d&&c.getEntry(d)){if(c.getLeafId()!==d)try{c.branch(d)}catch{(0,g.$9)(a)}}else d&&(0,g.$9)(a);return c}function l(a,b){return e.SessionManager.create(a,b)}function m(a,b){var c;return c=k(a,b),{getEntries:()=>c.getEntries(),getLeafId:()=>c.getLeafId(),getTree:()=>c.getTree(),getHeader:()=>c.getHeader(),getSessionName:()=>c.getSessionName(),getSessionId:()=>c.getSessionId(),getSessionFile:()=>c.getSessionFile(),getCwd:()=>c.getCwd(),getEntry:a=>c.getEntry(a),getBranch:a=>void 0===a?c.getBranch():c.getBranch(a),buildSessionContext:()=>c.buildSessionContext(),appendSessionInfo:a=>c.appendSessionInfo(a),appendCustomEntry:(a,b)=>c.appendCustomEntry(a,b),appendModelChange:(a,b)=>c.appendModelChange(a,b),branch:a=>c.branch(a),createBranchedSession:a=>c.createBranchedSession(a),getSessionDir:()=>c.getSessionDir(),getLastEntryId:()=>(function(a){let b=a.getEntries();for(let a=b.length-1;a>=0;a--){let c=b[a];if(c&&"object"==typeof c&&"id"in c&&"string"==typeof c.id)return c.id}return null})(c)}}function n(a,b){let c=k(a),d=c.getHeader();if(!d||"session"!==d.type)return;b?d.parentSession=b:delete d.parentSession;let e=i(c);e.rewriteFile(),(0,f.existsSync)(a)&&e.markFlushed()}e=(h.then?(await h)():h)[0],d()}catch(a){d(a)}})},96487:()=>{}};
@@ -1,4 +1,4 @@
1
- "use strict";exports.id=6192,exports.ids=[6192],exports.modules={1060:(a,b,c)=>{c.d(b,{Ac:()=>n,GO:()=>i,X:()=>k,_4:()=>d,cV:()=>j,k2:()=>l,oC:()=>m});let d=262144,e={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},f={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},g={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},h={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function i(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function j(a){return e[i(a)]??null}function k(a){return f[i(a)]??null}function l(a){return g[i(a)]??null}function m(a){return h[i(a)]??null}function n(a){let b=i(a);return"pdf"===b||"docx"===b?b:null}},59216:(a,b,c)=>{c.d(b,{SQ:()=>A,$G:()=>w});var d=c(79646),e=c(29021),f=c.n(e),g=c(33873),h=c.n(g),i=c(28354),j=c(1060);let k=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function l(a){let b=`${a.indexStatus}${a.worktreeStatus}`;return"??"===b?{status:"untracked",code:"U"}:k.has(b)||b.includes("U")?{status:"conflict",code:"C"}:b.includes("D")?{status:"deleted",code:"D"}:b.includes("R")||b.includes("C")?{status:"renamed",code:"R"}:b.includes("A")?{status:"added",code:"A"}:{status:"modified",code:"M"}}function m(a,b){return`${a}\u0000${b}`}let n=(0,i.promisify)(d.execFile),o=new Map,p=new Map;function q(a,b){o.delete(m(a,b))}async function r(a,b,c=8388608){let{stdout:d}=await n("git",["-C",a,...b],{timeout:1e4,maxBuffer:c,env:{...process.env,LC_ALL:"C"}});return d}async function s(a){try{return(await r(a,["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}async function t(a){try{let[b,c]=(await r(a,["rev-parse","--show-toplevel","HEAD"])).trim().split("\n");if(!b)return null;return{repositoryRoot:b,head:c?.trim()||null}}catch{try{let b=(await r(a,["rev-parse","--show-toplevel"])).trim();return b?{repositoryRoot:b,head:null}:null}catch{return null}}}function u(a,b){let c=h().relative(h().resolve(a),h().resolve(b));return""===c||!c.startsWith(`..${h().sep}`)&&".."!==c&&!h().isAbsolute(c)}async function v(a){return function(a){let b=a.split("\0"),c=[];for(let a=0;a<b.length;a++){let d=b[a];if(!d||d.length<4||" "!==d[2])continue;let e=d[0],f=d[1],g={path:d.slice(3),indexStatus:e,worktreeStatus:f};("R"===e||"C"===e||"R"===f||"C"===f)&&(g.originalPath=b[++a]||void 0),c.push(g)}return c}(await r(a,["status","--porcelain=v1","-z","--untracked-files=all"]))}async function w(a){let b=Date.now(),c=p.get(a);if(c&&b-c.fetchedAt<800)return c.response;let d=await x(a);return p.set(a,{fetchedAt:b,response:d}),d}async function x(a){let b=await s(a);if(!b)return{isGitRepository:!1,repositoryRoot:null,files:[]};let c=(await v(b)).flatMap(c=>{let d=h().resolve(b,c.path);return u(a,d)?[{filePath:d,...l(c),indexStatus:c.indexStatus,worktreeStatus:c.worktreeStatus}]:[]});return{isGitRepository:!0,repositoryRoot:b,files:c}}function y(a,b){let c=b.endsWith("\n"),d=b.split("\n");c&&d.pop();let e=d.map(a=>`+${a}`).join("\n"),f=!c&&d.length>0?"\n\":"";return`diff --git a/${a} b/${a}
1
+ "use strict";exports.id=6192,exports.ids=[6192],exports.modules={1060:(a,b,c)=>{c.d(b,{Ac:()=>n,GO:()=>i,X:()=>k,_4:()=>d,cV:()=>j,k2:()=>l,oC:()=>m});let d=262144,e={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},f={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},g={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},h={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function i(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function j(a){return e[i(a)]??null}function k(a){return f[i(a)]??null}function l(a){return g[i(a)]??null}function m(a){return h[i(a)]??null}function n(a){let b=i(a);return"pdf"===b||"docx"===b?b:null}},25252:(a,b,c)=>{c.d(b,{HM:()=>e,wz:()=>f});var d=c(50593);function e(){return globalThis.__piAdditionalAllowedRoots||(globalThis.__piAdditionalAllowedRoots=new Set),globalThis.__piAdditionalAllowedRoots}function f(a){if(!a)return;let b=(0,d.Nw)(a);e().add(b),globalThis.__piAllowedRootsCache?.roots.add(b)}},59216:(a,b,c)=>{c.d(b,{SQ:()=>A,$G:()=>w});var d=c(79646),e=c(29021),f=c.n(e),g=c(33873),h=c.n(g),i=c(28354),j=c(1060);let k=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function l(a){let b=`${a.indexStatus}${a.worktreeStatus}`;return"??"===b?{status:"untracked",code:"U"}:k.has(b)||b.includes("U")?{status:"conflict",code:"C"}:b.includes("D")?{status:"deleted",code:"D"}:b.includes("R")||b.includes("C")?{status:"renamed",code:"R"}:b.includes("A")?{status:"added",code:"A"}:{status:"modified",code:"M"}}function m(a,b){return`${a}\u0000${b}`}let n=(0,i.promisify)(d.execFile),o=new Map,p=new Map;function q(a,b){o.delete(m(a,b))}async function r(a,b,c=8388608){let{stdout:d}=await n("git",["-C",a,...b],{timeout:1e4,maxBuffer:c,env:{...process.env,LC_ALL:"C"}});return d}async function s(a){try{return(await r(a,["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}async function t(a){try{let[b,c]=(await r(a,["rev-parse","--show-toplevel","HEAD"])).trim().split("\n");if(!b)return null;return{repositoryRoot:b,head:c?.trim()||null}}catch{try{let b=(await r(a,["rev-parse","--show-toplevel"])).trim();return b?{repositoryRoot:b,head:null}:null}catch{return null}}}function u(a,b){let c=h().relative(h().resolve(a),h().resolve(b));return""===c||!c.startsWith(`..${h().sep}`)&&".."!==c&&!h().isAbsolute(c)}async function v(a){return function(a){let b=a.split("\0"),c=[];for(let a=0;a<b.length;a++){let d=b[a];if(!d||d.length<4||" "!==d[2])continue;let e=d[0],f=d[1],g={path:d.slice(3),indexStatus:e,worktreeStatus:f};("R"===e||"C"===e||"R"===f||"C"===f)&&(g.originalPath=b[++a]||void 0),c.push(g)}return c}(await r(a,["status","--porcelain=v1","-z","--untracked-files=all"]))}async function w(a){let b=Date.now(),c=p.get(a);if(c&&b-c.fetchedAt<800)return c.response;let d=await x(a);return p.set(a,{fetchedAt:b,response:d}),d}async function x(a){let b=await s(a);if(!b)return{isGitRepository:!1,repositoryRoot:null,files:[]};let c=(await v(b)).flatMap(c=>{let d=h().resolve(b,c.path);return u(a,d)?[{filePath:d,...l(c),indexStatus:c.indexStatus,worktreeStatus:c.worktreeStatus}]:[]});return{isGitRepository:!0,repositoryRoot:b,files:c}}function y(a,b){let c=b.endsWith("\n"),d=b.split("\n");c&&d.pop();let e=d.map(a=>`+${a}`).join("\n"),f=!c&&d.length>0?"\n\":"";return`diff --git a/${a} b/${a}
2
2
  new file mode 100644
3
3
  --- /dev/null
4
4
  +++ b/${a}