@henlii/pidance 0.2.28 → 0.2.30

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 (264) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +11 -10
  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 +8 -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 +3 -3
  21. package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  22. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  23. package/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
  24. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  25. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  26. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  27. package/.next/server/app/api/about/route.js +1 -1
  28. package/.next/server/app/api/agent/[id]/bash-output/route.js +1 -1
  29. package/.next/server/app/api/agent/[id]/events/route.js +2 -2
  30. package/.next/server/app/api/agent/[id]/route.js +1 -1
  31. package/.next/server/app/api/agent/new/route.js +1 -1
  32. package/.next/server/app/api/agent/running/events/route.js +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 -0
  35. package/.next/server/app/api/agent/submissions/[submissionId]/route_client-reference-manifest.js +1 -0
  36. package/.next/server/app/api/agent-settings/route.js +2 -2
  37. package/.next/server/app/api/attachments/route.js +1 -1
  38. package/.next/server/app/api/auth/all-providers/route.js +1 -1
  39. package/.next/server/app/api/auth/api-key/[provider]/route.js +1 -1
  40. package/.next/server/app/api/auth/login/[provider]/route.js +2 -2
  41. package/.next/server/app/api/auth/logout/[provider]/route.js +1 -1
  42. package/.next/server/app/api/auth/providers/route.js +1 -1
  43. package/.next/server/app/api/auth/ui-session/route.js +1 -1
  44. package/.next/server/app/api/auth/ui-sessions/[id]/route.js +1 -1
  45. package/.next/server/app/api/auth/ui-sessions/route.js +1 -1
  46. package/.next/server/app/api/cwd/browse/route.js +1 -1
  47. package/.next/server/app/api/cwd/validate/route.js +1 -1
  48. package/.next/server/app/api/default-cwd/route.js +1 -1
  49. package/.next/server/app/api/file-index/route.js +1 -1
  50. package/.next/server/app/api/files/[...path]/route.js +1 -1
  51. package/.next/server/app/api/git/diff/route.js +1 -1
  52. package/.next/server/app/api/git/status/route.js +1 -1
  53. package/.next/server/app/api/home/route.js +1 -1
  54. package/.next/server/app/api/message-media/route.js +1 -1
  55. package/.next/server/app/api/models/route.js +1 -1
  56. package/.next/server/app/api/models-config/raw/route.js +1 -1
  57. package/.next/server/app/api/models-config/route.js +1 -1
  58. package/.next/server/app/api/models-config/test/route.js +1 -1
  59. package/.next/server/app/api/plugins/route.js +1 -1
  60. package/.next/server/app/api/plugins/search/route.js +1 -1
  61. package/.next/server/app/api/plugins/updates/route.js +1 -1
  62. package/.next/server/app/api/preferences/route.js +1 -1
  63. package/.next/server/app/api/project-assets/route.js +2 -2
  64. package/.next/server/app/api/prompts/route.js +1 -1
  65. package/.next/server/app/api/pty/route.js +2 -2
  66. package/.next/server/app/api/sessions/[id]/archive/route.js +1 -1
  67. package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
  68. package/.next/server/app/api/sessions/[id]/command-entry/route.js +1 -1
  69. package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
  70. package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
  71. package/.next/server/app/api/sessions/[id]/export/route.js +1 -1
  72. package/.next/server/app/api/sessions/[id]/info/route.js +1 -1
  73. package/.next/server/app/api/sessions/[id]/outline/route.js +1 -1
  74. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  75. package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
  76. package/.next/server/app/api/sessions/[id]/tool-results/[toolCallId]/route.js +1 -1
  77. package/.next/server/app/api/sessions/route.js +1 -1
  78. package/.next/server/app/api/sessions/search/route.js +1 -1
  79. package/.next/server/app/api/settings/raw/route.js +2 -2
  80. package/.next/server/app/api/settings/remote/route.js +1 -1
  81. package/.next/server/app/api/skills/check/route.js +1 -1
  82. package/.next/server/app/api/skills/install/route.js +1 -1
  83. package/.next/server/app/api/skills/route.js +1 -1
  84. package/.next/server/app/api/skills/search/route.js +1 -1
  85. package/.next/server/app/api/skills/update/route.js +1 -1
  86. package/.next/server/app/api/subagent-runs/route.js +1 -1
  87. package/.next/server/app/api/update/apply/route.js +2 -2
  88. package/.next/server/app/api/update/check/route.js +1 -1
  89. package/.next/server/app/api/worktrees/route.js +1 -1
  90. package/.next/server/app/icon.png/route.js +1 -1
  91. package/.next/server/app/index.html +1 -1
  92. package/.next/server/app/index.rsc +5 -5
  93. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  94. package/.next/server/app/index.segments/_full.segment.rsc +5 -5
  95. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  96. package/.next/server/app/index.segments/_index.segment.rsc +3 -3
  97. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  98. package/.next/server/app/page.js +15 -15
  99. package/.next/server/app/page_client-reference-manifest.js +1 -1
  100. package/.next/server/app-paths-manifest.json +11 -10
  101. package/.next/server/chunks/188.js +1 -1
  102. package/.next/server/chunks/2356.js +2 -0
  103. package/.next/server/chunks/3379.js +1 -1
  104. package/.next/server/chunks/3557.js +1 -0
  105. package/.next/server/chunks/5274.js +1 -1
  106. package/.next/server/chunks/5304.js +2 -2
  107. package/.next/server/chunks/5582.js +1 -1
  108. package/.next/server/chunks/6192.js +1 -1
  109. package/.next/server/chunks/7594.js +5 -5
  110. package/.next/server/chunks/9935.js +1 -0
  111. package/.next/server/instrumentation.js +1 -1
  112. package/.next/server/middleware-build-manifest.js +1 -1
  113. package/.next/server/pages/404.html +1 -1
  114. package/.next/server/pages/500.html +1 -1
  115. package/.next/server/server-reference-manifest.json +1 -1
  116. package/.next/static/{Ni2HugOTDE44QzNWaiTkR → 7Pv6SoXSxrYy0FZPYHHKJ}/_buildManifest.js +1 -1
  117. package/.next/static/chunks/9780-e89266f79eb581fe.js +1 -0
  118. package/.next/static/chunks/app/_global-error/page-3154b10ff0f29211.js +1 -0
  119. package/.next/static/chunks/app/api/about/route-3154b10ff0f29211.js +1 -0
  120. package/.next/static/chunks/app/api/agent/[id]/bash-output/route-3154b10ff0f29211.js +1 -0
  121. package/.next/static/chunks/app/api/agent/[id]/events/route-3154b10ff0f29211.js +1 -0
  122. package/.next/static/chunks/app/api/agent/[id]/route-3154b10ff0f29211.js +1 -0
  123. package/.next/static/chunks/app/api/agent/new/route-3154b10ff0f29211.js +1 -0
  124. package/.next/static/chunks/app/api/agent/running/events/route-3154b10ff0f29211.js +1 -0
  125. package/.next/static/chunks/app/api/agent/running/route-3154b10ff0f29211.js +1 -0
  126. package/.next/static/chunks/app/api/agent/submissions/[submissionId]/route-3154b10ff0f29211.js +1 -0
  127. package/.next/static/chunks/app/api/agent-settings/route-3154b10ff0f29211.js +1 -0
  128. package/.next/static/chunks/app/api/attachments/route-3154b10ff0f29211.js +1 -0
  129. package/.next/static/chunks/app/api/auth/all-providers/route-3154b10ff0f29211.js +1 -0
  130. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-3154b10ff0f29211.js +1 -0
  131. package/.next/static/chunks/app/api/auth/login/[provider]/route-3154b10ff0f29211.js +1 -0
  132. package/.next/static/chunks/app/api/auth/logout/[provider]/route-3154b10ff0f29211.js +1 -0
  133. package/.next/static/chunks/app/api/auth/providers/route-3154b10ff0f29211.js +1 -0
  134. package/.next/static/chunks/app/api/auth/ui-session/route-3154b10ff0f29211.js +1 -0
  135. package/.next/static/chunks/app/api/auth/ui-sessions/[id]/route-3154b10ff0f29211.js +1 -0
  136. package/.next/static/chunks/app/api/auth/ui-sessions/route-3154b10ff0f29211.js +1 -0
  137. package/.next/static/chunks/app/api/cwd/browse/route-3154b10ff0f29211.js +1 -0
  138. package/.next/static/chunks/app/api/cwd/validate/route-3154b10ff0f29211.js +1 -0
  139. package/.next/static/chunks/app/api/default-cwd/route-3154b10ff0f29211.js +1 -0
  140. package/.next/static/chunks/app/api/file-index/route-3154b10ff0f29211.js +1 -0
  141. package/.next/static/chunks/app/api/files/[...path]/route-3154b10ff0f29211.js +1 -0
  142. package/.next/static/chunks/app/api/git/diff/route-3154b10ff0f29211.js +1 -0
  143. package/.next/static/chunks/app/api/git/status/route-3154b10ff0f29211.js +1 -0
  144. package/.next/static/chunks/app/api/home/route-3154b10ff0f29211.js +1 -0
  145. package/.next/static/chunks/app/api/message-media/route-3154b10ff0f29211.js +1 -0
  146. package/.next/static/chunks/app/api/models/route-3154b10ff0f29211.js +1 -0
  147. package/.next/static/chunks/app/api/models-config/raw/route-3154b10ff0f29211.js +1 -0
  148. package/.next/static/chunks/app/api/models-config/route-3154b10ff0f29211.js +1 -0
  149. package/.next/static/chunks/app/api/models-config/test/route-3154b10ff0f29211.js +1 -0
  150. package/.next/static/chunks/app/api/plugins/route-3154b10ff0f29211.js +1 -0
  151. package/.next/static/chunks/app/api/plugins/search/route-3154b10ff0f29211.js +1 -0
  152. package/.next/static/chunks/app/api/plugins/updates/route-3154b10ff0f29211.js +1 -0
  153. package/.next/static/chunks/app/api/preferences/route-3154b10ff0f29211.js +1 -0
  154. package/.next/static/chunks/app/api/project-assets/route-3154b10ff0f29211.js +1 -0
  155. package/.next/static/chunks/app/api/prompts/route-3154b10ff0f29211.js +1 -0
  156. package/.next/static/chunks/app/api/pty/route-3154b10ff0f29211.js +1 -0
  157. package/.next/static/chunks/app/api/sessions/[id]/archive/route-3154b10ff0f29211.js +1 -0
  158. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-3154b10ff0f29211.js +1 -0
  159. package/.next/static/chunks/app/api/sessions/[id]/command-entry/route-3154b10ff0f29211.js +1 -0
  160. package/.next/static/chunks/app/api/sessions/[id]/context/route-3154b10ff0f29211.js +1 -0
  161. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-3154b10ff0f29211.js +1 -0
  162. package/.next/static/chunks/app/api/sessions/[id]/export/route-3154b10ff0f29211.js +1 -0
  163. package/.next/static/chunks/app/api/sessions/[id]/info/route-3154b10ff0f29211.js +1 -0
  164. package/.next/static/chunks/app/api/sessions/[id]/outline/route-3154b10ff0f29211.js +1 -0
  165. package/.next/static/chunks/app/api/sessions/[id]/route-3154b10ff0f29211.js +1 -0
  166. package/.next/static/chunks/app/api/sessions/[id]/state/route-3154b10ff0f29211.js +1 -0
  167. package/.next/static/chunks/app/api/sessions/[id]/tool-results/[toolCallId]/route-3154b10ff0f29211.js +1 -0
  168. package/.next/static/chunks/app/api/sessions/route-3154b10ff0f29211.js +1 -0
  169. package/.next/static/chunks/app/api/sessions/search/route-3154b10ff0f29211.js +1 -0
  170. package/.next/static/chunks/app/api/settings/raw/route-3154b10ff0f29211.js +1 -0
  171. package/.next/static/chunks/app/api/settings/remote/route-3154b10ff0f29211.js +1 -0
  172. package/.next/static/chunks/app/api/skills/check/route-3154b10ff0f29211.js +1 -0
  173. package/.next/static/chunks/app/api/skills/install/route-3154b10ff0f29211.js +1 -0
  174. package/.next/static/chunks/app/api/skills/route-3154b10ff0f29211.js +1 -0
  175. package/.next/static/chunks/app/api/skills/search/route-3154b10ff0f29211.js +1 -0
  176. package/.next/static/chunks/app/api/skills/update/route-3154b10ff0f29211.js +1 -0
  177. package/.next/static/chunks/app/api/subagent-runs/route-3154b10ff0f29211.js +1 -0
  178. package/.next/static/chunks/app/api/update/apply/route-3154b10ff0f29211.js +1 -0
  179. package/.next/static/chunks/app/api/update/check/route-3154b10ff0f29211.js +1 -0
  180. package/.next/static/chunks/app/api/worktrees/route-3154b10ff0f29211.js +1 -0
  181. package/.next/static/chunks/app/page-05c85e412b0302f9.js +25 -0
  182. package/.next/static/chunks/next/dist/client/components/builtin/app-error-3154b10ff0f29211.js +1 -0
  183. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-3154b10ff0f29211.js +1 -0
  184. package/.next/static/chunks/next/dist/client/components/builtin/not-found-3154b10ff0f29211.js +1 -0
  185. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-3154b10ff0f29211.js +1 -0
  186. package/.next/static/css/2655240c351314b2.css +1 -0
  187. package/README.en.md +19 -15
  188. package/README.md +17 -13
  189. package/README.zh-CN.md +11 -204
  190. package/bin/pidance-http-server.js +10 -0
  191. package/bin/pty-manager.cjs +3 -12
  192. package/bin/pty-shell.cjs +27 -0
  193. package/bin/pty-worker.js +17 -8
  194. package/package.json +2 -2
  195. package/.next/static/chunks/9780-4b76db8fbfb345c2.js +0 -1
  196. package/.next/static/chunks/app/_global-error/page-005f7c16c8d63642.js +0 -1
  197. package/.next/static/chunks/app/api/about/route-005f7c16c8d63642.js +0 -1
  198. package/.next/static/chunks/app/api/agent/[id]/bash-output/route-005f7c16c8d63642.js +0 -1
  199. package/.next/static/chunks/app/api/agent/[id]/events/route-005f7c16c8d63642.js +0 -1
  200. package/.next/static/chunks/app/api/agent/[id]/route-005f7c16c8d63642.js +0 -1
  201. package/.next/static/chunks/app/api/agent/new/route-005f7c16c8d63642.js +0 -1
  202. package/.next/static/chunks/app/api/agent/running/events/route-005f7c16c8d63642.js +0 -1
  203. package/.next/static/chunks/app/api/agent/running/route-005f7c16c8d63642.js +0 -1
  204. package/.next/static/chunks/app/api/agent-settings/route-005f7c16c8d63642.js +0 -1
  205. package/.next/static/chunks/app/api/attachments/route-005f7c16c8d63642.js +0 -1
  206. package/.next/static/chunks/app/api/auth/all-providers/route-005f7c16c8d63642.js +0 -1
  207. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-005f7c16c8d63642.js +0 -1
  208. package/.next/static/chunks/app/api/auth/login/[provider]/route-005f7c16c8d63642.js +0 -1
  209. package/.next/static/chunks/app/api/auth/logout/[provider]/route-005f7c16c8d63642.js +0 -1
  210. package/.next/static/chunks/app/api/auth/providers/route-005f7c16c8d63642.js +0 -1
  211. package/.next/static/chunks/app/api/auth/ui-session/route-005f7c16c8d63642.js +0 -1
  212. package/.next/static/chunks/app/api/auth/ui-sessions/[id]/route-005f7c16c8d63642.js +0 -1
  213. package/.next/static/chunks/app/api/auth/ui-sessions/route-005f7c16c8d63642.js +0 -1
  214. package/.next/static/chunks/app/api/cwd/browse/route-005f7c16c8d63642.js +0 -1
  215. package/.next/static/chunks/app/api/cwd/validate/route-005f7c16c8d63642.js +0 -1
  216. package/.next/static/chunks/app/api/default-cwd/route-005f7c16c8d63642.js +0 -1
  217. package/.next/static/chunks/app/api/file-index/route-005f7c16c8d63642.js +0 -1
  218. package/.next/static/chunks/app/api/files/[...path]/route-005f7c16c8d63642.js +0 -1
  219. package/.next/static/chunks/app/api/git/diff/route-005f7c16c8d63642.js +0 -1
  220. package/.next/static/chunks/app/api/git/status/route-005f7c16c8d63642.js +0 -1
  221. package/.next/static/chunks/app/api/home/route-005f7c16c8d63642.js +0 -1
  222. package/.next/static/chunks/app/api/message-media/route-005f7c16c8d63642.js +0 -1
  223. package/.next/static/chunks/app/api/models/route-005f7c16c8d63642.js +0 -1
  224. package/.next/static/chunks/app/api/models-config/raw/route-005f7c16c8d63642.js +0 -1
  225. package/.next/static/chunks/app/api/models-config/route-005f7c16c8d63642.js +0 -1
  226. package/.next/static/chunks/app/api/models-config/test/route-005f7c16c8d63642.js +0 -1
  227. package/.next/static/chunks/app/api/plugins/route-005f7c16c8d63642.js +0 -1
  228. package/.next/static/chunks/app/api/plugins/search/route-005f7c16c8d63642.js +0 -1
  229. package/.next/static/chunks/app/api/plugins/updates/route-005f7c16c8d63642.js +0 -1
  230. package/.next/static/chunks/app/api/preferences/route-005f7c16c8d63642.js +0 -1
  231. package/.next/static/chunks/app/api/project-assets/route-005f7c16c8d63642.js +0 -1
  232. package/.next/static/chunks/app/api/prompts/route-005f7c16c8d63642.js +0 -1
  233. package/.next/static/chunks/app/api/pty/route-005f7c16c8d63642.js +0 -1
  234. package/.next/static/chunks/app/api/sessions/[id]/archive/route-005f7c16c8d63642.js +0 -1
  235. package/.next/static/chunks/app/api/sessions/[id]/auto-name/route-005f7c16c8d63642.js +0 -1
  236. package/.next/static/chunks/app/api/sessions/[id]/command-entry/route-005f7c16c8d63642.js +0 -1
  237. package/.next/static/chunks/app/api/sessions/[id]/context/route-005f7c16c8d63642.js +0 -1
  238. package/.next/static/chunks/app/api/sessions/[id]/entries/[entryId]/thinking/route-005f7c16c8d63642.js +0 -1
  239. package/.next/static/chunks/app/api/sessions/[id]/export/route-005f7c16c8d63642.js +0 -1
  240. package/.next/static/chunks/app/api/sessions/[id]/info/route-005f7c16c8d63642.js +0 -1
  241. package/.next/static/chunks/app/api/sessions/[id]/outline/route-005f7c16c8d63642.js +0 -1
  242. package/.next/static/chunks/app/api/sessions/[id]/route-005f7c16c8d63642.js +0 -1
  243. package/.next/static/chunks/app/api/sessions/[id]/state/route-005f7c16c8d63642.js +0 -1
  244. package/.next/static/chunks/app/api/sessions/[id]/tool-results/[toolCallId]/route-005f7c16c8d63642.js +0 -1
  245. package/.next/static/chunks/app/api/sessions/route-005f7c16c8d63642.js +0 -1
  246. package/.next/static/chunks/app/api/sessions/search/route-005f7c16c8d63642.js +0 -1
  247. package/.next/static/chunks/app/api/settings/raw/route-005f7c16c8d63642.js +0 -1
  248. package/.next/static/chunks/app/api/settings/remote/route-005f7c16c8d63642.js +0 -1
  249. package/.next/static/chunks/app/api/skills/check/route-005f7c16c8d63642.js +0 -1
  250. package/.next/static/chunks/app/api/skills/install/route-005f7c16c8d63642.js +0 -1
  251. package/.next/static/chunks/app/api/skills/route-005f7c16c8d63642.js +0 -1
  252. package/.next/static/chunks/app/api/skills/search/route-005f7c16c8d63642.js +0 -1
  253. package/.next/static/chunks/app/api/skills/update/route-005f7c16c8d63642.js +0 -1
  254. package/.next/static/chunks/app/api/subagent-runs/route-005f7c16c8d63642.js +0 -1
  255. package/.next/static/chunks/app/api/update/apply/route-005f7c16c8d63642.js +0 -1
  256. package/.next/static/chunks/app/api/update/check/route-005f7c16c8d63642.js +0 -1
  257. package/.next/static/chunks/app/api/worktrees/route-005f7c16c8d63642.js +0 -1
  258. package/.next/static/chunks/app/page-354e6fd7f7df840b.js +0 -25
  259. package/.next/static/chunks/next/dist/client/components/builtin/app-error-005f7c16c8d63642.js +0 -1
  260. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-005f7c16c8d63642.js +0 -1
  261. package/.next/static/chunks/next/dist/client/components/builtin/not-found-005f7c16c8d63642.js +0 -1
  262. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-005f7c16c8d63642.js +0 -1
  263. package/.next/static/css/1c6fd1229e5153db.css +0 -1
  264. /package/.next/static/{Ni2HugOTDE44QzNWaiTkR → 7Pv6SoXSxrYy0FZPYHHKJ}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- "use strict";exports.id=7594,exports.ids=[7594],exports.modules={1060:(a,b,c)=>{c.d(b,{Ac:()=>n,GO:()=>i,X:()=>k,_4:()=>d,cV:()=>j,k2:()=>l,oC:()=>m});let d=262144,e={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},f={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},g={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},h={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function i(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function j(a){return e[i(a)]??null}function k(a){return f[i(a)]??null}function l(a){return g[i(a)]??null}function m(a){return h[i(a)]??null}function n(a){let b=i(a);return"pdf"===b||"docx"===b?b:null}},2416:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>w});var e=c(75430),f=c(60396),g=c(68524),h=c(89953),i=c(5815),j=c(85664),k=c(65107),l=c(95237),m=c(38195),n=c(62693),o=c(31524),p=c(52960),q=c(13737),r=c(60185),s=c(28121),t=c(87538),u=a([e,l,r,s]);function v(a){return"string"==typeof a&&a?a:void 0}[e,l,r,s]=u.then?(await u)():u;class x{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._scheduledRecheck=!1,this.onDestroyCallback=null,this._alive=!0,this.promptRunning=!1,this.lastStopReason=null,this.followUpQueue=[],this.followUpQueueRevision=0,this.followUpQueueHydrated=!1,this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],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.pendingBinaryBatches=[],this.destroyPromise=null,this.hasQueueSnapshot=!1,this.renderBridgeTheme=(0,t.Lm)(),this.toolRenderStates=new Map,this.realSessionId=a.sessionId,this.realSessionFile=a.sessionFile,this.idleTimeoutMs=a.idleTimeoutMs??3e4,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}onDestroy(a){this.onDestroyCallback=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||this.listeners.length>0)return;if(this.followUpQueue.length>0&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();let a=this.idleTimeoutMs;this.idleTimer=setTimeout(()=>{if((this.idleTimer=null,!this.isRunning()&&!this.flushingFollowUp)&&!(this.listeners.length>0)){if(this.followUpQueue.length>0&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();this.destroyAsync()}},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(a){console.error("[pidance] failed to persist follow-up hold:",a)}}hydrateFollowUpQueue(){if(this.followUpQueueHydrated)return;this.followUpQueueHydrated=!0;let a=(0,g.rV)(this.agentDir),b=(0,g.ql)(a,`sessionQueue.${this.realSessionId}`),c=a=>Array.isArray(a)?a.filter(a=>"string"==typeof a&&a.trim().length>0):[];if(Array.isArray(b)){this.followUpQueue=c(b);return}let d=b&&"object"==typeof b?b:null;this.followUpQueue=c(d?.items),"number"==typeof d?.revision&&(this.followUpQueueRevision=d.revision)}updateFollowUpQueue(a){this.followUpQueue=a,this.followUpQueueRevision+=1}persistFollowUpQueue(){try{(0,g.xP)(`sessionQueue.${this.realSessionId}`,{items:this.followUpQueue,revision:this.followUpQueueRevision},this.agentDir)}catch(a){console.error("[pidance] failed to persist follow-up queue:",a)}}scheduleFollowUpFlush(){!this._alive||!this.runtime||this.flushingFollowUp||0===this.followUpQueue.length||this.isFollowUpHeld()||this.isSettled()&&(this.flushingFollowUp=!0,this.followUpFlushAsOne=!0===(0,g.rV)(this.agentDir).queueFlushAsOne,this.followUpFlushOriginal=[...this.followUpQueue],this.followUpFlushBatch=this.followUpFlushAsOne?[this.followUpFlushOriginal.join("\n\n")]:[...this.followUpFlushOriginal],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.sendNextFollowUp())}async sendNextFollowUp(){if(!this.flushingFollowUp)return;if(this.isFollowUpHeld())return void this.abortFollowUpFlush();let a=this.followUpFlushBatch[this.followUpFlushCursor];if(void 0===a)return void this.finishFollowUpFlush();if(!this.isSettled())return void setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushCursor<this.followUpFlushBatch.length&&this.sendNextFollowUp()},80);this.followUpFlushConfirmed=!1;try{await this.send({type:"prompt",message:a}),this.removeDeliveredFollowUp()&&this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:a,remaining:[...this.followUpQueue]})}catch(b){let a=b instanceof Error?b.message:String(b);this.emit({type:"follow_up_flush_error",errorMessage:a}),this.abortFollowUpFlush()}}removeDeliveredFollowUp(){if(this.followUpFlushAsOne){let a=new Set(this.followUpFlushOriginal),b=this.followUpQueue.filter(b=>!a.has(b));return b.length!==this.followUpQueue.length&&(this.updateFollowUpQueue(b),this.persistFollowUpQueue(),!0)}let a=this.followUpFlushBatch[this.followUpFlushCursor];if(void 0===a)return!1;let b=this.followUpQueue.indexOf(a);if(b<0)return!1;let c=[...this.followUpQueue];return c.splice(b,1),this.updateFollowUpQueue(c),this.persistFollowUpQueue(),!0}confirmFollowUpFlush(){if(!this.flushingFollowUp||this.followUpFlushConfirmed)return;let a=this.followUpFlushBatch[this.followUpFlushCursor];if(void 0===a)return;this.followUpFlushConfirmed=!0,this.removeDeliveredFollowUp();let b=[...this.followUpQueue];(this.persistFollowUpQueue(),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:a,remaining:b}),this.followUpFlushAsOne)?this.finishFollowUpFlush():(this.followUpFlushCursor+=1,this.followUpFlushCursor>=this.followUpFlushBatch.length?this.finishFollowUpFlush():this.sendNextFollowUp())}abortFollowUpFlush(){this.flushingFollowUp&&(this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],this.persistFollowUpQueue(),this.resetIdleTimer())}finishFollowUpFlush(){this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],this.persistFollowUpQueue(),this.resetIdleTimer(),this.followUpQueue.length>0&&!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,m.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=v(a.method);if("setStatus"===b){let b=v(a.statusKey)??v(a.key)??"default",c=v(a.statusText)??v(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=v(a.widgetKey)??v(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,l.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(q.uG,a);this.emit({type:"message_end",entryId:e,message:(0,q.FH)(a,Date.now())})}(0,l.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&&x.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=x.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);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,k.$9)(this.realSessionFile),this.maybeAutoNameSession(),this.notifyRunning(),this.emit({type:"prompt_done"});break;case"agent_settled":this.promptRunning=!1,this.notifyRunning(),"completed"===this.lastStopReason?this.flushingFollowUp?this.followUpFlushConfirmed?this.sendNextFollowUp():this.confirmFollowUpFlush():this.scheduleFollowUpFlush():this.flushingFollowUp&&("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.abortFollowUpFlush();let c="agent_settled"===a.type&&!this.flushingFollowUp&&(0===this.followUpQueue.length||this.isFollowUpHeld());this.resetIdleTimer(),c&&this.destroyAsync();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"){this.confirmFollowUpFlush();let a=this.pendingBinaryBatches.shift();setImmediate(()=>{try{(0,l.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 d=a;if(b){let a=this.projectTurnMetrics();(void 0!==a.ttftMs||void 0!==a.tokensPerSecond)&&(d={...d,turnMetrics:a})}let e="message_end"===a.type&&a.message?.role==="assistant";if("agent_end"===a.type||e){let a=this.contextUsageSnapshot();a&&(d={...d,contextUsage:a})}this.emit(this.withRenderedToolLines(d))}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,t.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,t.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,t.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,t.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<x.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,l.G1)(a):(0,l.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,s._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:s.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:s.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:s.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,o.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.followUpQueue.length>0&&!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()??[])};c.queuedMessages={steering:this.hasQueueSnapshot?[...this.localQueue.steering]:[],followUp:[...this.followUpQueue],followUpRevision:this.followUpQueueRevision};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,j.qF)(a):(0,j.l$)(a),c=this.session.sessionManager.appendCustomEntry(j.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,r.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(q.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,q.FH)(f,Date.now())})}catch(a){console.error("[pidance] binary message event notification failed:",a)}return{entryId:g,binary:f}}async send(a){if(!this.runtime)throw Error("SDK session is not alive");let b=a.type;"get_state"!==b&&"ensure_session"!==b&&this.releaseStartupHold(),this.activeCommandCount+=1,this.resetIdleTimer();let c=this.session;try{switch(b){case"prompt":{let b=(0,p.JT)(a),d=this.promptReceipts.get(b.submissionId);if(d)return d;let e=b.submissionId,f=this.promptInFlight.get(e);if(f)return f;let g=(0,r.Nu)(b.binaryBlocks,this.agentDir);if(this.bashRunning)throw Error("Cannot send a prompt while a shell command is running");if(c.isCompacting){if(b.images?.length||g.length>0)throw Error("Media attachments cannot be queued while compaction is in progress");let a={submissionId:b.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.updateFollowUpQueue([...this.followUpQueue,b.message]),this.promptReceipts.set(b.submissionId,a),this.persistFollowUpQueue(),this.options.onSessionListInvalidate?.(),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 j=(async()=>{try{await new Promise((d,f)=>{let h=!1,j=()=>{c.isStreaming||c.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"}),this.resetIdleTimer())};c.prompt(b.message,{images:b.images??a.images,streamingBehavior:a.streamingBehavior,source:"rpc",preflightResult:a=>{a&&(h=!0,g.length>0&&this.pendingBinaryBatches.push({submissionId:e,blocks:g}),this.syncIdentityFromSession(),this.setFollowUpHeld(!1),this.options.onSessionListInvalidate?.(),d())}}).then(()=>{if(!h){h=!0;try{(0,l.kb)(c.sessionManager)}catch(a){console.error("[pidance] materialize after prompt failed:",a)}this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.(),d()}j()}).catch(a=>{"aborted"!==this.lastStopReason&&(this.lastStopReason="error"),this.setFollowUpHeld(!0),j(),h||(h=!0,f(a))})});let d={submissionId:b.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(e,d),d}catch(d){this.removePendingBinaryBatch(e),this.promptRunning=!1,this.lastStopReason="aborted"===this.lastStopReason?"aborted":"error",this.setFollowUpHeld(!0),(0,i.PI)(this.realSessionId),this.notifyRunning();let a=d instanceof Error?d.message:String(d);this.emit({type:"prompt_error",errorMessage:a}),this.emit({type:"prompt_done"});let c={submissionId:b.submissionId,sessionId:this.realSessionId,status:"rejected"};throw this.promptReceipts.set(e,c),d}finally{this.promptInFlight.delete(e)}})();return this.promptInFlight.set(e,j),j}case"abort":return this.lastStopReason="aborted",this.setFollowUpHeld(!0),this.promptRunning=!1,this.notifyRunning(),await c.abort(),this.notifyRunning(),null;case"get_state":return this.projectState();case"set_model":{let b=String(a.provider??""),d=String(a.modelId??""),e=(0,n.E)(c.modelRuntime,b,d);if(!e)try{e=(await c.modelRuntime.getAvailable()).find(a=>a.provider===b&&a.id===d)}catch{e=void 0}if(!e)throw Error(`Model not found: ${b}/${d}`);return await c.setModel((0,o.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return c.model&&(0,o.yu)(c.model),c.setThinkingLevel(a.level),this.options.onSessionListInvalidate?.(),null;case"compact":{let b=await c.compact("string"==typeof a.customInstructions?a.customInstructions:void 0);return this.options.onSessionListInvalidate?.(),this.notifyRunning(),this.resetIdleTimer(),b}case"steer":{let b=String(a.message??"");if(!this.isRunning()&&!this.flushingFollowUp)return this.send({type:"prompt",message:b,images:a.images,streamingBehavior:"steer"});return await c.steer(b,a.images),null}case"set_follow_up_queue":{let b=Array.isArray(a.items)?a.items.filter(a=>"string"==typeof a&&a.trim().length>0):[];return this.flushingFollowUp&&this.abortFollowUpFlush(),this.updateFollowUpQueue(b),this.persistFollowUpQueue(),this.isSettled()&&b.length>0&&this.scheduleFollowUpFlush(),this.resetIdleTimer(),{ok:!0,queued:this.followUpQueue.length}}case"follow_up":return await c.followUp(String(a.message??""),a.images),null;case"set_session_name":{let b=String(a.name??"").trim();if(!b)throw Error("Session name cannot be empty");return c.setSessionName(b),this.options.onSessionListInvalidate?.(),null}case"set_auto_compaction":return c.setAutoCompactionEnabled(!!a.enabled),null;case"set_auto_retry":return c.setAutoRetryEnabled(!!a.enabled),null;case"clear_queue":return c.clearQueue();case"get_tools":{let a=c.getAllTools(),b=new Set(c.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 c.setActiveToolsByName(b),this.activeToolNames=b,null}case"get_commands":{let a=[];for(let b of c.extensionRunner.getRegisteredCommands())a.push({name:b.invocationName,description:b.description,source:"extension",sourceInfo:b.sourceInfo});for(let b of c.promptTemplates)a.push({name:b.name,description:b.description,source:"prompt_template"});try{let b=c.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 c.getSessionStats();case"bash":if(c.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 c.executeBash(String(a.command??""),void 0,{excludeFromContext:!!a.excludeFromContext})}finally{this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),this.resetIdleTimer()}case"abort_bash":return c.abortBash(),this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),null;case"abort_compaction":return c.abortCompaction(),null;case"extension_ui_response":{let b=v(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=v(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=v(a.targetId);if(!b)throw Error("targetId is required");let d=await c.navigateTree(b,{summarize:a.summarize,customInstructions:v(a.customInstructions)});if(!d.cancelled&&this.realSessionFile){c.sessionManager.getLeafId();let a=c.sessionManager.getLeafId(),b=c.sessionManager.getEntries(),d=b.at(-1)?.id;a&&d&&a!==d?(0,k.R3)(this.realSessionFile,a):this.realSessionFile&&(0,k.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:d.cancelled}}case"select_leaf_exact":{let b=v(a.entryId);if(!b)throw Error("entryId is required");if(this.options.navigationActions)return this.options.navigationActions.selectLeafExact(this.sessionId,b);let d=await c.navigateTree(b,{summarize:!1});if(!d.cancelled&&this.realSessionFile){let a=c.sessionManager.getLeafId(),b=c.sessionManager.getEntries().at(-1)?.id;a&&b&&a!==b?(0,k.R3)(this.realSessionFile,a):(0,k.$9)(this.realSessionFile)}return{cancelled:d.cancelled}}case"branch_from_assistant":{let b=v(a.assistantEntryId);if(!b)throw Error("assistantEntryId is required");if(this.options.navigationActions)return this.options.navigationActions.branchFromAssistant(this.sessionId,b);throw Error("branch_from_assistant is unavailable")}case"create_session_from_leaf":{let b=v(a.entryId);if(!b)throw Error("entryId is required");if(this.options.navigationActions)return this.options.navigationActions.createSessionFromLeaf(this.sessionId,b);throw Error("create_session_from_leaf is unavailable")}case"set_branch_label":{let b=v(a.targetId);if(!b)throw Error("targetId is required");let d=void 0===a.label||null===a.label?void 0:String(a.label);return c.sessionManager.appendLabelChange(b,d),this.options.onSessionListInvalidate?.(),null}case"reload":return await c.reload(),await this.rebindSession(),null;case"get_last_assistant_text":return{text:c.getLastAssistantText()};case"ensure_session":return null;default:throw Error(`Unsupported command: ${b}`)}}finally{this.activeCommandCount=Math.max(0,this.activeCommandCount-1),0===this.activeCommandCount&&this.resetIdleTimer()}}destroy(){this.destroyAsync()}async destroyAsync(){if(this.destroyPromise)return this.destroyPromise;if(this._alive||this.runtime){if(this.activeCommandCount>0){if(this._scheduledRecheck)return;this._scheduledRecheck=!0,setTimeout(()=>{this._scheduledRecheck=!1,!this.destroyPromise&&this._alive&&this.destroyAsync()},0);return}return 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)}this.promptRunning=!1,this.bashRunning=!1,this.bashCommand=null,this.flushingFollowUp=!1,this.followUpFlushBatch=[],this.followUpFlushCursor=0,this.followUpFlushConfirmed=!1,this.followUpFlushAsOne=!1,this.followUpFlushOriginal=[],(0,i.PI)(this.realSessionId),this.onDestroyCallback?.(),this.notifyRunning()})(),this.destroyPromise}}}async function w(a){let b=new x(a);return await b.start(),b}d()}catch(a){d(a)}})},5815:(a,b,c)=>{c.d(b,{MG:()=>h,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)}function h(){return e()}},26773:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>u,A4:()=>m,DU:()=>o,EM:()=>r,Fn:()=>t,HG:()=>q,OF:()=>w});var e=c(40402),f=c(95237);c(68524);var g=c(2416),h=c(5815),i=c(89953),j=a([e,f,g]);function k(){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 l(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function m(a){return k().get(a)}function n(){return[...l().keys()]}async function o(a){let b=l().get(a);if(!b)return null;try{return(await b).realSessionId}catch{return null}}function p(){let a=new Set(n());for(let[b,c]of k())c.isRunning()&&a.add(c.sessionId||b);return[...a]}function q(){return p()}[e,f,g]=j.then?(await j)():j;let y=new Map;function r(a,b=Date.now()){let c={},d=(0,h.MG)(),e=p(),f=new Set(e);for(let a of e){let e=d.get(a)??y.get(a)??b;y.set(a,e),c[a]=e}for(let a of[...y.keys()])f.has(a)||y.delete(a);return c}function s(){return globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners}function t(a){let b=s();return b.add(a),()=>{b.delete(a)}}function u(){let a=[];for(let[b,c]of k()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}let z="",A=new Set,B=null;function v(){!function a(){let b=new Set(function(){let a=new Set(n());for(let[b,c]of k())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,i.AZ)(a),A.add(a);for(let a of[...A])b.has(a)||((0,i.Hl)(a),A.delete(a));if(0===b.size){B&&(clearInterval(B),B=null);return}B||(B=setInterval(()=>{a()},8e3),B.unref?.())}();let a=q(),b=u(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c!==z)for(let b of(z=c,s()))try{b(a)}catch{}}async function w(a,b,c,d,e){return x(a,b,c,d,e)}async function x(a,b,c,d,f){let h=k(),j=l(),m=h.get(a);if(m?.isAlive())return{session:m,realSessionId:a};let n=j.get(a);if(n)return n;if(!(0,i.kP)(a))throw Error(i.GT);v();let o=(async()=>{try{let j=await (0,g.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>v(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=k(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,i.kP)(b),(0,i.Hl)(a))}}),l=j.sessionId,m=j.sessionFile;return m&&(0,e.O8)(l,m),l!==a&&(0,i.kP)(l),j.onDestroy(()=>{h.get(l)===j&&h.delete(l),a!==l&&h.get(a)===j&&h.delete(a),(0,i.Hl)(l),a!==l&&(0,i.Hl)(a),v()}),h.set(l,j),j.beginExtensionBinding(),{session:j,realSessionId:l}}catch(b){throw(0,i.Hl)(a),v(),b}})().finally(()=>{j.delete(a),v()});return j.set(a,o),o}d()}catch(a){d(a)}})},28121:(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(69835),j=c(80547),k=c(1060),l=c(60185),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)}})},31524:(a,b,c)=>{c.d(b,{Ut:()=>e,eU:()=>f,yu:()=>g});let d=["off","minimal","low","medium","high","xhigh","max"];function e(a,b){return a?d.filter(a=>b?.[a]!==null):["off"]}function f(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 g(a){let b=f(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}},37594:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{C9:()=>H,DQ:()=>G,Md:()=>F,Yz:()=>E,mB:()=>K});var e=c(29021),f=c(33873),g=c(80547),h=c(60396),i=c(95237),j=c(52960),k=c(79495),l=c(81879),m=c(46935),n=c(31514),o=c(65107),p=c(56429),q=c(40402),r=c(85664),s=c(15461),t=c(76817),u=c(86226),v=c(68524),w=c(89953),x=c(50955),y=c(40239),z=c(5815),A=c(99911),B=c(26773),C=c(68816),D=a([g,i,l,p,q,B]);[g,i,l,p,q,B]=D.then?(await D)():D;let G="Subagent sessions are read-only";class H extends Error{constructor(){super(G)}toString(){return this.message}}async function E(a,b){if(await b(a))throw new H}function F(a){let b=a instanceof Error?a.message:String(a);return a instanceof H||b===G?403:b.includes("Session not found")?404:(0,w.wE)(a)||b===w.GT||"Session is being deleted"===b||b.includes("closed while its title")?409:500}let I={listAllSessions:q.dQ,resolveSessionPath:q.os,getRpcSession:p.A4,waitForSessionStart:p.DU,startRpcSession:p.OF,getRunningRpcSessionIds:p.HG,listPendingExtensionUi:p.$k,subscribeRunningSessions:p.Fn,allowFileRoot:g.wz,invalidateSessionListCache:q.mD,openSessionCwd:a=>(0,i.kW)(a).getHeader()?.cwd??process.cwd(),openSessionManager:a=>(0,q.Zx)({filePath:a}),openSessionView:i.kW,reparentSessionFile:i.i5,existsSync:e.existsSync,now:()=>Date.now(),archiveFs:y.Iq},J=["systemPrompt"],K=function(a={}){let b={...I,...a},c=(0,y.Ki)({fs:b.archiveFs,agentDir:b.archiveAgentDir,resolveSessionPath:b.resolveSessionPath,readSessionHeader:q.eP,isReadOnly:async a=>{let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},isRunning:a=>b.getRunningRpcSessionIds().includes(a),getSessionInfo:async a=>(await b.listAllSessions()).find(b=>b.id===a)??null,invalidateSessionListCache:b.invalidateSessionListCache,now:()=>new Date(b.now()).toISOString()}),d=()=>(0,y.$T)(b.archiveFs??y.Iq,b.archiveAgentDir?.()??(0,h.$M)()),g=new Map,p=async a=>{let c=b.getRpcSession(a);if(c){if("function"==typeof c.destroyAsync)return void await c.destroyAsync();c.isAlive()&&c.destroy()}},D=async(a,b)=>{if(!(0,w.kP)(a))throw Error(w.GT);try{return await b()}finally{(0,w.Hl)(a)}},F=async(a,b)=>(await p(a),D(a,b)),G={async listSessions(){let a=await b.listAllSessions(),{active:c,archived:e}=(0,y.uD)(a,d());return{sessions:c,archivedSessions:e,archivedCount:e.length,runningSessionIds:b.getRunningRpcSessionIds()}},async listArchivedSessions(){let a=await b.listAllSessions();return(0,y.uD)(a,d()).archived},async listActiveSessions(){let a=await b.listAllSessions();return(0,y.uD)(a,d()).active},listAllSessions:async()=>b.listAllSessions(),async isArchived(a){let c=await b.listAllSessions();return(0,y.YV)(c,d()).has(a)},archiveSession:async a=>c.archiveSession(a),restoreSession:async a=>c.restoreSession(a),archiveSessions:async a=>c.archiveSessions(a),restoreSessions:async a=>c.restoreSessions(a),removeArchiveRecordAfterPermanentDelete(a){(0,y.rQ)(b.archiveFs??y.Iq,b.archiveAgentDir?.()??(0,h.$M)(),a)},resolvePath:a=>b.resolveSessionPath(a),getSessionInfo:async a=>a&&"string"==typeof a?(await b.listAllSessions()).find(b=>b.id===a)??null:null,async isReadOnly(a){let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},async getReadView(a){let c=await b.resolveSessionPath(a);if(!c)return null;let d=b.getRpcSession(a),e=d?.inner;return d?.isAlive()&&e?.sessionManager?{source:"live",filePath:c,manager:e.sessionManager}:{source:"disk",filePath:c,manager:b.openSessionManager(c)}},getLive(a){let c=b.getRpcSession(a);return c?.isAlive()?c:void 0},getLiveSession:a=>G.getLive(a),isLive:a=>!!G.getLive(a),async ensureLive(a){if(await E(a,G.isReadOnly),g.has(a))throw Error("Session is being deleted");let c=G.getLive(a);if(c)return c;if((0,w.wy)(a))throw Error(w.GT);let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=b.openSessionCwd(d),{session:f}=await b.startRpcSession(a,d,e,void 0,H);return f},destroy(a){b.getRpcSession(a)?.destroy()},async destroyAsync(a){let c=b.getRpcSession(a);c&&("function"==typeof c.destroyAsync?await c.destroyAsync():c.destroy())},deleteSession(a){let c=g.get(a);if(c)return c;let d=(async()=>{await E(a,G.isReadOnly);let c=await b.waitForSessionStart?.(a)??a,d=await b.resolveSessionPath(a);if(!d){try{(0,v.xP)(`sessionQueue.${a}`,null),(0,v.xP)(`sessionQueueHold.${a}`,null)}catch(a){console.error("[pidance] failed to clear queue prefs after missing delete:",a)}return(0,q.BR)(a),b.invalidateSessionListCache(),G.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:0}}if((0,w.wy)(a)||(0,w.wy)(c))throw Error(w.GT);let g=(0,q.eP)(d)?.parentSession,h=(0,q.eP)(d)?.id===a?(0,x.ku)(d,a):[],i=b.getRpcSession(c)??b.getRpcSession(a),j=b.getRunningRpcSessionIds();if(i?.isAlive?.()&&(j.includes(a)||j.includes(c)))try{await i.send({type:"abort"})}catch(a){console.error("[pidance] abort before delete failed:",a)}return await G.destroyAsync(i?.sessionId??c),D(i?.sessionId??c,async()=>{let c=d.replace(/\\/g,"/").split("/").slice(0,-1).join("/");try{for(let a of(0,e.readdirSync)(c).filter(a=>a.endsWith(".jsonl")&&(0,f.join)(c,a)!==d)){let e=(0,f.join)(c,a);try{let a=(0,q.eP)(e);a?.type==="session"&&a.parentSession===d&&(a.id?(await b.waitForSessionStart?.(a.id),await F(a.id,()=>{b.reparentSessionFile(e,g)})):b.reparentSessionFile(e,g))}catch{}}}catch{}try{(0,e.unlinkSync)(d)}catch(a){if("ENOENT"!==a.code)throw a}(0,o.$9)(d);let i=(0,f.resolve)(d.slice(0,-6)),j=(0,x.uq)(h,i,q.BR);try{(0,v.xP)(`sessionQueue.${a}`,null),(0,v.xP)(`sessionQueueHold.${a}`,null)}catch(a){console.error("[pidance] failed to clear queue prefs after delete:",a)}return(0,q.BR)(a),b.invalidateSessionListCache(),G.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:j}})})();return g.set(a,d),d.finally(()=>{g.get(a)===d&&g.delete(a)})},async start(a,c,d,e){if(await E(a,G.isReadOnly),g.has(a))throw Error("Session is being deleted");return b.startRpcSession(a,c,d,e,H)},send:async(a,b)=>(await G.ensureLive(a)).send(b),async submitPrompt(a,b){await E(a,G.isReadOnly);let c=(0,j.JT)(b);try{let b=await G.send(a,c);if(b&&"object"==typeof b&&b.status)return b;return{submissionId:c.submissionId,sessionId:a,status:"accepted"}}catch(b){if((0,w.wE)(b))throw b;return{submissionId:c.submissionId,sessionId:a,status:"rejected"}}},async getAgentState(a,b){if(await G.isReadOnly(a))return{live:!1,activeRun:!1,readOnly:!0};let c=G.getLive(a);if(!c)return{live:!1,activeRun:!1,...(0,w.wy)(a)?{lockedByOther:!0}:{}};let d=await c.send({type:"get_state"}),e="function"==typeof c.isRunning?!!c.isRunning():!!(d&&(d.isStreaming||d.isPromptRunning||d.isCompacting||d.isBashRunning));return{live:!0,activeRun:e,lockedByOther:!1,state:function(a,b){if(!b?.light||!a||"object"!=typeof a||Array.isArray(a))return a;let c={...a};for(let a of J)delete c[a];return c}(d,b)}},async renameSession(a,c){await E(a,G.isReadOnly);let d=c.trim();if(!d)throw Error("name is required");let e=G.getLive(a);if(e?.isAlive()){await e.send({type:"set_session_name",name:d}),b.invalidateSessionListCache();return}let f=await b.resolveSessionPath(a);if(!f)throw Error("Session not found");await F(a,()=>{b.openSessionView(f).appendSessionInfo(d),b.invalidateSessionListCache()})},async autoNameSession(a){await E(a,G.isReadOnly);let b=await G.ensureLive(a);await b.waitUntilReady?.();let c=await G.getNavigationSnapshot(a);if(!c)throw Error("Session not found");let d=c.context.messages??[],e=(0,k.CL)(),f=await (0,k.K)({messages:d,provider:e.provider,modelId:e.modelId,baseUrl:e.baseUrl,api:e.api,apiKey:e.apiKey,headers:e.headers});if(!b.isAlive())throw Error("The session was closed while its title was being generated. Please try again.");try{await b.send({type:"set_session_name",name:f.title})}catch{await G.destroyAsync(a),await G.renameSession(a,f.title)}return{title:f.title,usage:f.usage??null}},async exportSession(a,c){let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");return(0,l.by)(d,c)},async getNavigationSnapshot(a,c={}){let d=await G.getReadView(a);if(!d)return null;let{filePath:e,manager:f}=d,{leafId:g,tree:h,context:i,header:j,sessionName:k}=(0,q.jK)(f,c),l=j?.parentSession?await (0,q.u1)(j.parentSession):void 0,m=(await b.listAllSessions()).find(b=>b.id===a),n=j?{path:e,id:j.id,cwd:j.cwd??"",name:k,created:j.timestamp,modified:j.timestamp,messageCount:i.totalMessageCount??i.messages.length,firstMessage:m?.firstMessage??"(no messages)",parentSessionId:l,...m?.subagent?{subagent:m.subagent,readOnly:!0}:{}}:null;return{filePath:e,leafId:g,tree:h,context:i,header:j,sessionName:k,parentSessionId:l,info:n}},async getUserMessageOutline(a){let b=await G.getReadView(a);if(!b)return[];let c=b.manager,d=c.getEntries?.()??[],e=(0,q.CM)(d,c.getLeafId());return(0,A.Xm)((0,q.tY)(d,e))},async getContextPage(a,b){let c,d=await G.getReadView(a);if(!d)return{context:null};let e=d.manager,f=e.getEntries?.()??[],g=(0,q.Uv)(f,b.leafId,{deferThinking:b.deferThinking,deferToolResultImages:b.deferToolResultImages}),h=b.limit;if(b.around){let a=(0,m.PV)(g,b.around,h??m._w,{toEnd:!0===b.aroundToEnd});if(!a)return{context:null,notFound:b.around};c=a}else c=b.after?(0,m.WP)(g,b.after,h??m._w):b.before?(0,m.tr)(g,b.before,h??m._w):null!==h?(0,m.G1)(g,h):{...g,hasMoreBefore:!1,totalMessageCount:g.messages.length};return{context:c}},async getEntryThinking(a,b,c){let d=await G.getReadView(a);if(!d)return null;let e=d.manager.getEntries().find(a=>a.id===b);if(!e||"message"!==e.type||e.message?.role!=="assistant")return null;let f=e.message.content?.[c];return f&&(0,n.mv)(f.type)?{thinking:(0,n.Ux)(f)}:null},async getToolResultDetails(a,b){let c=await G.getReadView(a);if(!c)return null;let d=c.manager.getEntries().find(a=>"message"===a.type&&a.message?.role==="toolResult"&&a.message.toolCallId===b);return d?{details:d.message?.details??null,content:Array.isArray(d.message?.content)?d.message.content:[]}:null},async appendActivity(a,c){await E(a,G.isReadOnly);let d=G.getLive(a),e=!!d?.inner?.sessionManager,f=d?.appendActivity;return d?.isAlive()&&e&&"function"==typeof f?await f.call(d,c):await F(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,r.l$)(c),f=b.openSessionView(d).appendCustomEntry(r.cP,e);return b.invalidateSessionListCache(),{entryId:f,activity:e}})},appendCommandEntry:async(a,c)=>(await E(a,G.isReadOnly),await F(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,s.fc)(c);if(!e.command)throw Error("command is required");let f=b.openSessionView(d).appendCustomEntry(s.OE,e);return b.invalidateSessionListCache(),{entryId:f,data:e}})),async createNew({cwd:a,command:c}){if(!a||"string"!=typeof a)throw Error("cwd is required");if(!b.existsSync(a))throw Error(`Directory does not exist: ${a}`);let{provider:d,modelId:e,toolNames:f,thinkingLevel:g,...h}=c,j=`__new__${b.now()}`,{session:k,realSessionId:l}=await b.startRpcSession(j,"",a,f,H);if(b.allowFileRoot(a),b.invalidateSessionListCache(),d&&e&&await k.send({type:"set_model",provider:d,modelId:e}),g&&await k.send({type:"set_thinking_level",level:g}),"ensure_session"===h.type){try{let a=k.inner,b=a?.sessionManager;b&&"function"==typeof b.getSessionFile&&(0,i.kb)(b)}catch(a){console.error("[pidance] materialize ensure_session failed:",a)}return{sessionId:l,data:null}}let m=await k.send(h);return{sessionId:l,data:m}},getRunningIds:()=>b.getRunningRpcSessionIds(),getRunningStartedAt(){let a=new Set(b.getRunningRpcSessionIds()),c={};for(let[b,d]of(0,z.MG)())a.has(b)&&(c[b]=d);for(let[b,d]of Object.entries((0,B.EM)()))!a.has(b)||b in c||(c[b]=d);return c},async searchFulltext(a,c={}){let d=await (0,C.s)(a,{limits:void 0!==c.maxHits?{maxHits:c.maxHits}:void 0}),e=c.scope??"active";if("all"===e)return d;let f=await b.listAllSessions(),g=(0,y.$T)(b.archiveFs??y.Iq,b.archiveAgentDir?.()??(0,h.$M)()),i=(0,y.mT)(d.sessionIds,f,g,e);return{...d,sessionIds:d.sessionIds.filter(a=>i.has(a)),hits:d.hits.filter(a=>i.has(a.sessionId))}},listPendingExtensionUi:()=>b.listPendingExtensionUi(),subscribeRunning:a=>b.subscribeRunningSessions(a),async selectLeafExact(a,c){if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let d=c.trim(),e=b.getRpcSession(a);if(e?.isAlive?.()&&e.inner?.isBashRunning)throw Error("Cannot switch branch while a shell command is running");return F(a,async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let e=b.openSessionView(c),f=e.getLeafId();if(d===f)return{cancelled:!1};if(d===e.getLastEntryId())return(0,o.$9)(c),{cancelled:!1};if(!e.getEntry(d))throw Error(`Entry ${d} not found`);try{return e.branch(d),(0,o.R3)(c,d),{cancelled:!1}}finally{b.invalidateSessionListCache()}})},async branchFromAssistant(a,c){if("string"!=typeof c||""===c.trim())throw Error("assistantEntryId is required");let d=c.trim(),e=b.getRpcSession(a);if(e?.isAlive?.()&&e.inner?.isBashRunning)throw Error("Cannot branch while a shell command is running");return F(a,async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let e=b.openSessionView(c),f=e.getLeafId();if(!f)throw Error("Session has no leaf");let g=e.getBranch(f),h=e.getEntry(d);if(!h)throw Error("Entry not found");if("message"!==h.type||h.message?.role!=="assistant")throw Error("Only assistant messages can be branched from");let i=(0,t.wo)(g,d);try{return e.branch(i),i===e.getLastEntryId()?(0,o.$9)(c):(0,o.R3)(c,i),{cancelled:!1}}finally{b.invalidateSessionListCache()}})},async createSessionFromLeaf(a,c){if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let d=c.trim(),e=b.getRpcSession(a),f=e?.inner;return F(a,async()=>{let c=(f?.sessionFile||e?.sessionFile)??await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let g=(0,i.kW)(c),h=g.getEntry(d);if(!h)throw Error("Invalid entry ID");let j=d;if("message"===h.type&&h.message?.role==="assistant"){let a=g.getLeafId();if(!a)throw Error("Session has no leaf");let b=g.getBranch(a);j=(0,t.wo)(b,d)}let k=g.getSessionDir(),l=(0,i.G1)(c,k),m=l.createBranchedSession(j);if(!m)throw Error("Failed to create session");(0,i.kb)(l);let n=(0,i.kW)(m,k),o=n.getSessionId();(0,q.O8)(o,m),b.invalidateSessionListCache();let p=f?.model;return p&&(0,u.yN)(n.getEntries().some(a=>"model_change"===a.type),{provider:p.provider,modelId:p.id})&&n.appendModelChange(p.provider,p.id),{cancelled:!1,newSessionId:o}})}},H={selectLeafExact:(a,b)=>G.selectLeafExact(a,b),branchFromAssistant:(a,b)=>G.branchFromAssistant(a,b),createSessionFromLeaf:(a,b)=>G.createSessionFromLeaf(a,b)};return G}();d()}catch(a){d(a)}})},38195:(a,b,c)=>{c.d(b,{t:()=>g});var d=c(716),e=c(87538);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={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),a({type:"extension_ui_request",id:c,method:"custom",closed:!0,lines:[]}),d(b))},k=()=>{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})};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 l=function(a,b=92,c=40){return Object.freeze({terminal:Object.freeze({columns:b,rows:c,kittyProtocolActive:!1}),requestRender:a})}(()=>{k()},92,40),m=(0,e.Lm)()??j.theme;Promise.resolve().then(()=>b(l,m,{},h)).then(a=>{g||(f=a,k())}).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:j,pending:b,statuses:g,widgets:h,pendingSnapshot:c,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(),g.clear(),h.clear()}}}},40239:(a,b,c)=>{c.d(b,{$T:()=>m,Iq:()=>g,J3:()=>t,Ki:()=>u,YV:()=>q,mT:()=>r,rQ:()=>p,uD:()=>s});var d=c(29021),e=c(33873),f=c(60396);let g={existsSync:d.existsSync,lstatSync:d.lstatSync,mkdirSync:d.mkdirSync,readFileSync:(a,b)=>(0,d.readFileSync)(a,b),writeFileSync:(a,b,c)=>(0,d.writeFileSync)(a,b,c),renameSync:d.renameSync,unlinkSync:d.unlinkSync,readdirSync:d.readdirSync};function h(a=(0,f.$M)()){return(0,e.join)(a,"pidance-archive")}function i(a){return"string"!=typeof a||a.length<8||a.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(a)?null:`${a}.json`}function j(a,b){try{let c=h(b);if(!a.existsSync(c))return null;let d=a.lstatSync(c);if(d.isSymbolicLink()||!d.isDirectory())return null;return c}catch{return null}}function k(a){return"object"==typeof a&&null!==a&&!(1!==a.version||"string"!=typeof a.sessionId||0===a.sessionId.length||"string"!=typeof a.sessionPath||0===a.sessionPath.length||"string"!=typeof a.archivedAt||Number.isNaN(Date.parse(a.archivedAt)))}function l(a,b,c){let d=i(c);if(!d)return null;let f=j(a,b);if(!f)return null;let g=(0,e.join)(f,d);try{if(!a.existsSync(g)||a.lstatSync(g).isSymbolicLink())return null;let b=a.readFileSync(g,"utf8");if(b.length>65536)return null;let d=JSON.parse(b);if(!k(d)||d.sessionId!==c)return null;return d}catch{return null}}function m(a,b){let c=globalThis.__piArchiveRecordsCache;if(c&&Date.now()-c.ts<5e3)return c.records;let d=j(a,b),e=[];if(d){let c=[];try{c=a.readdirSync(d)}catch{c=[]}for(let d of c){let c=function(a){if("string"!=typeof a||!a.endsWith(".json"))return null;let b=a.slice(0,-5);return b.length<8||b.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(b)?null:b}(d);if(!c)continue;let f=l(a,b,c);f&&e.push(f)}}return globalThis.__piArchiveRecordsCache={records:e,ts:Date.now()},e}function n(){globalThis.__piArchiveRecordsCache=void 0}function o(a,b,c){let d=i(c);if(!d)return!1;let f=j(a,b);if(!f)return!1;let g=(0,e.join)(f,d);try{if(!a.existsSync(g))return!1;return a.unlinkSync(g),n(),!a.existsSync(g)}catch{return!1}}function p(a,b,c){o(a,b,c)}function q(a,b){let c=new Map;for(let a of b)c.set(a.sessionId,a);let d=new Set;for(let b of a){let a=c.get(b.id);a&&a.sessionPath===b.path&&d.add(b.id)}return d}function r(a,b,c,d){let e=q(b,c),f=new Set;for(let b of a){let a=e.has(b);("active"===d?!a:a)&&f.add(b)}return f}function s(a,b){let c=q(a,b),d=new Map;for(let a of b)d.set(a.sessionId,a);let e=[],f=[];for(let b of a)if(c.has(b.id)){let a=d.get(b.id);f.push({...b,archivedAt:a?a.archivedAt:void 0})}else e.push(b);return{active:e,archived:f}}class t extends Error{constructor(){super("Session is running; cannot archive while active")}toString(){return this.message}}function u(a){let b=a.fs??g,c=()=>a.agentDir?.()??(0,f.$M)(),d=async d=>{if(await a.isReadOnly(d))throw Error("Subagent sessions are read-only");if(a.isRunning(d))throw new t;let f=await a.resolveSessionPath(d);if(!f)throw Error("Session not found");let g=a.readSessionHeader(f);if(!g||g.id!==d)throw Error("Session header id mismatch");let j={version:1,sessionId:d,sessionPath:f,archivedAt:a.now()};return!function(a,b,c){let d=i(c.sessionId);if(!d)throw Error("Invalid session id");if(!k(c))throw Error("Invalid archive record");let f=function(a,b){let c=h(b);try{a.existsSync(c)||a.mkdirSync(c,{recursive:!0});let b=a.lstatSync(c);if(b.isSymbolicLink()||!b.isDirectory())return null;return c}catch{return null}}(a,b);if(!f)throw Error("Archive directory unavailable");let g=(0,e.join)(f,d),j=(0,e.join)(f,`.${d}.${process.pid}.${Date.now().toString(36)}.tmp`);try{a.writeFileSync(j,JSON.stringify(c),{encoding:"utf8",flag:"wx"}),a.renameSync(j,g),n()}catch(b){try{a.existsSync(j)&&a.unlinkSync(j)}catch{}throw b}}(b,c(),j),a.invalidateSessionListCache(),j.archivedAt},j=async d=>{if(null===l(b,c(),d))throw Error("Session is not archived");if(!await a.resolveSessionPath(d))throw Error("Session not found");if(!o(b,c(),d))throw Error("Failed to remove archive record");return a.invalidateSessionListCache(),a.getSessionInfo(d)},m=async a=>{let b=[],c=[];for(let e of a)try{await d(e),b.push(e)}catch(a){c.push({id:e,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}},p=async a=>{let b=[],c=[];for(let d of a)try{await j(d),b.push(d)}catch(a){c.push({id:d,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}};return{archiveSession:d,restoreSession:j,archiveSessions:m,restoreSessions:p}}},46935:(a,b,c)=>{c.d(b,{G1:()=>h,NN:()=>g,PV:()=>i,Uf:()=>d,WP:()=>j,_w:()=>e,tr:()=>k});let d=80,e=80;function f(a,b){return"number"==typeof a&&Number.isFinite(a)?Math.max(1,Math.min(Math.floor(a),500)):b}function g(a,b=d){let c=a.get("limit")??a.get("tail");if(null===c||""===c)return null;let e=Number(c);return!Number.isFinite(e)||e<=0?b:f(e,b)}function h(a,b=d){let c=a.messages.length,e=f(b,d);if(c<=e)return{...a,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:c};let g=c-e;return{messages:a.messages.slice(g),entryIds:a.entryIds.slice(g),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:c}}function i(a,b,c=e,d={}){let g=a.messages.length,h=a.entryIds.indexOf(b);if(h<0)return null;let j=f(c,e),k=Math.max(0,h-Math.max(1,Math.floor(j/2))),l=d.toEnd?g:Math.min(g,k+j);return{messages:a.messages.slice(k,l),entryIds:a.entryIds.slice(k,l),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:k>0,hasMoreAfter:l<g,totalMessageCount:g}}function j(a,b,c=e){let d=a.messages.length,g=a.entryIds.indexOf(b);if(g<0||g>=d-1)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:d};let h=Math.min(d,g+1+f(c,e));return{messages:a.messages.slice(g+1,h),entryIds:a.entryIds.slice(g+1,h),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:h<d,totalMessageCount:d}}function k(a,b,c=e){let d=a.messages.length,g=a.entryIds.indexOf(b);if(g<=0)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:d};let h=Math.max(0,g-f(c,e));return{messages:a.messages.slice(h,g),entryIds:a.entryIds.slice(h,g),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:h>0,hasMoreAfter:!0,totalMessageCount:d}}},52960:(a,b,c)=>{c.d(b,{D_:()=>i,JT:()=>h,QR:()=>j});var d=c(13737);function e(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`sub-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function f(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");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 g(a){if("string"!=typeof a.message)throw Error("message is required");return a.message}function h(a,b=e){return{type:"prompt",message:g(a),submissionId:"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b(),images:f(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 i(a){return"prompt"===a||"abort"===a||"steer"===a||"follow_up"===a}function j(a,b=e){if(!a||"object"!=typeof a||Array.isArray(a))throw Error("command is required");let c=a.type;if("prompt"===c)return h(a,b);if("abort"===c)return{type:"abort"};if("steer"===c)return{type:"steer",message:g(a),images:f(a.images)};if("follow_up"===c)return{type:"follow_up",message:g(a),images:f(a.images)};throw Error(`Unsupported message command: ${String(c)}`)}},53023:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Uj:()=>j});var e=c(85664),f=c(93127),g=c(95237),h=a([f,g]);function i(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}[f,g]=h.then?(await h)():h;let k=`
1
+ "use strict";exports.id=7594,exports.ids=[7594],exports.modules={1060:(a,b,c)=>{c.d(b,{Ac:()=>n,GO:()=>i,X:()=>k,_4:()=>d,cV:()=>j,k2:()=>l,oC:()=>m});let d=262144,e={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},f={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},g={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},h={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function i(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function j(a){return e[i(a)]??null}function k(a){return f[i(a)]??null}function l(a){return g[i(a)]??null}function m(a){return h[i(a)]??null}function n(a){let b=i(a);return"pdf"===b||"docx"===b?b:null}},2416:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>y,v7:()=>z});var e=c(75430),f=c(60396),g=c(68524),h=c(89953),i=c(5815),j=c(69835),k=c(99014),l=c(85664),m=c(65107),n=c(95237),o=c(38195),p=c(62693),q=c(31524),r=c(52960),s=c(13737),t=c(60185),u=c(28121),v=c(87538),w=a([e,j,n,t,u]);[e,j,n,t,u]=w.then?(await w)():w;let z="Session writer is busy: a command is still in flight";function x(a){return"string"==typeof a&&a?a:void 0}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,v.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||this.listeners.length>0)return;if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();let a=this.idleTimeoutMs;this.idleTimer=setTimeout(()=>{if((this.idleTimer=null,!this.isRunning()&&!this.flushingFollowUp)&&!(this.listeners.length>0)){if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();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,r.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=x(a.method);if("setStatus"===b){let b=x(a.statusKey)??x(a.key)??"default",c=x(a.statusText)??x(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=x(a.widgetKey)??x(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(s.uG,a);this.emit({type:"message_end",entryId:e,message:(0,s.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,v.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,v.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,v.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,v.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,u._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:u.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:u.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:u.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,q.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,t.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(s.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,s.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,r.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,t.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){let a=this.reject(c.submissionId,"bash");return this.promptReceipts.set(c.submissionId,a),a}if(d.isCompacting){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||(this.promptRunning||d.isStreaming)&&"steer"!==a.streamingBehavior){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,r.K2)(g);if(d.isStreaming&&(0,r.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,q.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return d.model&&(0,q.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,r._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,r.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,r.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,r.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,r.$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=x(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=x(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=x(a.targetId);if(!b)throw Error("targetId is required");let c=await d.navigateTree(b,{summarize:a.summarize,customInstructions:x(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=x(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=x(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=x(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=x(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(z);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 y(a){let b=new A(a);return await b.start(),b}d()}catch(a){d(a)}})},5815:(a,b,c)=>{c.d(b,{MG:()=>h,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)}function h(){return e()}},26773:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>u,A4:()=>m,DU:()=>o,EM:()=>r,Fn:()=>t,HG:()=>q,OF:()=>w});var e=c(40402),f=c(95237);c(68524);var g=c(2416),h=c(5815),i=c(89953),j=a([e,f,g]);function k(){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 l(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function m(a){return k().get(a)}function n(){return[...l().keys()]}async function o(a){let b=l().get(a);if(!b)return null;try{return(await b).realSessionId}catch{return null}}function p(){let a=new Set(n());for(let[b,c]of k())c.isRunning()&&a.add(c.sessionId||b);return[...a]}function q(){return p()}[e,f,g]=j.then?(await j)():j;let y=new Map;function r(a,b=Date.now()){let c={},d=(0,h.MG)(),e=p(),f=new Set(e);for(let a of e){let e=d.get(a)??y.get(a)??b;y.set(a,e),c[a]=e}for(let a of[...y.keys()])f.has(a)||y.delete(a);return c}function s(){return globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners}function t(a){let b=s();return b.add(a),()=>{b.delete(a)}}function u(){let a=[];for(let[b,c]of k()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}let z="",A=new Set,B=null;function v(){!function a(){let b=new Set(function(){let a=new Set(n());for(let[b,c]of k())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,i.AZ)(a),A.add(a);for(let a of[...A])b.has(a)||((0,i.Hl)(a),A.delete(a));if(0===b.size){B&&(clearInterval(B),B=null);return}B||(B=setInterval(()=>{a()},8e3),B.unref?.())}();let a=q(),b=u(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c!==z)for(let b of(z=c,s()))try{b(a)}catch{}}async function w(a,b,c,d,e){return x(a,b,c,d,e)}async function x(a,b,c,d,f){let h=k(),j=l(),m=h.get(a);if(m?.isAlive())return{session:m,realSessionId:a};let n=j.get(a);if(n)return n;if(!(0,i.kP)(a))throw Error(i.GT);v();let o=(async()=>{try{let j=await (0,g.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>v(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=k(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,i.kP)(b),(0,i.Hl)(a))}}),l=j.sessionId,m=j.sessionFile;return m&&(0,e.O8)(l,m),l!==a&&(0,i.kP)(l),j.onDestroy(()=>{h.get(l)===j&&h.delete(l),a!==l&&h.get(a)===j&&h.delete(a),(0,i.Hl)(l),a!==l&&(0,i.Hl)(a),v()}),h.set(l,j),j.beginExtensionBinding(),{session:j,realSessionId:l}}catch(b){throw(0,i.Hl)(a),v(),b}})().finally(()=>{j.delete(a),v()});return j.set(a,o),o}d()}catch(a){d(a)}})},28121:(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(69835),j=c(80547),k=c(1060),l=c(60185),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)}})},31524:(a,b,c)=>{c.d(b,{Ut:()=>e,eU:()=>f,yu:()=>g});let d=["off","minimal","low","medium","high","xhigh","max"];function e(a,b){return a?d.filter(a=>b?.[a]!==null):["off"]}function f(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 g(a){let b=f(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}},37594:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{C9:()=>L,DQ:()=>K,Md:()=>I,Wl:()=>J,Yz:()=>H,mB:()=>P});var e=c(29021),f=c(716),g=c(33873),h=c(80547),i=c(91898),j=c(60396),k=c(95237),l=c(52960),m=c(79495),n=c(81879),o=c(46935),p=c(31514),q=c(65107),r=c(56429),s=c(40402),t=c(85664),u=c(15461),v=c(76817),w=c(86226),x=c(68524),y=c(89953),z=c(50955),A=c(40239),B=c(5815),C=c(99911),D=c(26773),E=c(2416),F=c(68816),G=a([h,i,k,n,r,s,D,E]);[h,i,k,n,r,s,D,E]=G.then?(await G)():G;let K="Subagent sessions are read-only";class L extends Error{constructor(){super(K)}toString(){return this.message}}async function H(a,b){if(await b(a))throw new L}function I(a){let b=a instanceof Error?a.message:String(a);return a instanceof L||b===K?403:b.includes("Session not found")?404:(0,y.wE)(a)||b===y.GT||b===E.v7||"Session is being deleted"===b||b.includes("closed while its title")?409:500}function J(a){let b=a instanceof Error?a.message:String(a);return"cwd is required"===b||b.startsWith("Directory does not exist:")?400:I(a)}let M="Submission was cancelled",N={listAllSessions:s.dQ,resolveSessionPath:s.os,getRpcSession:r.A4,waitForSessionStart:r.DU,startRpcSession:r.OF,getRunningRpcSessionIds:r.HG,listPendingExtensionUi:r.$k,subscribeRunningSessions:r.Fn,allowFileRoot:h.wz,invalidateSessionListCache:s.mD,openSessionCwd:a=>(0,k.kW)(a).getHeader()?.cwd??process.cwd(),openSessionManager:a=>(0,s.Zx)({filePath:a}),openSessionView:k.kW,reparentSessionFile:k.i5,existsSync:e.existsSync,now:()=>Date.now(),archiveFs:A.Iq},O=["systemPrompt"],P=function(a={}){let b={...N,...a},c=(0,A.Ki)({fs:b.archiveFs,agentDir:b.archiveAgentDir,resolveSessionPath:b.resolveSessionPath,readSessionHeader:s.eP,isReadOnly:async a=>{let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},isRunning:a=>b.getRunningRpcSessionIds().includes(a),getSessionInfo:async a=>(await b.listAllSessions()).find(b=>b.id===a)??null,invalidateSessionListCache:b.invalidateSessionListCache,now:()=>new Date(b.now()).toISOString()}),d=()=>(0,A.$T)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)()),h=new Map,r=new Map,E=a=>{if(r.set(a.submissionId,{info:a,cancelRequested:!1,cancelApplied:!1}),!(r.size<=500))for(let[b,c]of r){if(r.size<=500)break;b!==a.submissionId&&"completed"===c.info.status&&r.delete(b)}},G=async a=>{let c=b.getRpcSession(a);if(c){if("function"==typeof c.destroyAsync)return void await c.destroyAsync();c.isAlive()&&c.destroy()}},I=async(a,b)=>{if(!(0,y.kP)(a))throw Error(y.GT);try{return await b()}finally{(0,y.Hl)(a)}},J=async(a,b,c)=>(c?await c():await G(a),I(a,b)),K={async listSessions(){let a=await b.listAllSessions(),{active:c,archived:e}=(0,A.uD)(a,d());return{sessions:c,archivedSessions:e,archivedCount:e.length,runningSessionIds:b.getRunningRpcSessionIds()}},async listArchivedSessions(){let a=await b.listAllSessions();return(0,A.uD)(a,d()).archived},async listActiveSessions(){let a=await b.listAllSessions();return(0,A.uD)(a,d()).active},listAllSessions:async()=>b.listAllSessions(),async isArchived(a){let c=await b.listAllSessions();return(0,A.YV)(c,d()).has(a)},archiveSession:async a=>c.archiveSession(a),restoreSession:async a=>c.restoreSession(a),archiveSessions:async a=>c.archiveSessions(a),restoreSessions:async a=>c.restoreSessions(a),removeArchiveRecordAfterPermanentDelete(a){(0,A.rQ)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)(),a)},resolvePath:a=>b.resolveSessionPath(a),getSessionInfo:async a=>a&&"string"==typeof a?(await b.listAllSessions()).find(b=>b.id===a)??null:null,async isReadOnly(a){let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},async getReadView(a){let c=await b.resolveSessionPath(a);if(!c)return null;let d=b.getRpcSession(a),e=d?.inner;return d?.isAlive()&&e?.sessionManager?{source:"live",filePath:c,manager:e.sessionManager}:{source:"disk",filePath:c,manager:b.openSessionManager(c)}},getLive(a){let c=b.getRpcSession(a);return c?.isAlive()?c:void 0},getLiveSession:a=>K.getLive(a),isLive:a=>!!K.getLive(a),async ensureLive(a){if(await H(a,K.isReadOnly),h.has(a))throw Error("Session is being deleted");let c=K.getLive(a);if(c)return c;if((0,y.wy)(a))throw Error(y.GT);let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=b.openSessionCwd(d),{session:f}=await b.startRpcSession(a,d,e,void 0,L);return f},destroy(a){b.getRpcSession(a)?.destroy()},async destroyAsync(a){let c=b.getRpcSession(a);c&&("function"==typeof c.destroyAsync?await c.destroyAsync():c.destroy())},deleteSession(a){let c=h.get(a);if(c)return c;let d=(async()=>{await H(a,K.isReadOnly);let c=await b.waitForSessionStart?.(a)??a,d=await b.resolveSessionPath(a);if(!d){try{(0,x.xP)(`sessionQueue.${a}`,null),(0,x.xP)(`sessionQueueHold.${a}`,null)}catch(a){console.error("[pidance] failed to clear queue prefs after missing delete:",a)}return(0,s.BR)(a),b.invalidateSessionListCache(),K.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:0}}if((0,y.wy)(a)||(0,y.wy)(c))throw Error(y.GT);let f=(0,s.eP)(d)?.parentSession,h=(0,s.eP)(d)?.id===a?(0,z.ku)(d,a):[],j=b.getRpcSession(c)??b.getRpcSession(a),k=b.getRunningRpcSessionIds();if(j?.isAlive?.()&&(k.includes(a)||k.includes(c)))try{await j.send({type:"abort"})}catch(a){console.error("[pidance] abort before delete failed:",a)}return await K.destroyAsync(j?.sessionId??c),I(j?.sessionId??c,async()=>{let c=d.replace(/\\/g,"/").split("/").slice(0,-1).join("/");try{for(let a of(0,e.readdirSync)(c).filter(a=>a.endsWith(".jsonl")&&(0,g.join)(c,a)!==d)){let e=(0,g.join)(c,a);try{let a=(0,s.eP)(e);a?.type==="session"&&a.parentSession===d&&(a.id?(await b.waitForSessionStart?.(a.id),await J(a.id,()=>{b.reparentSessionFile(e,f)})):b.reparentSessionFile(e,f))}catch{}}}catch{}try{(0,e.unlinkSync)(d)}catch(a){if("ENOENT"!==a.code)throw a}(0,q.$9)(d);let j=(0,g.resolve)(d.slice(0,-6)),k=(0,z.uq)(h,j,s.BR);try{(0,x.xP)(`sessionQueue.${a}`,null),(0,x.xP)(`sessionQueueHold.${a}`,null)}catch(a){console.error("[pidance] failed to clear queue prefs after delete:",a)}try{(0,i.Fx)()}catch(a){console.error("[pidance] failed to sweep attachments:",a)}return(0,s.BR)(a),b.invalidateSessionListCache(),K.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:k}})})();return h.set(a,d),d.finally(()=>{h.get(a)===d&&h.delete(a)})},async start(a,c,d,e){if(await H(a,K.isReadOnly),h.has(a))throw Error("Session is being deleted");return b.startRpcSession(a,c,d,e,L)},send:async(a,b)=>(await K.ensureLive(a)).send(b),async submitPrompt(a,b){await H(a,K.isReadOnly);let c=(0,l.JT)(b);try{let b=await K.send(a,c);if(b&&"object"==typeof b&&b.status)return b;return{submissionId:c.submissionId,sessionId:a,status:"rejected",reason:"error"}}catch(b){if((0,y.wE)(b))throw b;return{submissionId:c.submissionId,sessionId:a,status:"rejected",reason:(0,l.K2)(b)}}},async getAgentState(a,b){if(await K.isReadOnly(a))return{live:!1,activeRun:!1,readOnly:!0};let c=K.getLive(a);if(!c)return{live:!1,activeRun:!1,...(0,y.wy)(a)?{lockedByOther:!0}:{}};let d=await c.send({type:"get_state"}),e="function"==typeof c.isRunning?!!c.isRunning():!!(d&&(d.isStreaming||d.isPromptRunning||d.isCompacting||d.isBashRunning));return{live:!0,activeRun:e,lockedByOther:!1,state:function(a,b){if(!b?.light||!a||"object"!=typeof a||Array.isArray(a))return a;let c={...a};for(let a of O)delete c[a];return c}(d,b)}},async renameSession(a,c){await H(a,K.isReadOnly);let d=c.trim();if(!d)throw Error("name is required");let e=K.getLive(a);if(e?.isAlive()){await e.send({type:"set_session_name",name:d}),b.invalidateSessionListCache();return}let f=await b.resolveSessionPath(a);if(!f)throw Error("Session not found");await J(a,()=>{b.openSessionView(f).appendSessionInfo(d),b.invalidateSessionListCache()})},async autoNameSession(a){await H(a,K.isReadOnly);let b=await K.ensureLive(a);await b.waitUntilReady?.();let c=await K.getNavigationSnapshot(a);if(!c)throw Error("Session not found");let d=c.context.messages??[],e=(0,m.CL)(),f=await (0,m.K)({messages:d,provider:e.provider,modelId:e.modelId,baseUrl:e.baseUrl,api:e.api,apiKey:e.apiKey,headers:e.headers});if(!b.isAlive())throw Error("The session was closed while its title was being generated. Please try again.");try{await b.send({type:"set_session_name",name:f.title})}catch{await K.destroyAsync(a),await K.renameSession(a,f.title)}return{title:f.title,usage:f.usage??null}},async exportSession(a,c){let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");return(0,n.by)(d,c)},async getNavigationSnapshot(a,c={}){let d=await K.getReadView(a);if(!d)return null;let{filePath:e,manager:f}=d,{leafId:g,tree:h,context:i,header:j,sessionName:k}=(0,s.jK)(f,c),l=j?.parentSession?await (0,s.u1)(j.parentSession):void 0,m=(await b.listAllSessions()).find(b=>b.id===a),n=j?{path:e,id:j.id,cwd:j.cwd??"",name:k,created:j.timestamp,modified:j.timestamp,messageCount:i.totalMessageCount??i.messages.length,firstMessage:m?.firstMessage??"(no messages)",parentSessionId:l,...m?.subagent?{subagent:m.subagent,readOnly:!0}:{}}:null;return{filePath:e,leafId:g,tree:h,context:i,header:j,sessionName:k,parentSessionId:l,info:n}},async getUserMessageOutline(a){let b=await K.getReadView(a);if(!b)return[];let c=b.manager,d=c.getEntries?.()??[],e=(0,s.CM)(d,c.getLeafId());return(0,C.Xm)((0,s.tY)(d,e))},async getContextPage(a,b){let c,d=await K.getReadView(a);if(!d)return{context:null};let e=d.manager,f=e.getEntries?.()??[],g=(0,s.Uv)(f,b.leafId,{deferThinking:b.deferThinking,deferToolResultImages:b.deferToolResultImages}),h=b.limit;if(b.around){let a=(0,o.PV)(g,b.around,h??o._w,{toEnd:!0===b.aroundToEnd});if(!a)return{context:null,notFound:b.around};c=a}else c=b.after?(0,o.WP)(g,b.after,h??o._w):b.before?(0,o.tr)(g,b.before,h??o._w):null!==h?(0,o.G1)(g,h):{...g,hasMoreBefore:!1,totalMessageCount:g.messages.length};return{context:c}},async getEntryThinking(a,b,c){let d=await K.getReadView(a);if(!d)return null;let e=d.manager.getEntries().find(a=>a.id===b);if(!e||"message"!==e.type||e.message?.role!=="assistant")return null;let f=e.message.content?.[c];return f&&(0,p.mv)(f.type)?{thinking:(0,p.Ux)(f)}:null},async getToolResultDetails(a,b){let c=await K.getReadView(a);if(!c)return null;let d=c.manager.getEntries().find(a=>"message"===a.type&&a.message?.role==="toolResult"&&a.message.toolCallId===b);return d?{details:d.message?.details??null,content:Array.isArray(d.message?.content)?d.message.content:[]}:null},async appendActivity(a,c){await H(a,K.isReadOnly);let d=K.getLive(a),e=!!d?.inner?.sessionManager,f=d?.appendActivity;return d?.isAlive()&&e&&"function"==typeof f?await f.call(d,c):await J(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,t.l$)(c),f=b.openSessionView(d).appendCustomEntry(t.cP,e);return b.invalidateSessionListCache(),{entryId:f,activity:e}})},appendCommandEntry:async(a,c)=>(await H(a,K.isReadOnly),await J(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,u.fc)(c);if(!e.command)throw Error("command is required");let f=b.openSessionView(d).appendCustomEntry(u.OE,e);return b.invalidateSessionListCache(),{entryId:f,data:e}})),async createNew({cwd:a,command:c}){let d;if(!a||"string"!=typeof a)throw Error("cwd is required");if(!b.existsSync(a))throw Error(`Directory does not exist: ${a}`);let{provider:e,modelId:g,toolNames:h,thinkingLevel:i,...j}=c,l="string"==typeof j.submissionId?j.submissionId:void 0,m=(d="string"==typeof j.message?j.message:"",`${a}\u0000${d}`);if(l){let a=r.get(l);if(a){if(a.info.fingerprint&&a.info.fingerprint!==m)throw a.info.status="conflict",Error("Submission conflict: this submissionId was already used with different content");if(a.cancelRequested)throw a.info.status="cancelled",Error(M);if(a.info.sessionId)return{sessionId:a.info.sessionId,data:null}}E({submissionId:l,status:"pending",fingerprint:m})}let n=`__new__${(0,f.randomUUID)()}`,{session:o,realSessionId:p}=await b.startRpcSession(n,"",a,h,L),q=l?r.get(l):void 0,s=q?.cancelRequested===!0;q&&(q.info.sessionId=p,q.info.status=s?"cancelled":"starting"),b.allowFileRoot(a),b.invalidateSessionListCache();try{if(s||(e&&g&&await o.send({type:"set_model",provider:e,modelId:g}),i&&await o.send({type:"set_thinking_level",level:i}),l&&r.get(l)?.cancelRequested))throw await K.destroyAsync(p),Error(M)}catch(a){throw q&&(q.info.error=a instanceof Error?a.message:String(a)),a}if("ensure_session"===j.type){try{let a=o.inner,b=a?.sessionManager;b&&"function"==typeof b.getSessionFile&&(0,k.kb)(b)}catch(a){console.error("[pidance] materialize ensure_session failed:",a)}return{sessionId:p,data:null}}let t=await o.send(j);return q&&(q.info.status="accepted",q.info.sessionId=p),{sessionId:p,data:t}},getSubmission(a){let b=r.get(a);return b?{...b.info}:null},cancelSubmission(a){let c=r.get(a);if(!c)return E({submissionId:a,status:"cancelled"}),r.get(a).cancelRequested=!0,Promise.resolve({submissionId:a,status:"pending"});c.cancelRequested=!0;let d=c.info.sessionId;if(!d)return c.info.status="cancelled",Promise.resolve({submissionId:a,status:"pending"});if(c.cancelApplied)return Promise.resolve({submissionId:a,status:"confirmed"});c.cancelApplied=!0,c.info.status="cancelled";let e=b.getRpcSession(d);return e?.isAlive()?(async()=>{try{await e.send({type:"abort"})}catch(a){console.error("[pidance] cancel submission abort failed:",a)}return{submissionId:a,status:"confirmed"}})():Promise.resolve({submissionId:a,status:"confirmed"})},getRunningIds:()=>b.getRunningRpcSessionIds(),getRunningStartedAt(){let a=new Set(b.getRunningRpcSessionIds()),c={};for(let[b,d]of(0,B.MG)())a.has(b)&&(c[b]=d);for(let[b,d]of Object.entries((0,D.EM)()))!a.has(b)||b in c||(c[b]=d);return c},async searchFulltext(a,c={}){let d=await (0,F.s)(a,{limits:void 0!==c.maxHits?{maxHits:c.maxHits}:void 0}),e=c.scope??"active";if("all"===e)return d;let f=await b.listAllSessions(),g=(0,A.$T)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)()),h=(0,A.mT)(d.sessionIds,f,g,e);return{...d,sessionIds:d.sessionIds.filter(a=>h.has(a)),hits:d.hits.filter(a=>h.has(a.sessionId))}},listPendingExtensionUi:()=>b.listPendingExtensionUi(),subscribeRunning:a=>b.subscribeRunningSessions(a),async selectLeafExact(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let f=c.trim(),g=b.getRpcSession(a);if(g?.isAlive?.()&&g.inner?.isBashRunning)throw Error("Cannot switch branch while a shell command is running");return e=async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=b.openSessionView(c),e=d.getLeafId();if(f===e)return{cancelled:!1};if(f===d.getLastEntryId())return(0,q.$9)(c),{cancelled:!1};if(!d.getEntry(f))throw Error(`Entry ${f} not found`);try{return d.branch(f),(0,q.R3)(c,f),{cancelled:!1}}finally{b.invalidateSessionListCache()}},J(a,e,d)},async branchFromAssistant(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("assistantEntryId is required");let f=c.trim(),g=b.getRpcSession(a);if(g?.isAlive?.()&&g.inner?.isBashRunning)throw Error("Cannot branch while a shell command is running");return e=async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=b.openSessionView(c),e=d.getLeafId();if(!e)throw Error("Session has no leaf");let g=d.getBranch(e),h=d.getEntry(f);if(!h)throw Error("Entry not found");if("message"!==h.type||h.message?.role!=="assistant")throw Error("Only assistant messages can be branched from");let i=(0,v.wo)(g,f);try{return d.branch(i),i===d.getLastEntryId()?(0,q.$9)(c):(0,q.R3)(c,i),{cancelled:!1}}finally{b.invalidateSessionListCache()}},J(a,e,d)},async createSessionFromLeaf(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let f=c.trim(),g=b.getRpcSession(a),h=g?.inner;return e=async()=>{let c=(h?.sessionFile||g?.sessionFile)??await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=(0,k.kW)(c),e=d.getEntry(f);if(!e)throw Error("Invalid entry ID");let i=f;if("message"===e.type&&e.message?.role==="assistant"){let a=d.getLeafId();if(!a)throw Error("Session has no leaf");let b=d.getBranch(a);i=(0,v.wo)(b,f)}let j=d.getSessionDir(),l=(0,k.G1)(c,j),m=l.createBranchedSession(i);if(!m)throw Error("Failed to create session");(0,k.kb)(l);let n=(0,k.kW)(m,j),o=n.getSessionId();(0,s.O8)(o,m),b.invalidateSessionListCache();let p=h?.model;return p&&(0,w.yN)(n.getEntries().some(a=>"model_change"===a.type),{provider:p.provider,modelId:p.id})&&n.appendModelChange(p.provider,p.id),{cancelled:!1,newSessionId:o}},J(a,e,d)}},L={selectLeafExact:(a,b,c)=>K.selectLeafExact(a,b,c),branchFromAssistant:(a,b,c)=>K.branchFromAssistant(a,b,c),createSessionFromLeaf:(a,b,c)=>K.createSessionFromLeaf(a,b,c)};return K}();d()}catch(a){d(a)}})},38195:(a,b,c)=>{c.d(b,{t:()=>g});var d=c(716),e=c(87538);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()}}}},40239:(a,b,c)=>{c.d(b,{$T:()=>m,Iq:()=>g,J3:()=>t,Ki:()=>u,YV:()=>q,mT:()=>r,rQ:()=>p,uD:()=>s});var d=c(29021),e=c(33873),f=c(60396);let g={existsSync:d.existsSync,lstatSync:d.lstatSync,mkdirSync:d.mkdirSync,readFileSync:(a,b)=>(0,d.readFileSync)(a,b),writeFileSync:(a,b,c)=>(0,d.writeFileSync)(a,b,c),renameSync:d.renameSync,unlinkSync:d.unlinkSync,readdirSync:d.readdirSync};function h(a=(0,f.$M)()){return(0,e.join)(a,"pidance-archive")}function i(a){return"string"!=typeof a||a.length<8||a.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(a)?null:`${a}.json`}function j(a,b){try{let c=h(b);if(!a.existsSync(c))return null;let d=a.lstatSync(c);if(d.isSymbolicLink()||!d.isDirectory())return null;return c}catch{return null}}function k(a){return"object"==typeof a&&null!==a&&!(1!==a.version||"string"!=typeof a.sessionId||0===a.sessionId.length||"string"!=typeof a.sessionPath||0===a.sessionPath.length||"string"!=typeof a.archivedAt||Number.isNaN(Date.parse(a.archivedAt)))}function l(a,b,c){let d=i(c);if(!d)return null;let f=j(a,b);if(!f)return null;let g=(0,e.join)(f,d);try{if(!a.existsSync(g)||a.lstatSync(g).isSymbolicLink())return null;let b=a.readFileSync(g,"utf8");if(b.length>65536)return null;let d=JSON.parse(b);if(!k(d)||d.sessionId!==c)return null;return d}catch{return null}}function m(a,b){let c=globalThis.__piArchiveRecordsCache;if(c&&Date.now()-c.ts<5e3)return c.records;let d=j(a,b),e=[];if(d){let c=[];try{c=a.readdirSync(d)}catch{c=[]}for(let d of c){let c=function(a){if("string"!=typeof a||!a.endsWith(".json"))return null;let b=a.slice(0,-5);return b.length<8||b.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(b)?null:b}(d);if(!c)continue;let f=l(a,b,c);f&&e.push(f)}}return globalThis.__piArchiveRecordsCache={records:e,ts:Date.now()},e}function n(){globalThis.__piArchiveRecordsCache=void 0}function o(a,b,c){let d=i(c);if(!d)return!1;let f=j(a,b);if(!f)return!1;let g=(0,e.join)(f,d);try{if(!a.existsSync(g))return!1;return a.unlinkSync(g),n(),!a.existsSync(g)}catch{return!1}}function p(a,b,c){o(a,b,c)}function q(a,b){let c=new Map;for(let a of b)c.set(a.sessionId,a);let d=new Set;for(let b of a){let a=c.get(b.id);a&&a.sessionPath===b.path&&d.add(b.id)}return d}function r(a,b,c,d){let e=q(b,c),f=new Set;for(let b of a){let a=e.has(b);("active"===d?!a:a)&&f.add(b)}return f}function s(a,b){let c=q(a,b),d=new Map;for(let a of b)d.set(a.sessionId,a);let e=[],f=[];for(let b of a)if(c.has(b.id)){let a=d.get(b.id);f.push({...b,archivedAt:a?a.archivedAt:void 0})}else e.push(b);return{active:e,archived:f}}class t extends Error{constructor(){super("Session is running; cannot archive while active")}toString(){return this.message}}function u(a){let b=a.fs??g,c=()=>a.agentDir?.()??(0,f.$M)(),d=async d=>{if(await a.isReadOnly(d))throw Error("Subagent sessions are read-only");if(a.isRunning(d))throw new t;let f=await a.resolveSessionPath(d);if(!f)throw Error("Session not found");let g=a.readSessionHeader(f);if(!g||g.id!==d)throw Error("Session header id mismatch");let j={version:1,sessionId:d,sessionPath:f,archivedAt:a.now()};return!function(a,b,c){let d=i(c.sessionId);if(!d)throw Error("Invalid session id");if(!k(c))throw Error("Invalid archive record");let f=function(a,b){let c=h(b);try{a.existsSync(c)||a.mkdirSync(c,{recursive:!0});let b=a.lstatSync(c);if(b.isSymbolicLink()||!b.isDirectory())return null;return c}catch{return null}}(a,b);if(!f)throw Error("Archive directory unavailable");let g=(0,e.join)(f,d),j=(0,e.join)(f,`.${d}.${process.pid}.${Date.now().toString(36)}.tmp`);try{a.writeFileSync(j,JSON.stringify(c),{encoding:"utf8",flag:"wx"}),a.renameSync(j,g),n()}catch(b){try{a.existsSync(j)&&a.unlinkSync(j)}catch{}throw b}}(b,c(),j),a.invalidateSessionListCache(),j.archivedAt},j=async d=>{if(null===l(b,c(),d))throw Error("Session is not archived");if(!await a.resolveSessionPath(d))throw Error("Session not found");if(!o(b,c(),d))throw Error("Failed to remove archive record");return a.invalidateSessionListCache(),a.getSessionInfo(d)},m=async a=>{let b=[],c=[];for(let e of a)try{await d(e),b.push(e)}catch(a){c.push({id:e,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}},p=async a=>{let b=[],c=[];for(let d of a)try{await j(d),b.push(d)}catch(a){c.push({id:d,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}};return{archiveSession:d,restoreSession:j,archiveSessions:m,restoreSessions:p}}},46935:(a,b,c)=>{c.d(b,{G1:()=>h,NN:()=>g,PV:()=>i,Uf:()=>d,WP:()=>j,_w:()=>e,tr:()=>k});let d=80,e=80;function f(a,b){return"number"==typeof a&&Number.isFinite(a)?Math.max(1,Math.min(Math.floor(a),500)):b}function g(a,b=d){let c=a.get("limit")??a.get("tail");if(null===c||""===c)return null;let e=Number(c);return!Number.isFinite(e)||e<=0?b:f(e,b)}function h(a,b=d){let c=a.messages.length,e=f(b,d);if(c<=e)return{...a,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:c};let g=c-e;return{messages:a.messages.slice(g),entryIds:a.entryIds.slice(g),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:c}}function i(a,b,c=e,d={}){let g=a.messages.length,h=a.entryIds.indexOf(b);if(h<0)return null;let j=f(c,e),k=Math.max(0,h-Math.max(1,Math.floor(j/2))),l=d.toEnd?g:Math.min(g,k+j);return{messages:a.messages.slice(k,l),entryIds:a.entryIds.slice(k,l),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:k>0,hasMoreAfter:l<g,totalMessageCount:g}}function j(a,b,c=e){let d=a.messages.length,g=a.entryIds.indexOf(b);if(g<0||g>=d-1)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:d};let h=Math.min(d,g+1+f(c,e));return{messages:a.messages.slice(g+1,h),entryIds:a.entryIds.slice(g+1,h),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:h<d,totalMessageCount:d}}function k(a,b,c=e){let d=a.messages.length,g=a.entryIds.indexOf(b);if(g<=0)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:d};let h=Math.max(0,g-f(c,e));return{messages:a.messages.slice(h,g),entryIds:a.entryIds.slice(h,g),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:h>0,hasMoreAfter:!0,totalMessageCount:d}}},52960:(a,b,c)=>{c.d(b,{$3:()=>o,D_:()=>s,JT:()=>k,K2:()=>g,QR:()=>t,QT:()=>p,TJ:()=>r,_3:()=>n,in:()=>f,s:()=>q});var d=c(13737),e=c(99014);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)}}function s(a){return"prompt"===a||"abort"===a||"steer"===a||"follow_up"===a||"set_follow_up_queue"===a||"dispatch_follow_up_queue"===a||"recall_follow_up_queue"===a}function t(a,b=h){if(!a||"object"!=typeof a||Array.isArray(a))throw Error("command is required");let c=a.type;if("prompt"===c)return k(a,b);if("abort"===c)return{type:"abort"};if("steer"===c)return n(a,b);if("follow_up"===c)return o(a,b);if("set_follow_up_queue"===c)return p(a,b);if("dispatch_follow_up_queue"===c)return q(a,b);if("recall_follow_up_queue"===c)return r(a,b);throw Error(`Unsupported message command: ${String(c)}`)}},53023:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Uj:()=>j});var e=c(85664),f=c(93127),g=c(95237),h=a([f,g]);function i(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}[f,g]=h.then?(await h)():h;let k=`
2
2
  .pidance-activity{margin:1.5rem 0;padding:1rem 1.25rem;border:1px solid #ccc;border-radius:8px;background:#fafafa;color:#222;font-family:system-ui,-apple-system,Segoe UI,sans-serif;font-size:14px;line-height:1.45}
3
3
  .pidance-activity h2{margin:0 0 0.75rem;font-size:1.1rem;font-weight:600}
4
4
  .pidance-activity-card{margin:0.75rem 0;padding:0.75rem 1rem;border:1px solid #ddd;border-radius:6px;background:#fff}
@@ -10,7 +10,7 @@
10
10
  .pidance-activity-kind{display:inline-block;padding:0.1rem 0.45rem;border-radius:4px;background:#eee;font-weight:600;text-transform:uppercase;letter-spacing:0.03em;font-size:11px}
11
11
  .pidance-activity-card h3{margin:0 0 0.5rem;font-size:1rem;font-weight:600;word-break:break-word}
12
12
  .pidance-activity-content{margin:0;padding:0.5rem 0.65rem;border-radius:4px;background:#f5f5f5;color:#111;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px;white-space:pre-wrap;word-break:break-word;overflow-x:auto}
13
- `.trim();function j(a,b,c={}){let d=(0,g.kW)(b);return function(a,b,c={}){let d=function(a,b={}){let c=b.leafId,d="string"==typeof c&&c.length>0?c:void 0;if(void 0!==d&&!a.getEntry(d))throw new f.Zq(`Invalid leafId: ${d}`);let g=void 0!==d?a.getBranch(d):a.getBranch(),h=[];for(let a of g){if(!(0,e.o7)(a))continue;let b=(0,e.p_)(a.data);if(!b)continue;let c={entryId:a.id,activity:b};"string"==typeof a.timestamp&&a.timestamp.length>0&&(c.timestamp=a.timestamp),h.push(c)}return h}(b,c),g=function(a){if(0===a.length)return"";let b=a.map(a=>{let{activity:b,entryId:c,timestamp:d}=a,e=i(b.kind),f=i(b.title),g=i(b.content),h=[`<span class="pidance-activity-kind">${e}</span>`];return void 0!==d&&h.push(`<time datetime="${i(d)}">${i(d)}</time>`),void 0!==b.source&&h.push(`<span class="pidance-activity-source">source: ${i(b.source)}</span>`),void 0!==b.requestId&&h.push(`<span class="pidance-activity-request-id">requestId: ${i(b.requestId)}</span>`),`<article class="pidance-activity-card" data-kind="${e}" data-entry-id="${i(c)}"><div class="pidance-activity-meta">${h.join("")}</div><h3>${f}</h3><pre class="pidance-activity-content">${g}</pre></article>`}).join("\n");return['<section class="pidance-activity" id="pidance-session-activity" aria-label="Session activity">',`<style>${k}</style>`,"<h2>Session activity</h2>",b,"</section>"].join("\n")}(d);return function(a,b){let c;if(0===b.length)return a;let d=/<\/body\s*>/i.exec(a);if(!d||void 0===d.index)return`${a}${b}`;let e=d.index,f=d[0],g=/<\/body\s*>/gi;for(;null!==(c=g.exec(a));)e=c.index,f=c[0];return a.slice(0,e)+b+"\n"+f+a.slice(e+f.length)}(a,g)}(a,d,c)}d()}catch(a){d(a)}})},56429:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>e.$k,A4:()=>e.A4,DU:()=>e.DU,Fn:()=>e.Fn,HG:()=>e.HG,OF:()=>e.OF});var e=c(26773),f=a([e]);e=(f.then?(await f)():f)[0],d()}catch(a){d(a)}})},60185:(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(60396),h=c(69835),i=c(13737),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)}})},62693:(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)}},68524:(a,b,c)=>{c.d(b,{ql:()=>l,rU:()=>n,rV:()=>i,xP:()=>m});var d=c(89477),e=c(86697),f=c(60396);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=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{}}}function k(a,b){let c=g(b),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let h=`${c}.${process.pid}.${Date.now()}.tmp`;try{(0,d.writeFileSync)(h,JSON.stringify(a,null,2),{flag:"wx",mode:384}),(0,d.renameSync)(h,c)}catch(a){try{(0,d.unlinkSync)(h)}catch{}throw a}}function l(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 m(a,b,c=(0,f.$M)()){j(c,()=>{let d=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}(d,a,b),k(d,c)})}function n(a,b=(0,f.$M)()){j(b,()=>{k(function(a,b){let c={...a};for(let[a,d]of Object.entries(b))if(null===d)delete c[a];else if(h(d)&&h(c[a])){let b={...c[a]};for(let[a,c]of Object.entries(d))null===c?delete b[a]:b[a]=c;c[a]=b}else c[a]=d;return c}(i(b),a),b)})}},68816:(a,b,c)=>{c.d(b,{s:()=>q});var d=c(89477),e=c(25680),f=c(86697),g=c(60396);let h={maxHits:40,maxFiles:120,maxBytesPerFile:2097152,maxTotalBytes:0x2000000,snippetRadius:48},i=/\b(OR|AND|NOT|NEAR)\b/,j=/"([^"]*)"|(\S+)/g,k=new Set(["and","or","not","near"]);function l(a,b,c=h.snippetRadius){let d=a.replace(/\s+/g," ").trim();if(!d)return"";let e=b.trim();if(!e)return d.slice(0,2*c);let f=d.toLowerCase().indexOf(e.toLowerCase());if(f<0)return d.length>2*c?`${d.slice(0,2*c)}…`:d;let g=Math.max(0,f-c),i=Math.min(d.length,f+e.length+c),j=g>0?"…":"",k=i<d.length?"…":"";return`${j}${d.slice(g,i)}${k}`}function m(a,b){if(!b(a))return!1;try{return(0,d.statSync)(a).isFile()&&(0,d.statSync)(a).size>0}catch{return!1}}function n(a){let b=function(){try{let a=c(79868);if("function"==typeof a?.DatabaseSync)return a.DatabaseSync}catch{}try{let{createRequire:a}=c(55822),b=a(__filename)("node:sqlite");if("function"==typeof b?.DatabaseSync)return b.DatabaseSync}catch{}return null}();if(!b)return null;let d=a.replace(/\\/g,"/"),e=`file:${d}?mode=ro&immutable=1`;try{return new b(e,{readOnly:!0})}catch{}try{return new b(a,{readOnly:!0})}catch{return null}}async function o(a,b,c=h){let f,g=b.trim().toLowerCase();if(!g)return[];let i=0;try{i=(0,d.statSync)(a).size}catch{return[]}if(i<=0||i>c.maxBytesPerFile)return[];let j=[],k=(f=(a.replace(/\\/g,"/").split("/").pop()??"").match(/_([0-9a-fA-F-]{8,})\.jsonl$/),f?.[1]??null),m=0,n=(0,d.createReadStream)(a,{encoding:"utf8"}),p=(0,e.createInterface)({input:n,crlfDelay:1/0});try{for await(let a of p){if((m+=Buffer.byteLength(a,"utf8")+1)>c.maxBytesPerFile)break;let d=function(a){let b,c=a.trim();if(!c||"{"!==c[0])return null;try{b=JSON.parse(c)}catch{return null}if(!b||"object"!=typeof b)return null;let d=b;if("session"===d.type&&"string"==typeof d.id)return{sessionId:d.id,text:""};if("message"!==d.type)return null;let e=d.message;if(!e||"object"!=typeof e)return null;let f="string"==typeof e.role?e.role:void 0;if("user"!==f&&"assistant"!==f&&"system"!==f)return null;let g=function(a){if("string"==typeof a)return a;if(!Array.isArray(a))return"";let b=[];for(let c of a){if("string"==typeof c){b.push(c);continue}c&&"object"==typeof c&&("string"==typeof c.text?b.push(c.text):"string"==typeof c.content?b.push(c.content):"string"==typeof c.thinking&&b.push(c.thinking))}return b.join("\n").trim()}(e.content);return g?{messageId:"string"==typeof d.id?d.id:void 0,role:f,timestamp:"string"==typeof d.timestamp?d.timestamp:"string"==typeof e.timestamp?e.timestamp:void 0,text:g}:null}(a);if(d){if(d.sessionId){k=d.sessionId;continue}k&&d.text.toLowerCase().includes(g)&&j.push({sessionId:k,role:d.role,snippet:l(d.text,b,c.snippetRadius),timestamp:d.timestamp??"",messageId:d.messageId})}}}catch{}finally{p.close(),n.destroy()}return j}function p(a){let b=new Set,c=[];for(let d of a)b.has(d.sessionId)||(b.add(d.sessionId),c.push(d.sessionId));return c}async function q(a,b={}){let c=a.trim(),e={...h,...b.limits},r={...{getAgentDir:g.$M,resolveHermesDbPath:a=>(function(a,b=d.existsSync){let c=(0,f.join)(a,"hermes-memory-config.json");if(b(c))try{let h=JSON.parse((0,d.readFileSync)(c,"utf8"));if("string"==typeof h.memoryDir&&h.memoryDir.trim()){var e,g;let c=(e=h.memoryDir.trim(),g=a,"~"===e?process.env.HOME??g:e.startsWith("~/")||e.startsWith("~\\")?(0,f.join)(process.env.HOME??g,e.slice(2)):e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)?e:(0,f.join)(g,e)),d=(0,f.join)(c,"sessions.db");if(b(d)&&m(d,b))return d}}catch{}for(let c of[(0,f.join)(a,"pi-hermes-memory","sessions.db"),(0,f.join)(a,"memory","sessions.db")])if(b(c)&&m(c,b))return c;return null})(a),openSqliteReadonly:n,listJsonlFiles:a=>(function(a,b){if(!(0,d.existsSync)(a))return[];let c=[],e=a=>{let g;if(!(c.length>=b)){try{g=(0,d.readdirSync)(a,{withFileTypes:!0})}catch{return}for(let d of(g.sort((a,b)=>b.name.localeCompare(a.name)),g)){if(c.length>=b)return;let g=(0,f.join)(a,d.name);if(d.isDirectory()){e(g);continue}d.isFile()&&d.name.endsWith(".jsonl")&&c.push(g)}}};return e(a),c})(a,h.maxFiles),scanJsonlFile:o,existsSync:d.existsSync},...b.deps};if(!c)return{query:"",source:"none",hits:[],sessionIds:[]};let s=r.getAgentDir(),t=r.resolveHermesDbPath(s);if(t){let a=r.openSqliteReadonly(t);if(a)try{let b=function(a,b,c){let d=d=>{let e=`
13
+ `.trim();function j(a,b,c={}){let d=(0,g.kW)(b);return function(a,b,c={}){let d=function(a,b={}){let c=b.leafId,d="string"==typeof c&&c.length>0?c:void 0;if(void 0!==d&&!a.getEntry(d))throw new f.Zq(`Invalid leafId: ${d}`);let g=void 0!==d?a.getBranch(d):a.getBranch(),h=[];for(let a of g){if(!(0,e.o7)(a))continue;let b=(0,e.p_)(a.data);if(!b)continue;let c={entryId:a.id,activity:b};"string"==typeof a.timestamp&&a.timestamp.length>0&&(c.timestamp=a.timestamp),h.push(c)}return h}(b,c),g=function(a){if(0===a.length)return"";let b=a.map(a=>{let{activity:b,entryId:c,timestamp:d}=a,e=i(b.kind),f=i(b.title),g=i(b.content),h=[`<span class="pidance-activity-kind">${e}</span>`];return void 0!==d&&h.push(`<time datetime="${i(d)}">${i(d)}</time>`),void 0!==b.source&&h.push(`<span class="pidance-activity-source">source: ${i(b.source)}</span>`),void 0!==b.requestId&&h.push(`<span class="pidance-activity-request-id">requestId: ${i(b.requestId)}</span>`),`<article class="pidance-activity-card" data-kind="${e}" data-entry-id="${i(c)}"><div class="pidance-activity-meta">${h.join("")}</div><h3>${f}</h3><pre class="pidance-activity-content">${g}</pre></article>`}).join("\n");return['<section class="pidance-activity" id="pidance-session-activity" aria-label="Session activity">',`<style>${k}</style>`,"<h2>Session activity</h2>",b,"</section>"].join("\n")}(d);return function(a,b){let c;if(0===b.length)return a;let d=/<\/body\s*>/i.exec(a);if(!d||void 0===d.index)return`${a}${b}`;let e=d.index,f=d[0],g=/<\/body\s*>/gi;for(;null!==(c=g.exec(a));)e=c.index,f=c[0];return a.slice(0,e)+b+"\n"+f+a.slice(e+f.length)}(a,g)}(a,d,c)}d()}catch(a){d(a)}})},56429:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>e.$k,A4:()=>e.A4,DU:()=>e.DU,Fn:()=>e.Fn,HG:()=>e.HG,OF:()=>e.OF});var e=c(26773),f=a([e]);e=(f.then?(await f)():f)[0],d()}catch(a){d(a)}})},60185:(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(60396),h=c(69835),i=c(13737),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)}})},62693:(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)}},68524:(a,b,c)=>{c.d(b,{Nj:()=>n,UQ:()=>h,m6:()=>g,ql:()=>l,rU:()=>o,rV:()=>i,xP:()=>m});var d=c(89477),e=c(86697),f=c(60396);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=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{}}}function k(a,b){let c=g(b),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let h=`${c}.${process.pid}.${Date.now()}.tmp`;try{(0,d.writeFileSync)(h,JSON.stringify(a,null,2),{flag:"wx",mode:384}),(0,d.renameSync)(h,c)}catch(a){try{(0,d.unlinkSync)(h)}catch{}throw a}}function l(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 m(a,b,c=(0,f.$M)()){j(c,()=>{let d=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}(d,a,b),k(d,c)})}function n(a){let b={},c=[];for(let[d,e]of Object.entries(a)){if("sessionQueue"===d||d.startsWith("sessionQueue.")){c.push(d);continue}b[d]=e}return{patch:b,dropped:c}}function o(a,b=(0,f.$M)()){j(b,()=>{k(function(a,b){let c={...a};for(let[a,d]of Object.entries(b))if(null===d)delete c[a];else if(h(d)&&h(c[a])){let b={...c[a]};for(let[a,c]of Object.entries(d))null===c?delete b[a]:b[a]=c;c[a]=b}else c[a]=d;return c}(i(b),a),b)})}},68816:(a,b,c)=>{c.d(b,{s:()=>q});var d=c(89477),e=c(25680),f=c(86697),g=c(60396);let h={maxHits:40,maxFiles:120,maxBytesPerFile:2097152,maxTotalBytes:0x2000000,snippetRadius:48},i=/\b(OR|AND|NOT|NEAR)\b/,j=/"([^"]*)"|(\S+)/g,k=new Set(["and","or","not","near"]);function l(a,b,c=h.snippetRadius){let d=a.replace(/\s+/g," ").trim();if(!d)return"";let e=b.trim();if(!e)return d.slice(0,2*c);let f=d.toLowerCase().indexOf(e.toLowerCase());if(f<0)return d.length>2*c?`${d.slice(0,2*c)}…`:d;let g=Math.max(0,f-c),i=Math.min(d.length,f+e.length+c),j=g>0?"…":"",k=i<d.length?"…":"";return`${j}${d.slice(g,i)}${k}`}function m(a,b){if(!b(a))return!1;try{return(0,d.statSync)(a).isFile()&&(0,d.statSync)(a).size>0}catch{return!1}}function n(a){let b=function(){try{let a=c(79868);if("function"==typeof a?.DatabaseSync)return a.DatabaseSync}catch{}try{let{createRequire:a}=c(55822),b=a(__filename)("node:sqlite");if("function"==typeof b?.DatabaseSync)return b.DatabaseSync}catch{}return null}();if(!b)return null;let d=a.replace(/\\/g,"/"),e=`file:${d}?mode=ro&immutable=1`;try{return new b(e,{readOnly:!0})}catch{}try{return new b(a,{readOnly:!0})}catch{return null}}async function o(a,b,c=h){let f,g=b.trim().toLowerCase();if(!g)return[];let i=0;try{i=(0,d.statSync)(a).size}catch{return[]}if(i<=0||i>c.maxBytesPerFile)return[];let j=[],k=(f=(a.replace(/\\/g,"/").split("/").pop()??"").match(/_([0-9a-fA-F-]{8,})\.jsonl$/),f?.[1]??null),m=0,n=(0,d.createReadStream)(a,{encoding:"utf8"}),p=(0,e.createInterface)({input:n,crlfDelay:1/0});try{for await(let a of p){if((m+=Buffer.byteLength(a,"utf8")+1)>c.maxBytesPerFile)break;let d=function(a){let b,c=a.trim();if(!c||"{"!==c[0])return null;try{b=JSON.parse(c)}catch{return null}if(!b||"object"!=typeof b)return null;let d=b;if("session"===d.type&&"string"==typeof d.id)return{sessionId:d.id,text:""};if("message"!==d.type)return null;let e=d.message;if(!e||"object"!=typeof e)return null;let f="string"==typeof e.role?e.role:void 0;if("user"!==f&&"assistant"!==f&&"system"!==f)return null;let g=function(a){if("string"==typeof a)return a;if(!Array.isArray(a))return"";let b=[];for(let c of a){if("string"==typeof c){b.push(c);continue}c&&"object"==typeof c&&("string"==typeof c.text?b.push(c.text):"string"==typeof c.content?b.push(c.content):"string"==typeof c.thinking&&b.push(c.thinking))}return b.join("\n").trim()}(e.content);return g?{messageId:"string"==typeof d.id?d.id:void 0,role:f,timestamp:"string"==typeof d.timestamp?d.timestamp:"string"==typeof e.timestamp?e.timestamp:void 0,text:g}:null}(a);if(d){if(d.sessionId){k=d.sessionId;continue}k&&d.text.toLowerCase().includes(g)&&j.push({sessionId:k,role:d.role,snippet:l(d.text,b,c.snippetRadius),timestamp:d.timestamp??"",messageId:d.messageId})}}}catch{}finally{p.close(),n.destroy()}return j}function p(a){let b=new Set,c=[];for(let d of a)b.has(d.sessionId)||(b.add(d.sessionId),c.push(d.sessionId));return c}async function q(a,b={}){let c=a.trim(),e={...h,...b.limits},r={...{getAgentDir:g.$M,resolveHermesDbPath:a=>(function(a,b=d.existsSync){let c=(0,f.join)(a,"hermes-memory-config.json");if(b(c))try{let h=JSON.parse((0,d.readFileSync)(c,"utf8"));if("string"==typeof h.memoryDir&&h.memoryDir.trim()){var e,g;let c=(e=h.memoryDir.trim(),g=a,"~"===e?process.env.HOME??g:e.startsWith("~/")||e.startsWith("~\\")?(0,f.join)(process.env.HOME??g,e.slice(2)):e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)?e:(0,f.join)(g,e)),d=(0,f.join)(c,"sessions.db");if(b(d)&&m(d,b))return d}}catch{}for(let c of[(0,f.join)(a,"pi-hermes-memory","sessions.db"),(0,f.join)(a,"memory","sessions.db")])if(b(c)&&m(c,b))return c;return null})(a),openSqliteReadonly:n,listJsonlFiles:a=>(function(a,b){if(!(0,d.existsSync)(a))return[];let c=[],e=a=>{let g;if(!(c.length>=b)){try{g=(0,d.readdirSync)(a,{withFileTypes:!0})}catch{return}for(let d of(g.sort((a,b)=>b.name.localeCompare(a.name)),g)){if(c.length>=b)return;let g=(0,f.join)(a,d.name);if(d.isDirectory()){e(g);continue}d.isFile()&&d.name.endsWith(".jsonl")&&c.push(g)}}};return e(a),c})(a,h.maxFiles),scanJsonlFile:o,existsSync:d.existsSync},...b.deps};if(!c)return{query:"",source:"none",hits:[],sessionIds:[]};let s=r.getAgentDir(),t=r.resolveHermesDbPath(s);if(t){let a=r.openSqliteReadonly(t);if(a)try{let b=function(a,b,c){let d=d=>{let e=`
14
14
  SELECT
15
15
  m.session_id AS session_id,
16
16
  m.role AS role,
@@ -35,7 +35,7 @@
35
35
  WHERE m.content LIKE ? ESCAPE '\\'
36
36
  ORDER BY m.timestamp DESC
37
37
  LIMIT ?
38
- `,e=`%${b.trim().replace(/[\\%_]/g,"\\$&")}%`;return a.prepare(d).all(e,c).filter(a=>"string"==typeof a.session_id&&a.session_id).map(a=>({sessionId:a.session_id,role:"string"==typeof a.role?a.role:void 0,snippet:l(String(a.content??""),b),timestamp:"string"==typeof a.timestamp?a.timestamp:"",messageId:"string"==typeof a.message_id?a.message_id:void 0}))}catch{return[]}}(a,c,e.maxHits);return{query:c,source:"fts",hits:b,sessionIds:p(b)}}catch{}finally{try{a.close()}catch{}}}let u=(0,f.join)(s,"sessions");if(!r.existsSync(u))return{query:c,source:"jsonl",hits:[],sessionIds:[]};let v=r.listJsonlFiles(u).slice(0,e.maxFiles),w=[],x=0;for(let a of v){if(w.length>=e.maxHits)break;let b=0;try{b=(0,d.statSync)(a).size}catch{continue}if(!(b<=0)){if(x+b>e.maxTotalBytes)break;for(let d of(x+=b,await r.scanJsonlFile(a,c,e)))if(w.push(d),w.length>=e.maxHits)break}}return w.sort((a,b)=>(b.timestamp||"").localeCompare(a.timestamp||"")),{query:c,source:"jsonl",hits:w.slice(0,e.maxHits),sessionIds:p(w)}}},69835:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Gt:()=>u,Lj:()=>t,Md:()=>s,eq:()=>n,ki:()=>r,qo:()=>m,uF:()=>o,xd:()=>q});var e=c(29021),f=c(33873),g=c(55511),h=c(27910),i=c(77725),j=c(60396),k=c(80547),l=a([k]);k=(l.then?(await l)():l)[0];let s=0x1900000,t=0x6400000,u=0x20000000;function m(a=(0,j.$M)()){return(0,k.Nw)((0,f.join)(a,"pidance-attachments"))}function n(a=(0,j.$M)()){let b=m(a);return(0,e.existsSync)(b)||(0,e.mkdirSync)(b,{recursive:!0,mode:448}),(0,k.wz)(b),b}function o(a){let b=(a.replace(/\\/g,"/").split("/").pop()??"file").replace(/\0/g,"").replace(/^\.+/,"").trim()||"file";if(b.length<=180)return b;let c=b.lastIndexOf(".");if(c>0&&b.length-c<=20){let a=b.slice(c);return b.slice(0,180-a.length)+a}return b.slice(0,180)}function p(a,b=Date.now()){let c=o(a),d=new Date(b).toISOString().replace(/[:.]/g,"-"),e=(0,g.randomUUID)().slice(0,8);return`${d}_${e}_${c}`}async function q(a,b,c=(0,j.$M)(),d=u){let l=n(c),m=p(a),r=(0,f.join)(l,m),s=(0,f.join)(l,`.${m}.${(0,g.randomUUID)()}.tmp`),t=0,v=new h.Transform({transform(a,b,c){let e=Buffer.isBuffer(a)?a:Buffer.from(a);(t+=e.length)>d?c(Error(`message media exceeds ${d} bytes`)):c(null,e)}});try{await (0,i.pipeline)(h.Readable.fromWeb(b),v,(0,e.createWriteStream)(s,{flags:"wx",mode:384})),(0,e.renameSync)(s,r)}catch(a){try{(0,e.unlinkSync)(s)}catch{}throw a}return{path:(0,k.Nw)(r),name:o(a),storedName:m,size:t}}function r(a,b,c=(0,j.$M)()){let d=n(c),g=p(a),h=(0,f.join)(d,g);return(0,e.writeFileSync)(h,b,{flag:"wx",mode:384}),{path:(0,k.Nw)(h),name:o(a),storedName:g,size:b.length}}d()}catch(a){d(a)}})},76817:(a,b,c)=>{c.d(b,{wo:()=>d});function d(a,b){let c=a.findIndex(a=>a.id===b);if(-1===c)return b;let d=b;for(let b=c+1;b<a.length;b+=1){let c=a[b];if("message"===c.type&&c.message?.role==="user")break;d=c.id}return d}},79495:(a,b,c)=>{c.d(b,{CL:()=>n,K:()=>k});var d=c(89477),e=c(60396),f=c(92395);let g=`Create a concise title for this session based on the conversation above.
38
+ `,e=`%${b.trim().replace(/[\\%_]/g,"\\$&")}%`;return a.prepare(d).all(e,c).filter(a=>"string"==typeof a.session_id&&a.session_id).map(a=>({sessionId:a.session_id,role:"string"==typeof a.role?a.role:void 0,snippet:l(String(a.content??""),b),timestamp:"string"==typeof a.timestamp?a.timestamp:"",messageId:"string"==typeof a.message_id?a.message_id:void 0}))}catch{return[]}}(a,c,e.maxHits);return{query:c,source:"fts",hits:b,sessionIds:p(b)}}catch{}finally{try{a.close()}catch{}}}let u=(0,f.join)(s,"sessions");if(!r.existsSync(u))return{query:c,source:"jsonl",hits:[],sessionIds:[]};let v=r.listJsonlFiles(u).slice(0,e.maxFiles),w=[],x=0;for(let a of v){if(w.length>=e.maxHits)break;let b=0;try{b=(0,d.statSync)(a).size}catch{continue}if(!(b<=0)){if(x+b>e.maxTotalBytes)break;for(let d of(x+=b,await r.scanJsonlFile(a,c,e)))if(w.push(d),w.length>=e.maxHits)break}}return w.sort((a,b)=>(b.timestamp||"").localeCompare(a.timestamp||"")),{query:c,source:"jsonl",hits:w.slice(0,e.maxHits),sessionIds:p(w)}}},69835:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$t:()=>w,Gt:()=>z,Lj:()=>y,Md:()=>x,eq:()=>n,fb:()=>u,fm:()=>v,ki:()=>r,qo:()=>m,uF:()=>o,vy:()=>t,xd:()=>q});var e=c(29021),f=c(33873),g=c(55511),h=c(27910),i=c(77725),j=c(60396),k=c(80547),l=a([k]);k=(l.then?(await l)():l)[0];let x=0x1900000,y=0x6400000,z=0x20000000;function m(a=(0,j.$M)()){return(0,k.Nw)((0,f.join)(a,"pidance-attachments"))}function n(a=(0,j.$M)()){let b=m(a);return(0,e.existsSync)(b)||(0,e.mkdirSync)(b,{recursive:!0,mode:448}),(0,k.wz)(b),b}function o(a){let b=(a.replace(/\\/g,"/").split("/").pop()??"file").replace(/\0/g,"").replace(/^\.+/,"").trim()||"file";if(b.length<=180)return b;let c=b.lastIndexOf(".");if(c>0&&b.length-c<=20){let a=b.slice(c);return b.slice(0,180-a.length)+a}return b.slice(0,180)}function p(a,b=Date.now()){let c=o(a),d=new Date(b).toISOString().replace(/[:.]/g,"-"),e=(0,g.randomUUID)().slice(0,8);return`${d}_${e}_${c}`}async function q(a,b,c=(0,j.$M)(),d=z){let l=n(c),m=p(a),r=(0,f.join)(l,m),s=(0,f.join)(l,`.${m}.${(0,g.randomUUID)()}.tmp`),t=0,u=new h.Transform({transform(a,b,c){let e=Buffer.isBuffer(a)?a:Buffer.from(a);(t+=e.length)>d?c(Error(`message media exceeds ${d} bytes`)):c(null,e)}});try{await (0,i.pipeline)(h.Readable.fromWeb(b),u,(0,e.createWriteStream)(s,{flags:"wx",mode:384})),(0,e.renameSync)(s,r)}catch(a){try{(0,e.unlinkSync)(s)}catch{}throw a}return{path:(0,k.Nw)(r),name:o(a),storedName:m,size:t}}function r(a,b,c=(0,j.$M)()){let d=n(c),g=p(a),h=(0,f.join)(d,g);return(0,e.writeFileSync)(h,b,{flag:"wx",mode:384}),{path:(0,k.Nw)(h),name:o(a),storedName:g,size:b.length}}function s(a,b,c){let d=a.trim();if(!d)return null;try{let a=(0,k.Nw)((0,e.realpathSync)(n(b))),f=(0,k.Nw)((0,e.realpathSync)(d));if(f!==a&&!f.startsWith(`${a}/`)||!(0,e.statSync)(f).isFile())return null;return c(f)}catch{return null}}function t(a,b=(0,j.$M)()){return s(a,b,a=>(0,e.statSync)(a).size)}function u(a,b=(0,j.$M)(),c=0x1900000){return s(a,b,a=>(0,e.statSync)(a).size>c?null:(0,e.readFileSync)(a).toString("base64"))}function v(a,b=(0,j.$M)()){return s(a,b,a=>{try{return(0,e.unlinkSync)(a),!0}catch{return!1}})??!1}function w(a=(0,j.$M)()){let b=[];return function a(b,c){for(let d of(()=>{try{return(0,e.readdirSync)(b,{withFileTypes:!0})}catch{return[]}})()){let g=(0,f.join)(b,d.name);if(d.isDirectory()){a(g,c);continue}if(d.isFile())try{let a=(0,e.statSync)(g);c.push({path:(0,k.Nw)(g),size:a.size,mtimeMs:a.mtimeMs})}catch{}}}(m(a),b),b}d()}catch(a){d(a)}})},76817:(a,b,c)=>{c.d(b,{wo:()=>d});function d(a,b){let c=a.findIndex(a=>a.id===b);if(-1===c)return b;let d=b;for(let b=c+1;b<a.length;b+=1){let c=a[b];if("message"===c.type&&c.message?.role==="user")break;d=c.id}return d}},79495:(a,b,c)=>{c.d(b,{CL:()=>n,K:()=>k});var d=c(89477),e=c(60396),f=c(92395);let g=`Create a concise title for this session based on the conversation above.
39
39
 
40
40
  Requirements:
41
41
  - Match the primary language used by the user.
@@ -98,6 +98,6 @@ ${g}`:[...Array.isArray(b.content)?b.content:[],{type:"text",text:g}];return[...
98
98
  containsActive.set(node, has);
99
99
  }
100
100
  }`));return{body:(0,k.Uj)(c,q),contentType:"text/html; charset=utf-8",fileName:f}}finally{(0,g.rmSync)(m,{force:!0}),(0,g.rmSync)(n,{force:!0})}}d()}catch(a){d(a)}})},86226:(a,b,c)=>{c.d(b,{yN:()=>d});function d(a,b){return!a&&!!b}},87538:(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}}},89953:(a,b,c)=>{c.d(b,{AZ:()=>u,GT:()=>h,Hl:()=>v,kP:()=>t,wE:()=>s,wy:()=>w});var d=c(716),e=c(89477),f=c(86697),g=c(60396);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)}
101
- `,{mode:384}),(0,e.renameSync)(c,a)}function r(a,b){return b-a.heartbeatAt<=2e4&&l(a.pid)}function s(a){return(a instanceof Error?a.message:String(a)).includes("locked by another Pidance process")}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&&r(f,c))||f.pid===process.pid)&&(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,c)||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&&!!r(d,c)&&d.pid!==process.pid}},92395:(a,b,c)=>{c.d(b,{Ej:()=>q,FN:()=>j,J7:()=>s,Tj:()=>r,oT:()=>m,wq:()=>i,xH:()=>t});var d=c(89477),e=c(86697),f=c(60396);function g(a){return(0,e.join)((0,e.resolve)(a),".pi","settings.json")}function h(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function i(a){if(!(0,d.existsSync)(a))return{};try{let b=JSON.parse((0,d.readFileSync)(a,"utf8"));return h(b)?{...b}:{}}catch{return{}}}function j(a,b){let c=(0,e.dirname)(a);(0,d.mkdirSync)(c,{recursive:!0});let f=`${a}.${process.pid}.${Date.now()}.tmp`,g=`${JSON.stringify(b,null,2)}
101
+ `,{mode:384}),(0,e.renameSync)(c,a)}function r(a){return!!(a&&l(a.pid))}function s(a){return(a instanceof Error?a.message:String(a)).includes("locked by another Pidance process")}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)}},91898:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Fx:()=>k});var e=c(29021),f=c(33873),g=c(60396),h=c(69835),i=c(68524),j=a([h]);function k(a={}){let b=a.agentDir??(0,g.$M)(),c=a.ttlMs??2592e6,d=a.now??Date.now(),j=(0,h.$t)(b),l=j.filter(a=>d-a.mtimeMs>c);if(0===l.length)return{scanned:j.length,candidates:0,deleted:0,bytes:0,complete:!0};let m=function(a,b=(0,g.$M)()){let c=function(a){let b=(0,i.m6)(a);if(!(0,e.existsSync)(b))return{};try{let a=JSON.parse((0,e.readFileSync)(b,"utf8"));return(0,i.UQ)(a)?a:null}catch{return null}}(b);if(null===c)return null;let d=function(a){if(!(0,e.existsSync)(a))return[];let b=[],c=a=>{let d=(()=>{try{return(0,e.readdirSync)(a,{withFileTypes:!0})}catch{return null}})();if(null===d)return!1;for(let e of d){let d=(0,f.join)(a,e.name);if(e.isDirectory()){if(!c(d))return!1;continue}e.isFile()&&e.name.endsWith(".jsonl")&&b.push(d)}return!0};return c(a)?b:null}((0,f.join)(b,"sessions"));if(null===d)return null;let h=new Set,j=a.map(a=>{var b;return{path:a,escaped:(b=a,JSON.stringify(b).slice(1,-1))}}),k=a=>{for(let b of j)!h.has(b.path)&&(a.includes(b.path)||a.includes(b.escaped))&&h.add(b.path)};for(let a of(k(JSON.stringify(c)),d)){let b;if(h.size===j.length)break;try{b=(0,e.readFileSync)(a,"utf8")}catch{return null}k(b)}return h}(l.map(a=>a.path),b);if(null===m)return{scanned:j.length,candidates:l.length,deleted:0,bytes:0,complete:!1};let n=0,o=0;for(let a of l)!m.has(a.path)&&(0,h.fm)(a.path,b)&&(n+=1,o+=a.size);return{scanned:j.length,candidates:l.length,deleted:n,bytes:o,complete:!0}}h=(j.then?(await j)():j)[0],d()}catch(a){d(a)}})},92395:(a,b,c)=>{c.d(b,{Ej:()=>q,FN:()=>j,J7:()=>s,Tj:()=>r,oT:()=>m,wq:()=>i,xH:()=>t});var d=c(89477),e=c(86697),f=c(60396);function g(a){return(0,e.join)((0,e.resolve)(a),".pi","settings.json")}function h(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function i(a){if(!(0,d.existsSync)(a))return{};try{let b=JSON.parse((0,d.readFileSync)(a,"utf8"));return h(b)?{...b}:{}}catch{return{}}}function j(a,b){let c=(0,e.dirname)(a);(0,d.mkdirSync)(c,{recursive:!0});let f=`${a}.${process.pid}.${Date.now()}.tmp`,g=`${JSON.stringify(b,null,2)}
102
102
  `;try{(0,d.writeFileSync)(f,g,{flag:"wx",mode:384}),(0,d.renameSync)(f,a)}catch(a){try{(0,d.unlinkSync)(f)}catch{}throw a}}function k(a){return"string"==typeof a&&a.length>0?a:void 0}function l(a,b){return"all"===a||"one-at-a-time"===a?a:b}class m{constructor(a={}){this.dirty=!1;const b=a.agentDir??(0,f.$M)();this.globalPath=(0,e.join)((0,e.resolve)(b),"settings.json"),this.global=i(this.globalPath)}static create(a,b){return new m({agentDir:b})}view(){return this.global}getDefaultProvider(){return k(this.view().defaultProvider)}getDefaultModel(){return k(this.view().defaultModel)}getDefaultThinkingLevel(){return k(this.view().defaultThinkingLevel)}getSteeringMode(){return l(this.view().steeringMode,"one-at-a-time")}getFollowUpMode(){return l(this.view().followUpMode,"one-at-a-time")}getCompactionSettings(){let a=h(this.view().compaction)?this.view().compaction:{};return{enabled:"boolean"!=typeof a.enabled||a.enabled,reserveTokens:"number"==typeof a.reserveTokens?a.reserveTokens:16384,keepRecentTokens:"number"==typeof a.keepRecentTokens?a.keepRecentTokens:2e4}}getRetrySettings(){let a=h(this.view().retry)?this.view().retry:{};return{enabled:"boolean"!=typeof a.enabled||a.enabled,maxRetries:"number"==typeof a.maxRetries?a.maxRetries:3,baseDelayMs:"number"==typeof a.baseDelayMs?a.baseDelayMs:2e3}}getPackages(){return this.global.packages}setDefaultProvider(a){this.global.defaultProvider=a,this.dirty=!0}setDefaultModel(a){this.global.defaultModel=a,this.dirty=!0}setDefaultModelAndProvider(a,b){this.global.defaultProvider=a,this.global.defaultModel=b,this.dirty=!0}setDefaultThinkingLevel(a){this.global.defaultThinkingLevel=a,this.dirty=!0}setSteeringMode(a){this.global.steeringMode=a,this.dirty=!0}setFollowUpMode(a){this.global.followUpMode=a,this.dirty=!0}setCompactionEnabled(a){let b=h(this.global.compaction)?{...this.global.compaction}:{};b.enabled=a,this.global.compaction=b,this.dirty=!0}setRetryEnabled(a){let b=h(this.global.retry)?{...this.global.retry}:{};b.enabled=a,this.global.retry=b,this.dirty=!0}setPackages(a){this.global.packages=a,this.dirty=!0}async flush(){this.dirty&&(j(this.globalPath,this.global),this.dirty=!1)}flushSync(){this.dirty&&(j(this.globalPath,this.global),this.dirty=!1)}}function n(a){return Array.isArray(a)?a:[]}function o(a){return"string"==typeof a?a:a.source}function p(a){return"string"!=typeof a&&Array.isArray(a.extensions)&&0===a.extensions.length&&Array.isArray(a.skills)&&0===a.skills.length&&Array.isArray(a.prompts)&&0===a.prompts.length&&Array.isArray(a.themes)&&0===a.themes.length}function q(a,b={}){return"global"===a?n(i(b.agentDir?(0,e.join)((0,e.resolve)(b.agentDir),"settings.json"):(0,f.pA)()).packages):b.cwd?n(i(g(b.cwd)).packages):[]}function r(a,b,c={}){if("global"===a){let a=c.agentDir?(0,e.join)((0,e.resolve)(c.agentDir),"settings.json"):(0,f.pA)(),d=i(a);d.packages=b,j(a,d);return}if(!c.cwd)throw Error("project packages 需要 cwd");let d=g(c.cwd),h=i(d);h.packages=b,j(d,h)}function s(a,b,c,d={}){let e=q(b,d),f=!1,g=e.map(b=>o(b)!==a?b:(f=!0,c)?{..."string"==typeof b?{source:b}:b,extensions:[],skills:[],prompts:[],themes:[]}:o(b));return!!f&&(r(b,g,d),!0)}function t(a){let b=new Map;for(let c of q("global",a))b.set(`global\0${o(c)}`,p(c));if(a.cwd)for(let c of q("project",a))b.set(`project\0${o(c)}`,p(c));return b}},93127:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Nw:()=>h,Zq:()=>k,rW:()=>l,wr:()=>i,ye:()=>j});var e=c(33873),f=c(95237),g=a([f]);f=(g.then?(await g)():g)[0];class k extends Error{constructor(a){super(a),this.name="SessionExportError",this.code="bad-request"}}function h(a){return null===a||""===a?"html":"jsonl"===a?"jsonl":null}function i(a,b={}){let c=(0,f.kW)(a);return function(a,b={}){let c=b.leafId,d="string"==typeof c&&c.length>0?c:void 0;if(void 0!==d&&!a.getEntry(d))throw new k(`Invalid leafId: ${d}`);let e=void 0!==d?a.getBranch(d):a.getBranch(),g=(b.now??(()=>new Date))().toISOString(),h={type:"session",version:f.iR,id:a.getSessionId(),timestamp:g,cwd:a.getCwd()},i=[JSON.stringify(h)],j=null;for(let a of e){let b={...a,parentId:j};i.push(JSON.stringify(b)),j=a.id}return`${i.join("\n")}
103
- `}(c,b)}function j(a){let b=(0,e.basename)(a,".jsonl");return`pi-session-${b}.jsonl`}let l="application/x-ndjson; charset=utf-8";d()}catch(a){d(a)}})},99911:(a,b,c)=>{c.d(b,{Xm:()=>d});function d(a){let b=[];for(let d of a){if(d?.type!=="message")continue;let a=d.message;if(!a||"user"!==a.role)continue;let e="string"==typeof d.id&&d.id?d.id:null;if(e){var c;b.push({entryId:e,ordinal:b.length,text:"string"==typeof(c=a.content)?c:Array.isArray(c)?c.filter(a=>a?.type==="text"&&"string"==typeof a.text).map(a=>a.text).join("\n"):"",..."number"==typeof a.timestamp?{timestamp:a.timestamp}:{}})}}return b}}};
103
+ `}(c,b)}function j(a){let b=(0,e.basename)(a,".jsonl");return`pi-session-${b}.jsonl`}let l="application/x-ndjson; charset=utf-8";d()}catch(a){d(a)}})},99014:(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:()=>p,Pt:()=>n,S1:()=>g,X_:()=>o,gC:()=>m,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 a.map(a=>a.text)}function n(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 o(a,b){return{text:[...m(a),...b?.trim()?[b.trim()]:[]].map(a=>a.trim()).filter(a=>a.length>0).join("\n"),media:p(a)}}function p(a){return a.flatMap(a=>a.media??[])}},99911:(a,b,c)=>{c.d(b,{Xm:()=>d});function d(a){let b=[];for(let d of a){if(d?.type!=="message")continue;let a=d.message;if(!a||"user"!==a.role)continue;let e="string"==typeof d.id&&d.id?d.id:null;if(e){var c;b.push({entryId:e,ordinal:b.length,text:"string"==typeof(c=a.content)?c:Array.isArray(c)?c.filter(a=>a?.type==="text"&&"string"==typeof a.text).map(a=>a.text).join("\n"):"",..."number"==typeof a.timestamp?{timestamp:a.timestamp}:{}})}}return b}}};