@henlii/pidance 0.2.31 → 0.2.33

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 (257) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +17 -16
  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 +6 -0
  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 +2 -2
  21. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  22. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  23. package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  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 +1 -1
  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 +1 -1
  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 +1 -1
  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 -0
  47. package/.next/server/app/api/cwd/create/route_client-reference-manifest.js +1 -0
  48. package/.next/server/app/api/cwd/validate/route.js +1 -1
  49. package/.next/server/app/api/default-cwd/route.js +1 -1
  50. package/.next/server/app/api/file-index/route.js +1 -1
  51. package/.next/server/app/api/files/[...path]/route.js +1 -1
  52. package/.next/server/app/api/git/diff/route.js +1 -1
  53. package/.next/server/app/api/git/status/route.js +1 -1
  54. package/.next/server/app/api/home/route.js +1 -1
  55. package/.next/server/app/api/message-media/route.js +1 -1
  56. package/.next/server/app/api/models/route.js +1 -1
  57. package/.next/server/app/api/models-config/raw/route.js +1 -1
  58. package/.next/server/app/api/models-config/route.js +1 -1
  59. package/.next/server/app/api/models-config/test/route.js +1 -1
  60. package/.next/server/app/api/plugins/route.js +1 -1
  61. package/.next/server/app/api/plugins/search/route.js +1 -1
  62. package/.next/server/app/api/plugins/updates/route.js +1 -1
  63. package/.next/server/app/api/preferences/route.js +1 -1
  64. package/.next/server/app/api/project-assets/route.js +2 -2
  65. package/.next/server/app/api/prompts/route.js +1 -1
  66. package/.next/server/app/api/pty/route.js +2 -2
  67. package/.next/server/app/api/sessions/[id]/archive/route.js +1 -1
  68. package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
  69. package/.next/server/app/api/sessions/[id]/command-entry/route.js +1 -1
  70. package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
  71. package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
  72. package/.next/server/app/api/sessions/[id]/export/route.js +1 -1
  73. package/.next/server/app/api/sessions/[id]/info/route.js +1 -1
  74. package/.next/server/app/api/sessions/[id]/outline/route.js +1 -1
  75. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  76. package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
  77. package/.next/server/app/api/sessions/[id]/tool-results/[toolCallId]/route.js +1 -1
  78. package/.next/server/app/api/sessions/route.js +1 -1
  79. package/.next/server/app/api/sessions/search/route.js +1 -1
  80. package/.next/server/app/api/settings/raw/route.js +2 -2
  81. package/.next/server/app/api/settings/remote/route.js +1 -1
  82. package/.next/server/app/api/skills/check/route.js +1 -1
  83. package/.next/server/app/api/skills/install/route.js +1 -1
  84. package/.next/server/app/api/skills/route.js +1 -1
  85. package/.next/server/app/api/skills/search/route.js +1 -1
  86. package/.next/server/app/api/skills/update/route.js +1 -1
  87. package/.next/server/app/api/subagent-runs/route.js +1 -1
  88. package/.next/server/app/api/update/apply/route.js +2 -2
  89. package/.next/server/app/api/update/check/route.js +1 -1
  90. package/.next/server/app/api/worktrees/route.js +1 -1
  91. package/.next/server/app/icon.png/route.js +1 -1
  92. package/.next/server/app/index.html +1 -1
  93. package/.next/server/app/index.rsc +4 -4
  94. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  95. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  96. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  97. package/.next/server/app/index.segments/_index.segment.rsc +2 -2
  98. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  99. package/.next/server/app/page.js +15 -15
  100. package/.next/server/app/page_client-reference-manifest.js +1 -1
  101. package/.next/server/app-paths-manifest.json +17 -16
  102. package/.next/server/chunks/188.js +1 -1
  103. package/.next/server/chunks/329.js +1 -1
  104. package/.next/server/chunks/3379.js +1 -1
  105. package/.next/server/chunks/4127.js +1 -0
  106. package/.next/server/chunks/5253.js +1 -0
  107. package/.next/server/chunks/5274.js +1 -1
  108. package/.next/server/chunks/5304.js +1 -1
  109. package/.next/server/chunks/5582.js +1 -1
  110. package/.next/server/chunks/7594.js +1 -1
  111. package/.next/server/chunks/9935.js +1 -1
  112. package/.next/server/instrumentation.js +1 -1
  113. package/.next/server/middleware-build-manifest.js +1 -1
  114. package/.next/server/pages/404.html +1 -1
  115. package/.next/server/pages/500.html +1 -1
  116. package/.next/server/server-reference-manifest.json +1 -1
  117. package/.next/static/0jTCyAHZ1cMAQtbthkA6a/_buildManifest.js +1 -0
  118. package/.next/static/chunks/9780-b283d1d0384d11b4.js +1 -0
  119. package/.next/static/chunks/app/{api/agent/[id]/bash-output/route-3154b10ff0f29211.js → _global-error/page-fb11d0d31328bf72.js} +1 -1
  120. package/.next/static/chunks/app/{_global-error/page-3154b10ff0f29211.js → api/about/route-fb11d0d31328bf72.js} +1 -1
  121. package/.next/static/chunks/app/api/{agent-settings/route-3154b10ff0f29211.js → agent/[id]/bash-output/route-fb11d0d31328bf72.js} +1 -1
  122. package/.next/static/chunks/app/api/agent/[id]/events/route-fb11d0d31328bf72.js +1 -0
  123. package/.next/static/chunks/app/api/agent/[id]/route-fb11d0d31328bf72.js +1 -0
  124. package/.next/static/chunks/app/api/agent/new/route-fb11d0d31328bf72.js +1 -0
  125. package/.next/static/chunks/app/api/agent/running/events/route-fb11d0d31328bf72.js +1 -0
  126. package/.next/static/chunks/app/api/agent/running/route-fb11d0d31328bf72.js +1 -0
  127. package/.next/static/chunks/app/api/agent/submissions/[submissionId]/route-fb11d0d31328bf72.js +1 -0
  128. package/.next/static/chunks/app/api/{about/route-3154b10ff0f29211.js → agent-settings/route-fb11d0d31328bf72.js} +1 -1
  129. package/.next/static/chunks/app/api/attachments/route-fb11d0d31328bf72.js +1 -0
  130. package/.next/static/chunks/app/api/auth/all-providers/route-fb11d0d31328bf72.js +1 -0
  131. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-fb11d0d31328bf72.js +1 -0
  132. package/.next/static/chunks/app/api/auth/login/[provider]/route-fb11d0d31328bf72.js +1 -0
  133. package/.next/static/chunks/app/api/auth/logout/[provider]/route-fb11d0d31328bf72.js +1 -0
  134. package/.next/static/chunks/app/api/auth/providers/route-fb11d0d31328bf72.js +1 -0
  135. package/.next/static/chunks/app/api/auth/ui-session/route-fb11d0d31328bf72.js +1 -0
  136. package/.next/static/chunks/app/api/auth/ui-sessions/[id]/route-fb11d0d31328bf72.js +1 -0
  137. package/.next/static/chunks/app/api/auth/ui-sessions/route-fb11d0d31328bf72.js +1 -0
  138. package/.next/static/chunks/app/api/cwd/browse/route-fb11d0d31328bf72.js +1 -0
  139. package/.next/static/chunks/app/api/cwd/create/route-fb11d0d31328bf72.js +1 -0
  140. package/.next/static/chunks/app/api/cwd/validate/route-fb11d0d31328bf72.js +1 -0
  141. package/.next/static/chunks/app/api/default-cwd/route-fb11d0d31328bf72.js +1 -0
  142. package/.next/static/chunks/app/api/file-index/route-fb11d0d31328bf72.js +1 -0
  143. package/.next/static/chunks/app/api/files/[...path]/route-fb11d0d31328bf72.js +1 -0
  144. package/.next/static/chunks/app/api/git/diff/route-fb11d0d31328bf72.js +1 -0
  145. package/.next/static/chunks/app/api/git/status/route-fb11d0d31328bf72.js +1 -0
  146. package/.next/static/chunks/app/api/home/route-fb11d0d31328bf72.js +1 -0
  147. package/.next/static/chunks/app/api/message-media/route-fb11d0d31328bf72.js +1 -0
  148. package/.next/static/chunks/app/api/models/route-fb11d0d31328bf72.js +1 -0
  149. package/.next/static/chunks/app/api/models-config/raw/route-fb11d0d31328bf72.js +1 -0
  150. package/.next/static/chunks/app/api/models-config/route-fb11d0d31328bf72.js +1 -0
  151. package/.next/static/chunks/app/api/models-config/test/route-fb11d0d31328bf72.js +1 -0
  152. package/.next/static/chunks/app/api/plugins/route-fb11d0d31328bf72.js +1 -0
  153. package/.next/static/chunks/app/api/plugins/search/route-fb11d0d31328bf72.js +1 -0
  154. package/.next/static/chunks/app/api/plugins/updates/route-fb11d0d31328bf72.js +1 -0
  155. package/.next/static/chunks/app/api/preferences/route-fb11d0d31328bf72.js +1 -0
  156. package/.next/static/chunks/app/api/project-assets/route-fb11d0d31328bf72.js +1 -0
  157. package/.next/static/chunks/app/api/prompts/route-fb11d0d31328bf72.js +1 -0
  158. package/.next/static/chunks/app/api/pty/route-fb11d0d31328bf72.js +1 -0
  159. package/.next/static/chunks/app/api/sessions/[id]/archive/route-fb11d0d31328bf72.js +1 -0
  160. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-fb11d0d31328bf72.js +1 -0
  161. package/.next/static/chunks/app/api/sessions/[id]/command-entry/route-fb11d0d31328bf72.js +1 -0
  162. package/.next/static/chunks/app/api/sessions/[id]/context/route-fb11d0d31328bf72.js +1 -0
  163. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-fb11d0d31328bf72.js +1 -0
  164. package/.next/static/chunks/app/api/sessions/[id]/export/route-fb11d0d31328bf72.js +1 -0
  165. package/.next/static/chunks/app/api/sessions/[id]/info/route-fb11d0d31328bf72.js +1 -0
  166. package/.next/static/chunks/app/api/sessions/[id]/outline/route-fb11d0d31328bf72.js +1 -0
  167. package/.next/static/chunks/app/api/sessions/[id]/route-fb11d0d31328bf72.js +1 -0
  168. package/.next/static/chunks/app/api/sessions/[id]/state/route-fb11d0d31328bf72.js +1 -0
  169. package/.next/static/chunks/app/api/sessions/[id]/tool-results/[toolCallId]/route-fb11d0d31328bf72.js +1 -0
  170. package/.next/static/chunks/app/api/sessions/route-fb11d0d31328bf72.js +1 -0
  171. package/.next/static/chunks/app/api/sessions/search/route-fb11d0d31328bf72.js +1 -0
  172. package/.next/static/chunks/app/api/settings/raw/route-fb11d0d31328bf72.js +1 -0
  173. package/.next/static/chunks/app/api/settings/remote/route-fb11d0d31328bf72.js +1 -0
  174. package/.next/static/chunks/app/api/skills/check/route-fb11d0d31328bf72.js +1 -0
  175. package/.next/static/chunks/app/api/skills/install/route-fb11d0d31328bf72.js +1 -0
  176. package/.next/static/chunks/app/api/skills/route-fb11d0d31328bf72.js +1 -0
  177. package/.next/static/chunks/app/api/skills/search/route-fb11d0d31328bf72.js +1 -0
  178. package/.next/static/chunks/app/api/skills/update/route-fb11d0d31328bf72.js +1 -0
  179. package/.next/static/chunks/app/api/subagent-runs/route-fb11d0d31328bf72.js +1 -0
  180. package/.next/static/chunks/app/api/update/apply/route-fb11d0d31328bf72.js +1 -0
  181. package/.next/static/chunks/app/api/update/check/route-fb11d0d31328bf72.js +1 -0
  182. package/.next/static/chunks/app/api/worktrees/route-fb11d0d31328bf72.js +1 -0
  183. package/.next/static/chunks/app/page-f29f2997141a81c4.js +25 -0
  184. package/.next/static/chunks/next/dist/client/components/builtin/app-error-fb11d0d31328bf72.js +1 -0
  185. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-fb11d0d31328bf72.js +1 -0
  186. package/.next/static/chunks/next/dist/client/components/builtin/not-found-fb11d0d31328bf72.js +1 -0
  187. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-fb11d0d31328bf72.js +1 -0
  188. package/README.en.md +1 -1
  189. package/README.md +1 -1
  190. package/package.json +1 -2
  191. package/.next/static/chunks/9780-f8d2d505d4ce420b.js +0 -1
  192. package/.next/static/chunks/app/api/agent/[id]/events/route-3154b10ff0f29211.js +0 -1
  193. package/.next/static/chunks/app/api/agent/[id]/route-3154b10ff0f29211.js +0 -1
  194. package/.next/static/chunks/app/api/agent/new/route-3154b10ff0f29211.js +0 -1
  195. package/.next/static/chunks/app/api/agent/running/events/route-3154b10ff0f29211.js +0 -1
  196. package/.next/static/chunks/app/api/agent/running/route-3154b10ff0f29211.js +0 -1
  197. package/.next/static/chunks/app/api/agent/submissions/[submissionId]/route-3154b10ff0f29211.js +0 -1
  198. package/.next/static/chunks/app/api/attachments/route-3154b10ff0f29211.js +0 -1
  199. package/.next/static/chunks/app/api/auth/all-providers/route-3154b10ff0f29211.js +0 -1
  200. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-3154b10ff0f29211.js +0 -1
  201. package/.next/static/chunks/app/api/auth/login/[provider]/route-3154b10ff0f29211.js +0 -1
  202. package/.next/static/chunks/app/api/auth/logout/[provider]/route-3154b10ff0f29211.js +0 -1
  203. package/.next/static/chunks/app/api/auth/providers/route-3154b10ff0f29211.js +0 -1
  204. package/.next/static/chunks/app/api/auth/ui-session/route-3154b10ff0f29211.js +0 -1
  205. package/.next/static/chunks/app/api/auth/ui-sessions/[id]/route-3154b10ff0f29211.js +0 -1
  206. package/.next/static/chunks/app/api/auth/ui-sessions/route-3154b10ff0f29211.js +0 -1
  207. package/.next/static/chunks/app/api/cwd/browse/route-3154b10ff0f29211.js +0 -1
  208. package/.next/static/chunks/app/api/cwd/validate/route-3154b10ff0f29211.js +0 -1
  209. package/.next/static/chunks/app/api/default-cwd/route-3154b10ff0f29211.js +0 -1
  210. package/.next/static/chunks/app/api/file-index/route-3154b10ff0f29211.js +0 -1
  211. package/.next/static/chunks/app/api/files/[...path]/route-3154b10ff0f29211.js +0 -1
  212. package/.next/static/chunks/app/api/git/diff/route-3154b10ff0f29211.js +0 -1
  213. package/.next/static/chunks/app/api/git/status/route-3154b10ff0f29211.js +0 -1
  214. package/.next/static/chunks/app/api/home/route-3154b10ff0f29211.js +0 -1
  215. package/.next/static/chunks/app/api/message-media/route-3154b10ff0f29211.js +0 -1
  216. package/.next/static/chunks/app/api/models/route-3154b10ff0f29211.js +0 -1
  217. package/.next/static/chunks/app/api/models-config/raw/route-3154b10ff0f29211.js +0 -1
  218. package/.next/static/chunks/app/api/models-config/route-3154b10ff0f29211.js +0 -1
  219. package/.next/static/chunks/app/api/models-config/test/route-3154b10ff0f29211.js +0 -1
  220. package/.next/static/chunks/app/api/plugins/route-3154b10ff0f29211.js +0 -1
  221. package/.next/static/chunks/app/api/plugins/search/route-3154b10ff0f29211.js +0 -1
  222. package/.next/static/chunks/app/api/plugins/updates/route-3154b10ff0f29211.js +0 -1
  223. package/.next/static/chunks/app/api/preferences/route-3154b10ff0f29211.js +0 -1
  224. package/.next/static/chunks/app/api/project-assets/route-3154b10ff0f29211.js +0 -1
  225. package/.next/static/chunks/app/api/prompts/route-3154b10ff0f29211.js +0 -1
  226. package/.next/static/chunks/app/api/pty/route-3154b10ff0f29211.js +0 -1
  227. package/.next/static/chunks/app/api/sessions/[id]/archive/route-3154b10ff0f29211.js +0 -1
  228. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-3154b10ff0f29211.js +0 -1
  229. package/.next/static/chunks/app/api/sessions/[id]/command-entry/route-3154b10ff0f29211.js +0 -1
  230. package/.next/static/chunks/app/api/sessions/[id]/context/route-3154b10ff0f29211.js +0 -1
  231. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-3154b10ff0f29211.js +0 -1
  232. package/.next/static/chunks/app/api/sessions/[id]/export/route-3154b10ff0f29211.js +0 -1
  233. package/.next/static/chunks/app/api/sessions/[id]/info/route-3154b10ff0f29211.js +0 -1
  234. package/.next/static/chunks/app/api/sessions/[id]/outline/route-3154b10ff0f29211.js +0 -1
  235. package/.next/static/chunks/app/api/sessions/[id]/route-3154b10ff0f29211.js +0 -1
  236. package/.next/static/chunks/app/api/sessions/[id]/state/route-3154b10ff0f29211.js +0 -1
  237. package/.next/static/chunks/app/api/sessions/[id]/tool-results/[toolCallId]/route-3154b10ff0f29211.js +0 -1
  238. package/.next/static/chunks/app/api/sessions/route-3154b10ff0f29211.js +0 -1
  239. package/.next/static/chunks/app/api/sessions/search/route-3154b10ff0f29211.js +0 -1
  240. package/.next/static/chunks/app/api/settings/raw/route-3154b10ff0f29211.js +0 -1
  241. package/.next/static/chunks/app/api/settings/remote/route-3154b10ff0f29211.js +0 -1
  242. package/.next/static/chunks/app/api/skills/check/route-3154b10ff0f29211.js +0 -1
  243. package/.next/static/chunks/app/api/skills/install/route-3154b10ff0f29211.js +0 -1
  244. package/.next/static/chunks/app/api/skills/route-3154b10ff0f29211.js +0 -1
  245. package/.next/static/chunks/app/api/skills/search/route-3154b10ff0f29211.js +0 -1
  246. package/.next/static/chunks/app/api/skills/update/route-3154b10ff0f29211.js +0 -1
  247. package/.next/static/chunks/app/api/subagent-runs/route-3154b10ff0f29211.js +0 -1
  248. package/.next/static/chunks/app/api/update/apply/route-3154b10ff0f29211.js +0 -1
  249. package/.next/static/chunks/app/api/update/check/route-3154b10ff0f29211.js +0 -1
  250. package/.next/static/chunks/app/api/worktrees/route-3154b10ff0f29211.js +0 -1
  251. package/.next/static/chunks/app/page-7ce92402be11ddab.js +0 -25
  252. package/.next/static/chunks/next/dist/client/components/builtin/app-error-3154b10ff0f29211.js +0 -1
  253. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-3154b10ff0f29211.js +0 -1
  254. package/.next/static/chunks/next/dist/client/components/builtin/not-found-3154b10ff0f29211.js +0 -1
  255. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-3154b10ff0f29211.js +0 -1
  256. package/.next/static/x-V0zJf8EyxlJ1TEkkcah/_buildManifest.js +0 -1
  257. /package/.next/static/{x-V0zJf8EyxlJ1TEkkcah → 0jTCyAHZ1cMAQtbthkA6a}/_ssgManifest.js +0 -0
@@ -0,0 +1 @@
1
+ "use strict";exports.id=4127,exports.ids=[4127],exports.modules={84127:(a,b,c)=>{c.d(b,{UQ:()=>h,m6:()=>g,ql:()=>j,readPidancePrefs:()=>i,xP:()=>k});var d=c(89477),e=c(86697),f=c(92783);function g(a=(0,f.$M)()){return(0,e.join)(a,"pidance-preferences.json")}function h(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function i(a=(0,f.$M)()){let b=g(a);if(!(0,d.existsSync)(b))return{};try{let a=JSON.parse((0,d.readFileSync)(b,"utf8"));return h(a)?a:{}}catch{return{}}}function j(a,b){let c=b.split("."),d=a;for(let a of c){if("object"!=typeof d||null===d)return;d=d[a]}return d}function k(a,b,c=(0,f.$M)()){!function(a,b){let c=g(a),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let h=`${c}.lock`,i=Date.now()+15e3,j=null;for(;null===j;)try{j=(0,d.openSync)(h,"wx",384)}catch(a){if("EEXIST"!==a.code)throw a;try{Date.now()-(0,d.statSync)(h).mtimeMs>6e4&&(0,d.unlinkSync)(h)}catch{}if(Date.now()>=i)throw Error("Timed out acquiring Pidance preferences lock");!function(){let a=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(a,0,0,10)}()}try{return b()}finally{(0,d.closeSync)(j);try{(0,d.unlinkSync)(h)}catch{}}}(c,()=>{let f=i(c);!function(a,b,c){let d=b.split("."),e=a;for(let a=0;a<d.length-1;a++){let b=d[a],c=e[b];("object"!=typeof c||null===c||Array.isArray(c))&&(e[b]={}),e=e[b]}let f=d[d.length-1];null==c?delete e[f]:e[f]=c}(f,a,b);let h=g(c),j=(0,e.dirname)(h);(0,d.existsSync)(j)||(0,d.mkdirSync)(j,{recursive:!0,mode:448});let k=`${h}.${process.pid}.${Date.now()}.tmp`;try{(0,d.writeFileSync)(k,JSON.stringify(f,null,2),{flag:"wx",mode:384}),(0,d.renameSync)(k,h)}catch(a){try{(0,d.unlinkSync)(k)}catch{}throw a}})}},92783:(a,b,c)=>{c.d(b,{$M:()=>f});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")}}};
@@ -0,0 +1 @@
1
+ "use strict";exports.id=5253,exports.ids=[5253],exports.modules={15253:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{syncProjectTrustBackfill:()=>m});var e=c(89477),f=c(86697),g=c(75430),h=c(92783),i=a([g]);function j(a,b){let c,d=(0,f.join)(b,"trust.json");if(!(0,e.existsSync)(d))return!1;try{let a=JSON.parse((0,e.readFileSync)(d,"utf8"));if("object"!=typeof a||null===a||Array.isArray(a))return!1;c=a}catch{return!1}let g=a;try{g=(0,e.realpathSync)(a)}catch{}return!0===c[g]||!0===c[a]}function k(a){return"object"!=typeof a||null===a||Array.isArray(a)?{}:a}function l(a){return"string"==typeof a&&a.trim().length>0}function m(a,b=(0,h.$M)()){var c=b;try{let b=(()=>{var b,c;let d;return{trust:(b=k(a),c="projectRoots",d=k(b.sidebarUi),function(a){if(!Array.isArray(a))return[];let b=[],c=new Set;for(let d of a){if("string"!=typeof d)continue;let a=d.trim();!a||c.has(a)||(c.add(a),b.push(a))}return b}(void 0!==d[c]?d[c]:b[c])),revoke:[]}})();if(0===b.trust.length&&0===b.revoke.length)return{trusted:0,revoked:0,failed:[]};return function(a,b=(0,h.$M)()){let c={trusted:0,revoked:0,failed:[]};for(let d of a.trust)if(l(d))try{(function(a,b=(0,h.$M)()){return!(!l(a)||j(a,b))&&(new g.ProjectTrustStore(b).set(a,!0),!0)})(d,b)&&(c.trusted+=1)}catch(a){c.failed.push(d),console.warn(`[pidance] failed to trust project ${d}: ${a instanceof Error?a.message:String(a)}`)}for(let d of a.revoke)if(l(d))try{(function(a,b=(0,h.$M)()){return!!l(a)&&!!j(a,b)&&(new g.ProjectTrustStore(b).set(a,null),!0)})(d,b)&&(c.revoked+=1)}catch(a){c.failed.push(d),console.warn(`[pidance] failed to revoke project trust ${d}: ${a instanceof Error?a.message:String(a)}`)}return c}(b,c)}catch(a){return console.warn(`[pidance] project trust sync failed: ${a instanceof Error?a.message:String(a)}`),{trusted:0,revoked:0,failed:[]}}}g=(i.then?(await i)():i)[0],d()}catch(a){d(a)}})},92783:(a,b,c)=>{c.d(b,{$M:()=>f});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")}}};
@@ -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.31".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.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)}
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.rV)(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.rV)(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.rV)(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.rV)();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:()=>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)}
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)}}};