@jetcrab/pi-desk 1.1.12 → 1.1.13-dev

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 (315) hide show
  1. package/docs/plugins.md +21 -1
  2. package/package.json +2 -2
  3. package/src/app/api/work-sessions/rename/route.ts +1 -0
  4. package/src/client/l2_biz/auth/l2-login.tsx +1 -1
  5. package/src/client/l2_biz/plugin-host/l2-plugin-session-sidebar-tab.tsx +6 -2
  6. package/src/client/l2_biz/settings/l2-auth-settings.tsx +1 -1
  7. package/src/client/l2_biz/settings/views/l2-appearance-settings.tsx +1 -16
  8. package/src/client/l2_biz/task-center/l2-task-center.tsx +4 -30
  9. package/src/client/l2_biz/workbench/file-workspace/l2-plugin-standalone-file-preview.tsx +45 -7
  10. package/src/client/l2_biz/workbench/hooks/l2-work-session-rename.ts +57 -0
  11. package/src/client/l2_biz/workbench/l2-work-session-columns.tsx +0 -11
  12. package/src/client/l2_biz/workbench/l2-work-session-sidebar.tsx +107 -6
  13. package/src/client/l2_biz/workbench/l2-workbench-biz.ts +5 -0
  14. package/src/client/l2_biz/workbench/l2-workbench-chat-composer.tsx +333 -350
  15. package/src/client/l2_biz/workbench/l2-workbench.tsx +46 -1
  16. package/src/client/l2_biz/workbench/views/l2-work-session-rename-dialog.tsx +88 -0
  17. package/src/client/l3_modules/project-files/l3-markdown-preview.module.css +81 -0
  18. package/src/client/l3_modules/project-files/l3-markdown-preview.tsx +52 -0
  19. package/src/client/l3_modules/project-files/l3-project-document-view.tsx +26 -8
  20. package/src/client/l3_modules/project-files/l3-project-file-runtime.ts +16 -1
  21. package/src/client/l3_modules/project-files/l3-project-text-preview.ts +5 -0
  22. package/src/client/l3_modules/work-session-visual/l3-work-session-visual-effects.module.css +0 -36
  23. package/src/client/l3_modules/work-session-visual/l3-work-session-visual-view.tsx +0 -5
  24. package/src/client/l4_foundation/plugin-host/l4-plugin-host-runtime.ts +71 -1
  25. package/src/client/l4_foundation/styles/l4-globals.css +0 -19
  26. package/src/client/l4_foundation/ui/code/l4-code-preview.tsx +2 -1
  27. package/src/common/l2_biz/auth/l2-auth-contract.ts +2 -2
  28. package/src/common/l2_biz/auth/l2-auth-messages.ts +2 -2
  29. package/src/common/l2_biz/settings/l2-settings-messages.ts +0 -6
  30. package/src/common/l2_biz/work-session/l2-work-session-contract.ts +9 -0
  31. package/src/common/l2_biz/workbench/l2-workbench-locale-messages.ts +6 -0
  32. package/src/common/l3_modules/project-files/l3-project-files-locale-messages.ts +4 -0
  33. package/src/common/l4_foundation/locale/l4-host-error-messages.ts +6 -0
  34. package/src/server/l1_entry/api/l1-work-session-rename-route.ts +52 -0
  35. package/src/server/l2_biz/work-session/l2-work-session-chat-runtime.ts +5 -0
  36. package/src/server/l2_biz/work-session/l2-work-session-manage.ts +13 -0
  37. package/src/server/l3_modules/work-session/l3-work-session.ts +4 -0
  38. package/src/server/l4_foundation/pi/l4-pi-chat-worker.ts +12 -1
  39. package/src/server/l4_foundation/pi/l4-pi-work-session-runtime.ts +5 -0
  40. package/temp/build/pi-desk/release/.next/BUILD_ID +1 -1
  41. package/temp/build/pi-desk/release/.next/app-path-routes-manifest.json +1 -0
  42. package/temp/build/pi-desk/release/.next/build-manifest.json +3 -3
  43. package/temp/build/pi-desk/release/.next/prerender-manifest.json +3 -3
  44. package/temp/build/pi-desk/release/.next/react-loadable-manifest.json +1 -2
  45. package/temp/build/pi-desk/release/.next/required-server-files.js +3 -3
  46. package/temp/build/pi-desk/release/.next/required-server-files.json +3 -3
  47. package/temp/build/pi-desk/release/.next/routes-manifest.json +6 -0
  48. package/temp/build/pi-desk/release/.next/server/app/_global-error/page.js +1 -1
  49. package/temp/build/pi-desk/release/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  50. package/temp/build/pi-desk/release/.next/server/app/_global-error.html +1 -1
  51. package/temp/build/pi-desk/release/.next/server/app/_global-error.rsc +1 -1
  52. package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  53. package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  54. package/temp/build/pi-desk/release/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  55. package/temp/build/pi-desk/release/.next/server/app/_not-found/page.js +1 -1
  56. package/temp/build/pi-desk/release/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  57. package/temp/build/pi-desk/release/.next/server/app/api/auth/login/route.js +2 -2
  58. package/temp/build/pi-desk/release/.next/server/app/api/auth/logout/route.js +1 -1
  59. package/temp/build/pi-desk/release/.next/server/app/api/auth-settings/get/route.js +1 -1
  60. package/temp/build/pi-desk/release/.next/server/app/api/auth-settings/replace/route.js +1 -1
  61. package/temp/build/pi-desk/release/.next/server/app/api/capability-modes/get/route.js +1 -1
  62. package/temp/build/pi-desk/release/.next/server/app/api/capability-modes/replace/route.js +1 -1
  63. package/temp/build/pi-desk/release/.next/server/app/api/chat/context/get/route.js +1 -1
  64. package/temp/build/pi-desk/release/.next/server/app/api/chat/images/get/route.js +1 -1
  65. package/temp/build/pi-desk/release/.next/server/app/api/chat/messages/get/route.js +1 -1
  66. package/temp/build/pi-desk/release/.next/server/app/api/health/route.js +1 -1
  67. package/temp/build/pi-desk/release/.next/server/app/api/mcp-check/get/route.js +1 -1
  68. package/temp/build/pi-desk/release/.next/server/app/api/mcp-settings/del/route.js +1 -1
  69. package/temp/build/pi-desk/release/.next/server/app/api/mcp-settings/get/route.js +1 -1
  70. package/temp/build/pi-desk/release/.next/server/app/api/mcp-settings/replace/route.js +1 -1
  71. package/temp/build/pi-desk/release/.next/server/app/api/model-catalog/list/route.js +1 -1
  72. package/temp/build/pi-desk/release/.next/server/app/api/model-settings/get/route.js +1 -1
  73. package/temp/build/pi-desk/release/.next/server/app/api/model-settings/replace/route.js +1 -1
  74. package/temp/build/pi-desk/release/.next/server/app/api/pi/directories/list/route.js +1 -1
  75. package/temp/build/pi-desk/release/.next/server/app/api/pi/directory-entries/list/route.js +1 -1
  76. package/temp/build/pi-desk/release/.next/server/app/api/pi/directory-ignores/list/route.js +1 -1
  77. package/temp/build/pi-desk/release/.next/server/app/api/pi/directory-ignores/replace/route.js +1 -1
  78. package/temp/build/pi-desk/release/.next/server/app/api/pi/models/list/route.js +1 -1
  79. package/temp/build/pi-desk/release/.next/server/app/api/pi/session-user-messages/list/route.js +1 -1
  80. package/temp/build/pi-desk/release/.next/server/app/api/pi/sessions/list/route.js +1 -1
  81. package/temp/build/pi-desk/release/.next/server/app/api/plugin-catalog/get/route.js +1 -1
  82. package/temp/build/pi-desk/release/.next/server/app/api/plugin-catalog/search/route.js +1 -1
  83. package/temp/build/pi-desk/release/.next/server/app/api/plugin-catalog/settings-get/route.js +1 -1
  84. package/temp/build/pi-desk/release/.next/server/app/api/plugin-catalog/settings-replace/route.js +1 -1
  85. package/temp/build/pi-desk/release/.next/server/app/api/plugins/add/route.js +1 -1
  86. package/temp/build/pi-desk/release/.next/server/app/api/plugins/apply/route.js +1 -1
  87. package/temp/build/pi-desk/release/.next/server/app/api/plugins/batch/route.js +1 -1
  88. package/temp/build/pi-desk/release/.next/server/app/api/plugins/browser-resources/[resourceGroup]/[...resourcePath]/route.js +1 -1
  89. package/temp/build/pi-desk/release/.next/server/app/api/plugins/del/route.js +1 -1
  90. package/temp/build/pi-desk/release/.next/server/app/api/plugins/enabled-set/route.js +1 -1
  91. package/temp/build/pi-desk/release/.next/server/app/api/plugins/get/route.js +1 -1
  92. package/temp/build/pi-desk/release/.next/server/app/api/plugins/host-runtime/[runtimeVersion]/[...resourcePath]/route.js +1 -1
  93. package/temp/build/pi-desk/release/.next/server/app/api/plugins/list/route.js +1 -1
  94. package/temp/build/pi-desk/release/.next/server/app/api/plugins/reload/route.js +1 -1
  95. package/temp/build/pi-desk/release/.next/server/app/api/plugins/update/route.js +1 -1
  96. package/temp/build/pi-desk/release/.next/server/app/api/project-files/get/route.js +1 -1
  97. package/temp/build/pi-desk/release/.next/server/app/api/project-files/list/route.js +1 -1
  98. package/temp/build/pi-desk/release/.next/server/app/api/project-files/reveal/route.js +1 -1
  99. package/temp/build/pi-desk/release/.next/server/app/api/project-files/search/route.js +1 -1
  100. package/temp/build/pi-desk/release/.next/server/app/api/project-git/get/route.js +1 -1
  101. package/temp/build/pi-desk/release/.next/server/app/api/project-git-branches/list/route.js +1 -1
  102. package/temp/build/pi-desk/release/.next/server/app/api/project-git-changes/list/route.js +1 -1
  103. package/temp/build/pi-desk/release/.next/server/app/api/project-git-diff/get/route.js +1 -1
  104. package/temp/build/pi-desk/release/.next/server/app/api/project-git-heads/get/route.js +1 -1
  105. package/temp/build/pi-desk/release/.next/server/app/api/project-git-log/list/route.js +1 -1
  106. package/temp/build/pi-desk/release/.next/server/app/api/project-model-default/get/route.js +1 -1
  107. package/temp/build/pi-desk/release/.next/server/app/api/project-model-default/replace/route.js +1 -1
  108. package/temp/build/pi-desk/release/.next/server/app/api/skill-files/get/route.js +1 -1
  109. package/temp/build/pi-desk/release/.next/server/app/api/skill-files/list/route.js +1 -1
  110. package/temp/build/pi-desk/release/.next/server/app/api/skill-files/replace/route.js +1 -1
  111. package/temp/build/pi-desk/release/.next/server/app/api/skills/list/route.js +1 -1
  112. package/temp/build/pi-desk/release/.next/server/app/api/task-center/images/get/route.js +1 -1
  113. package/temp/build/pi-desk/release/.next/server/app/api/task-center/messages/get/route.js +1 -1
  114. package/temp/build/pi-desk/release/.next/server/app/api/work-session-git-branch/add/route.js +1 -1
  115. package/temp/build/pi-desk/release/.next/server/app/api/work-session-git-branch/replace/route.js +1 -1
  116. package/temp/build/pi-desk/release/.next/server/app/api/work-session-tree/get/route.js +1 -1
  117. package/temp/build/pi-desk/release/.next/server/app/api/work-session-tree-entry/get/route.js +1 -1
  118. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/add/route.js +1 -1
  119. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/branch/route.js +1 -1
  120. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/del/route.js +1 -1
  121. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/rename/route.js +1 -0
  122. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/rename/route_client-reference-manifest.js +1 -0
  123. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/replace/route.js +1 -1
  124. package/temp/build/pi-desk/release/.next/server/app/api/work-sessions/sort/route.js +1 -1
  125. package/temp/build/pi-desk/release/.next/server/app/favicon.ico/route.js +1 -1
  126. package/temp/build/pi-desk/release/.next/server/app/login/page.js +1 -1
  127. package/temp/build/pi-desk/release/.next/server/app/login/page_client-reference-manifest.js +1 -1
  128. package/temp/build/pi-desk/release/.next/server/app/page.js +80 -314
  129. package/temp/build/pi-desk/release/.next/server/app/page_client-reference-manifest.js +1 -1
  130. package/temp/build/pi-desk/release/.next/server/app-paths-manifest.json +1 -0
  131. package/temp/build/pi-desk/release/.next/server/chunks/23054.js +1 -1
  132. package/temp/build/pi-desk/release/.next/server/chunks/25406.js +8 -8
  133. package/temp/build/pi-desk/release/.next/server/chunks/33658.js +296 -0
  134. package/temp/build/pi-desk/release/.next/server/chunks/35985.js +5 -5
  135. package/temp/build/pi-desk/release/.next/server/chunks/48180.js +1 -1
  136. package/temp/build/pi-desk/release/.next/server/chunks/49900.js +2 -2
  137. package/temp/build/pi-desk/release/.next/server/chunks/6917.js +1 -1
  138. package/temp/build/pi-desk/release/.next/server/chunks/82499.js +3 -3
  139. package/temp/build/pi-desk/release/.next/server/chunks/92386.js +3 -3
  140. package/temp/build/pi-desk/release/.next/server/chunks/94296.js +2 -2
  141. package/temp/build/pi-desk/release/.next/server/middleware-build-manifest.js +1 -1
  142. package/temp/build/pi-desk/release/.next/server/middleware-react-loadable-manifest.js +1 -1
  143. package/temp/build/pi-desk/release/.next/server/pages/500.html +1 -1
  144. package/temp/build/pi-desk/release/.next/server/server-reference-manifest.json +1 -1
  145. package/temp/build/pi-desk/release/.next/static/YdOQ7klRBI5tJb5NpDVLW/_buildManifest.js +1 -0
  146. package/temp/build/pi-desk/release/.next/static/chunks/31087-ba426d09d6f68bfd.js +1 -0
  147. package/temp/build/pi-desk/release/.next/static/chunks/39654-b5fedd762ea0312e.js +238 -0
  148. package/temp/build/pi-desk/release/.next/static/chunks/49516-cc4dcd84d64ab4fe.js +81 -0
  149. package/temp/build/pi-desk/release/.next/static/chunks/75130-d2ca74894aff8085.js +13 -0
  150. package/temp/build/pi-desk/release/.next/static/chunks/app/_global-error/page-5137efe26947191b.js +1 -0
  151. package/temp/build/pi-desk/release/.next/static/chunks/app/_not-found/page-5137efe26947191b.js +1 -0
  152. package/temp/build/pi-desk/release/.next/static/chunks/app/api/auth/login/route-5137efe26947191b.js +1 -0
  153. package/temp/build/pi-desk/release/.next/static/chunks/app/api/auth/logout/route-5137efe26947191b.js +1 -0
  154. package/temp/build/pi-desk/release/.next/static/chunks/app/api/auth-settings/get/route-5137efe26947191b.js +1 -0
  155. package/temp/build/pi-desk/release/.next/static/chunks/app/api/auth-settings/replace/route-5137efe26947191b.js +1 -0
  156. package/temp/build/pi-desk/release/.next/static/chunks/app/api/capability-modes/get/route-5137efe26947191b.js +1 -0
  157. package/temp/build/pi-desk/release/.next/static/chunks/app/api/capability-modes/replace/route-5137efe26947191b.js +1 -0
  158. package/temp/build/pi-desk/release/.next/static/chunks/app/api/chat/context/get/route-5137efe26947191b.js +1 -0
  159. package/temp/build/pi-desk/release/.next/static/chunks/app/api/chat/images/get/route-5137efe26947191b.js +1 -0
  160. package/temp/build/pi-desk/release/.next/static/chunks/app/api/chat/messages/get/route-5137efe26947191b.js +1 -0
  161. package/temp/build/pi-desk/release/.next/static/chunks/app/api/health/route-5137efe26947191b.js +1 -0
  162. package/temp/build/pi-desk/release/.next/static/chunks/app/api/mcp-check/get/route-5137efe26947191b.js +1 -0
  163. package/temp/build/pi-desk/release/.next/static/chunks/app/api/mcp-settings/del/route-5137efe26947191b.js +1 -0
  164. package/temp/build/pi-desk/release/.next/static/chunks/app/api/mcp-settings/get/route-5137efe26947191b.js +1 -0
  165. package/temp/build/pi-desk/release/.next/static/chunks/app/api/mcp-settings/replace/route-5137efe26947191b.js +1 -0
  166. package/temp/build/pi-desk/release/.next/static/chunks/app/api/model-catalog/list/route-5137efe26947191b.js +1 -0
  167. package/temp/build/pi-desk/release/.next/static/chunks/app/api/model-settings/get/route-5137efe26947191b.js +1 -0
  168. package/temp/build/pi-desk/release/.next/static/chunks/app/api/model-settings/replace/route-5137efe26947191b.js +1 -0
  169. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/directories/list/route-5137efe26947191b.js +1 -0
  170. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/directory-entries/list/route-5137efe26947191b.js +1 -0
  171. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/directory-ignores/list/route-5137efe26947191b.js +1 -0
  172. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/directory-ignores/replace/route-5137efe26947191b.js +1 -0
  173. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/models/list/route-5137efe26947191b.js +1 -0
  174. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/session-user-messages/list/route-5137efe26947191b.js +1 -0
  175. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/sessions/list/route-5137efe26947191b.js +1 -0
  176. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugin-catalog/get/route-5137efe26947191b.js +1 -0
  177. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugin-catalog/search/route-5137efe26947191b.js +1 -0
  178. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugin-catalog/settings-get/route-5137efe26947191b.js +1 -0
  179. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugin-catalog/settings-replace/route-5137efe26947191b.js +1 -0
  180. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/add/route-5137efe26947191b.js +1 -0
  181. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/apply/route-5137efe26947191b.js +1 -0
  182. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/batch/route-5137efe26947191b.js +1 -0
  183. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/browser-resources/[resourceGroup]/[...resourcePath]/route-5137efe26947191b.js +1 -0
  184. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/del/route-5137efe26947191b.js +1 -0
  185. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/enabled-set/route-5137efe26947191b.js +1 -0
  186. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/get/route-5137efe26947191b.js +1 -0
  187. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/host-runtime/[runtimeVersion]/[...resourcePath]/route-5137efe26947191b.js +1 -0
  188. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/list/route-5137efe26947191b.js +1 -0
  189. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/reload/route-5137efe26947191b.js +1 -0
  190. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/update/route-5137efe26947191b.js +1 -0
  191. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-files/get/route-5137efe26947191b.js +1 -0
  192. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-files/list/route-5137efe26947191b.js +1 -0
  193. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-files/reveal/route-5137efe26947191b.js +1 -0
  194. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-files/search/route-5137efe26947191b.js +1 -0
  195. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git/get/route-5137efe26947191b.js +1 -0
  196. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git-branches/list/route-5137efe26947191b.js +1 -0
  197. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git-changes/list/route-5137efe26947191b.js +1 -0
  198. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git-diff/get/route-5137efe26947191b.js +1 -0
  199. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git-heads/get/route-5137efe26947191b.js +1 -0
  200. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git-log/list/route-5137efe26947191b.js +1 -0
  201. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-model-default/get/route-5137efe26947191b.js +1 -0
  202. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-model-default/replace/route-5137efe26947191b.js +1 -0
  203. package/temp/build/pi-desk/release/.next/static/chunks/app/api/skill-files/get/route-5137efe26947191b.js +1 -0
  204. package/temp/build/pi-desk/release/.next/static/chunks/app/api/skill-files/list/route-5137efe26947191b.js +1 -0
  205. package/temp/build/pi-desk/release/.next/static/chunks/app/api/skill-files/replace/route-5137efe26947191b.js +1 -0
  206. package/temp/build/pi-desk/release/.next/static/chunks/app/api/skills/list/route-5137efe26947191b.js +1 -0
  207. package/temp/build/pi-desk/release/.next/static/chunks/app/api/task-center/images/get/route-5137efe26947191b.js +1 -0
  208. package/temp/build/pi-desk/release/.next/static/chunks/app/api/task-center/messages/get/route-5137efe26947191b.js +1 -0
  209. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-session-git-branch/add/route-5137efe26947191b.js +1 -0
  210. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-session-git-branch/replace/route-5137efe26947191b.js +1 -0
  211. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-session-tree/get/route-5137efe26947191b.js +1 -0
  212. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-session-tree-entry/get/route-5137efe26947191b.js +1 -0
  213. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/add/route-5137efe26947191b.js +1 -0
  214. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/branch/route-5137efe26947191b.js +1 -0
  215. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/del/route-5137efe26947191b.js +1 -0
  216. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/rename/route-5137efe26947191b.js +1 -0
  217. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/replace/route-5137efe26947191b.js +1 -0
  218. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/sort/route-5137efe26947191b.js +1 -0
  219. package/temp/build/pi-desk/release/.next/static/chunks/app/layout-358978b7cfe69a5f.js +3 -0
  220. package/temp/build/pi-desk/release/.next/static/chunks/app/login/page-84892b06243891f0.js +1 -0
  221. package/temp/build/pi-desk/release/.next/static/chunks/app/page-cc05e71bf51adb57.js +158 -0
  222. package/temp/build/pi-desk/release/.next/static/chunks/next/dist/client/components/builtin/app-error-5137efe26947191b.js +1 -0
  223. package/temp/build/pi-desk/release/.next/static/chunks/next/dist/client/components/builtin/forbidden-5137efe26947191b.js +1 -0
  224. package/temp/build/pi-desk/release/.next/static/chunks/next/dist/client/components/builtin/unauthorized-5137efe26947191b.js +1 -0
  225. package/temp/build/pi-desk/release/.next/static/chunks/webpack-40a782fc8a3535b9.js +1 -0
  226. package/temp/build/pi-desk/release/.next/static/css/095a062e18f96657.css +1 -0
  227. package/temp/build/pi-desk/release/.next/static/css/{adb1d4e48dd43c0a.css → 949d0d1a99d5de92.css} +1 -1
  228. package/temp/build/pi-desk/release/.next/trace-build +1 -1
  229. package/src/client/l2_biz/workbench/hooks/l2-work-session-column-motion.ts +0 -87
  230. package/src/client/l3_modules/work-session-visual/l3-work-session-status-border.tsx +0 -66
  231. package/src/client/l4_foundation/ui/l4-power-saving.ts +0 -45
  232. package/src/client/l4_foundation/ui/l4-window-reveal.ts +0 -30
  233. package/temp/build/pi-desk/release/.next/server/chunks/56284.js +0 -62
  234. package/temp/build/pi-desk/release/.next/static/96geGVI-j_dC6I3k-XFCB/_buildManifest.js +0 -1
  235. package/temp/build/pi-desk/release/.next/static/chunks/31087-333cae396a52f232.js +0 -1
  236. package/temp/build/pi-desk/release/.next/static/chunks/45992-92d8b8b10fcfbb6b.js +0 -13
  237. package/temp/build/pi-desk/release/.next/static/chunks/47340-c1c09c77c1a88514.js +0 -318
  238. package/temp/build/pi-desk/release/.next/static/chunks/57208-d6d38167dabb91e4.js +0 -1
  239. package/temp/build/pi-desk/release/.next/static/chunks/app/_global-error/page-dde4fd973791f7f7.js +0 -1
  240. package/temp/build/pi-desk/release/.next/static/chunks/app/_not-found/page-dde4fd973791f7f7.js +0 -1
  241. package/temp/build/pi-desk/release/.next/static/chunks/app/api/auth/login/route-dde4fd973791f7f7.js +0 -1
  242. package/temp/build/pi-desk/release/.next/static/chunks/app/api/auth/logout/route-dde4fd973791f7f7.js +0 -1
  243. package/temp/build/pi-desk/release/.next/static/chunks/app/api/auth-settings/get/route-dde4fd973791f7f7.js +0 -1
  244. package/temp/build/pi-desk/release/.next/static/chunks/app/api/auth-settings/replace/route-dde4fd973791f7f7.js +0 -1
  245. package/temp/build/pi-desk/release/.next/static/chunks/app/api/capability-modes/get/route-dde4fd973791f7f7.js +0 -1
  246. package/temp/build/pi-desk/release/.next/static/chunks/app/api/capability-modes/replace/route-dde4fd973791f7f7.js +0 -1
  247. package/temp/build/pi-desk/release/.next/static/chunks/app/api/chat/context/get/route-dde4fd973791f7f7.js +0 -1
  248. package/temp/build/pi-desk/release/.next/static/chunks/app/api/chat/images/get/route-dde4fd973791f7f7.js +0 -1
  249. package/temp/build/pi-desk/release/.next/static/chunks/app/api/chat/messages/get/route-dde4fd973791f7f7.js +0 -1
  250. package/temp/build/pi-desk/release/.next/static/chunks/app/api/health/route-dde4fd973791f7f7.js +0 -1
  251. package/temp/build/pi-desk/release/.next/static/chunks/app/api/mcp-check/get/route-dde4fd973791f7f7.js +0 -1
  252. package/temp/build/pi-desk/release/.next/static/chunks/app/api/mcp-settings/del/route-dde4fd973791f7f7.js +0 -1
  253. package/temp/build/pi-desk/release/.next/static/chunks/app/api/mcp-settings/get/route-dde4fd973791f7f7.js +0 -1
  254. package/temp/build/pi-desk/release/.next/static/chunks/app/api/mcp-settings/replace/route-dde4fd973791f7f7.js +0 -1
  255. package/temp/build/pi-desk/release/.next/static/chunks/app/api/model-catalog/list/route-dde4fd973791f7f7.js +0 -1
  256. package/temp/build/pi-desk/release/.next/static/chunks/app/api/model-settings/get/route-dde4fd973791f7f7.js +0 -1
  257. package/temp/build/pi-desk/release/.next/static/chunks/app/api/model-settings/replace/route-dde4fd973791f7f7.js +0 -1
  258. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/directories/list/route-dde4fd973791f7f7.js +0 -1
  259. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/directory-entries/list/route-dde4fd973791f7f7.js +0 -1
  260. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/directory-ignores/list/route-dde4fd973791f7f7.js +0 -1
  261. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/directory-ignores/replace/route-dde4fd973791f7f7.js +0 -1
  262. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/models/list/route-dde4fd973791f7f7.js +0 -1
  263. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/session-user-messages/list/route-dde4fd973791f7f7.js +0 -1
  264. package/temp/build/pi-desk/release/.next/static/chunks/app/api/pi/sessions/list/route-dde4fd973791f7f7.js +0 -1
  265. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugin-catalog/get/route-dde4fd973791f7f7.js +0 -1
  266. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugin-catalog/search/route-dde4fd973791f7f7.js +0 -1
  267. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugin-catalog/settings-get/route-dde4fd973791f7f7.js +0 -1
  268. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugin-catalog/settings-replace/route-dde4fd973791f7f7.js +0 -1
  269. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/add/route-dde4fd973791f7f7.js +0 -1
  270. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/apply/route-dde4fd973791f7f7.js +0 -1
  271. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/batch/route-dde4fd973791f7f7.js +0 -1
  272. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/browser-resources/[resourceGroup]/[...resourcePath]/route-dde4fd973791f7f7.js +0 -1
  273. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/del/route-dde4fd973791f7f7.js +0 -1
  274. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/enabled-set/route-dde4fd973791f7f7.js +0 -1
  275. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/get/route-dde4fd973791f7f7.js +0 -1
  276. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/host-runtime/[runtimeVersion]/[...resourcePath]/route-dde4fd973791f7f7.js +0 -1
  277. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/list/route-dde4fd973791f7f7.js +0 -1
  278. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/reload/route-dde4fd973791f7f7.js +0 -1
  279. package/temp/build/pi-desk/release/.next/static/chunks/app/api/plugins/update/route-dde4fd973791f7f7.js +0 -1
  280. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-files/get/route-dde4fd973791f7f7.js +0 -1
  281. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-files/list/route-dde4fd973791f7f7.js +0 -1
  282. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-files/reveal/route-dde4fd973791f7f7.js +0 -1
  283. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-files/search/route-dde4fd973791f7f7.js +0 -1
  284. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git/get/route-dde4fd973791f7f7.js +0 -1
  285. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git-branches/list/route-dde4fd973791f7f7.js +0 -1
  286. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git-changes/list/route-dde4fd973791f7f7.js +0 -1
  287. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git-diff/get/route-dde4fd973791f7f7.js +0 -1
  288. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git-heads/get/route-dde4fd973791f7f7.js +0 -1
  289. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-git-log/list/route-dde4fd973791f7f7.js +0 -1
  290. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-model-default/get/route-dde4fd973791f7f7.js +0 -1
  291. package/temp/build/pi-desk/release/.next/static/chunks/app/api/project-model-default/replace/route-dde4fd973791f7f7.js +0 -1
  292. package/temp/build/pi-desk/release/.next/static/chunks/app/api/skill-files/get/route-dde4fd973791f7f7.js +0 -1
  293. package/temp/build/pi-desk/release/.next/static/chunks/app/api/skill-files/list/route-dde4fd973791f7f7.js +0 -1
  294. package/temp/build/pi-desk/release/.next/static/chunks/app/api/skill-files/replace/route-dde4fd973791f7f7.js +0 -1
  295. package/temp/build/pi-desk/release/.next/static/chunks/app/api/skills/list/route-dde4fd973791f7f7.js +0 -1
  296. package/temp/build/pi-desk/release/.next/static/chunks/app/api/task-center/images/get/route-dde4fd973791f7f7.js +0 -1
  297. package/temp/build/pi-desk/release/.next/static/chunks/app/api/task-center/messages/get/route-dde4fd973791f7f7.js +0 -1
  298. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-session-git-branch/add/route-dde4fd973791f7f7.js +0 -1
  299. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-session-git-branch/replace/route-dde4fd973791f7f7.js +0 -1
  300. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-session-tree/get/route-dde4fd973791f7f7.js +0 -1
  301. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-session-tree-entry/get/route-dde4fd973791f7f7.js +0 -1
  302. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/add/route-dde4fd973791f7f7.js +0 -1
  303. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/branch/route-dde4fd973791f7f7.js +0 -1
  304. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/del/route-dde4fd973791f7f7.js +0 -1
  305. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/replace/route-dde4fd973791f7f7.js +0 -1
  306. package/temp/build/pi-desk/release/.next/static/chunks/app/api/work-sessions/sort/route-dde4fd973791f7f7.js +0 -1
  307. package/temp/build/pi-desk/release/.next/static/chunks/app/layout-839162b6cfae8347.js +0 -3
  308. package/temp/build/pi-desk/release/.next/static/chunks/app/login/page-4532a3bbee48e219.js +0 -1
  309. package/temp/build/pi-desk/release/.next/static/chunks/app/page-4b6367cde5c04597.js +0 -158
  310. package/temp/build/pi-desk/release/.next/static/chunks/next/dist/client/components/builtin/app-error-dde4fd973791f7f7.js +0 -1
  311. package/temp/build/pi-desk/release/.next/static/chunks/next/dist/client/components/builtin/forbidden-dde4fd973791f7f7.js +0 -1
  312. package/temp/build/pi-desk/release/.next/static/chunks/next/dist/client/components/builtin/unauthorized-dde4fd973791f7f7.js +0 -1
  313. package/temp/build/pi-desk/release/.next/static/chunks/webpack-735430d61da52e9d.js +0 -1
  314. package/temp/build/pi-desk/release/.next/static/css/4a5dda7ff3a82c4a.css +0 -1
  315. /package/temp/build/pi-desk/release/.next/static/{96geGVI-j_dC6I3k-XFCB → YdOQ7klRBI5tJb5NpDVLW}/_ssgManifest.js +0 -0
@@ -1,2 +1,2 @@
1
- exports.id=94296,exports.ids=[94296],exports.modules={73:(a,b,c)=>{"use strict";let{Writable:d}=c(27910),e=c(95374),{BINARY_TYPES:f,EMPTY_BUFFER:g,kStatusCode:h,kWebSocket:i}=c(46929),{concat:j,toArrayBuffer:k,unmask:l}=c(52218),{isValidStatusCode:m,isValidUTF8:n}=c(47591),o=Buffer[Symbol.species];class p extends d{constructor(a={}){super(),this._allowSynchronousEvents=void 0===a.allowSynchronousEvents||a.allowSynchronousEvents,this._binaryType=a.binaryType||f[0],this._extensions=a.extensions||{},this._isServer=!!a.isServer,this._maxBufferedChunks=0|a.maxBufferedChunks,this._maxFragments=0|a.maxFragments,this._maxPayload=0|a.maxPayload,this._skipUTF8Validation=!!a.skipUTF8Validation,this[i]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(a,b,c){return 8===this._opcode&&0==this._state?c():this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks?void c(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS")):void(this._bufferedBytes+=a.length,this._buffers.push(a),this.startLoop(c))}consume(a){if(this._bufferedBytes-=a,a===this._buffers[0].length)return this._buffers.shift();if(a<this._buffers[0].length){let b=this._buffers[0];return this._buffers[0]=new o(b.buffer,b.byteOffset+a,b.length-a),new o(b.buffer,b.byteOffset,a)}let b=Buffer.allocUnsafe(a);do{let c=this._buffers[0],d=b.length-a;a>=c.length?b.set(this._buffers.shift(),d):(b.set(new Uint8Array(c.buffer,c.byteOffset,a),d),this._buffers[0]=new o(c.buffer,c.byteOffset+a,c.length-a)),a-=c.length}while(a>0);return b}startLoop(a){this._loop=!0;do switch(this._state){case 0:this.getInfo(a);break;case 1:this.getPayloadLength16(a);break;case 2:this.getPayloadLength64(a);break;case 3:this.getMask();break;case 4:this.getData(a);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||a()}getInfo(a){if(this._bufferedBytes<2){this._loop=!1;return}let b=this.consume(2);if((48&b[0])!=0)return void a(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));let c=(64&b[0])==64;if(c&&!this._extensions[e.extensionName])return void a(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._fin=(128&b[0])==128,this._opcode=15&b[0],this._payloadLength=127&b[1],0===this._opcode){if(c)return void a(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void a(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void a(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=c}else{if(!(this._opcode>7)||!(this._opcode<11))return void a(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void a(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(c)return void a(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void a(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=(128&b[1])==128,this._isServer){if(!this._masked)return void a(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void a(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(a)}getPayloadLength16(a){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(a)}getPayloadLength64(a){if(this._bufferedBytes<8){this._loop=!1;return}let b=this.consume(8),c=b.readUInt32BE(0);c>2097151?a(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=0x100000000*c+b.readUInt32BE(4),this.haveLength(a))}haveLength(a){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?a(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(a){let b=g;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}b=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!=0&&l(b,this._mask)}if(this._opcode>7)return void this.controlMessage(b,a);if(this._maxFragments>0&&++this._numFragments>this._maxFragments)return void a(this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));if(this._compressed){this._state=5,this.decompress(b,a);return}b.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(b)),this.dataMessage(a)}decompress(a,b){this._extensions[e.extensionName].decompress(a,this._fin,(a,c)=>{if(a)return b(a);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return void b(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(c)}this.dataMessage(b),0===this._state&&this.startLoop(b)})}dataMessage(a){if(!this._fin){this._state=0;return}let b=this._messageLength,c=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],2===this._opcode){let d;d="nodebuffer"===this._binaryType?j(c,b):"arraybuffer"===this._binaryType?k(j(c,b)):"blob"===this._binaryType?new Blob(c):c,this._allowSynchronousEvents?(this.emit("message",d,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",d,!0),this._state=0,this.startLoop(a)}))}else{let d=j(c,b);if(!this._skipUTF8Validation&&!n(d))return void a(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));5===this._state||this._allowSynchronousEvents?(this.emit("message",d,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",d,!1),this._state=0,this.startLoop(a)}))}}controlMessage(a,b){if(8===this._opcode){if(0===a.length)this._loop=!1,this.emit("conclude",1005,g),this.end();else{let c=a.readUInt16BE(0);if(!m(c))return void b(this.createError(RangeError,`invalid status code ${c}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE"));let d=new o(a.buffer,a.byteOffset+2,a.length-2);if(!this._skipUTF8Validation&&!n(d))return void b(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));this._loop=!1,this.emit("conclude",c,d),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",a),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",a),this._state=0,this.startLoop(b)}))}createError(a,b,c,d,e){this._loop=!1,this._errored=!0;let f=new a(c?`Invalid WebSocket frame: ${b}`:b);return Error.captureStackTrace(f,this.createError),f.code=e,f[h]=d,f}}a.exports=p},7586:a=>{"use strict";let b=Symbol("kDone"),c=Symbol("kRun");class d{constructor(a){this[b]=()=>{this.pending--,this[c]()},this.concurrency=a||1/0,this.jobs=[],this.pending=0}add(a){this.jobs.push(a),this[c]()}[c](){if(this.pending!==this.concurrency&&this.jobs.length){let a=this.jobs.shift();this.pending++,a(this[b])}}}a.exports=d},8663:(a,b,c)=>{"use strict";c.d(b,{H:()=>j});var d=c(36153),e=c(3329),f=c(88277),g=c(69375);let h=d.Ik({source:e.R}).strict(),i=d.Ik({}).strict(),j=Object.freeze({subscribe:(0,g.Vc)({path:"pi/ui/subscribe",inputSchema:h,outputSchema:f.P}),unsubscribe:(0,g.Vc)({path:"pi/ui/unsubscribe",inputSchema:h,outputSchema:i}),respond:(0,g.Vc)({path:"pi/ui/respond",inputSchema:h.extend({response:f.YB}).strict(),outputSchema:i}),event:(0,g._G)({path:"pi/ui/event",bodySchema:h.extend({event:f.Z$}).strict()})})},9763:(a,b,c)=>{"use strict";c.a(a,async(a,b)=>{try{var d=c(17691);c(77598),c(73024),c(76760);var e=c(36153),f=a([d]);d=(f.then?(await f)():f)[0];let g=e.Ik({loggedInAt:e.ai().int().nonnegative()});e.YO(g),b()}catch(a){b(a)}})},16050:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{K:()=>j});var e=c(45407),f=c(55490),g=c(25406),h=c(33448),i=a([e,f,g,h]);function j(){if(!globalThis.__piDeskTaskCenterRuntime){let a=(0,g.getL2WorkSessionManage)();globalThis.__piDeskTaskCenterRuntime=new e.rt(async b=>{let c=await a.getWorkSession(b.workId);if(!c||c.sessionId!==b.sessionId||c.branchId!==b.branchId)throw new f.dM(b);return(0,h.ls)(b.sessionId)})}return globalThis.__piDeskTaskCenterRuntime}[e,f,g,h]=i.then?(await i)():i,d()}catch(a){d(a)}})},18331:(a,b,c)=>{"use strict";c.d(b,{bm:()=>k});var d=c(36153),e=c(69375),f=c(72497);d.Yj().min(32).max(128).regex(/^[A-Za-z0-9_-]+$/);let g="/api/plugins/host-runtime/v1";Object.freeze({imports:Object.freeze({react:`${g}/base.js`,"react/jsx-runtime":`${g}/base.js`,"react/jsx-dev-runtime":`${g}/base.js`,"react-dom":`${g}/base.js`,"react-dom/client":`${g}/base.js`,"@jetcrab/pi-desk-sdk/react/base":`${g}/base.js`,"@jetcrab/pi-desk-sdk/react/markdown":`${g}/markdown.js`})}),d.eu("v1");let h=d.Ik({pluginName:f.tv,url:d.Yj().regex(/^\/api\/plugins\/browser-resources\/[A-Za-z0-9_-]{32,128}\/entry\.js$/,"Browser Entry URL 无效")}).strict(),i=d.Ik({}).strict(),j=d.Ik({entries:d.YO(h)}).strict(),k=Object.freeze({list:(0,e.Vc)({path:"plugins/browser-entries/list",inputSchema:i,outputSchema:j})})},18611:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{T:()=>j});var e=c(37497),f=c(55490),g=c(9570),h=a([f,g]);function i(a,b){return a.workId===b.workId&&a.sessionId===b.sessionId&&a.branchId===b.branchId}[f,g]=h.then?(await h)():h;class j{constructor(a,b){this.connection=a,this.manage=b,this.subscriptionsByWorkId=new Map,this.operationTail=Promise.resolve(),this.disposed=!1,this.routes=Object.freeze([{path:e.P6.subscribe.path,access:"ready",handle:a=>this.enqueueSubscribe(a)},{path:e.P6.send.path,access:"ready",handle:a=>this.send(a)},{path:e.P6.interrupt.path,access:"ready",handle:a=>this.interrupt(a)},{path:e.P6.compact.path,access:"ready",handle:a=>this.compact(a)},{path:e.P6.reload.path,access:"ready",handle:a=>this.reload(a)},{path:e.P6.presentationSet.path,access:"ready",handle:a=>this.setPresentation(a)},{path:e.P6.queueRestore.path,access:"ready",handle:a=>this.restoreQueue(a)},{path:e.P6.modelSet.path,access:"ready",handle:a=>this.setModel(a)},{path:e.P6.capabilityModeSet.path,access:"ready",handle:a=>this.setCapabilityMode(a)}]),this.unsubscribeMessages=this.manage.subscribeMessageEvents(a=>this.handleRuntimeEvent(a))}dispose(){this.disposed||(this.disposed=!0,this.unsubscribeMessages(),this.subscriptionsByWorkId.clear())}enqueueSubscribe(a){let b=()=>this.subscribe(a),c=this.operationTail.then(b,b);return this.operationTail=c.then(()=>void 0,()=>void 0),c}async subscribe(a){let b,c=e.P6.subscribe,d=c.inputSchema.safeParse(a.body);if(!d.success)return void this.connection.sendError(c.path,a.head.requestId,400,"聊天订阅参数无效",{key:"errors:chatSubscribeInvalid"});let g=new Map;for(let a of d.data.subscriptions)g.set(a.source.workId,this.subscriptionsByWorkId.get(a.source.workId)),this.subscriptionsByWorkId.set(a.source.workId,{source:a.source,status:"syncing",queuedEvents:[],overflowed:!1});try{b=await this.manage.prepareChatSourceSyncs(d.data.subscriptions)}catch(h){this.restoreSubscriptions(g);let b=h instanceof f.dM;b||console.error("[Pi Desk][ChatSocket] 聊天 Source 订阅初始化失败",{clientId:this.connection.clientId,connectionId:this.connection.connectionId,requestId:a.head.requestId,sources:d.data.subscriptions.map(a=>a.source),errorName:h instanceof Error?h.name:"UnknownError",errorMessage:h instanceof Error?h.message:String(h),errorStack:h instanceof Error?h.stack:void 0});let e=h instanceof Error?h.message.slice(0,32e3):null;this.connection.sendError(c.path,a.head.requestId,b?409:500,b?"聊天订阅绑定已过期":e||"聊天订阅初始化失败",b?{key:"errors:chatSubscribeExpired"}:e?void 0:{key:"errors:chatSubscribeFailed"});return}if(!this.disposed&&this.connection.isCurrent()){this.connection.sendSuccess(c,a.head.requestId,{});try{for(let a of b)await this.finishSync(a.source,a.event,a.watermark);console.info("[Pi Desk][ChatSocket] 聊天 Source 订阅完成",{clientId:this.connection.clientId,connectionId:this.connection.connectionId,sourceCount:b.length})}catch(a){console.error("[Pi Desk][ChatSocket] 聊天 Source 同步失败",{clientId:this.connection.clientId,connectionId:this.connection.connectionId,errorName:a instanceof Error?a.name:"UnknownError"}),this.connection.close(1011,"聊天消息同步失败")}}}async send(a){let b=e.P6.send,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"聊天发送参数无效",{key:"errors:chatSendInvalid"});if(Buffer.byteLength(JSON.stringify({head:a.head,body:c.data}),"utf8")>g.lr)return void this.connection.sendError(b.path,a.head.requestId,413,"聊天发送内容超过 31MB",{key:"errors:chatSendTooLarge"});try{console.info("[Pi Desk][ChatSocket] 聊天发送开始",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId,sessionId:c.data.source.sessionId,branchId:c.data.source.branchId,mode:c.data.mode});let d=await this.manage.sendChat(c.data);console.info("[Pi Desk][ChatSocket] 聊天发送已接纳",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId,tempId:d.tempId}),this.connection.sendSuccess(b,a.head.requestId,d)}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"发送聊天消息失败")}}async interrupt(a){let b=e.P6.interrupt,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"聊天打断参数无效",{key:"errors:chatInterruptInvalid"});try{await this.manage.interruptChat(c.data.source),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"打断当前响应失败")}}async compact(a){let b=e.P6.compact,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"上下文压缩参数无效",{key:"errors:chatCompactInvalid"});try{console.info("[Pi Desk][ChatSocket] 手动上下文压缩开始",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId,sessionId:c.data.source.sessionId,branchId:c.data.source.branchId}),await this.manage.compactChat(c.data.source),console.info("[Pi Desk][ChatSocket] 手动上下文压缩完成",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId}),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"压缩上下文失败")}}async reload(a){let b=e.P6.reload,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi 配置重载参数无效",{key:"errors:chatReloadInvalid"});try{console.info("[Pi Desk][ChatSocket] Pi 配置重载开始",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId,sessionId:c.data.source.sessionId,branchId:c.data.source.branchId}),await this.manage.reloadChat(c.data.source,c.data.mode),console.info("[Pi Desk][ChatSocket] Pi 配置重载完成",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId}),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"重载 Pi 配置失败")}}async setPresentation(a){let b=e.P6.presentationSet,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"消息展示模式参数无效");try{await this.manage.setChatPresentation(c.data.source,c.data.mode),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"切换消息展示失败")}}async restoreQueue(a){let b=e.P6.queueRestore,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"恢复队列参数无效",{key:"errors:chatRestoreInvalid"});try{let d=await this.manage.restoreChatQueue(c.data.source),e=Buffer.byteLength(JSON.stringify({head:{op:"resp",path:b.path,requestId:a.head.requestId},body:{code:0,msg:"",data:d}}),"utf8");if(e>g.lr){console.error("[Pi Desk][ChatSocket] 队列恢复响应突破应用上限",{workId:c.data.source.workId,responseBytes:e}),this.connection.sendError(b.path,a.head.requestId,500,"恢复内容超过传输上限",{key:"errors:chatRestoreTooLarge"});return}this.connection.sendSuccess(b,a.head.requestId,d)}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"恢复全部排队消息失败")}}async setModel(a){let b=e.P6.modelSet,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"模型设置参数无效",{key:"errors:chatModelInvalid"});try{await this.manage.setChatModel(c.data),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"设置模型失败")}}async setCapabilityMode(a){let b=e.P6.capabilityModeSet,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"能力模式参数无效",{key:"errors:chatModeInvalid"});try{await this.manage.setChatCapabilityMode(c.data),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"切换能力模式失败")}}sendCommandError(a,b,c,d){if(c instanceof f.dM||c instanceof Error&&"L2ChatSourceBindingError"===c.name)return void this.connection.sendError(a,b,409,"聊天 Source 已过期",{key:"errors:sourceExpired"});if(c instanceof f.nJ||c instanceof Error&&"L2ChatLifecycleBlockedError"===c.name)return void this.connection.sendError(a,b,409,"工作会话正在替换或切换分支",{key:"errors:chatSourceBusy"});let e=c instanceof Error&&c.message?c.message:d;console.warn("[Pi Desk][ChatSocket] 聊天命令执行失败",{path:a,errorName:c instanceof Error?c.name:"UnknownError",message:e}),this.connection.sendError(a,b,400,e)}async finishSync(a,b,c){let d=b,f=c;for(;;){let b=this.subscriptionsByWorkId.get(a.workId);if(!b||!i(b.source,a))return;if(b.overflowed){b.overflowed=!1,b.queuedEvents=[];let[c]=await this.manage.prepareChatSourceSyncs([{source:a,cursor:null}]);if(!c)return;d=c.event,f=c.watermark;continue}for(this.connection.sendPush(e.P6.sourceEvent,{source:a,event:d});;){let c=b.queuedEvents.filter(a=>a.version>f);for(let d of(b.queuedEvents=[],c))this.connection.sendPush(e.P6.sourceEvent,{source:a,event:d.event}),f=d.version;if(b.overflowed)break;if(!(b.queuedEvents.length>0)){b.status="ready";return}}}}handleRuntimeEvent(a){if(this.disposed||!this.connection.isCurrent())return;let b=this.subscriptionsByWorkId.get(a.source.workId);if(b&&i(b.source,a.source)){if("source_invalidated"===a.type)return void this.subscriptionsByWorkId.delete(a.source.workId);if("syncing"===b.status){if(b.overflowed)return;if(b.queuedEvents.length>=128){b.queuedEvents=[],b.overflowed=!0;return}b.queuedEvents.push({version:a.version,event:a.event});return}this.connection.sendPush(e.P6.sourceEvent,{source:a.source,event:a.event})}}restoreSubscriptions(a){for(let[b,c]of a)c?this.subscriptionsByWorkId.set(b,c):this.subscriptionsByWorkId.delete(b)}}d()}catch(a){d(a)}})},18753:(a,b,c)=>{"use strict";let{tokenChars:d}=c(47591);function e(a,b,c){void 0===a[b]?a[b]=[c]:a[b].push(c)}a.exports={format:function(a){return Object.keys(a).map(b=>{let c=a[b];return Array.isArray(c)||(c=[c]),c.map(a=>[b].concat(Object.keys(a).map(b=>{let c=a[b];return Array.isArray(c)||(c=[c]),c.map(a=>!0===a?b:`${b}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(a){let b,c,f=Object.create(null),g=Object.create(null),h=!1,i=!1,j=!1,k=-1,l=-1,m=-1,n=0;for(;n<a.length;n++)if(l=a.charCodeAt(n),void 0===b)if(-1===m&&1===d[l])-1===k&&(k=n);else if(0!==n&&(32===l||9===l))-1===m&&-1!==k&&(m=n);else if(59===l||44===l){if(-1===k)throw SyntaxError(`Unexpected character at index ${n}`);-1===m&&(m=n);let c=a.slice(k,m);44===l?(e(f,c,g),g=Object.create(null)):b=c,k=m=-1}else throw SyntaxError(`Unexpected character at index ${n}`);else if(void 0===c)if(-1===m&&1===d[l])-1===k&&(k=n);else if(32===l||9===l)-1===m&&-1!==k&&(m=n);else if(59===l||44===l){if(-1===k)throw SyntaxError(`Unexpected character at index ${n}`);-1===m&&(m=n),e(g,a.slice(k,m),!0),44===l&&(e(f,b,g),g=Object.create(null),b=void 0),k=m=-1}else if(61===l&&-1!==k&&-1===m)c=a.slice(k,n),k=m=-1;else throw SyntaxError(`Unexpected character at index ${n}`);else if(i){if(1!==d[l])throw SyntaxError(`Unexpected character at index ${n}`);-1===k?k=n:h||(h=!0),i=!1}else if(j)if(1===d[l])-1===k&&(k=n);else if(34===l&&-1!==k)j=!1,m=n;else if(92===l)i=!0;else throw SyntaxError(`Unexpected character at index ${n}`);else if(34===l&&61===a.charCodeAt(n-1))j=!0;else if(-1===m&&1===d[l])-1===k&&(k=n);else if(-1!==k&&(32===l||9===l))-1===m&&(m=n);else if(59===l||44===l){if(-1===k)throw SyntaxError(`Unexpected character at index ${n}`);-1===m&&(m=n);let d=a.slice(k,m);h&&(d=d.replace(/\\/g,""),h=!1),e(g,c,d),44===l&&(e(f,b,g),g=Object.create(null),b=void 0),c=void 0,k=m=-1}else throw SyntaxError(`Unexpected character at index ${n}`);if(-1===k||j||32===l||9===l)throw SyntaxError("Unexpected end of input");-1===m&&(m=n);let o=a.slice(k,m);return void 0===b?e(f,o,g):(void 0===c?e(g,o,!0):h?e(g,c,o.replace(/\\/g,"")):e(g,c,o),e(f,b,g)),f}}},24202:(a,b,c)=>{"use strict";c.d(b,{dZ:()=>f});var d=c(44429),e=c(87048);function f(a,b){if("snapshot"===b.type){var c;return c=b.snapshot,a.taskId!==c.taskId||a.body?.kind!=="conversation"||c.body?.kind!=="conversation"?c:d.ui.parse({...c,body:{kind:"conversation",truncated:c.body.truncated,...(0,e.zR)(a.body,c.body.messages,c.body.temporaryMessages)}})}if("unavailable"===b.type)return null;if("text_append"===b.type){if(a.body?.kind!=="text")throw Error("Text append requires a text task detail snapshot");return{...a,body:{...a.body,text:a.body.text+b.text}}}if(a.body?.kind!=="conversation")throw Error("Conversation event requires a conversation task detail snapshot");return{...a,body:{...(0,e.FR)(a.body,b.event),kind:"conversation",truncated:a.body.truncated}}}},26272:(a,b,c)=>{"use strict";c.d(b,{V:()=>g});var d=c(77598),e=c(69375);c(37234),c(18753),c(95374),c(73),c(58773),c(74972);var f=c(42027);c(89373);class g{constructor(a,b){this.clientId=a,this.socket=b,this.connectionId=(0,d.randomUUID)(),this.inFlightRequestIds=new Set,this.requestHandler=null,this.closeListener=null,this.heartbeat=null,this.alive=!0,this.current=!0,this.started=!1,this.disposed=!1,this.handleHeartbeat=()=>{this.alive?(this.alive=!1,this.socket.ping()):this.terminate()},this.handlePong=()=>{this.alive=!0},this.handleMessage=(a,b)=>{let c;if(!this.current)return;if(b)return void this.socket.close(1003,"仅支持文本 JSON 消息");try{c=JSON.parse(Array.isArray(a)?Buffer.concat(a).toString("utf8"):a instanceof ArrayBuffer?Buffer.from(a).toString("utf8"):a.toString("utf8"))}catch{this.socket.close(1007,"JSON 格式无效");return}let d=e.tU.safeParse(c);if(!d.success)return void this.socket.close(1008,"消息信封或方向无效");let f=d.data.head.requestId;if(this.inFlightRequestIds.has(f))return void this.sendError(d.data.head.path,f,409,"requestId 正在处理中",{key:"common:duplicateRequest"});if(this.inFlightRequestIds.size>=32)return void this.sendError(d.data.head.path,f,429,"当前连接并发请求过多",{key:"common:tooManyRequests"});let g=this.requestHandler;g?(this.inFlightRequestIds.add(f),g(d.data).catch(a=>{console.error("[Pi Desk][AppSocketConnection] 请求处理失败",{clientId:this.clientId,connectionId:this.connectionId,path:d.data.head.path,errorName:a instanceof Error?a.name:"UnknownError"}),this.sendError(d.data.head.path,f,500,"服务端请求处理失败",{key:"common:serverRequestFailed"})}).finally(()=>{this.inFlightRequestIds.delete(f)})):this.sendError(d.data.head.path,f,503,"应用 WebSocket 尚未就绪",{key:"common:socketUnavailable"})},this.handleClose=(a,b)=>{let c={code:a,reason:b.toString("utf8")},d=this.closeListener;this.dispose();try{d?.(c)}catch(a){console.error("[Pi Desk][AppSocketConnection] 关闭监听器执行失败",{clientId:this.clientId,connectionId:this.connectionId,errorName:a instanceof Error?a.name:"UnknownError"})}finally{this.resolveClosed(c)}},this.handleError=a=>{console.error("[Pi Desk][AppSocketConnection] 连接错误",{clientId:this.clientId,connectionId:this.connectionId,errorName:a.name,message:a.message})},this.closedPromise=new Promise(a=>{this.resolveClosed=a})}start(a,b){if(this.started)throw Error("AppSocket connection has already started");this.started=!0,this.requestHandler=a,this.closeListener=b,this.heartbeat=setInterval(this.handleHeartbeat,3e4),this.socket.on("pong",this.handlePong),this.socket.on("message",this.handleMessage),this.socket.on("close",this.handleClose),this.socket.on("error",this.handleError)}isCurrent(){return this.current&&!this.disposed}sendSuccess(a,b,c){this.sendJson(e.hE.parse({head:{op:"resp",path:a.path,requestId:b},body:{code:0,msg:"",data:a.outputSchema.parse(c)}}))}sendError(a,b,c,d,f){this.sendJson(e.hE.parse({head:{op:"resp",path:a,requestId:b},body:{code:c,msg:d,data:null,...f?{i18n:f}:{}}}))}sendPush(a,b){this.sendJson(e.Od.parse({head:{op:"push",path:a.path},body:a.bodySchema.parse(b)}))}supersede(){!this.disposed&&this.current&&(this.current=!1,this.socket.close(e.P9,"连接已被替换"))}close(a=1e3,b="连接已关闭"){if(!this.disposed){if(this.current=!1,this.socket.readyState===f.OPEN)return void this.socket.close(a,b);this.socket.readyState!==f.CLOSED&&this.socket.terminate()}}terminate(){this.disposed||(this.current=!1,this.socket.terminate())}waitForClose(){return this.closedPromise}sendJson(a){if(this.isCurrent()&&this.socket.readyState===f.OPEN){if(this.socket.bufferedAmount>0x2000000)return void this.terminate();try{this.socket.send(JSON.stringify(a))}catch{this.terminate()}}}dispose(){this.disposed||(this.disposed=!0,this.current=!1,this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.inFlightRequestIds.clear(),this.requestHandler=null,this.closeListener=null,this.socket.off("pong",this.handlePong),this.socket.off("message",this.handleMessage),this.socket.off("close",this.handleClose),this.socket.off("error",this.handleError))}}},28026:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{B4:()=>h,UM:()=>i});var e=c(72497),f=c(6108),g=a([f]);f=(g.then?(await g)():g)[0];class j{constructor(a=(0,f.hZ)()){this.runtime=a,this.disposed=!1}setState(a,b){this.ensureActive();let c=e.tv.parse(a),d=null===b?null:e.Dz.parse(b);if(null!==d&&Buffer.byteLength(JSON.stringify(d),"utf8")>65536)throw Error("Plugin global state exceeds 64KB");let f=this.runtime.readSnapshot().plugins[c];if(null===d){if(void 0===f)return}else if(void 0!==f&&JSON.stringify(f)===JSON.stringify(d))return;this.runtime.applyInternal({key:"plugins",update:{pluginName:c,state:null===d?null:structuredClone(d)}})}releasePlugin(a){this.disposed||this.setState(a,null)}dispose(){this.disposed=!0}ensureActive(){if(this.disposed)throw Error("App Plugin State Runtime has been disposed")}}function h(){return globalThis.__piDeskAppPluginStateRuntime||(globalThis.__piDeskAppPluginStateRuntime=new j),globalThis.__piDeskAppPluginStateRuntime}function i(){let a=globalThis.__piDeskAppPluginStateRuntime;globalThis.__piDeskAppPluginStateRuntime=void 0,a?.dispose()}d()}catch(a){d(a)}})},28363:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{Y:()=>h});var e=c(36623),f=c(50906),g=a([f]);f=(g.then?(await g)():g)[0];class h{constructor(a){this.connection=a,this.disposed=!1,this.auth=new f.c(a=>{!this.disposed&&this.connection.isCurrent()&&this.connection.sendPush(e.c.state,a)}),this.routes=Object.freeze([this.route(e.c.list,async()=>({providers:await this.auth.list()})),this.route(e.c.start,async a=>(await this.auth.start(a.provider,a.loginId),{})),this.route(e.c.respond,a=>(this.auth.respond(a.loginId,a.promptId,a.value),{})),this.route(e.c.cancel,a=>(this.auth.cancel(a.loginId),{})),this.route(e.c.logout,async a=>(await this.auth.logout(a.provider),{}))])}dispose(){this.disposed||(this.disposed=!0,this.auth.dispose())}route(a,b){return{path:a.path,access:"ready",handle:async c=>{let d=a.inputSchema.safeParse(c.body);if(!d.success)return void this.connection.sendError(a.path,c.head.requestId,400,"账号操作参数无效");if(!this.disposed&&this.connection.isCurrent())try{let e=await b(d.data);!this.disposed&&this.connection.isCurrent()&&this.connection.sendSuccess(a,c.head.requestId,e)}catch(b){if(this.disposed||!this.connection.isCurrent())return;if(b instanceof f.m)return void this.connection.sendError(a.path,c.head.requestId,b.code,b.message);console.warn("[Pi Desk][ModelAuthSocket] 账号请求失败",{stage:a.path,errorName:b instanceof Error?b.name:"UnknownError"}),this.connection.sendError(a.path,c.head.requestId,500,"账号操作失败,请重试")}}}}}d()}catch(a){d(a)}})},30119:(a,b,c)=>{"use strict";c.d(b,{cx:()=>j});var d=c(36153),e=c(3329),f=c(69375),g=c(72497);let h=d.gM("scope",[d.Ik({scope:d.eu("global")}).strict(),d.Ik({scope:d.eu("session"),source:e.R}).strict()]),i=d.Ik({pluginName:g.tv,target:h,event:g.f7,data:g.Dz}).strict(),j=(0,f._G)({path:"plugins/push",bodySchema:i})},31442:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{L2AppRuntimeTargetNotFoundError:()=>i.fA,createL2AppNotificationPublisher:()=>l,createL2PluginAppRuntimeSink:()=>m,disposeL2AppRuntime:()=>n,getL2AppRuntime:()=>k});var e=c(13127),f=c(8438),g=c(5034),h=c(28026),i=c(6108),j=a([f,g,h,i]);function k(){let a=(0,i.hZ)();if(globalThis.__piDeskModeNamesBinding?.runtime!==a){globalThis.__piDeskModeNamesBinding?.dispose();let b=(0,f.O)(),c=()=>{a.applyInternal({key:"capabilityModes",update:(0,e.HE)(b.read())})};c(),globalThis.__piDeskModeNamesBinding={runtime:a,dispose:b.subscribe(c)}}return a}function l(){let a=(0,g.UM)().createPublisher();return{publish:b=>a.publish({...b,event:null}),update:(b,c)=>a.update(b,c),delete:b=>a.delete(b),dispose:()=>a.dispose()}}function m(){let a=(0,g.UM)(),b=(0,h.B4)();return{setState:(a,c)=>b.setState(a,c),publishNotification:(b,c)=>a.publishPlugin(b,c),updateNotification:(b,c,d)=>a.updatePlugin(b,c,d),deleteNotification:(b,c)=>a.deletePlugin(b,c),releasePlugin:c=>{a.releasePlugin(c),b.releasePlugin(c)}}}function n(){globalThis.__piDeskModeNamesBinding?.dispose(),globalThis.__piDeskModeNamesBinding=void 0,(0,g.HM)(),(0,h.UM)(),(0,i.s6)()}[f,g,h,i]=j.then?(await j)():j,d()}catch(a){d(a)}})},33495:(a,b,c)=>{"use strict";c.d(b,{rn:()=>m});var d=c(36153),e=c(3329),f=c(44429),g=c(69375);let h=d.Ik({source:e.R,taskId:f.mQ.nullable()}).strict(),i=d.Ik({snapshot:f.ui.nullable()}).strict(),j=d.Ik({source:e.R,taskId:f.mQ}).strict(),k=d.Ik({}).strict(),l=d.Ik({source:e.R,taskId:f.mQ,event:f.gm}).strict(),m=Object.freeze({detailWatch:(0,g.Vc)({path:"task-center/detail-watch",inputSchema:h,outputSchema:i}),interrupt:(0,g.Vc)({path:"task-center/interrupt",inputSchema:j,outputSchema:k}),detailEvent:(0,g._G)({path:"task-center/detail-event",bodySchema:l})})},36388:(a,b,c)=>{"use strict";let{kForOnEventAttribute:d,kListener:e}=c(46929),f=Symbol("kCode"),g=Symbol("kData"),h=Symbol("kError"),i=Symbol("kMessage"),j=Symbol("kReason"),k=Symbol("kTarget"),l=Symbol("kType"),m=Symbol("kWasClean");class n{constructor(a){this[k]=null,this[l]=a}get target(){return this[k]}get type(){return this[l]}}Object.defineProperty(n.prototype,"target",{enumerable:!0}),Object.defineProperty(n.prototype,"type",{enumerable:!0});class o extends n{constructor(a,b={}){super(a),this[f]=void 0===b.code?0:b.code,this[j]=void 0===b.reason?"":b.reason,this[m]=void 0!==b.wasClean&&b.wasClean}get code(){return this[f]}get reason(){return this[j]}get wasClean(){return this[m]}}Object.defineProperty(o.prototype,"code",{enumerable:!0}),Object.defineProperty(o.prototype,"reason",{enumerable:!0}),Object.defineProperty(o.prototype,"wasClean",{enumerable:!0});class p extends n{constructor(a,b={}){super(a),this[h]=void 0===b.error?null:b.error,this[i]=void 0===b.message?"":b.message}get error(){return this[h]}get message(){return this[i]}}Object.defineProperty(p.prototype,"error",{enumerable:!0}),Object.defineProperty(p.prototype,"message",{enumerable:!0});class q extends n{constructor(a,b={}){super(a),this[g]=void 0===b.data?null:b.data}get data(){return this[g]}}function r(a,b,c){"object"==typeof a&&a.handleEvent?a.handleEvent.call(a,c):a.call(b,c)}Object.defineProperty(q.prototype,"data",{enumerable:!0}),a.exports={CloseEvent:o,ErrorEvent:p,Event:n,EventTarget:{addEventListener(a,b,c={}){let f;for(let f of this.listeners(a))if(!c[d]&&f[e]===b&&!f[d])return;if("message"===a)f=function(a,c){let d=new q("message",{data:c?a:a.toString()});d[k]=this,r(b,this,d)};else if("close"===a)f=function(a,c){let d=new o("close",{code:a,reason:c.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});d[k]=this,r(b,this,d)};else if("error"===a)f=function(a){let c=new p("error",{error:a,message:a.message});c[k]=this,r(b,this,c)};else{if("open"!==a)return;f=function(){let a=new n("open");a[k]=this,r(b,this,a)}}f[d]=!!c[d],f[e]=b,c.once?this.once(a,f):this.on(a,f)},removeEventListener(a,b){for(let c of this.listeners(a))if(c[e]===b&&!c[d]){this.removeListener(a,c);break}}},MessageEvent:q}},36623:(a,b,c)=>{"use strict";c.d(b,{c:()=>n});var d=c(36153),e=c(69375);let f=d.Ik({}).strict(),g=d.Yj().trim().min(1).max(128),h=d.Yj().max(32768),i=d.Ik({url:h,label:h.optional()}).strict(),j=d.Ik({provider:g,name:h,loggedIn:d.zM(),conflict:d.Yj().nullable()}).strict(),k=d.Ik({id:d.Yj().uuid(),type:d.k5(["text","secret","select","manual_code"]),message:h,placeholder:h.optional(),options:d.YO(d.Ik({id:h,label:h,description:h.optional()}).strict()).optional()}).strict(),l=d.gM("type",[d.Ik({type:d.eu("auth_url"),url:h,instructions:h.optional()}).strict(),d.Ik({type:d.eu("device_code"),userCode:h,verificationUri:h}).strict(),d.Ik({type:d.eu("info"),message:h,links:d.YO(i).optional()}).strict(),d.Ik({type:d.eu("progress"),message:h}).strict()]),m=d.Ik({loginId:d.Yj().uuid(),provider:g,status:d.k5(["running","completed","cancelled","error"]),notice:l.nullable(),prompt:k.nullable(),message:d.Yj().nullable()}).strict(),n=Object.freeze({list:(0,e.Vc)({path:"model-auth/list",inputSchema:f,outputSchema:d.Ik({providers:d.YO(j)}).strict()}),start:(0,e.Vc)({path:"model-auth/start",inputSchema:d.Ik({loginId:d.Yj().uuid(),provider:g}).strict(),outputSchema:f}),respond:(0,e.Vc)({path:"model-auth/respond",inputSchema:d.Ik({loginId:d.Yj().uuid(),promptId:d.Yj().uuid(),value:h}).strict(),outputSchema:f}),cancel:(0,e.Vc)({path:"model-auth/cancel",inputSchema:d.Ik({loginId:d.Yj().uuid()}).strict(),outputSchema:f}),logout:(0,e.Vc)({path:"model-auth/logout",inputSchema:d.Ik({provider:g}).strict(),outputSchema:f}),state:(0,e._G)({path:"model-auth/state",bodySchema:m})})},37234:(a,b,c)=>{"use strict";c(42027);let{Duplex:d}=c(27910);function e(a){a.emit("close")}function f(){!this.destroyed&&this._writableState.finished&&this.destroy()}function g(a){this.removeListener("error",g),this.destroy(),0===this.listenerCount("error")&&this.emit("error",a)}a.exports=function(a,b){let c=!0,h=new d({...b,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return a.on("message",function(b,c){let d=!c&&h._readableState.objectMode?b.toString():b;h.push(d)||a.pause()}),a.once("error",function(a){h.destroyed||(c=!1,h.destroy(a))}),a.once("close",function(){h.destroyed||h.push(null)}),h._destroy=function(b,d){if(a.readyState===a.CLOSED){d(b),process.nextTick(e,h);return}let f=!1;a.once("error",function(a){f=!0,d(a)}),a.once("close",function(){f||d(b),process.nextTick(e,h)}),c&&a.terminate()},h._final=function(b){a.readyState===a.CONNECTING?a.once("open",function(){h._final(b)}):null!==a._socket&&(a._socket._writableState.finished?(b(),h._readableState.endEmitted&&h.destroy()):(a._socket.once("finish",function(){b()}),a.close()))},h._read=function(){a.isPaused&&a.resume()},h._write=function(b,c,d){a.readyState===a.CONNECTING?a.once("open",function(){h._write(b,c,d)}):a.send(b,d)},h.on("end",f),h.on("error",g),h}},37497:(a,b,c)=>{"use strict";c.d(b,{P6:()=>K});var d=c(36153),e=c(62695),f=c(75278),g=c(69375);let h=d.Ik({source:e.Pi,cursor:e.UR}).strict(),i=d.Ik({subscriptions:d.YO(h).min(1)}).strict().superRefine((a,b)=>{let c=new Set;for(let[d,e]of a.subscriptions.entries())c.has(e.source.workId)&&b.addIssue({code:"custom",message:"subscriptions cannot contain duplicate workId values",path:["subscriptions",d,"source","workId"]}),c.add(e.source.workId)}),j=d.Ik({}).strict(),k=d.YO(e.wR).superRefine((a,b)=>{let c=new Set;for(let[d,e]of a.entries())d>0&&e.location.index!==a[d-1].location.index+1&&b.addIssue({code:"custom",message:"chat sync message indexes must be continuous",path:[d,"location","index"]}),c.has(e.location.entryId)&&b.addIssue({code:"custom",message:"chat sync entryId values must be unique",path:[d,"location","entryId"]}),c.add(e.location.entryId)}),l=d.Ik({type:d.eu("session_sync"),mode:d.eu("full"),baseCursor:d.ch(),messages:k,temporaryMessages:d.YO(e.yI),runtime:e.wf}).strict().superRefine((a,b)=>{a.messages[0]&&0!==a.messages[0].location.index&&b.addIssue({code:"custom",message:"full sync must start at index 0",path:["messages",0,"location","index"]})}),m=d.Ik({type:d.eu("session_sync"),mode:d.eu("incremental"),baseCursor:e.DK,messages:k,temporaryMessages:d.YO(e.yI),runtime:e.wf}).strict().superRefine((a,b)=>{let c=a.messages[0];c&&c.location.index!==a.baseCursor.index+1&&b.addIssue({code:"custom",message:"incremental sync must start after baseCursor",path:["messages",0,"location","index"]})}),n=d.KC([l,m]),o=f.hS,p=f.ef,q=f.gK,r=f.PS,s=d.Ik({type:d.eu("runtime_update"),runtime:e.wf}).strict(),t=d.KC([n,o,p,q,r,s]),u=d.Ik({source:e.Pi,event:t}).strict(),v=d.k5(["auto","follow_up"]),w=d.Ik({source:e.Pi,mode:v,text:d.Yj(),images:d.YO(e.xh).max(10)}).strict().refine(a=>a.text.trim().length>0||a.images.length>0,{message:"chat input requires text or images"}),x=d.Ik({tempId:e.R3.shape.tempId}).strict(),y=d.Ik({source:e.Pi}).strict(),z=d.Ik({}).strict(),A=y.extend({mode:e.TV.optional()}).strict(),B=y.extend({mode:e.TV}).strict(),C=d.Ik({}).strict(),D=d.Ik({}).strict(),E=d.Ik({text:d.Yj(),images:d.YO(e.xh)}).strict(),F=d.Ik({source:e.Pi,model:e.w$}).strict(),G=d.Ik({}).strict(),H=d.Ik({source:e.Pi,capabilityMode:e.wf.shape.capabilityMode}).strict(),I=d.Ik({}).strict();d.k5(["chat/subscribe","chat/send","chat/interrupt","chat/reload","chat/presentation-set","chat/compact","chat/queue-restore","chat/model-set","chat/capability-mode-set"]);let J=d.eu("chat/source-event"),K=Object.freeze({subscribe:(0,g.Vc)({path:"chat/subscribe",inputSchema:i,outputSchema:j,timeoutMs:125e3}),send:(0,g.Vc)({path:"chat/send",inputSchema:w,outputSchema:x,timeoutMs:12e4}),interrupt:(0,g.Vc)({path:"chat/interrupt",inputSchema:y,outputSchema:z}),reload:(0,g.Vc)({path:"chat/reload",inputSchema:A,outputSchema:C,timeoutMs:125e3}),presentationSet:(0,g.Vc)({path:"chat/presentation-set",inputSchema:B,outputSchema:C}),compact:(0,g.Vc)({path:"chat/compact",inputSchema:y,outputSchema:D,timeoutMs:6e5}),queueRestore:(0,g.Vc)({path:"chat/queue-restore",inputSchema:y,outputSchema:E}),modelSet:(0,g.Vc)({path:"chat/model-set",inputSchema:F,outputSchema:G}),capabilityModeSet:(0,g.Vc)({path:"chat/capability-mode-set",inputSchema:H,outputSchema:I}),sourceEvent:(0,g._G)({path:J.value,bodySchema:u})})},37721:(a,b,c)=>{},42027:(a,b,c)=>{"use strict";let d=c(94735),e=c(55591),f=c(81630),g=c(91645),h=c(34631),{randomBytes:i,createHash:j}=c(55511),{Duplex:k,Readable:l}=c(27910),{URL:m}=c(79551),n=c(95374),o=c(73),p=c(58773),{isBlob:q}=c(47591),{BINARY_TYPES:r,CLOSE_TIMEOUT:s,EMPTY_BUFFER:t,GUID:u,kForOnEventAttribute:v,kListener:w,kStatusCode:x,kWebSocket:y,NOOP:z}=c(46929),{EventTarget:{addEventListener:A,removeEventListener:B}}=c(36388),{format:C,parse:D}=c(18753),{toBuffer:E}=c(52218),F=Symbol("kAborted"),G=[8,13],H=["CONNECTING","OPEN","CLOSING","CLOSED"],I=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class J extends d{constructor(a,b,c){super(),this._binaryType=r[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=t,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=J.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==a?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===b?b=[]:Array.isArray(b)||("object"==typeof b&&null!==b?(c=b,b=[]):b=[b]),function a(b,c,d,g){let h,k,l,o,p={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:s,protocolVersion:G[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...g,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(b._autoPong=p.autoPong,b._closeTimeout=p.closeTimeout,!G.includes(p.protocolVersion))throw RangeError(`Unsupported protocol version: ${p.protocolVersion} (supported versions: ${G.join(", ")})`);if(c instanceof m)h=c;else try{h=new m(c)}catch{throw SyntaxError(`Invalid URL: ${c}`)}"http:"===h.protocol?h.protocol="ws:":"https:"===h.protocol&&(h.protocol="wss:"),b._url=h.href;let q="wss:"===h.protocol,r="ws+unix:"===h.protocol;if("ws:"===h.protocol||q||r?r&&!h.pathname?k="The URL's pathname is empty":h.hash&&(k="The URL contains a fragment identifier"):k='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',k){let a=SyntaxError(k);if(0!==b._redirects)return void K(b,a);throw a}let t=q?443:80,v=i(16).toString("base64"),w=q?e.request:f.request,x=new Set;if(p.createConnection=p.createConnection||(q?M:L),p.defaultPort=p.defaultPort||t,p.port=h.port||t,p.host=h.hostname.startsWith("[")?h.hostname.slice(1,-1):h.hostname,p.headers={...p.headers,"Sec-WebSocket-Version":p.protocolVersion,"Sec-WebSocket-Key":v,Connection:"Upgrade",Upgrade:"websocket"},p.path=h.pathname+h.search,p.timeout=p.handshakeTimeout,p.perMessageDeflate&&(l=new n({...p.perMessageDeflate,isServer:!1,maxPayload:p.maxPayload}),p.headers["Sec-WebSocket-Extensions"]=C({[n.extensionName]:l.offer()})),d.length){for(let a of d){if("string"!=typeof a||!I.test(a)||x.has(a))throw SyntaxError("An invalid or duplicated subprotocol was specified");x.add(a)}p.headers["Sec-WebSocket-Protocol"]=d.join(",")}if(p.origin&&(p.protocolVersion<13?p.headers["Sec-WebSocket-Origin"]=p.origin:p.headers.Origin=p.origin),(h.username||h.password)&&(p.auth=`${h.username}:${h.password}`),r){let a=p.path.split(":");p.socketPath=a[0],p.path=a[1]}if(p.followRedirects){if(0===b._redirects){b._originalIpc=r,b._originalSecure=q,b._originalHostOrSocketPath=r?p.socketPath:h.host;let a=g&&g.headers;if(g={...g,headers:{}},a)for(let[b,c]of Object.entries(a))g.headers[b.toLowerCase()]=c}else if(0===b.listenerCount("redirect")){let a=r?!!b._originalIpc&&p.socketPath===b._originalHostOrSocketPath:!b._originalIpc&&h.host===b._originalHostOrSocketPath;a&&(!b._originalSecure||q)||(delete p.headers.authorization,delete p.headers.cookie,a||delete p.headers.host,p.auth=void 0)}p.auth&&!g.headers.authorization&&(g.headers.authorization="Basic "+Buffer.from(p.auth).toString("base64")),o=b._req=w(p),b._redirects&&b.emit("redirect",b.url,o)}else o=b._req=w(p);p.timeout&&o.on("timeout",()=>{N(b,o,"Opening handshake has timed out")}),o.on("error",a=>{null===o||o[F]||(o=b._req=null,K(b,a))}),o.on("response",e=>{let f=e.headers.location,h=e.statusCode;if(f&&p.followRedirects&&h>=300&&h<400){let e;if(++b._redirects>p.maxRedirects)return void N(b,o,"Maximum redirects exceeded");o.abort();try{e=new m(f,c)}catch(a){K(b,SyntaxError(`Invalid URL: ${f}`));return}a(b,e,d,g)}else b.emit("unexpected-response",o,e)||N(b,o,`Unexpected server response: ${e.statusCode}`)}),o.on("upgrade",(a,c,d)=>{let e;if(b.emit("upgrade",a),b.readyState!==J.CONNECTING)return;o=b._req=null;let f=a.headers.upgrade;if(void 0===f||"websocket"!==f.toLowerCase())return void N(b,c,"Invalid Upgrade header");let g=j("sha1").update(v+u).digest("base64");if(a.headers["sec-websocket-accept"]!==g)return void N(b,c,"Invalid Sec-WebSocket-Accept header");let h=a.headers["sec-websocket-protocol"];if(void 0!==h?x.size?x.has(h)||(e="Server sent an invalid subprotocol"):e="Server sent a subprotocol but none was requested":x.size&&(e="Server sent no subprotocol"),e)return void N(b,c,e);h&&(b._protocol=h);let i=a.headers["sec-websocket-extensions"];if(void 0!==i){let a;if(!l)return void N(b,c,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");try{a=D(i)}catch(a){N(b,c,"Invalid Sec-WebSocket-Extensions header");return}let d=Object.keys(a);if(1!==d.length||d[0]!==n.extensionName)return void N(b,c,"Server indicated an extension that was not requested");try{l.accept(a[n.extensionName])}catch(a){N(b,c,"Invalid Sec-WebSocket-Extensions header");return}b._extensions[n.extensionName]=l}b.setSocket(c,d,{allowSynchronousEvents:p.allowSynchronousEvents,generateMask:p.generateMask,maxBufferedChunks:p.maxBufferedChunks,maxFragments:p.maxFragments,maxPayload:p.maxPayload,skipUTF8Validation:p.skipUTF8Validation})}),p.finishRequest?p.finishRequest(o,b):o.end()}(this,a,b,c)):(this._autoPong=c.autoPong,this._closeTimeout=c.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(a){r.includes(a)&&(this._binaryType=a,this._receiver&&(this._receiver._binaryType=a))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(a,b,c){let d=new o({allowSynchronousEvents:c.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:c.maxBufferedChunks,maxFragments:c.maxFragments,maxPayload:c.maxPayload,skipUTF8Validation:c.skipUTF8Validation}),e=new p(a,this._extensions,c.generateMask);this._receiver=d,this._sender=e,this._socket=a,d[y]=this,e[y]=this,a[y]=this,d.on("conclude",P),d.on("drain",Q),d.on("error",R),d.on("message",T),d.on("ping",U),d.on("pong",V),e.onerror=X,a.setTimeout&&a.setTimeout(0),a.setNoDelay&&a.setNoDelay(),b.length>0&&a.unshift(b),a.on("close",Z),a.on("data",$),a.on("end",_),a.on("error",aa),this._readyState=J.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=J.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[n.extensionName]&&this._extensions[n.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=J.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(a,b){if(this.readyState!==J.CLOSED){if(this.readyState===J.CONNECTING)return void N(this,this._req,"WebSocket was closed before the connection was established");if(this.readyState===J.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=J.CLOSING,this._sender.close(a,b,!this._isServer,a=>{!a&&(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Y(this)}}pause(){this.readyState!==J.CONNECTING&&this.readyState!==J.CLOSED&&(this._paused=!0,this._socket.pause())}ping(a,b,c){if(this.readyState===J.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof a?(c=a,a=b=void 0):"function"==typeof b&&(c=b,b=void 0),"number"==typeof a&&(a=a.toString()),this.readyState!==J.OPEN)?O(this,a,c):(void 0===b&&(b=!this._isServer),this._sender.ping(a||t,b,c))}pong(a,b,c){if(this.readyState===J.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof a?(c=a,a=b=void 0):"function"==typeof b&&(c=b,b=void 0),"number"==typeof a&&(a=a.toString()),this.readyState!==J.OPEN)?O(this,a,c):(void 0===b&&(b=!this._isServer),this._sender.pong(a||t,b,c))}resume(){this.readyState!==J.CONNECTING&&this.readyState!==J.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(a,b,c){if(this.readyState===J.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof b&&(c=b,b={}),"number"==typeof a&&(a=a.toString()),this.readyState!==J.OPEN)return void O(this,a,c);let d={binary:"string"!=typeof a,mask:!this._isServer,compress:!0,fin:!0,...b};this._extensions[n.extensionName]||(d.compress=!1),this._sender.send(a||t,d,c)}terminate(){if(this.readyState!==J.CLOSED){if(this.readyState===J.CONNECTING)return void N(this,this._req,"WebSocket was closed before the connection was established");this._socket&&(this._readyState=J.CLOSING,this._socket.destroy())}}}function K(a,b){a._readyState=J.CLOSING,a._errorEmitted=!0,a.emit("error",b),a.emitClose()}function L(a){return a.path=a.socketPath,g.connect(a)}function M(a){return a.path=void 0,a.servername||""===a.servername||(a.servername=g.isIP(a.host)?"":a.host),h.connect(a)}function N(a,b,c){a._readyState=J.CLOSING;let d=Error(c);Error.captureStackTrace(d,N),b.setHeader?(b[F]=!0,b.abort(),b.socket&&!b.socket.destroyed&&b.socket.destroy(),process.nextTick(K,a,d)):(b.destroy(d),b.once("error",a.emit.bind(a,"error")),b.once("close",a.emitClose.bind(a)))}function O(a,b,c){if(b){let c=q(b)?b.size:E(b).length;a._socket?a._sender._bufferedBytes+=c:a._bufferedAmount+=c}if(c){let b=Error(`WebSocket is not open: readyState ${a.readyState} (${H[a.readyState]})`);process.nextTick(c,b)}}function P(a,b){let c=this[y];c._closeFrameReceived=!0,c._closeMessage=b,c._closeCode=a,void 0!==c._socket[y]&&(c._socket.removeListener("data",$),process.nextTick(W,c._socket),1005===a?c.close():c.close(a,b))}function Q(){let a=this[y];a.isPaused||a._socket.resume()}function R(a){let b=this[y];void 0!==b._socket[y]&&(b._socket.removeListener("data",$),process.nextTick(W,b._socket),b.close(a[x])),b._errorEmitted||(b._errorEmitted=!0,b.emit("error",a))}function S(){this[y].emitClose()}function T(a,b){this[y].emit("message",a,b)}function U(a){let b=this[y];b._autoPong&&b.pong(a,!this._isServer,z),b.emit("ping",a)}function V(a){this[y].emit("pong",a)}function W(a){a.resume()}function X(a){let b=this[y];b.readyState!==J.CLOSED&&(b.readyState===J.OPEN&&(b._readyState=J.CLOSING,Y(b)),this._socket.end(),b._errorEmitted||(b._errorEmitted=!0,b.emit("error",a)))}function Y(a){a._closeTimer=setTimeout(a._socket.destroy.bind(a._socket),a._closeTimeout)}function Z(){let a=this[y];if(this.removeListener("close",Z),this.removeListener("data",$),this.removeListener("end",_),a._readyState=J.CLOSING,!this._readableState.endEmitted&&!a._closeFrameReceived&&!a._receiver._writableState.errorEmitted&&0!==this._readableState.length){let b=this.read(this._readableState.length);a._receiver.write(b)}a._receiver.end(),this[y]=void 0,clearTimeout(a._closeTimer),a._receiver._writableState.finished||a._receiver._writableState.errorEmitted?a.emitClose():(a._receiver.on("error",S),a._receiver.on("finish",S))}function $(a){this[y]._receiver.write(a)||this.pause()}function _(){let a=this[y];a._readyState=J.CLOSING,a._receiver.end(),this.end()}function aa(){let a=this[y];this.removeListener("error",aa),this.on("error",z),a&&(a._readyState=J.CLOSING,this.destroy())}Object.defineProperty(J,"CONNECTING",{enumerable:!0,value:H.indexOf("CONNECTING")}),Object.defineProperty(J.prototype,"CONNECTING",{enumerable:!0,value:H.indexOf("CONNECTING")}),Object.defineProperty(J,"OPEN",{enumerable:!0,value:H.indexOf("OPEN")}),Object.defineProperty(J.prototype,"OPEN",{enumerable:!0,value:H.indexOf("OPEN")}),Object.defineProperty(J,"CLOSING",{enumerable:!0,value:H.indexOf("CLOSING")}),Object.defineProperty(J.prototype,"CLOSING",{enumerable:!0,value:H.indexOf("CLOSING")}),Object.defineProperty(J,"CLOSED",{enumerable:!0,value:H.indexOf("CLOSED")}),Object.defineProperty(J.prototype,"CLOSED",{enumerable:!0,value:H.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(a=>{Object.defineProperty(J.prototype,a,{enumerable:!0})}),["open","error","close","message"].forEach(a=>{Object.defineProperty(J.prototype,`on${a}`,{enumerable:!0,get(){for(let b of this.listeners(a))if(b[v])return b[w];return null},set(b){for(let b of this.listeners(a))if(b[v]){this.removeListener(a,b);break}"function"==typeof b&&this.addEventListener(a,b,{[v]:!0})}})}),J.prototype.addEventListener=A,J.prototype.removeEventListener=B,a.exports=J},43973:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{G:()=>i});var e=c(23349),f=c(71779),g=c(25406),h=a([g]);g=(h.then?(await h)():h)[0];class i{constructor(a,b,c){this.connection=a,this.manage=b,this.appRuntime=c,this.status="new",this.dirty=!1,this.disposed=!1,this.unsubscribeWorkSessions=null,this.unsubscribeAppRuntime=null,this.routes=Object.freeze([{path:e.kM.list.path,access:"bootstrap",handle:a=>this.initialize(a)},{path:e.kM.acknowledgeCompleted.path,access:"ready",handle:a=>this.acknowledgeCompleted(a)}])}isReady(){return"ready"===this.status&&!this.disposed}dispose(){this.disposed||(this.disposed=!0,this.status="new",this.unsubscribeWorkSessions?.(),this.unsubscribeWorkSessions=null,this.unsubscribeAppRuntime?.(),this.unsubscribeAppRuntime=null)}async initialize(a){let b=e.kM.list;if("initializing"===this.status)return void this.connection.sendError(b.path,a.head.requestId,409,"工作会话正在初始化",{key:"errors:sessionsInitializing"});if(!b.inputSchema.safeParse(a.body).success)return void this.connection.sendError(b.path,a.head.requestId,400,"工作会话初始化参数无效",{key:"errors:sessionsInitializeInvalid"});this.status="initializing",this.dirty=!1,this.unsubscribeWorkSessions?.(),this.unsubscribeWorkSessions=this.manage.subscribeUpdates(a=>{if(!this.disposed&&this.connection.isCurrent()){if("initializing"===this.status){this.dirty=!0;return}"ready"===this.status&&this.connection.sendPush(e.kM.update,a)}}),this.unsubscribeAppRuntime?.(),this.unsubscribeAppRuntime=this.appRuntime.subscribe(a=>{if(!this.disposed&&this.connection.isCurrent()){if("initializing"===this.status){this.dirty=!0;return}"ready"===this.status&&this.connection.sendPush(f.R.update,a)}});try{let c,d;do if(this.dirty=!1,c=await this.manage.listWorkSessions(),d=this.appRuntime.readSnapshot(),this.disposed||!this.connection.isCurrent())return;while(this.dirty);let e={...c,appRuntime:d};this.status="ready",this.connection.sendSuccess(b,a.head.requestId,e),console.info("[Pi Desk][WorkSessionSocket] 工作会话初始化完成",{clientId:this.connection.clientId,connectionId:this.connection.connectionId,workSessionCount:e.workSessions.length,notificationCount:e.appRuntime.notifications.length,pluginStateCount:Object.keys(e.appRuntime.plugins).length})}catch(c){this.status="new",this.unsubscribeWorkSessions?.(),this.unsubscribeWorkSessions=null,this.unsubscribeAppRuntime?.(),this.unsubscribeAppRuntime=null,console.error("[Pi Desk][WorkSessionSocket] 工作会话初始化失败",{clientId:this.connection.clientId,connectionId:this.connection.connectionId,errorName:c instanceof Error?c.name:"UnknownError"}),this.connection.sendError(b.path,a.head.requestId,500,"工作会话初始化失败",{key:"errors:sessionsInitializeFailed"})}}async acknowledgeCompleted(a){let b=e.kM.acknowledgeCompleted,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"工作会话完成确认参数无效",{key:"errors:completionAckInvalid"});try{await this.manage.acknowledgeCompleted(c.data.workId),this.connection.sendSuccess(b,a.head.requestId,{workId:c.data.workId})}catch(d){let c=d instanceof g.WorkSessionNotFoundError;this.connection.sendError(b.path,a.head.requestId,c?404:500,c?"工作会话不存在":"确认工作会话完成状态失败",{key:c?"errors:sessionMissing":"errors:completionAckFailed"})}}}d()}catch(a){d(a)}})},44429:(a,b,c)=>{"use strict";c.d(b,{Ld:()=>z,NN:()=>y,gm:()=>w,mQ:()=>j,ui:()=>u});var d=c(36153),e=c(3329),f=c(56255),g=c(75278),h=c(78143),i=c(75106);let j=d.Yj().trim().min(1).max(200),k=d.Yj().trim().min(1).max(100).nullable(),l=d.Yj().trim().min(1).max(100).nullable(),m=d.Yj().trim().min(1).max(200),n=d.Ik({label:d.Yj().trim().min(1).max(64),value:d.Yj().trim().min(1).max(500)}).strict(),o=d.Yj().trim().min(1).max(300).nullable(),p=d.k5(["running","completed","failed","stopped","interrupted"]),q=d.Ik({taskId:j,taskKind:k,taskType:l,title:m,info:d.YO(n).max(12),status:p,activity:o,startedAt:i.k,endedAt:i.k.nullable()}).strict().superRefine((a,b)=>{"running"===a.status&&null!==a.endedAt&&b.addIssue({code:"custom",message:"running task requires endedAt=null",path:["endedAt"]}),"running"!==a.status&&null===a.endedAt&&b.addIssue({code:"custom",message:"terminal task requires endedAt",path:["endedAt"]})});d.Ik({tasks:d.YO(q)}).strict().superRefine((a,b)=>{let c=new Set;for(let[d,e]of a.tasks.entries())c.has(e.taskId)&&b.addIssue({code:"custom",message:"taskId values must be unique",path:["tasks",d,"taskId"]}),c.add(e.taskId)});let r=d.Ik({kind:d.eu("text"),text:d.Yj(),truncated:d.zM()}).strict(),s=f.RX.extend({kind:d.eu("conversation"),truncated:d.zM()}).strict(),t=d.KC([d.ch(),r,s]),u=d.Ik({taskId:j,canInterrupt:d.zM(),body:t}).strict(),v=g.mv,w=d.KC([d.Ik({type:d.eu("snapshot"),snapshot:u}).strict(),d.Ik({type:d.eu("text_append"),text:d.Yj().min(1)}).strict(),d.Ik({type:d.eu("conversation_event"),event:v}).strict(),d.Ik({type:d.eu("unavailable")}).strict()]),x=d.Ik({source:e.R,taskId:j,entryId:h.Rv}).strict(),y=f.XM;x.extend({imageIndex:d.ai().int().nonnegative()}).strict();let z=f.y0},45407:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{Y3:()=>q,o3:()=>p,qc:()=>r,rt:()=>n,x4:()=>o});var e=c(44429),f=c(24202),g=c(5340),h=c(32757),i=c(15819),j=c(63178),k=a([g,h,i,j]);[g,h,i,j]=k.then?(await k)():k;class n{constructor(a){this.resolveRuntime=a,this.commandTails=new Map}async watchDetail(a,b,c){let d=await this.resolveRuntime(a),e=[],g=null,h=null,i=!1,k=!1,l=d=>{if(!k){if(!i||!g||!h)return void e.push(d);try{let b=(0,j.I)(a,g,d);if(!b)return;let e=(0,f.dZ)(g,b);e&&(g=e),c(b)}catch(f){console.warn("[Pi Desk][TaskCenterRuntime] 任务详情增量无效,重建 Snapshot",{workId:a.workId,taskId:b,eventType:d.type,errorName:f instanceof Error?f.name:"UnknownError"});let e=(0,j.C)(a,h.readSnapshot());g=e,c({type:"snapshot",snapshot:e})}}};try{for(let c of(h=await d.watchTaskDetail(b,l),await this.resolveRuntime(a),g=(0,j.C)(a,h.snapshot),i=!0,e.splice(0)))l(c);return{snapshot:g,release:()=>{k||(k=!0,e.length=0,h?.release(),h=null,g=null)}}}catch(a){throw k=!0,h?.release(),m(a)}}async getMessageDetail(a,b,c){try{let d=await this.resolveRuntime(a),{index:f,entry:h}=await d.readTaskMessage(b,c),i=(0,g.Cz)(f,h.entryId,h.timestampMs,h.message,a);if(!i.fixed.hasDetail||void 0===i.detail)throw new t(c);return e.NN.parse({index:f,entryId:c,detail:i.detail})}catch(a){throw l(a)}}async getImage(a,b,c,d){try{let f=await this.resolveRuntime(a);return e.Ld.parse(await f.readTaskImage(b,c,d))}catch(a){throw l(a)}}interrupt(a,b){let c=JSON.stringify([a.workId,a.sessionId,a.branchId,b]),d=this.commandTails.get(c)??Promise.resolve(),e=async()=>{let c=await this.resolveRuntime(a);await c.interruptTask(b)},f=d.then(e,e),g=f.then(()=>void 0,()=>void 0);return this.commandTails.set(c,g),g.finally(()=>{this.commandTails.get(c)===g&&this.commandTails.delete(c)}),f.catch(a=>Promise.reject(m(a)))}}function l(a){let b=m(a);return b===a?new s(a instanceof Error?a.message:"Task detail source is unavailable"):b}function m(a){return a instanceof i.cI||a instanceof h.L9?new o(a.message):a instanceof i.JF?new p(a.message):a instanceof h.dw?new q(a.message):a instanceof h.HJ?new r(a.message):a}class o extends Error{constructor(a){super(a),this.name="L2TaskNotFoundError"}}class p extends Error{constructor(a){super(a),this.name="L2TaskNotInterruptibleError"}}class q extends Error{constructor(a){super(a),this.name="L2TaskDetailUnsupportedError"}}class r extends Error{constructor(a){super(a),this.name="L2TaskMessageNotFoundError"}}class s extends Error{constructor(a){super(a),this.name="L2TaskDetailUnavailableError"}}class t extends Error{constructor(a){super(`Task message does not provide canonical detail: ${a}`),this.name="L2TaskMessageDetailUnavailableError"}}d()}catch(a){d(a)}})},46929:a=>{"use strict";let b=["nodebuffer","arraybuffer","fragments"],c="u">typeof Blob;c&&b.push("blob"),a.exports={BINARY_TYPES:b,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:c,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},47389:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{k:()=>j});var e=c(8663),f=c(55490),g=c(45870),h=a([f]);function i(a){return JSON.stringify([a.workId,a.sessionId,a.branchId])}f=(h.then?(await h)():h)[0];class j{constructor(a,b){this.connection=a,this.manage=b,this.subscriptions=new Map,this.disposed=!1,this.releaseSources=b.subscribeMessageEvents(a=>{"source_invalidated"===a.type&&this.release(i(a.source))}),this.routes=[{path:e.H.subscribe.path,access:"ready",handle:async a=>this.subscribe(a)},{path:e.H.unsubscribe.path,access:"ready",handle:async a=>this.unsubscribe(a)},{path:e.H.respond.path,access:"ready",handle:async a=>this.respond(a)}]}dispose(){if(!this.disposed)for(let a of(this.disposed=!0,this.releaseSources(),this.subscriptions.keys()))this.release(a)}subscribe(a){if(this.disposed||!this.connection.isCurrent())return;let b=e.H.subscribe,c=b.inputSchema.safeParse(a.body);if(!c.success)return this.invalid(a);try{let{source:d}=c.data,f=this.manage.getNativeUi(d),g=i(d);this.release(g),this.subscriptions.set(g,f.subscribe(a=>{!this.disposed&&this.connection.isCurrent()&&this.connection.sendPush(e.H.event,{source:d,event:a})})),this.connection.sendSuccess(b,a.head.requestId,f.snapshot())}catch(b){this.fail(a,b)}}unsubscribe(a){if(this.disposed||!this.connection.isCurrent())return;let b=e.H.unsubscribe,c=b.inputSchema.safeParse(a.body);if(!c.success)return this.invalid(a);this.release(i(c.data.source)),this.connection.sendSuccess(b,a.head.requestId,{})}respond(a){if(this.disposed||!this.connection.isCurrent())return;let b=e.H.respond,c=b.inputSchema.safeParse(a.body);if(!c.success)return this.invalid(a);try{this.manage.getNativeUi(c.data.source).respond(c.data.response),this.connection.sendSuccess(b,a.head.requestId,{})}catch(b){this.fail(a,b)}}release(a){this.subscriptions.get(a)?.(),this.subscriptions.delete(a)}invalid(a){this.connection.sendError(a.head.path,a.head.requestId,400,"插件交互参数无效")}fail(a,b){let c=b instanceof f.dM?409:b instanceof g.H?b.code:500,d=b instanceof f.dM?"工作会话来源已变化":b instanceof Error?b.message:"插件交互失败";500===c&&console.error("[Pi Desk][NativeUI] 请求失败",{path:a.head.path,message:d}),this.connection.sendError(a.head.path,a.head.requestId,c,d)}}d()}catch(a){d(a)}})},47591:(a,b,c)=>{"use strict";let{isUtf8:d}=c(79428),{hasBlob:e}=c(46929);function f(a){let b=a.length,c=0;for(;c<b;)if((128&a[c])==0)c++;else if((224&a[c])==192){if(c+1===b||(192&a[c+1])!=128||(254&a[c])==192)return!1;c+=2}else if((240&a[c])==224){if(c+2>=b||(192&a[c+1])!=128||(192&a[c+2])!=128||224===a[c]&&(224&a[c+1])==128||237===a[c]&&(224&a[c+1])==160)return!1;c+=3}else{if((248&a[c])!=240||c+3>=b||(192&a[c+1])!=128||(192&a[c+2])!=128||(192&a[c+3])!=128||240===a[c]&&(240&a[c+1])==128||244===a[c]&&a[c+1]>143||a[c]>244)return!1;c+=4}return!0}if(a.exports={isBlob:function(a){return e&&"object"==typeof a&&"function"==typeof a.arrayBuffer&&"string"==typeof a.type&&"function"==typeof a.stream&&("Blob"===a[Symbol.toStringTag]||"File"===a[Symbol.toStringTag])},isValidStatusCode:function(a){return a>=1e3&&a<=1014&&1004!==a&&1005!==a&&1006!==a||a>=3e3&&a<=4999},isValidUTF8:f,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},d)a.exports.isValidUTF8=function(a){return a.length<24?f(a):d(a)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let b=c(93750);a.exports.isValidUTF8=function(a){return a.length<32?f(a):b(a)}}catch(a){}},50906:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{c:()=>k,m:()=>f.Q});var e=c(77598),f=c(58706),g=a([f]);f=(g.then?(await g)():g)[0];let j=new Set;function h(a){if(j.has(a))throw new f.Q(409,"该服务正在登录或退出,请等待当前操作结束");if(j.size>=32)throw new f.Q(429,"正在处理的账号操作过多,请稍后重试");j.add(a)}function i(a,b,c){console.warn("[Pi Desk][ModelAuth] 账号操作未完成",{provider:a.state.provider,loginId:a.state.loginId,stage:b,errorName:c instanceof Error?c.name:"UnknownError"})}class k{constructor(a){this.onState=a,this.active=null,this.disposed=!1,this.logoutControllers=new Set}async list(){return this.assertOpen(),(await f.I.create()).list()}async start(a,b){if(this.assertOpen(),this.active)throw new f.Q(409,"当前连接已有登录流程,请先完成或取消");h(a);let c={state:{loginId:b,provider:a,status:"running",notice:null,prompt:null,message:null},abort:new AbortController,timer:null,scheduled:null,pending:null};this.active=c,c.timer=setTimeout(()=>this.stop(c,!0),9e5);try{let b=await f.I.create(c.abort.signal),d=(await b.list(c.abort.signal)).find(b=>b.provider===a);if(!d)throw new f.Q(400,"该服务不支持账号登录");if(d.conflict)throw new f.Q(409,d.conflict);c.abort.signal.throwIfAborted(),this.assertOpen(),c.scheduled=setImmediate(()=>{c.scheduled=null,this.login(c,b)})}catch(b){if(this.release(c),j.delete(a),c.abort.signal.aborted)throw new f.Q(409,"登录流程已取消或超时");throw b}}respond(a,b,c){let d=this.getRun(a),e=d.pending;if(!e||e.id!==b)throw new f.Q(409,"该登录问题已结束,请使用当前问题");let g=d.state.prompt;if(g?.type==="select"&&!g.options?.some(a=>a.id===c))throw new f.Q(400,"请选择当前问题提供的选项");this.clearPrompt(d),e.resolve(c),this.push(d)}cancel(a){this.stop(this.getRun(a),!1)}async logout(a){this.assertOpen(),h(a);let b=new AbortController;this.logoutControllers.add(b);let c=setTimeout(()=>b.abort(),15e3);try{let c=await f.I.create(b.signal),d=(await c.list(b.signal)).find(b=>b.provider===a);if(!d)throw new f.Q(400,"该服务不支持账号登录");if(!d.loggedIn)throw new f.Q(409,"该服务没有已保存的账号登录");b.signal.throwIfAborted(),await c.logout(a,b.signal)}catch(c){if(console.warn("[Pi Desk][ModelAuth] 退出账号未完成",{provider:a,stage:"logout",errorName:c instanceof Error?c.name:"UnknownError"}),c instanceof f.Q)throw c;throw new f.Q(500,b.signal.aborted?"退出账号已取消或超时,请重新获取账号状态":"退出账号失败,请重试")}finally{clearTimeout(c),this.logoutControllers.delete(b),j.delete(a)}}dispose(){if(!this.disposed){for(let a of(this.disposed=!0,this.active&&this.stop(this.active,!1),this.logoutControllers))a.abort();this.logoutControllers.clear()}}assertOpen(){if(this.disposed)throw new f.Q(409,"账号连接已关闭")}getRun(a){this.assertOpen();let b=this.active;if(!b||b.state.loginId!==a||"running"!==b.state.status)throw new f.Q(409,"登录流程已结束或不属于当前连接");return b}push(a){this.disposed||this.onState({...a.state})}notify(a,b){"running"!==a.state.status||a.abort.signal.aborted||("progress"===b.type?(a.state.message=b.message,a.state.notice?.type!=="auth_url"&&a.state.notice?.type!=="device_code"&&(a.state.notice={type:"progress",message:b.message})):"info"===b.type?(a.state.notice={type:"info",message:b.message,...b.links?{links:b.links.map(a=>({...a}))}:{}},a.state.message=b.message):(a.state.notice="device_code"===b.type?{type:"device_code",userCode:b.userCode,verificationUri:b.verificationUri}:{...b},a.state.message=null),this.push(a))}prompt(a,b){if(a.abort.signal.aborted||"running"!==a.state.status||b.signal?.aborted)return Promise.reject(new DOMException("登录问题已取消","AbortError"));if(a.pending){let b=a.pending;this.clearPrompt(a),b.reject(new DOMException("登录问题已替换","AbortError"))}return new Promise((c,d)=>{let f=(0,e.randomUUID)(),g=()=>{a.pending?.id===f&&(this.clearPrompt(a),d(new DOMException("登录问题已取消","AbortError")),"running"===a.state.status&&this.push(a))};a.pending={id:f,resolve:c,reject:d,cleanup:()=>{a.abort.signal.removeEventListener("abort",g),b.signal?.removeEventListener("abort",g)}},a.state.prompt={id:f,type:b.type,message:b.message,..."select"===b.type?{options:b.options.map(a=>({...a}))}:{placeholder:b.placeholder}},a.abort.signal.addEventListener("abort",g,{once:!0}),b.signal?.addEventListener("abort",g,{once:!0}),this.push(a)})}clearPrompt(a){a.pending?.cleanup(),a.pending=null,a.state.prompt=null}stop(a,b){"running"===a.state.status&&(a.state.status=b?"error":"cancelled",a.state.message=b?"登录已超时,请重新开始":"登录已取消",i(a,b?"timeout":"cancel",new DOMException("登录已结束","AbortError")),this.release(a),a.abort.abort(),this.push(a),a.scheduled&&(clearImmediate(a.scheduled),a.scheduled=null,j.delete(a.state.provider)))}release(a){a.timer&&clearTimeout(a.timer),a.timer=null;let b=a.pending;this.clearPrompt(a),b?.reject(new DOMException("登录已结束","AbortError")),this.active===a&&(this.active=null)}async login(a,b){let c="login";try{this.push(a);let d=await b.login(a.state.provider,{signal:a.abort.signal,prompt:b=>this.prompt(a,b),notify:b=>this.notify(a,b)});if("running"!==a.state.status)return;d||i(a,"credential-sync",new DOMException("本地同步失败","CredentialSynchronizationError")),c="catalog",a.state.message="登录成功,正在更新模型目录",this.push(a);let e=d?"登录成功":"登录成功,但本地模型状态同步失败,请重新获取模型列表",f=new AbortController,g=AbortSignal.any([a.abort.signal,f.signal]),h=setTimeout(()=>f.abort(),15e3);try{await b.refreshCatalog(a.state.provider,g)}catch(b){i(a,c,b),e="登录成功,但模型目录刷新失败,请稍后重新获取模型列表"}finally{clearTimeout(h)}if("running"!==a.state.status)return;a.state.status="completed",a.state.message=e,this.release(a),this.push(a)}catch(b){if("running"!==a.state.status)return;i(a,c,b),a.state.status=a.abort.signal.aborted?"cancelled":"error",a.state.message=a.abort.signal.aborted?"登录已取消":"登录未完成,请重试",this.release(a),this.push(a)}finally{this.release(a),a.abort.abort(),j.delete(a.state.provider)}}}d()}catch(a){d(a)}})},52218:(a,b,c)=>{"use strict";let{EMPTY_BUFFER:d}=c(46929),e=Buffer[Symbol.species];function f(a,b,c,d,e){for(let f=0;f<e;f++)c[d+f]=a[f]^b[3&f]}function g(a,b){for(let c=0;c<a.length;c++)a[c]^=b[3&c]}function h(a){let b;return(h.readOnly=!0,Buffer.isBuffer(a))?a:(a instanceof ArrayBuffer?b=new e(a):ArrayBuffer.isView(a)?b=new e(a.buffer,a.byteOffset,a.byteLength):(b=Buffer.from(a),h.readOnly=!1),b)}if(a.exports={concat:function(a,b){if(0===a.length)return d;if(1===a.length)return a[0];let c=Buffer.allocUnsafe(b),f=0;for(let b=0;b<a.length;b++){let d=a[b];c.set(d,f),f+=d.length}return f<b?new e(c.buffer,c.byteOffset,f):c},mask:f,toArrayBuffer:function(a){return a.length===a.buffer.byteLength?a.buffer:a.buffer.slice(a.byteOffset,a.byteOffset+a.length)},toBuffer:h,unmask:g},!process.env.WS_NO_BUFFER_UTIL)try{let b=c(99407);a.exports.mask=function(a,c,d,e,g){g<48?f(a,c,d,e,g):b.mask(a,c,d,e,g)},a.exports.unmask=function(a,c){a.length<32?g(a,c):b.unmask(a,c)}}catch(a){}},58706:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{I:()=>o,Q:()=>m});var e=c(51455),f=c(76760),g=c(75430),h=a([g]);g=(h.then?(await h)():h)[0];class m extends Error{constructor(a,b){super(b),this.code=a,this.name="L4ModelAuthError"}}let n=["baseUrl","apiKey","headers","api","oauth","authHeader","compat"];async function i(a,b){let c;if(!b)return a;let d=new Promise((a,d)=>{c=()=>d(new DOMException("账号操作已取消","AbortError")),b.aborted?c():b.addEventListener("abort",c,{once:!0})});try{return await Promise.race([a,d])}finally{b.removeEventListener("abort",c)}}function j(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function k(a){return n.some(b=>void 0!==a[b])}async function l(a){let b,c;try{b=await (0,e.readFile)(a,"utf8")}catch(a){if(j(a)&&"ENOENT"===a.code)return new Set;throw new m(500,"无法读取模型配置,暂时不能进行账号操作")}try{let a=(65279===b.charCodeAt(0)?b.slice(1):b).replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g,a=>'"'===a[0]?a:"").replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g,(a,b)=>b??a);c=JSON.parse(a)}catch{throw new m(409,"模型配置格式无效,请先修正 models.json")}if(!j(c)||void 0!==c.providers&&!j(c.providers))throw new m(409,"模型配置格式无效,请先修正 models.json");let d=new Set;for(let[a,b]of Object.entries(c.providers??{})){if(!j(b))throw new m(409,"模型服务配置格式无效");(k(b)||Array.isArray(b.models)&&b.models.some(a=>j(a)&&k(a)))&&d.add(a)}return d}class o{constructor(a,b,c){this.runtime=a,this.conflicts=b,this.agentDir=c}static async create(a){let b=(0,g.getAgentDir)(),c=(0,f.join)(b,"models.json"),d=await i(l(c),a);a?.throwIfAborted();let e=await i(g.ModelRuntime.create({authPath:(0,f.join)(b,"auth.json"),modelsPath:c,refreshOnCreate:!1,allowModelNetwork:!1,signal:a}),a);return a?.throwIfAborted(),new o(e,d,b)}async list(a){let b=await i(this.runtime.listCredentials({signal:a}),a),c=new Set(b.filter(a=>"oauth"===a.type).map(a=>a.providerId));return this.runtime.getProviders().filter(a=>a.auth.oauth).map(a=>({provider:a.id,name:a.name,loggedIn:c.has(a.id),conflict:this.conflicts.has(a.id)?"同名服务已有自定义连接,会改变账号凭据的使用方式。请先将自定义连接改为独立服务 ID,再登录账号。":null}))}async login(a,b){try{return await i(this.runtime.login(a,"oauth",b,{getDeviceId:()=>g.SettingsManager.create(process.cwd(),this.agentDir).getOrCreateDeviceId()}),b.signal),!0}catch(a){if(a instanceof g.CredentialSynchronizationError&&"login"===a.operation)return!1;throw a}}async refreshCatalog(a,b){b.throwIfAborted();let c=await i(this.runtime.refresh({allowNetwork:!0,providers:[a],signal:b}),b);if(b.throwIfAborted(),c.aborted)throw Error("CatalogRefreshAborted");let d=c.errors.get(a);if(d)throw d}async logout(a,b){try{await i(this.runtime.logout(a,{signal:b}),b)}catch(a){if(a instanceof g.CredentialSynchronizationError&&"logout"===a.operation)throw new m(500,"账号已退出,但本地模型目录同步失败,请重新获取模型列表");throw a}}}d()}catch(a){d(a)}})},58773:(a,b,c)=>{"use strict";let d,{Duplex:e}=c(27910),{randomFillSync:f}=c(55511),{types:{isUint8Array:g}}=c(28354),h=c(95374),{EMPTY_BUFFER:i,kWebSocket:j,NOOP:k}=c(46929),{isBlob:l,isValidStatusCode:m}=c(47591),{mask:n,toBuffer:o}=c(52218),p=Symbol("kByteLength"),q=Buffer.alloc(4),r=8192;class s{constructor(a,b,c){this._extensions=b||{},c&&(this._generateMask=c,this._maskBuffer=Buffer.alloc(4)),this._socket=a,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=k,this[j]=void 0}static frame(a,b){let c,e,g=!1,h=2,i=!1;b.mask&&(c=b.maskBuffer||q,b.generateMask?b.generateMask(c):(8192===r&&(void 0===d&&(d=Buffer.alloc(8192)),f(d,0,8192),r=0),c[0]=d[r++],c[1]=d[r++],c[2]=d[r++],c[3]=d[r++]),i=(c[0]|c[1]|c[2]|c[3])==0,h=6),"string"==typeof a?e=(!b.mask||i)&&void 0!==b[p]?b[p]:(a=Buffer.from(a)).length:(e=a.length,g=b.mask&&b.readOnly&&!i);let j=e;e>=65536?(h+=8,j=127):e>125&&(h+=2,j=126);let k=Buffer.allocUnsafe(g?e+h:h);return(k[0]=b.fin?128|b.opcode:b.opcode,b.rsv1&&(k[0]|=64),k[1]=j,126===j?k.writeUInt16BE(e,2):127===j&&(k[2]=k[3]=0,k.writeUIntBE(e,4,6)),b.mask)?(k[1]|=128,k[h-4]=c[0],k[h-3]=c[1],k[h-2]=c[2],k[h-1]=c[3],i)?[k,a]:g?(n(a,c,k,h,e),[k]):(n(a,c,a,0,e),[k,a]):[k,a]}close(a,b,c,d){let e;if(void 0===a)e=i;else if("number"==typeof a&&m(a))if(void 0!==b&&b.length){let c=Buffer.byteLength(b);if(c>123)throw RangeError("The message must not be greater than 123 bytes");if((e=Buffer.allocUnsafe(2+c)).writeUInt16BE(a,0),"string"==typeof b)e.write(b,2);else if(g(b))e.set(b,2);else throw TypeError("Second argument must be a string or a Uint8Array")}else(e=Buffer.allocUnsafe(2)).writeUInt16BE(a,0);else throw TypeError("First argument must be a valid error code number");let f={[p]:e.length,fin:!0,generateMask:this._generateMask,mask:c,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,e,!1,f,d]):this.sendFrame(s.frame(e,f),d)}ping(a,b,c){let d,e;if("string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),d>125)throw RangeError("The data size must not be greater than 125 bytes");let f={[p]:d,fin:!0,generateMask:this._generateMask,mask:b,maskBuffer:this._maskBuffer,opcode:9,readOnly:e,rsv1:!1};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,!1,f,c]):this.getBlobData(a,!1,f,c):0!==this._state?this.enqueue([this.dispatch,a,!1,f,c]):this.sendFrame(s.frame(a,f),c)}pong(a,b,c){let d,e;if("string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),d>125)throw RangeError("The data size must not be greater than 125 bytes");let f={[p]:d,fin:!0,generateMask:this._generateMask,mask:b,maskBuffer:this._maskBuffer,opcode:10,readOnly:e,rsv1:!1};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,!1,f,c]):this.getBlobData(a,!1,f,c):0!==this._state?this.enqueue([this.dispatch,a,!1,f,c]):this.sendFrame(s.frame(a,f),c)}send(a,b,c){let d,e,f=this._extensions[h.extensionName],g=b.binary?2:1,i=b.compress;"string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),this._firstFragment?(this._firstFragment=!1,i&&f&&f.params[f._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=d>=f._threshold),this._compress=i):(i=!1,g=0),b.fin&&(this._firstFragment=!0);let j={[p]:d,fin:b.fin,generateMask:this._generateMask,mask:b.mask,maskBuffer:this._maskBuffer,opcode:g,readOnly:e,rsv1:i};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,this._compress,j,c]):this.getBlobData(a,this._compress,j,c):0!==this._state?this.enqueue([this.dispatch,a,this._compress,j,c]):this.dispatch(a,this._compress,j,c)}getBlobData(a,b,c,d){this._bufferedBytes+=c[p],this._state=2,a.arrayBuffer().then(a=>{if(this._socket.destroyed){let a=Error("The socket was closed while the blob was being read");process.nextTick(t,this,a,d);return}this._bufferedBytes-=c[p];let e=o(a);b?this.dispatch(e,b,c,d):(this._state=0,this.sendFrame(s.frame(e,c),d),this.dequeue())}).catch(a=>{process.nextTick(u,this,a,d)})}dispatch(a,b,c,d){if(!b)return void this.sendFrame(s.frame(a,c),d);let e=this._extensions[h.extensionName];this._bufferedBytes+=c[p],this._state=1,e.compress(a,c.fin,(a,b)=>{this._socket.destroyed?t(this,Error("The socket was closed while data was being compressed"),d):(this._bufferedBytes-=c[p],this._state=0,c.readOnly=!1,this.sendFrame(s.frame(b,c),d),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){let a=this._queue.shift();this._bufferedBytes-=a[3][p],Reflect.apply(a[0],this,a.slice(1))}}enqueue(a){this._bufferedBytes+=a[3][p],this._queue.push(a)}sendFrame(a,b){2===a.length?(this._socket.cork(),this._socket.write(a[0]),this._socket.write(a[1],b),this._socket.uncork()):this._socket.write(a[0],b)}}function t(a,b,c){"function"==typeof c&&c(b);for(let c=0;c<a._queue.length;c++){let d=a._queue[c],e=d[d.length-1];"function"==typeof e&&e(b)}}function u(a,b,c){t(a,b,c),a.onerror(b)}a.exports=s},58922:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{p:()=>j});var e=c(33495),f=c(45407),g=c(55490),h=a([f,g]);function i(a,b){return a.workId===b.workId&&a.sessionId===b.sessionId&&a.branchId===b.branchId}[f,g]=h.then?(await h)():h;class j{constructor(a,b,c){this.connection=a,this.manage=b,this.taskCenter=c,this.currentWatch=null,this.pendingWatch=null,this.operationTail=Promise.resolve(),this.disposed=!1,this.unsubscribeSources=this.manage.subscribeMessageEvents(a=>this.handleSourceEvent(a)),this.routes=Object.freeze([{path:e.rn.detailWatch.path,access:"ready",handle:a=>this.enqueue(()=>this.watch(a))},{path:e.rn.interrupt.path,access:"ready",handle:a=>this.interrupt(a)}])}dispose(){this.disposed||(this.disposed=!0,this.unsubscribeSources(),this.pendingWatch=null,this.releaseCurrentWatch())}enqueue(a){let b=this.operationTail.then(a,a);return this.operationTail=b.then(()=>void 0,()=>void 0),b}async watch(a){let b=e.rn.detailWatch,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"任务详情参数无效");if(this.releaseCurrentWatch(),null===c.data.taskId)return void this.connection.sendSuccess(b,a.head.requestId,{snapshot:null});let d={source:c.data.source,invalidated:!1};this.pendingWatch=d;try{let e=await this.createStableWatch(c.data.source,c.data.taskId);if(this.disposed||!this.connection.isCurrent())return void e.observation.release();if(d.invalidated)throw e.observation.release(),new g.dM(d.source);this.currentWatch=e,this.connection.sendSuccess(b,a.head.requestId,{snapshot:e.observation.snapshot}),e.status="ready",this.flushQueuedEvents(e),console.info("[Pi Desk][TaskCenterSocket] 任务详情观察完成",{clientId:this.connection.clientId,workId:e.source.workId,taskId:e.taskId})}catch(c){this.sendTaskError(b.path,a.head.requestId,c,"任务详情初始化失败")}finally{this.pendingWatch===d&&(this.pendingWatch=null)}}async createStableWatch(a,b){for(;;){let c=[],d={state:null},e=await this.taskCenter.watchDetail(a,b,a=>{let b=d.state;if(!b||this.currentWatch!==b||this.disposed){c.length<128&&c.push(a);return}this.handleDetailEvent(b,a)}),f={source:a,taskId:b,observation:e,status:"syncing",queuedEvents:c,overflowed:c.length>=128};if(d.state=f,!f.overflowed)return f;e.release()}}handleDetailEvent(a,b){if(this.currentWatch===a&&!this.disposed&&this.connection.isCurrent()){if("syncing"===a.status){if(a.queuedEvents.length>=128){a.queuedEvents.length=0,a.overflowed=!0;return}a.queuedEvents.push(b);return}this.connection.sendPush(e.rn.detailEvent,{source:a.source,taskId:a.taskId,event:b}),"unavailable"===b.type&&this.releaseCurrentWatch()}}flushQueuedEvents(a){if(this.currentWatch===a){if(a.overflowed)return void this.connection.close(1011,"任务详情同步队列溢出");for(let b of a.queuedEvents.splice(0))if(this.connection.sendPush(e.rn.detailEvent,{source:a.source,taskId:a.taskId,event:b}),"unavailable"===b.type)return void this.releaseCurrentWatch()}}async interrupt(a){let b=e.rn.interrupt,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"任务打断参数无效");try{await this.taskCenter.interrupt(c.data.source,c.data.taskId),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendTaskError(b.path,a.head.requestId,c,"打断任务失败")}}sendTaskError(a,b,c,d){c instanceof g.dM?this.connection.sendError(a,b,409,"工作会话来源已变化"):c instanceof f.x4?this.connection.sendError(a,b,404,"任务不存在"):c instanceof f.o3?this.connection.sendError(a,b,409,"任务当前不可打断"):c instanceof f.Y3?this.connection.sendError(a,b,409,"任务不支持该详情"):c instanceof f.qc?this.connection.sendError(a,b,404,"任务消息不存在"):(console.warn("[Pi Desk][TaskCenterSocket] 任务操作失败",{path:a,errorName:c instanceof Error?c.name:"UnknownError",message:c instanceof Error?c.message:d}),this.connection.sendError(a,b,500,d))}handleSourceEvent(a){if("source_invalidated"!==a.type)return;this.pendingWatch&&i(this.pendingWatch.source,a.source)&&(this.pendingWatch.invalidated=!0);let b=this.currentWatch;b&&i(b.source,a.source)&&(this.connection.sendPush(e.rn.detailEvent,{source:b.source,taskId:b.taskId,event:{type:"unavailable"}}),this.releaseCurrentWatch())}releaseCurrentWatch(){let a=this.currentWatch;this.currentWatch=null,a?.observation.release()}}d()}catch(a){d(a)}})},61667:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{k:()=>q});var e=c(30119),f=c(26272),g=c(81607),h=c(18611),i=c(79271),j=c(47389),k=c(28363),l=c(74344),m=c(58922),n=c(73246),o=c(43973),p=a([g,h,j,k,l,m,o]);[g,h,j,k,l,m,o]=p.then?(await p)():p;class q{constructor(a,b,c,d,e,p,q,r){this.authToken=c,this.onClose=r,this.routes=new Map,this.disposed=!1,this.connection=new f.V(b,a),this.workSessions=new o.G(this.connection,d,e),this.appRuntime=new g.U(this.connection,e),this.chat=new h.T(this.connection,d),this.plugins=new l.c(this.connection,d,()=>this.workSessions.isReady()),this.nativeUi=new j.k(this.connection,d),this.modelAuth=new k.Y(this.connection),this.pluginLogs=new i.m(this.connection),this.taskCenter=new m.p(this.connection,d,p),this.terminals=new n.D(this.connection,q,()=>this.workSessions.isReady()),this.registerRoutes(this.workSessions.routes),this.registerRoutes(this.appRuntime.routes),this.registerRoutes(this.chat.routes),this.registerRoutes(this.plugins.routes),this.registerRoutes(this.nativeUi.routes),this.registerRoutes(this.modelAuth.routes),this.registerRoutes(this.pluginLogs.routes),this.registerRoutes(this.taskCenter.routes),this.registerRoutes(this.terminals.routes)}start(){this.connection.start(a=>this.handleRequest(a),a=>{this.dispose(),this.onClose(this,a)}),console.info("[Pi Desk][AppSocketSession] 应用连接已建立",{clientId:this.connection.clientId,connectionId:this.connection.connectionId})}supersede(){this.disposeControllers(),this.connection.supersede()}close(a,b){this.disposeControllers(),this.connection.close(a,b)}terminate(){this.disposeControllers(),this.connection.terminate()}waitForClose(){return this.connection.waitForClose()}pushPlugin(a){!this.disposed&&this.workSessions.isReady()&&this.connection.sendPush(e.cx,a)}registerRoutes(a){for(let b of a){if(this.routes.has(b.path))throw Error(`Duplicate WebSocket route: ${b.path}`);this.routes.set(b.path,b)}}async handleRequest(a){let b=this.routes.get(a.head.path);b?"ready"!==b.access||this.workSessions.isReady()?await b.handle(a):this.connection.sendError(a.head.path,a.head.requestId,409,"工作会话尚未初始化",{key:"errors:sessionsNotReady"}):this.connection.sendError(a.head.path,a.head.requestId,404,"未知 WebSocket 路径",{key:"errors:socketUnknownPath"})}disposeControllers(){this.plugins.dispose(),this.nativeUi.dispose(),this.modelAuth.dispose(),this.pluginLogs.dispose(),this.taskCenter.dispose(),this.terminals.dispose(),this.chat.dispose(),this.appRuntime.dispose(),this.workSessions.dispose()}dispose(){this.disposed||(this.disposed=!0,this.disposeControllers())}}d()}catch(a){d(a)}})},62761:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{f4:()=>k});var e=c(17691),f=c(77598),g=c(73024),h=c(76760),i=c(36153),j=a([e]);e=(j.then?(await j)():j)[0];let l=i.Ik({passwordHash:i.Yj().regex(/^scrypt:[a-f0-9]{32}:[a-f0-9]{128}$/)}).strict().extend({username:i.Yj().trim().min(1).max(64).optional()});class m extends Error{constructor(){super("登录保护配置无法读取,请修复配置或删除 auth.json 后重新设置"),this.name="L4AuthConfigError"}}function k(){let a;try{a=(0,g.readFileSync)((0,h.join)((0,e.M)(),"auth.json"),"utf8")}catch(a){if(a instanceof Error&&"code"in a&&"ENOENT"===a.code)return null;throw new m}try{let b=l.parse(JSON.parse(a)),c=void 0===b.username?[b.passwordHash]:[b.username,b.passwordHash],d=(0,f.createHmac)("sha256",function(){let a=(0,g.readFileSync)((0,h.join)((0,e.M)(),"auth-session-key"),"utf8").trim();if(!/^[a-f0-9]{64}$/.test(a))throw new m;return a}()).update(JSON.stringify(c)).digest("hex");return{passwordHash:b.passwordHash,sessionSecret:d}}catch{throw new m}}d()}catch(a){d(a)}})},63178:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{C:()=>h,I:()=>i});var e=c(44429),f=c(5340),g=a([f]);function h(a,b){let c=null===b.body?null:"text"===b.body.kind?b.body:{kind:"conversation",messages:b.body.entries.map((b,c)=>(0,f.NA)((0,f.Cz)(c,b.entryId,b.timestampMs,b.message,a))),temporaryMessages:b.body.temporaryMessages.map(({tempId:b,message:c})=>(0,f.QS)(b,c,a)),truncated:b.body.truncated};return e.ui.parse({taskId:b.taskId,canInterrupt:b.canInterrupt,body:c})}function i(a,b,c){return"snapshot"===c.type?e.gm.parse({type:"snapshot",snapshot:h(a,c.snapshot)}):"text_append"===c.type||"unavailable"===c.type?e.gm.parse(c):function(a,b,c){if(b.body?.kind!=="conversation")throw Error("Task conversation event requires a conversation snapshot");let d=b.body;if("durable_append"===c.type)return e.gm.parse({type:"conversation_event",event:{type:"durable_append",messages:c.entries.map((b,c)=>(0,f.NA)((0,f.Cz)(d.messages.length+c,b.entryId,b.timestampMs,b.message,a)))}});if("message_start"===c.type)return e.gm.parse({type:"conversation_event",event:{type:"message_start",snapshot:(0,f.QS)(c.tempId,c.message,a)}});if("message_update"===c.type){let b=d.temporaryMessages.find(a=>a.location.tempId===c.tempId);if(!b)throw Error(`Task Temporary message was not found: ${c.tempId}`);let g=(0,f.Ht)(b,(0,f.QS)(c.tempId,c.message,a,!1,"update"));return g?e.gm.parse({type:"conversation_event",event:g}):null}return"message_commit"===c.type?e.gm.parse({type:"conversation_event",event:{type:"message_commit",location:{tempId:c.tempId},durable:{index:d.messages.length,entryId:c.entryId},fixed:{timestampMs:c.timestampMs}}}):e.gm.parse({type:"conversation_event",event:{type:"message_discard",location:{tempId:c.tempId}}})}(a,b,c.event)}f=(g.then?(await g)():g)[0],d()}catch(a){d(a)}})},71779:(a,b,c)=>{"use strict";c.d(b,{R:()=>f});var d=c(98761),e=c(69375);let f=Object.freeze({apply:(0,e.Vc)({path:"app-runtime/apply",inputSchema:d.$C,outputSchema:d.Pq}),update:(0,e._G)({path:"app-runtime/update",bodySchema:d.YT})})},72608:(a,b,c)=>{"use strict";c.d(b,{l$:()=>n,yd:()=>w});var d=c(77598),e=c(76760),f=c(75825),g=c(31421),h=c(51455),i=c(73024),j=c(48161);let k=(0,c(57975).promisify)(g.execFile),{createRequire:l}=process.getBuiltinModule("module"),m=l((0,e.join)(process.cwd(),"package.json"));class n extends Error{constructor(a,b){super(b),this.code=a,this.name="L4TerminalError"}}async function o(a){try{return await (0,h.access)(a,"win32"===process.platform?i.constants.F_OK:i.constants.X_OK),(await (0,h.stat)(a)).isFile()}catch{return!1}}async function p(a){let b=a??(0,j.homedir)();if(!(0,e.isAbsolute)(b))throw new n(400,"终端目录必须是绝对路径");try{if(!(await (0,h.stat)(b)).isDirectory())throw Error("not a directory")}catch{throw new n(400,"终端目录不存在或不是目录")}let c="/bin/sh",d=[];if("win32"===process.platform){let a=(process.env.PATH??"").split(e.delimiter).map(a=>(0,e.join)(a.replace(/^"|"$/g,""),"pwsh.exe"));for(let b of(a.push((0,e.join)(process.env.ProgramFiles??"C:/Program Files","PowerShell/7/pwsh.exe")),c=(0,e.join)(process.env.SystemRoot??"C:/Windows","System32/WindowsPowerShell/v1.0/powershell.exe"),a))if((0,e.isAbsolute)(b)&&await o(b)){c=b;break}d.push("-NoLogo","-NoProfile")}else process.env.SHELL&&(0,e.isAbsolute)(process.env.SHELL)&&await o(process.env.SHELL)&&(c=process.env.SHELL);if(!await o(c))throw new n(503,"没有可用的终端 Shell");return{cwd:b,file:c,args:d,shell:(0,e.basename)(c)}}class q{constructor(a,b,c){this.stopped=null,this.exited=!1,this.earlyInputBytes=0;try{const d=m("node-pty/package.json").version;if("1.1.0"!==d)throw Error(`不支持的 node-pty 版本:${d}`);if("win32"===process.platform&&18309>Number((0,j.release)().split(".")[2]))throw Error("系统 Windows 版本不支持稳定 ConPTY");const e=m("node-pty");if(this.pty=e.spawn(a.file,a.args,{cwd:a.cwd,cols:b,rows:c,name:"xterm-256color",env:{...process.env,TERM:"xterm-256color"},useConpty:!0,useConptyDll:!1}),"win32"===process.platform){const a=this.pty._agent;if(!a._useConpty||a._useConptyDll)throw Error("终端需要系统 ConPTY");this.workerExit=new Promise((b,c)=>{a._conoutSocketWorker._worker.once("exit",()=>b()),a._conoutSocketWorker._worker.once("error",c)}),this.workerExit.catch(()=>void 0)}else this.workerExit=null;this.processExit=new Promise(a=>{let b=this.pty.onExit(()=>{this.exited=!0,b.dispose(),a()})}),this.released=this.processExit.then(()=>this.releaseNative()),this.released.catch(a=>console.error("[Pi Desk][Terminal] 原生资源释放失败",{pid:this.pty.pid,error:a}))}catch(a){throw console.error("[Pi Desk][Terminal] PTY 加载或启动失败",{message:a instanceof Error?a.message:String(a)}),new n(503,"终端原生依赖不可用或 Shell 启动失败")}}write(a){if(this.exited)throw new n(409,"终端已经退出");let b="win32"===process.platform?this.pty:null;if(b?._isReady&&(this.earlyInputBytes=0),(b?b._agent._inSocket.writableLength+this.earlyInputBytes:this.pty._writeStream._writeQueue.reduce((a,b)=>a+b.buffer.length-b.offset,0))+Buffer.byteLength(a)>65536)throw new n(429,"终端输入缓冲已满");this.checkDeferredCapacity(),b&&!b._isReady&&(this.earlyInputBytes+=Buffer.byteLength(a)),this.pty.write(function(a){let b=[],c=0;for(let d of a.matchAll(/\x1b\[M[\x00-\xff]{3}/g)){let e=d.index;e>c&&b.push(Buffer.from(a.slice(c,e),"utf8")),b.push(Buffer.from(d[0],"latin1")),c=e+d[0].length}return 0===c?Buffer.from(a,"utf8"):(c<a.length&&b.push(Buffer.from(a.slice(c),"utf8")),Buffer.concat(b))}(a))}resize(a,b){this.checkDeferredCapacity(),this.pty.resize(a,b)}checkDeferredCapacity(){if("win32"===process.platform&&this.pty._deferreds.length>=256)throw new n(429,"终端初始化操作队列已满")}stop(){return this.stopped||(this.stopped=this.stopTree()),this.stopped}async stopTree(){let a,b=performance.now();if(!this.exited)if("win32"===process.platform)try{await k("taskkill.exe",["/PID",String(this.pty.pid),"/T","/F"],{windowsHide:!0,timeout:4e3,maxBuffer:65536})}catch(a){if(this.logStopFailure("终止进程树",b,a),!this.exited)throw a}else{let{stdout:a}=await k("ps",["-eo","pid=,ppid="],{timeout:2e3,maxBuffer:2097152}),b=a.trim().split("\n").map(a=>a.trim().split(/\s+/).map(Number)),c=new Set([this.pty.pid]),d=[],e=!0;for(;e;)for(let[a,f]of(e=!1,b))c.has(f)&&!c.has(a)&&(c.add(a),d.push(a),e=!0);for(let a of d.reverse())this.killUnix(a);this.killUnix(-this.pty.pid),this.pty.kill("SIGKILL")}let c=performance.now();try{await Promise.race([this.processExit,new Promise((b,c)=>{a=setTimeout(()=>c(Error("Shell 退出等待超时")),4e3)})])}catch(a){throw this.logStopFailure("等待 Shell 退出",b,a),a}finally{a&&clearTimeout(a)}let d=performance.now();await this.released,console.info("[Pi Desk][Terminal] 原生终端停止完成",{pid:this.pty.pid,terminateMs:Math.round(c-b),exitMs:Math.round(d-c),releaseMs:Math.round(performance.now()-d),totalMs:Math.round(performance.now()-b)})}logStopFailure(a,b,c){let d=null;try{process.kill(this.pty.pid,0),d=!0}catch(a){"ESRCH"===a.code&&(d=!1)}console.error("[Pi Desk][Terminal] 终端停止阶段失败",{pid:this.pty.pid,stage:a,elapsedMs:Math.round(performance.now()-b),processAlive:d,ptyExited:this.exited,nativeExitCode:"win32"===process.platform?this.pty._agent.exitCode??null:null,error:c})}killUnix(a){try{process.kill(a,"SIGKILL")}catch(a){if("ESRCH"!==a.code)throw a}}async releaseNative(){if("win32"!==process.platform)return;let a=this.pty._agent;a._inSocket.destroy(),a._outSocket.destroy(),a._conoutSocketWorker.dispose(),await this.workerExit}}class r{frame(a){let b=this.pending+a,c=0;for(let a=this.pending.length;a<b.length;a+=1){let d=b.charCodeAt(a);24===d||26===d?this.state="ground":"ground"===this.state?27===d?this.state="escape":155===d?this.state="csi":[144,152,157,158,159].includes(d)&&(this.osc=157===d,this.state="string"):"escape"===this.state?91===d?this.state="csi":[80,88,93,94,95].includes(d)?(this.osc=93===d,this.state="string"):d>=48&&d<=126&&(this.state="ground"):"csi"===this.state?27===d?this.state="escape":d>=64&&d<=126&&(this.state="ground"):"string"===this.state?156===d||this.osc&&7===d?this.state="ground":27===d&&(this.state="string-escape"):"string-escape"===this.state&&(92===d?this.state="ground":27!==d&&(this.state="string")),"ground"===this.state&&(c=a+1)}if(this.pending=b.slice(c),Buffer.byteLength(this.pending)>1048576)throw new n(429,"终端控制序列超出缓冲上限");return b.slice(0,c)}dispose(){this.pending=""}constructor(){this.pending="",this.state="ground",this.osc=!1}}let{createRequire:s}=process.getBuiltinModule("module"),t=s((0,e.join)(process.cwd(),"package.json"));class u{constructor(a,b,c,d){this.terminalId=a,this.onExit=c,this.framing=new r,this.listeners=new Set,this.tail=Promise.resolve(),this.queueBytes=0,this.operations=0,this.paused=!1,this.ended=!1,this.failed=!1,this.disposed=!1,this.disposing=null,this.ownerId=null,this.pendingActivations=new Set;try{const a=t("@xterm/headless"),b=t("@xterm/addon-serialize");this.screen=new a.Terminal({cols:100,rows:28,scrollback:f.XZ,allowProposedApi:!0,windowOptions:{pushTitle:!0,popTitle:!0}}),this.serializer=new b.SerializeAddon,this.screen.loadAddon(this.serializer)}catch(b){throw console.error("[Pi Desk][Terminal] 权威屏幕加载失败",{terminalId:a,error:b}),new n(503,"终端屏幕依赖不可用")}try{this.child=new q(b,this.screen.cols,this.screen.rows),console.info("[Pi Desk][Terminal] PTY 已启动",{terminalId:a,pid:this.child.pty.pid})}catch(a){throw this.screen.dispose(),a}this.subscriptions=[this.screen.onTitleChange(a=>{this.disposed||d(a)}),this.screen.onData(a=>{if(!this.ended&&!this.disposed&&!this.failed)try{this.child.write(a)}catch(a){this.fail(a)}}),this.child.pty.onData(a=>this.acceptOutput(a)),this.child.pty.onExit(({exitCode:b})=>{this.ended=!0,this.ownerId=null,this.enqueue(async()=>{await this.child.released,this.disposed||(this.emit({type:"exit",exitCode:b}),this.onExit(b),console.info("[Pi Desk][Terminal] Shell 已退出",{terminalId:a,exitCode:b}))},!1).catch(a=>this.fail(a))})]}watch(a){return this.enqueue(async()=>{if(this.ensureAvailable(),this.listeners.size>=64)throw new n(429,"终端观察连接过多");let b=this.snapshot();return this.listeners.add(a),{snapshot:b,dispose:()=>{this.listeners.delete(a)}}})}input(a){return!a||Buffer.byteLength(a)>f.Oi?Promise.reject(new n(400,"终端输入必须为 1~16KiB UTF-8")):this.enqueue(async()=>{this.ensureRunning(),this.child.write(a)})}activate(a,b,c){let d={ownerId:a,released:!1};return this.pendingActivations.add(d),this.enqueue(async()=>{this.ensureRunning(),d.released||(this.validateDimensions(b,c),this.resizeScreen(b,c),this.ownerId=a)}).finally(()=>{this.pendingActivations.delete(d)})}resize(a,b,c){return this.enqueue(async()=>{this.ensureAvailable(),this.ownerId!==a||this.ended||(this.validateDimensions(b,c),this.resizeScreen(b,c))})}releaseOwner(a){for(let b of(this.ownerId===a&&(this.ownerId=null),this.pendingActivations))b.ownerId===a&&(b.released=!0)}dispose(){return this.disposing||(this.disposing=this.disposeRuntime()),this.disposing}async disposeRuntime(){this.disposed=!0,this.ownerId=null,this.listeners.clear(),this.paused&&this.child.pty.resume();try{await this.child.stop(),await this.tail}finally{for(let a of this.subscriptions)a.dispose();this.framing.dispose(),this.screen.dispose()}}acceptOutput(a){let b;if(this.disposed||this.failed)return;try{if(Buffer.byteLength(a)>1048576)throw new n(429,"PTY 单批输出超限");b=this.framing.frame(a)}catch(a){this.fail(a);return}if(!b)return;let c=Buffer.byteLength(b);this.queueBytes+c>1048576||this.operations>=256?this.fail(new n(429,"PTY 解析队列溢出")):(this.queueBytes+=c,!this.paused&&this.queueBytes>=262144&&(this.paused=!0,this.child.pty.pause()),this.enqueue(async()=>{try{if(this.disposed)return;for(let a of function(a,b=16384){let c=[],d=0,e=0;for(let f=0;f<a.length;){let g=a.codePointAt(f),h=g<=127?1:g<=2047?2:g<=65535?3:4;e+h>b&&(c.push(a.slice(d,f)),d=f,e=0),e+=h,f+=g>65535?2:1}return d<a.length&&c.push(a.slice(d)),c}(b))await new Promise(b=>this.screen.write(a,b)),this.emit({type:"output",data:a})}finally{this.queueBytes-=c,this.paused&&this.queueBytes<=65536&&!this.disposed&&(this.paused=!1,this.child.pty.resume())}},!1).catch(a=>this.fail(a)))}enqueue(a,b=!0){if(b&&this.operations>=256)return Promise.reject(new n(429,"终端操作队列已满"));this.operations+=1;let c=this.tail.then(a);return this.tail=c.then(()=>void 0,()=>void 0).finally(()=>{this.operations-=1}),c}snapshot(){let a=f.XZ;for(;;){let b=this.serializer.serialize({scrollback:a});if(Buffer.byteLength(b)<=f.I1)return{cols:this.screen.cols,rows:this.screen.rows,data:b};if(0===a)throw new n(429,"终端当前画面超过快照上限");a=Math.floor(a/2)}}resizeScreen(a,b){(this.screen.cols!==a||this.screen.rows!==b)&&(this.child.resize(a,b),this.screen.resize(a,b),this.emit({type:"resize",cols:a,rows:b}))}validateDimensions(a,b){if(!Number.isInteger(a)||!Number.isInteger(b)||a<2||a>f.xb||b<2||b>f.tu)throw new n(400,"终端尺寸必须为 2~400 列、2~200 行")}ensureAvailable(){if(this.disposed)throw new n(503,"终端正在关闭")}ensureRunning(){if(this.ensureAvailable(),this.ended||this.failed)throw new n(409,"终端已经退出")}emit(a){for(let b of this.listeners)try{b(a)}catch(a){this.listeners.delete(b),console.warn("[Pi Desk][Terminal] 释放失败的观察者",{terminalId:this.terminalId,error:a})}}fail(a){this.failed||this.disposed||(this.failed=!0,console.error("[Pi Desk][Terminal] 终端处理失败,结束目标进程",{terminalId:this.terminalId,error:a}),this.paused&&(this.paused=!1,this.child.pty.resume()),this.child.stop().catch(a=>console.error("[Pi Desk][Terminal] 结束失败",{terminalId:this.terminalId,error:a})))}}class v{create(a){let b=performance.now();return this.enqueue(async()=>{let c=performance.now();if(this.ensureOpen(),this.list().filter(a=>"running"===a.status).length+this.releases.size>=16)throw new n(429,"运行中或尚未完成清理的终端已达 16 个上限");let e=await p(a),f=performance.now();this.ensureOpen();let g=(0,d.randomUUID)(),h=new u(g,e,a=>this.handleExit(g,a),a=>this.handleTitleChange(g,a)),i={terminalId:g,cwd:e.cwd,shell:e.shell,title:"",status:"running",exitCode:null};return this.records.set(g,{summary:i,runtime:h,titleTimer:null}),this.publish(),console.info("[Pi Desk][TerminalManage] 已创建终端",{terminalId:g,cwd:e.cwd,shell:e.shell,queueMs:Math.round(c-b),resolveMs:Math.round(f-c),startMs:Math.round(performance.now()-f),totalMs:Math.round(performance.now()-b)}),{...i}})}list(){return Array.from(this.records.values(),({summary:a})=>({...a}))}subscribeList(a){return this.ensureOpen(),this.listeners.add(a),()=>{this.listeners.delete(a)}}watch(a,b){return this.get(a).runtime.watch(b)}input(a,b){return this.get(a).runtime.input(b)}activate(a,b,c,d){return this.get(a).runtime.activate(b,c,d)}resize(a,b,c,d){return this.get(a).runtime.resize(b,c,d)}releaseOwner(a){for(let b of this.records.values())b.runtime.releaseOwner(a)}remove(a){let b=performance.now();return this.enqueue(async()=>{let c=this.get(a);this.clearTitleTimer(c),this.records.delete(a);let d=this.exitedIds.indexOf(a);-1!==d&&this.exitedIds.splice(d,1),this.release(c),this.publish(),console.info("[Pi Desk][TerminalManage] 已接纳终端关闭",{terminalId:a,elapsedMs:Math.round(performance.now()-b)})})}release(a){let b=a.summary.terminalId,c=performance.now(),d=new Promise(a=>setImmediate(a)).then(()=>a.runtime.dispose());this.releases.set(b,d),d.then(()=>{this.releases.delete(b),console.info("[Pi Desk][TerminalManage] 终端资源已释放",{terminalId:b,elapsedMs:Math.round(performance.now()-c)})},a=>{console.error("[Pi Desk][TerminalManage] 终端资源清理失败",{terminalId:b,elapsedMs:Math.round(performance.now()-c),error:a})})}dispose(){if(!this.disposing){for(let a of(this.closing=!0,this.listeners.clear(),this.records.values()))this.clearTitleTimer(a);this.disposing=this.disposeAll()}return this.disposing}async disposeAll(){await this.tail;let a=await Promise.allSettled([...this.releases.values(),...Array.from(this.records.values(),a=>a.runtime.dispose())]);this.records.clear(),this.releases.clear(),this.exitedIds.length=0;let b=a.filter(a=>"rejected"===a.status);if(b.length)throw console.error("[Pi Desk][TerminalManage] 终端集合释放失败",{errors:b.map(a=>a.reason)}),AggregateError(b.map(a=>a.reason),"终端资源未完全释放")}handleTitleChange(a,b){let c=this.records.get(a);if(!c||this.closing)return;let d=b.replace(/\p{Cc}/gu,"").slice(0,512);c.summary.title!==d&&(c.summary.title=d,c.titleTimer||(c.titleTimer=setTimeout(()=>this.publish(),50)))}clearTitleTimer(a){a.titleTimer&&clearTimeout(a.titleTimer),a.titleTimer=null}handleExit(a,b){let c=this.records.get(a);if(c&&!this.closing&&"exited"!==c.summary.status){for(c.summary={...c.summary,status:"exited",exitCode:b},this.exitedIds.push(a);this.exitedIds.length>16;){let a=this.exitedIds.shift(),b=this.records.get(a);this.records.delete(a),b&&(this.clearTitleTimer(b),this.release(b))}this.publish()}}publish(){if(this.closing)return;for(let a of this.records.values())this.clearTitleTimer(a);let a=this.list();for(let b of this.listeners)try{b(a)}catch(a){this.listeners.delete(b),console.warn("[Pi Desk][TerminalManage] 列表观察失败",{error:a})}}get(a){this.ensureOpen();let b=this.records.get(a);if(!b)throw new n(404,"终端不存在");return b}ensureOpen(){if(this.closing)throw new n(503,"终端服务正在关闭")}enqueue(a){if(this.closing)return Promise.reject(new n(503,"终端服务正在关闭"));if(this.pending>=64)return Promise.reject(new n(429,"终端集合操作队列已满"));this.pending+=1;let b=this.tail.then(a);return this.tail=b.then(()=>void 0,()=>void 0).finally(()=>{this.pending-=1}),b}constructor(){this.records=new Map,this.exitedIds=[],this.releases=new Map,this.listeners=new Set,this.tail=Promise.resolve(),this.pending=0,this.closing=!1,this.disposing=null}}function w(){return globalThis.__piDeskTerminalManage||(globalThis.__piDeskTerminalManage=new v),globalThis.__piDeskTerminalManage}},73246:(a,b,c)=>{"use strict";c.d(b,{D:()=>m});var d=c(36153),e=c(69375),f=c(75825);let g=d.Yj().uuid(),h=d.Ik({}).strict(),i=d.Ik({terminalId:g,cwd:d.Yj().min(1),shell:d.Yj().min(1),title:d.Yj().max(512),status:d.k5(["running","exited"]),exitCode:d.ai().int().nullable()}).strict(),j=d.Ik({terminals:d.YO(i).max(32)}).strict(),k=Object.freeze({list:(0,e.Vc)({path:"terminals/list",inputSchema:h,outputSchema:j}),create:(0,e.Vc)({path:"terminals/create",inputSchema:d.Ik({cwd:d.Yj().min(1).max(32768).optional()}).strict(),outputSchema:i}),remove:(0,e.Vc)({path:"terminals/remove",inputSchema:d.Ik({terminalId:g}).strict(),outputSchema:h}),watch:(0,e.Vc)({path:"terminals/watch",inputSchema:d.Ik({terminalId:g.nullable()}).strict(),outputSchema:d.Ik({snapshot:f.CR.nullable()}).strict()}),unwatch:(0,e.Vc)({path:"terminals/unwatch",inputSchema:d.Ik({terminalId:g}).strict(),outputSchema:h}),input:(0,e.Vc)({path:"terminals/input",inputSchema:d.Ik({terminalId:g,data:d.Yj().min(1).max(f.Oi)}).strict(),outputSchema:h}),activate:(0,e.Vc)({path:"terminals/activate",inputSchema:d.Ik({terminalId:g,...f.XV}).strict(),outputSchema:h}),resize:(0,e.Vc)({path:"terminals/resize",inputSchema:d.Ik({terminalId:g,...f.XV}).strict(),outputSchema:h}),update:(0,e._G)({path:"terminals/update",bodySchema:j}),event:(0,e._G)({path:"terminals/event",bodySchema:d.Ik({terminalId:g,event:f.ED}).strict()})});var l=c(72608);class m{constructor(a,b,c){this.connection=a,this.manage=b,this.isReady=c,this.disposed=!1,this.unsubscribeList=null,this.watches=new Map,this.watchTail=Promise.resolve(),this.routes=[this.route(k.list,()=>(this.unsubscribeList||(this.unsubscribeList=this.manage.subscribeList(a=>{if(!this.active())return;let b=new Set(a.map(a=>a.terminalId));for(let a of this.watches.keys())b.has(a)||this.releaseWatch(a);this.connection.sendPush(k.update,{terminals:a})})),{terminals:this.manage.list()})),this.route(k.create,({cwd:a})=>this.manage.create(a)),this.route(k.remove,async({terminalId:a})=>(await this.manage.remove(a),{})),{path:k.watch.path,access:"ready",handle:a=>this.enqueueWatch(()=>this.watch(a))},{path:k.unwatch.path,access:"ready",handle:a=>this.enqueueWatch(()=>this.unwatch(a))},this.route(k.input,async({terminalId:a,data:b})=>(await this.manage.input(a,b),{})),this.route(k.activate,async({terminalId:a,cols:b,rows:c})=>(await this.manage.activate(a,this.connection.connectionId,b,c),this.active()||this.manage.releaseOwner(this.connection.connectionId),{})),this.route(k.resize,async({terminalId:a,cols:b,rows:c})=>(await this.manage.resize(a,this.connection.connectionId,b,c),{}))]}dispose(){this.disposed||(this.disposed=!0,this.unsubscribeList?.(),this.unsubscribeList=null,this.releaseAllWatches(),this.manage.releaseOwner(this.connection.connectionId))}active(){return!this.disposed&&this.connection.isCurrent()&&this.isReady()}route(a,b){return{path:a.path,access:"ready",handle:async c=>{if(!this.active())return;let d=a.inputSchema.safeParse(c.body);if(!d.success)return void this.connection.sendError(a.path,c.head.requestId,400,"终端请求参数无效");try{let e=b(d.data),f=e instanceof Promise?await e:e;this.active()&&this.connection.sendSuccess(a,c.head.requestId,f)}catch(a){this.sendError(c,a)}}}}enqueueWatch(a){let b=this.watchTail.then(a);return this.watchTail=b.catch(()=>void 0),b}async watch(a){if(!this.active())return;let b=k.watch,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"终端观察参数无效");if(null===c.data.terminalId){this.releaseAllWatches(),this.connection.sendSuccess(b,a.head.requestId,{snapshot:null});return}if(this.releaseWatch(c.data.terminalId),this.watches.size>=32)return void this.sendError(a,new l.l$(429,"终端观察已达 32 个上限"));let d={id:c.data.terminalId,dispose:null,events:[],bytes:0,syncing:!0,overflowed:!1,rebuilding:!1,timer:null};this.watches.set(d.id,d);try{await this.prepareSnapshot(d,c=>{this.connection.sendSuccess(b,a.head.requestId,{snapshot:c})})}catch(b){this.watches.get(d.id)===d&&this.releaseWatch(d.id),this.sendError(a,b)}}async unwatch(a){if(!this.active())return;let b=k.unwatch,c=b.inputSchema.safeParse(a.body);c.success?(this.releaseWatch(c.data.terminalId),this.connection.sendSuccess(b,a.head.requestId,{})):this.connection.sendError(b.path,a.head.requestId,400,"终端观察参数无效")}valid(a){return this.watches.get(a.id)===a&&this.active()}async prepareSnapshot(a,b){a.rebuilding=!0,a.syncing=!0;try{for(;this.valid(a);){a.dispose?.(),a.dispose=null,a.events=[],a.bytes=0,a.overflowed=!1;let c=await this.manage.watch(a.id,b=>this.acceptEvent(a,b));if(!this.valid(a))return void c.dispose();if(a.dispose=c.dispose,!a.overflowed){b(c.snapshot),a.syncing=!1,this.scheduleDrain(a);return}}}finally{a.rebuilding=!1}}acceptEvent(a,b){if(!this.valid(a)||a.overflowed)return;let c=this.eventBytes(b);if(a.bytes+c>524288||a.events.length>=128){a.overflowed=!0,a.syncing=!0,a.events=[],a.bytes=0,console.warn("[Pi Desk][TerminalSocket] 观察队列溢出,重建快照",{terminalId:a.id,connectionId:this.connection.connectionId}),a.rebuilding||this.enqueueWatch(async()=>{if(this.valid(a))try{await this.prepareSnapshot(a,b=>{this.connection.sendPush(k.event,{terminalId:a.id,event:{type:"snapshot",snapshot:b}})})}catch(b){console.error("[Pi Desk][TerminalSocket] 快照重建失败",{terminalId:a.id,error:b}),this.valid(a)&&(this.releaseWatch(a.id),this.connection.close(1011,"终端画面无法同步"))}});return}a.events.push(b),a.bytes+=c,a.syncing||this.scheduleDrain(a)}scheduleDrain(a){this.valid(a)&&!a.syncing&&!a.timer&&a.events.length&&(a.timer=setTimeout(()=>{if(a.timer=null,this.valid(a)&&!a.syncing){for(let b=0;b<4&&a.events.length&&this.valid(a);b+=1){let b=a.events.shift();a.bytes-=this.eventBytes(b),this.connection.sendPush(k.event,{terminalId:a.id,event:b})}this.scheduleDrain(a)}},8))}eventBytes(a){return"output"===a.type?Buffer.byteLength(a.data):"snapshot"===a.type?Buffer.byteLength(a.snapshot.data):32}releaseWatch(a){let b=this.watches.get(a);b&&(this.watches.delete(a),b.dispose?.(),b.timer&&clearTimeout(b.timer),b.events=[],b.bytes=0)}releaseAllWatches(){for(let a of this.watches.keys())this.releaseWatch(a)}sendError(a,b){if(this.active()){if(b instanceof l.l$)return void this.connection.sendError(a.head.path,a.head.requestId,b.code,b.message);console.error("[Pi Desk][TerminalSocket] 终端请求失败",{path:a.head.path,connectionId:this.connection.connectionId,error:b}),this.connection.sendError(a.head.path,a.head.requestId,500,"终端操作失败")}}}},74344:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{c:()=>r});var e=c(93951),f=c(50520),g=c(76217),h=c(18331),i=c(63210),j=c(42035),k=c(55490),l=c(6676),m=c(78922),n=c(36361),o=c(64007),p=c(99667),q=a([f,k,l,n,p]);[f,k,l,n,p]=q.then?(await q)():q;class r{constructor(a,b,c){this.connection=a,this.manage=b,this.disposed=!1,this.unsubscribeManagement=(0,f.getL2PluginManagement)().subscribe(()=>{!this.disposed&&c()&&this.connection.isCurrent()&&this.connection.sendPush(e.LC,{})}),this.routes=Object.freeze([{path:g.OY.invoke.path,access:"ready",handle:a=>this.invoke(a)},{path:h.bm.list.path,access:"ready",handle:a=>this.listBrowserEntries(a)},{path:i.QV.commandsList.path,access:"ready",handle:a=>this.listCommands(a)},{path:i.QV.commandExecute.path,access:"ready",handle:a=>this.executeCommand(a)},{path:i.QV.toolsList.path,access:"ready",handle:a=>this.listTools(a)},{path:i.QV.bashExecute.path,access:"ready",handle:a=>this.executeBash(a)},{path:i.QV.bashAbort.path,access:"ready",handle:a=>this.abortBash(a)}])}dispose(){this.disposed||(this.disposed=!0,this.unsubscribeManagement())}async invoke(a){let b=g.OY.invoke,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"插件调用参数无效");try{let d="global"===c.data.scope?await (0,n.getL4PiGlobalPluginRuntime)().invoke(c.data.pluginName,c.data.method,c.data.input):await this.manage.invokeSessionPluginMethod(c.data);this.connection.sendSuccess(b,a.head.requestId,d)}catch(d){this.sendInvokeError(b.path,a.head.requestId,d,c.data.pluginName,c.data.method)}}async listBrowserEntries(a){let b=h.bm.list;if(!b.inputSchema.safeParse(a.body).success)return void this.connection.sendError(b.path,a.head.requestId,400,"插件入口参数无效");try{let c=await (0,n.getL4PiGlobalPluginRuntime)().listBrowserEntries(),d=(0,m.IC)().replace(c);this.connection.sendSuccess(b,a.head.requestId,{entries:d.map(a=>({pluginName:a.entry.pluginName,url:a.url}))})}catch(c){console.error("[Pi Desk][PluginSocket] 查询 Browser Entry 失败",{errorName:c instanceof Error?c.name:"UnknownError",message:c instanceof Error?c.message:String(c)}),this.connection.sendError(b.path,a.head.requestId,500,"查询插件入口失败")}}async listCommands(a){let b=i.QV.commandsList,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi 命令参数无效");try{this.connection.sendSuccess(b,a.head.requestId,await this.manage.listNativeCommands(c.data))}catch(c){this.sendNativeError(b.path,a.head.requestId,c,"查询 Pi 命令失败")}}async executeCommand(a){let b=i.QV.commandExecute,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi 命令参数无效");try{await this.manage.executeNativeCommand(c.data),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendNativeError(b.path,a.head.requestId,c,"执行 Pi 命令失败")}}async listTools(a){let b=i.QV.toolsList,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi Tool 参数无效");try{this.connection.sendSuccess(b,a.head.requestId,await this.manage.listNativeTools(c.data))}catch(c){this.sendNativeError(b.path,a.head.requestId,c,"查询 Pi Tool 失败")}}async executeBash(a){let b=i.QV.bashExecute,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi Bash 参数无效");try{this.connection.sendSuccess(b,a.head.requestId,await this.manage.executeDirectBash(c.data))}catch(c){this.sendNativeError(b.path,a.head.requestId,c,"执行 Pi Bash 失败")}}async abortBash(a){let b=i.QV.bashAbort,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi Bash 参数无效");try{await this.manage.abortDirectBash(c.data),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendNativeError(b.path,a.head.requestId,c,"中止 Pi Bash 失败")}}sendNativeError(a,b,c,d){c instanceof k.dM?this.connection.sendError(a,b,409,"工作会话来源已变化"):c instanceof k.nJ?this.connection.sendError(a,b,409,"工作会话正在变更"):c instanceof l.X9?this.connection.sendError(a,b,404,"Pi 命令不存在"):c instanceof l.yT?this.connection.sendError(a,b,409,"当前工作会话已有 Bash 正在执行"):(console.warn("[Pi Desk][PluginSocket] Native Pi 调用失败",{path:a,errorName:c instanceof Error?c.name:"UnknownError",message:c instanceof Error?c.message:String(c)}),this.connection.sendError(a,b,500,c instanceof Error&&c.message?c.message:d))}sendInvokeError(a,b,c,d,e){c instanceof k.dM?this.connection.sendError(a,b,409,"工作会话来源已变化"):c instanceof k.nJ?this.connection.sendError(a,b,409,"工作会话正在变更"):c instanceof p.y||c instanceof Error&&"L4PiPluginRuntimeBusyError"===c.name?this.connection.sendError(a,b,409,"插件正在重载"):c instanceof o.Tk||c instanceof Error&&"L4PiPluginMethodNotFoundError"===c.name?this.connection.sendError(a,b,404,"插件方法不存在"):c instanceof o.Pu?"input"===c.direction?this.connection.sendError(a,b,413,"插件调用数据超过 2MB"):(console.warn("[Pi Desk][PluginSocket] 插件方法输出超过限制",{pluginName:d,method:e,path:a,errorName:c.name}),this.connection.sendError(a,b,500,`插件方法执行失败:${d}/${e} 返回数据超过 2MB,请缩小查询范围或减少返回内容`)):(0,j.LO)(c)?this.connection.sendError(a,b,c.code,c.message):(console.warn("[Pi Desk][PluginSocket] 插件方法执行失败",{pluginName:d,method:e,path:a,errorName:c instanceof Error?c.name:"UnknownError",message:c instanceof Error?c.message:"Unknown plugin method error"}),this.connection.sendError(a,b,500,"插件方法执行失败"))}}d()}catch(a){d(a)}})},74972:(a,b,c)=>{"use strict";let{tokenChars:d}=c(47591);a.exports={parse:function(a){let b=new Set,c=-1,e=-1,f=0;for(;f<a.length;f++){let g=a.charCodeAt(f);if(-1===e&&1===d[g])-1===c&&(c=f);else if(0!==f&&(32===g||9===g))-1===e&&-1!==c&&(e=f);else if(44===g){if(-1===c)throw SyntaxError(`Unexpected character at index ${f}`);-1===e&&(e=f);let d=a.slice(c,e);if(b.has(d))throw SyntaxError(`The "${d}" subprotocol is duplicated`);b.add(d),c=e=-1}else throw SyntaxError(`Unexpected character at index ${f}`)}if(-1===c||-1!==e)throw SyntaxError("Unexpected end of input");let g=a.slice(c,f);if(b.has(g))throw SyntaxError(`The "${g}" subprotocol is duplicated`);return b.add(g),b}}},75825:(a,b,c)=>{"use strict";c.d(b,{CR:()=>k,ED:()=>l,I1:()=>i,Oi:()=>h,XV:()=>j,XZ:()=>g,tu:()=>f,xb:()=>e});var d=c(36153);let e=400,f=200,g=2e3,h=16384,i=8388608,j={cols:d.ai().int().min(2).max(e),rows:d.ai().int().min(2).max(f)},k=d.Ik({...j,data:d.Yj().max(i)}).strict(),l=d.gM("type",[d.Ik({type:d.eu("snapshot"),snapshot:k}).strict(),d.Ik({type:d.eu("output"),data:d.Yj().min(1).max(65536)}).strict(),d.Ik({type:d.eu("resize"),...j}).strict(),d.Ik({type:d.eu("exit"),exitCode:d.ai().int()}).strict()])},76217:(a,b,c)=>{"use strict";c.d(b,{OY:()=>l});var d=c(36153),e=c(3329),f=c(69375);let g=d.Yj().trim().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),h=d.g1(d.Yj(),d.Pq()),i=d.Ik({pluginName:g,method:g,scope:d.eu("global"),input:h}).strict(),j=d.Ik({pluginName:g,method:g,scope:d.eu("session"),source:e.R,input:h}).strict(),k=d.gM("scope",[i,j]),l=Object.freeze({invoke:(0,f.Vc)({path:"plugins/invoke",inputSchema:k,outputSchema:h})})},78922:(a,b,c)=>{"use strict";c.d(b,{IC:()=>h,J:()=>i});var d=c(77598),e=c(57075);class f extends Error{constructor(a,b){super(`Plugin Browser resource was not found: ${a}/${b}`),this.name="L4PiPluginBrowserResourceNotFoundError"}}class g{replace(a){let b=new Set(a.map(a=>a.pluginName));if(b.size!==a.length)throw Error("Browser Entry 清单包含重复插件");if(a.reduce((a,b)=>a+b.snapshot.size,0)>0x8000000)throw Error("Browser 活动资源超过容量上限");for(let[a,c]of this.recordsByPlugin)b.has(a)||(this.recordsByPlugin.delete(a),this.retire(c));let c=a.map(a=>{let b=this.recordsByPlugin.get(a.pluginName),c=b?.resourceKey===a.resourceKey&&b.entryPath===a.entryPath?b:{pluginName:a.pluginName,resourceGroup:(0,d.randomBytes)(24).toString("base64url"),resourceKey:a.resourceKey,entryPath:a.entryPath,snapshot:a.snapshot,retiredAt:null};return b!==c&&(b&&this.retire(b),this.recordsByPlugin.set(a.pluginName,c),this.recordsByGroup.set(c.resourceGroup,c)),{resourceGroup:c.resourceGroup,url:`/api/plugins/browser-resources/${c.resourceGroup}/entry.js`,entry:a}});return this.prune(),c}async read(a,b){this.prune();let c=this.recordsByGroup.get(a),d=!(!b||b.length>4096||b.startsWith("/")||b.includes("\\")||b.includes("\0"))&&b.endsWith(".js")&&b.split("/").every(a=>""!==a&&"."!==a&&".."!==a)?c?.snapshot.modules.get(b):void 0;if(!d)throw new f(a,b);return{stream:e.Readable.toWeb(e.Readable.from([d.content])),size:d.content.length,etag:d.etag}}dispose(){this.pruneTimer&&clearTimeout(this.pruneTimer),this.pruneTimer=null,this.recordsByPlugin.clear(),this.recordsByGroup.clear()}retire(a){a.retiredAt??=Date.now()}prune(){this.pruneTimer&&clearTimeout(this.pruneTimer),this.pruneTimer=null;let a=Date.now(),b=[...this.recordsByGroup.values()].filter(a=>null!==a.retiredAt).sort((a,b)=>a.retiredAt-b.retiredAt),c=b.reduce((a,b)=>a+b.snapshot.size,0),d=b.length;for(let e of b)(a-e.retiredAt>=6e4||d>32||c>0x4000000)&&(this.recordsByGroup.delete(e.resourceGroup),c-=e.snapshot.size,d-=1);let e=b.find(a=>this.recordsByGroup.has(a.resourceGroup));e&&(this.pruneTimer=setTimeout(()=>this.prune(),Math.max(1,e.retiredAt+6e4-a)),this.pruneTimer.unref())}constructor(){this.recordsByPlugin=new Map,this.recordsByGroup=new Map,this.pruneTimer=null}}function h(){return globalThis.__piDeskPluginBrowserResourceRegistry||(globalThis.__piDeskPluginBrowserResourceRegistry=new g),globalThis.__piDeskPluginBrowserResourceRegistry}function i(){globalThis.__piDeskPluginBrowserResourceRegistry?.dispose(),globalThis.__piDeskPluginBrowserResourceRegistry=void 0}},79271:(a,b,c)=>{"use strict";c.d(b,{m:()=>r});var d=c(76760),e=c(36153),f=c(69375),g=c(72497);let h=e.Yj().trim().min(1).max(32768),i=e.Ik({text:e.Yj(),truncated:e.zM()}).strict(),j=e.KC([e.Ik({type:e.eu("text_append"),text:e.Yj().min(1)}).strict(),e.Ik({type:e.eu("snapshot"),snapshot:i}).strict(),e.Ik({type:e.eu("unavailable")}).strict()]),k=e.Ik({pluginName:g.tv,path:h}).strict(),l=e.Ik({snapshot:i}).strict(),m=e.Ik({}).strict(),n=e.Ik({pluginName:g.tv,path:h,event:j}).strict(),o=Object.freeze({watch:(0,f.Vc)({path:"plugins/logs/watch",inputSchema:k,outputSchema:l}),unwatch:(0,f.Vc)({path:"plugins/logs/unwatch",inputSchema:k,outputSchema:m}),event:(0,f._G)({path:"plugins/logs/event",bodySchema:n})});var p=c(78555);function q(a,b){return JSON.stringify([a,b])}class r{constructor(a){this.connection=a,this.watches=new Map,this.operationTail=Promise.resolve(),this.disposed=!1,this.routes=Object.freeze([{path:o.watch.path,access:"ready",handle:a=>this.enqueue(()=>this.watch(a))},{path:o.unwatch.path,access:"ready",handle:a=>this.enqueue(()=>this.unwatch(a))}])}dispose(){if(!this.disposed){for(let a of(this.disposed=!0,this.watches.values()))a.observation.release();this.watches.clear()}}enqueue(a){let b=this.operationTail.then(a,a);return this.operationTail=b.then(()=>void 0,()=>void 0),b}async watch(a){let b=o.watch,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"日志观察参数无效");if(!(0,d.isAbsolute)(c.data.path))return void this.connection.sendError(b.path,a.head.requestId,400,"日志路径必须是服务端绝对路径");let e=q(c.data.pluginName,c.data.path),f=this.watches.get(e);if(f)return void this.connection.sendSuccess(b,a.head.requestId,{snapshot:f.observation.readSnapshot()});if(this.watches.size>=16)return void this.connection.sendError(b.path,a.head.requestId,409,"当前页面观察的日志过多");try{let d=await this.createStableWatch(e,c.data.pluginName,c.data.path);if(this.disposed||!this.connection.isCurrent())return void d.observation.release();this.watches.set(e,d),this.connection.sendSuccess(b,a.head.requestId,{snapshot:d.observation.snapshot}),d.status="ready",this.flushQueuedEvents(d),console.info("[Pi Desk][PluginLogSocket] 日志观察完成",{clientId:this.connection.clientId,pluginName:d.pluginName,path:d.path})}catch(d){console.warn("[Pi Desk][PluginLogSocket] 初始化日志观察失败",{pluginName:c.data.pluginName,path:c.data.path,errorName:d instanceof Error?d.name:"UnknownError",message:d instanceof Error?d.message:String(d)}),this.connection.sendError(b.path,a.head.requestId,500,"读取日志失败")}}async createStableWatch(a,b,c){for(;;){let d=[],e={state:null},f=await (0,p.i)().observe(c,b=>{let c=e.state;if(!c||this.watches.get(a)!==c||this.disposed){d.length<128&&d.push(b);return}this.handleEvent(c,b)}),g={key:a,pluginName:b,path:c,observation:f,status:"syncing",queuedEvents:d,overflowed:d.length>=128};if(e.state=g,!g.overflowed)return g;f.release()}}async unwatch(a){let b=o.unwatch,c=b.inputSchema.safeParse(a.body);c.success?(0,d.isAbsolute)(c.data.path)?(this.releaseWatch(q(c.data.pluginName,c.data.path)),this.connection.sendSuccess(b,a.head.requestId,{})):this.connection.sendError(b.path,a.head.requestId,400,"日志路径必须是服务端绝对路径"):this.connection.sendError(b.path,a.head.requestId,400,"日志解除观察参数无效")}handleEvent(a,b){if(this.watches.get(a.key)===a&&!this.disposed&&this.connection.isCurrent()){if("syncing"===a.status){if(a.queuedEvents.length>=128){a.queuedEvents.length=0,a.overflowed=!0;return}a.queuedEvents.push(b);return}this.connection.sendPush(o.event,{pluginName:a.pluginName,path:a.path,event:b}),"unavailable"===b.type&&this.releaseWatch(a.key)}}flushQueuedEvents(a){if(this.watches.get(a.key)===a){if(a.overflowed){this.connection.sendPush(o.event,{pluginName:a.pluginName,path:a.path,event:{type:"snapshot",snapshot:a.observation.readSnapshot()}}),a.queuedEvents.length=0,a.overflowed=!1;return}for(let b of a.queuedEvents.splice(0))if(this.connection.sendPush(o.event,{pluginName:a.pluginName,path:a.path,event:b}),"unavailable"===b.type)return void this.releaseWatch(a.key)}}releaseWatch(a){let b=this.watches.get(a);b&&(this.watches.delete(a),b.observation.release())}}},80273:(a,b,c)=>{"use strict";c.d(b,{aJ:()=>g,nV:()=>h});var d=c(77598);let e=/^(\d+)\.([a-f0-9]{64})$/;function f(a){return(0,d.createHash)("sha256").update(a,"utf8").digest()}function g(a,b,c=Date.now()){var h,i;if(!a||!b)return!1;let j=e.exec(a);if(!j)return!1;let k=Number(j[1]);return!!Number.isSafeInteger(k)&&!(k<c)&&(h=j[2],i=(0,d.createHmac)("sha256",b).update(`Pi Desk web session:${k}`,"utf8").digest("hex"),(0,d.timingSafeEqual)(f(h),f(i)))}function h(a,b){if(a)for(let c of a.split(";")){let a=c.indexOf("=");if(!(a<0)&&c.slice(0,a).trim()===b)try{return decodeURIComponent(c.slice(a+1).trim())}catch{break}}}},81607:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{U:()=>h});var e=c(71779),f=c(31442),g=a([f]);f=(g.then?(await g)():g)[0];class h{constructor(a,b){this.connection=a,this.runtime=b,this.routes=Object.freeze([{path:e.R.apply.path,access:"ready",handle:a=>this.apply(a)}])}dispose(){}async apply(a){let b=e.R.apply,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"App Runtime 更新参数无效");try{await this.runtime.applyClient(c.data),this.connection.sendSuccess(b,a.head.requestId,{})}catch(d){let c=d instanceof f.L2AppRuntimeTargetNotFoundError;this.connection.sendError(b.path,a.head.requestId,c?404:500,c?"App Runtime 目标不存在":"App Runtime 更新失败")}}}d()}catch(a){d(a)}})},81882:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{Oe:()=>k,yJ:()=>l});var e=c(80273),f=c(62761),g=c(9763),h=c(5034),i=c(67841);c(37721);var j=a([f,g,h,i]);[f,g,h,i]=j.then?(await j)():j;let l="pi-desk-session";function k(a){var b;return b=(0,f.f4)(),null===b||(0,e.aJ)((0,e.nV)(a,l),b.sessionSecret)}d()}catch(a){d(a)}})},89373:(a,b,c)=>{"use strict";let d=c(94735),e=c(81630),{Duplex:f}=c(27910),{createHash:g}=c(55511),h=c(18753),i=c(95374),j=c(74972),k=c(42027),{CLOSE_TIMEOUT:l,GUID:m,kWebSocket:n}=c(46929),o=/^[+/0-9A-Za-z]{22}==$/;class p extends d{constructor(a,b){if(super(),null==(a={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:262144,maxFragments:16384,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:l,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:k,...a}).port&&!a.server&&!a.noServer||null!=a.port&&(a.server||a.noServer)||a.server&&a.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=a.port?(this._server=e.createServer((a,b)=>{let c=e.STATUS_CODES[426];b.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),b.end(c)}),this._server.listen(a.port,a.host,a.backlog,b)):a.server&&(this._server=a.server),this._server){const a=this.emit.bind(this,"connection");this._removeListeners=function(a,b){for(let c of Object.keys(b))a.on(c,b[c]);return function(){for(let c of Object.keys(b))a.removeListener(c,b[c])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(b,c,d)=>{this.handleUpgrade(b,c,d,a)}})}!0===a.perMessageDeflate&&(a.perMessageDeflate={}),a.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=a,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(a){if(2===this._state){a&&this.once("close",()=>{a(Error("The server is not running"))}),process.nextTick(q,this);return}if(a&&this.once("close",a),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(q,this);else{let a=this._server;this._removeListeners(),this._removeListeners=this._server=null,a.close(()=>{q(this)})}}shouldHandle(a){if(this.options.path){let b=a.url.indexOf("?");if((-1!==b?a.url.slice(0,b):a.url)!==this.options.path)return!1}return!0}handleUpgrade(a,b,c,d){b.on("error",r);let e=a.headers["sec-websocket-key"],f=a.headers.upgrade,g=+a.headers["sec-websocket-version"];if("GET"!==a.method)return void t(this,a,b,405,"Invalid HTTP method");if(void 0===f||"websocket"!==f.toLowerCase())return void t(this,a,b,400,"Invalid Upgrade header");if(void 0===e||!o.test(e))return void t(this,a,b,400,"Missing or invalid Sec-WebSocket-Key header");if(13!==g&&8!==g)return void t(this,a,b,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});if(!this.shouldHandle(a))return void s(b,400);let k=a.headers["sec-websocket-protocol"],l=new Set;if(void 0!==k)try{l=j.parse(k)}catch(c){t(this,a,b,400,"Invalid Sec-WebSocket-Protocol header");return}let m=a.headers["sec-websocket-extensions"],n={};if(this.options.perMessageDeflate&&void 0!==m){let c=new i({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let a=h.parse(m);a[i.extensionName]&&(c.accept(a[i.extensionName]),n[i.extensionName]=c)}catch(c){t(this,a,b,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:a.headers[`${8===g?"sec-websocket-origin":"origin"}`],secure:!!(a.socket.authorized||a.socket.encrypted),req:a};if(2===this.options.verifyClient.length)return void this.options.verifyClient(f,(f,g,h,i)=>{if(!f)return s(b,g||401,h,i);this.completeUpgrade(n,e,l,a,b,c,d)});if(!this.options.verifyClient(f))return s(b,401)}this.completeUpgrade(n,e,l,a,b,c,d)}completeUpgrade(a,b,c,d,e,f,j){if(!e.readable||!e.writable)return e.destroy();if(e[n])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return s(e,503);let k=g("sha1").update(b+m).digest("base64"),l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${k}`],o=new this.options.WebSocket(null,void 0,this.options);if(c.size){let a=this.options.handleProtocols?this.options.handleProtocols(c,d):c.values().next().value;a&&(l.push(`Sec-WebSocket-Protocol: ${a}`),o._protocol=a)}if(a[i.extensionName]){let b=a[i.extensionName].params,c=h.format({[i.extensionName]:[b]});l.push(`Sec-WebSocket-Extensions: ${c}`),o._extensions=a}this.emit("headers",l,d),e.write(l.concat("\r\n").join("\r\n")),e.removeListener("error",r),o.setSocket(e,f,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(o),o.on("close",()=>{this.clients.delete(o),this._shouldEmitClose&&!this.clients.size&&process.nextTick(q,this)})),j(o,d)}}function q(a){a._state=2,a.emit("close")}function r(){this.destroy()}function s(a,b,c,d){c=c||e.STATUS_CODES[b],d={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(c),...d},a.once("finish",a.destroy),a.end(`HTTP/1.1 ${b} ${e.STATUS_CODES[b]}\r
2
- `+Object.keys(d).map(a=>`${a}: ${d[a]}`).join("\r\n")+"\r\n\r\n"+c)}function t(a,b,c,d,e,f){if(a.listenerCount("wsClientError")){let d=Error(e);Error.captureStackTrace(d,t),a.emit("wsClientError",d,c,b)}else s(c,d,e,f)}a.exports=p},93750:()=>{},94296:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{getL1AppSocketRuntime:()=>r});var e=c(47757),f=c(81882),g=c(80273),h=c(50520),i=c(31442),j=c(25406),k=c(78922),l=c(36361),m=c(33448),n=c(16050),o=c(72608),p=c(61667),q=a([e,f,h,i,j,l,m,n,p]);[e,f,h,i,j,l,m,n,p]=q.then?(await q)():q;class s{constructor(){this.sessionsByClientId=new Map,this.manage=(0,j.getL2WorkSessionManage)(),this.appRuntime=(0,i.getL2AppRuntime)(),this.taskCenter=(0,n.K)(),this.terminals=(0,o.yd)(),this.manage.subscribePluginPushEvents(a=>this.pushPlugin(a))}accept(a,b,c){let d=this.sessionsByClientId.get(b),e=new p.k(a,b,(0,g.nV)(c,f.yJ),this.manage,this.appRuntime,this.taskCenter,this.terminals,(a,c)=>{this.sessionsByClientId.get(b)===a&&this.sessionsByClientId.delete(b),console.info("[Pi Desk][AppSocketRuntime] 应用连接已断开",{clientId:b,connectionId:a.connection.connectionId,code:c.code})});this.sessionsByClientId.set(b,e);try{e.start()}catch(a){throw d?this.sessionsByClientId.set(b,d):this.sessionsByClientId.delete(b),e.terminate(),a}d?.supersede()}async closeByAuthToken(a,b,c){let d=[];for(let[e,f]of this.sessionsByClientId)f.authToken===a&&(this.sessionsByClientId.delete(e),f.close(b,c),d.push(f));await Promise.all(d.map(a=>a.waitForClose()))}async closeAll(a,b){let c=[...this.sessionsByClientId.values()];for(let d of(this.sessionsByClientId.clear(),c))d.close(a,b);await Promise.all(c.map(a=>a.waitForClose()))}terminateAll(){let a=[...this.sessionsByClientId.values()];for(let b of(this.sessionsByClientId.clear(),a))b.terminate()}connectionCount(){return this.sessionsByClientId.size}pushPlugin(a){for(let b of this.sessionsByClientId.values())b.pushPlugin(a)}async disposePlugins(){(0,e.disposeL4PiDeskCommands)(),(0,h.disposeL2PluginManagement)(),await (0,l.disposeL4PiGlobalPluginRuntime)(),(0,k.J)(),(0,i.disposeL2AppRuntime)()}async disposeTerminals(){await this.terminals.dispose()}async disposeWorkSessions(){await (0,m.wz)()}}function r(){return globalThis.__piDeskAppSocketRuntime||(globalThis.__piDeskAppSocketRuntime=new s),globalThis.__piDeskAppSocketRuntime}d()}catch(a){d(a)}})},95374:(a,b,c)=>{"use strict";let d,e=c(74075),f=c(52218),g=c(7586),{kStatusCode:h}=c(46929),i=Buffer[Symbol.species],j=Buffer.from([0,0,255,255]),k=Symbol("permessage-deflate"),l=Symbol("total-length"),m=Symbol("callback"),n=Symbol("buffers"),o=Symbol("error");class p{constructor(a){this._options=a||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._maxPayload=0|this._options.maxPayload,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,d||(d=new g(void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10))}static get extensionName(){return"permessage-deflate"}offer(){let a={};return this._options.serverNoContextTakeover&&(a.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(a.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(a.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?a.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(a.client_max_window_bits=!0),a}accept(a){return a=this.normalizeParams(a),this.params=this._isServer?this.acceptAsServer(a):this.acceptAsClient(a),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let a=this._deflate[m];this._deflate.close(),this._deflate=null,a&&a(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(a){let b=this._options,c=a.find(a=>(!1!==b.serverNoContextTakeover||!a.server_no_context_takeover)&&(!a.server_max_window_bits||!1!==b.serverMaxWindowBits&&("number"!=typeof b.serverMaxWindowBits||!(b.serverMaxWindowBits>a.server_max_window_bits)))&&("number"!=typeof b.clientMaxWindowBits||("number"==typeof a.client_max_window_bits?!(b.clientMaxWindowBits>a.client_max_window_bits):!!a.client_max_window_bits)));if(!c)throw Error("None of the extension offers can be accepted");return b.serverNoContextTakeover&&(c.server_no_context_takeover=!0),b.clientNoContextTakeover&&(c.client_no_context_takeover=!0),"number"==typeof b.serverMaxWindowBits&&(c.server_max_window_bits=b.serverMaxWindowBits),"number"==typeof b.clientMaxWindowBits?c.client_max_window_bits=b.clientMaxWindowBits:(!0===c.client_max_window_bits||!1===b.clientMaxWindowBits)&&delete c.client_max_window_bits,c}acceptAsClient(a){let b=a[0];if(!1===this._options.clientNoContextTakeover&&b.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(b.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&b.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(b.client_max_window_bits=this._options.clientMaxWindowBits);return b}normalizeParams(a){return a.forEach(a=>{Object.keys(a).forEach(b=>{let c=a[b];if(c.length>1)throw Error(`Parameter "${b}" must have only a single value`);if(c=c[0],"client_max_window_bits"===b){if(!0!==c){let a=+c;if(!Number.isInteger(a)||a<8||a>15)throw TypeError(`Invalid value for parameter "${b}": ${c}`);c=a}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${b}": ${c}`)}else if("server_max_window_bits"===b){let a=+c;if(!Number.isInteger(a)||a<8||a>15)throw TypeError(`Invalid value for parameter "${b}": ${c}`);c=a}else if("client_no_context_takeover"===b||"server_no_context_takeover"===b){if(!0!==c)throw TypeError(`Invalid value for parameter "${b}": ${c}`)}else throw Error(`Unknown parameter "${b}"`);a[b]=c})}),a}decompress(a,b,c){d.add(d=>{this._decompress(a,b,(a,b)=>{d(),c(a,b)})})}compress(a,b,c){d.add(d=>{this._compress(a,b,(a,b)=>{d(),c(a,b)})})}_decompress(a,b,c){let d=this._isServer?"client":"server";if(!this._inflate){let a=`${d}_max_window_bits`,b="number"!=typeof this.params[a]?e.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=e.createInflateRaw({...this._options.zlibInflateOptions,windowBits:b}),this._inflate[k]=this,this._inflate[l]=0,this._inflate[n]=[],this._inflate.on("error",s),this._inflate.on("data",r)}this._inflate[m]=c,this._inflate.write(a),b&&this._inflate.write(j),this._inflate.flush(()=>{let a=this._inflate[o];if(a){this._inflate.close(),this._inflate=null,c(a);return}let e=f.concat(this._inflate[n],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[n]=[],b&&this.params[`${d}_no_context_takeover`]&&this._inflate.reset()),c(null,e)})}_compress(a,b,c){let d=this._isServer?"server":"client";if(!this._deflate){let a=`${d}_max_window_bits`,b="number"!=typeof this.params[a]?e.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=e.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:b}),this._deflate[l]=0,this._deflate[n]=[],this._deflate.on("data",q)}this._deflate[m]=c,this._deflate.write(a),this._deflate.flush(e.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=f.concat(this._deflate[n],this._deflate[l]);b&&(a=new i(a.buffer,a.byteOffset,a.length-4)),this._deflate[m]=null,this._deflate[l]=0,this._deflate[n]=[],b&&this.params[`${d}_no_context_takeover`]&&this._deflate.reset(),c(null,a)})}}function q(a){this[n].push(a),this[l]+=a.length}function r(a){(this[l]+=a.length,this[k]._maxPayload<1||this[l]<=this[k]._maxPayload)?this[n].push(a):(this[o]=RangeError("Max payload size exceeded"),this[o].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[o][h]=1009,this.removeListener("data",r),this.reset())}function s(a){(this[k]._inflate=null,this[o])?this[m](this[o]):(a[h]=1007,this[m](a))}a.exports=p},99407:()=>{}};
1
+ exports.id=94296,exports.ids=[94296],exports.modules={73:(a,b,c)=>{"use strict";let{Writable:d}=c(27910),e=c(95374),{BINARY_TYPES:f,EMPTY_BUFFER:g,kStatusCode:h,kWebSocket:i}=c(46929),{concat:j,toArrayBuffer:k,unmask:l}=c(52218),{isValidStatusCode:m,isValidUTF8:n}=c(47591),o=Buffer[Symbol.species];class p extends d{constructor(a={}){super(),this._allowSynchronousEvents=void 0===a.allowSynchronousEvents||a.allowSynchronousEvents,this._binaryType=a.binaryType||f[0],this._extensions=a.extensions||{},this._isServer=!!a.isServer,this._maxBufferedChunks=0|a.maxBufferedChunks,this._maxFragments=0|a.maxFragments,this._maxPayload=0|a.maxPayload,this._skipUTF8Validation=!!a.skipUTF8Validation,this[i]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(a,b,c){return 8===this._opcode&&0==this._state?c():this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks?void c(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS")):void(this._bufferedBytes+=a.length,this._buffers.push(a),this.startLoop(c))}consume(a){if(this._bufferedBytes-=a,a===this._buffers[0].length)return this._buffers.shift();if(a<this._buffers[0].length){let b=this._buffers[0];return this._buffers[0]=new o(b.buffer,b.byteOffset+a,b.length-a),new o(b.buffer,b.byteOffset,a)}let b=Buffer.allocUnsafe(a);do{let c=this._buffers[0],d=b.length-a;a>=c.length?b.set(this._buffers.shift(),d):(b.set(new Uint8Array(c.buffer,c.byteOffset,a),d),this._buffers[0]=new o(c.buffer,c.byteOffset+a,c.length-a)),a-=c.length}while(a>0);return b}startLoop(a){this._loop=!0;do switch(this._state){case 0:this.getInfo(a);break;case 1:this.getPayloadLength16(a);break;case 2:this.getPayloadLength64(a);break;case 3:this.getMask();break;case 4:this.getData(a);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||a()}getInfo(a){if(this._bufferedBytes<2){this._loop=!1;return}let b=this.consume(2);if((48&b[0])!=0)return void a(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));let c=(64&b[0])==64;if(c&&!this._extensions[e.extensionName])return void a(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._fin=(128&b[0])==128,this._opcode=15&b[0],this._payloadLength=127&b[1],0===this._opcode){if(c)return void a(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void a(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void a(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=c}else{if(!(this._opcode>7)||!(this._opcode<11))return void a(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void a(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(c)return void a(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void a(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=(128&b[1])==128,this._isServer){if(!this._masked)return void a(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void a(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(a)}getPayloadLength16(a){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(a)}getPayloadLength64(a){if(this._bufferedBytes<8){this._loop=!1;return}let b=this.consume(8),c=b.readUInt32BE(0);c>2097151?a(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=0x100000000*c+b.readUInt32BE(4),this.haveLength(a))}haveLength(a){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?a(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(a){let b=g;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}b=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!=0&&l(b,this._mask)}if(this._opcode>7)return void this.controlMessage(b,a);if(this._maxFragments>0&&++this._numFragments>this._maxFragments)return void a(this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));if(this._compressed){this._state=5,this.decompress(b,a);return}b.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(b)),this.dataMessage(a)}decompress(a,b){this._extensions[e.extensionName].decompress(a,this._fin,(a,c)=>{if(a)return b(a);if(c.length){if(this._messageLength+=c.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return void b(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(c)}this.dataMessage(b),0===this._state&&this.startLoop(b)})}dataMessage(a){if(!this._fin){this._state=0;return}let b=this._messageLength,c=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],2===this._opcode){let d;d="nodebuffer"===this._binaryType?j(c,b):"arraybuffer"===this._binaryType?k(j(c,b)):"blob"===this._binaryType?new Blob(c):c,this._allowSynchronousEvents?(this.emit("message",d,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",d,!0),this._state=0,this.startLoop(a)}))}else{let d=j(c,b);if(!this._skipUTF8Validation&&!n(d))return void a(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));5===this._state||this._allowSynchronousEvents?(this.emit("message",d,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",d,!1),this._state=0,this.startLoop(a)}))}}controlMessage(a,b){if(8===this._opcode){if(0===a.length)this._loop=!1,this.emit("conclude",1005,g),this.end();else{let c=a.readUInt16BE(0);if(!m(c))return void b(this.createError(RangeError,`invalid status code ${c}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE"));let d=new o(a.buffer,a.byteOffset+2,a.length-2);if(!this._skipUTF8Validation&&!n(d))return void b(this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8"));this._loop=!1,this.emit("conclude",c,d),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",a),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",a),this._state=0,this.startLoop(b)}))}createError(a,b,c,d,e){this._loop=!1,this._errored=!0;let f=new a(c?`Invalid WebSocket frame: ${b}`:b);return Error.captureStackTrace(f,this.createError),f.code=e,f[h]=d,f}}a.exports=p},7586:a=>{"use strict";let b=Symbol("kDone"),c=Symbol("kRun");class d{constructor(a){this[b]=()=>{this.pending--,this[c]()},this.concurrency=a||1/0,this.jobs=[],this.pending=0}add(a){this.jobs.push(a),this[c]()}[c](){if(this.pending!==this.concurrency&&this.jobs.length){let a=this.jobs.shift();this.pending++,a(this[b])}}}a.exports=d},8663:(a,b,c)=>{"use strict";c.d(b,{H:()=>j});var d=c(36153),e=c(3329),f=c(10658),g=c(69375);let h=d.Ik({source:e.R}).strict(),i=d.Ik({}).strict(),j=Object.freeze({subscribe:(0,g.Vc)({path:"pi/ui/subscribe",inputSchema:h,outputSchema:f.P}),unsubscribe:(0,g.Vc)({path:"pi/ui/unsubscribe",inputSchema:h,outputSchema:i}),respond:(0,g.Vc)({path:"pi/ui/respond",inputSchema:h.extend({response:f.YB}).strict(),outputSchema:i}),event:(0,g._G)({path:"pi/ui/event",bodySchema:h.extend({event:f.Z$}).strict()})})},9763:(a,b,c)=>{"use strict";c.a(a,async(a,b)=>{try{var d=c(17691);c(77598),c(73024),c(76760);var e=c(36153),f=a([d]);d=(f.then?(await f)():f)[0];let g=e.Ik({loggedInAt:e.ai().int().nonnegative()});e.YO(g),b()}catch(a){b(a)}})},16050:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{K:()=>j});var e=c(45407),f=c(55490),g=c(25406),h=c(33448),i=a([e,f,g,h]);function j(){if(!globalThis.__piDeskTaskCenterRuntime){let a=(0,g.getL2WorkSessionManage)();globalThis.__piDeskTaskCenterRuntime=new e.rt(async b=>{let c=await a.getWorkSession(b.workId);if(!c||c.sessionId!==b.sessionId||c.branchId!==b.branchId)throw new f.dM(b);return(0,h.ls)(b.sessionId)})}return globalThis.__piDeskTaskCenterRuntime}[e,f,g,h]=i.then?(await i)():i,d()}catch(a){d(a)}})},18331:(a,b,c)=>{"use strict";c.d(b,{bm:()=>k});var d=c(36153),e=c(69375),f=c(72497);d.Yj().min(32).max(128).regex(/^[A-Za-z0-9_-]+$/);let g="/api/plugins/host-runtime/v1";Object.freeze({imports:Object.freeze({react:`${g}/base.js`,"react/jsx-runtime":`${g}/base.js`,"react/jsx-dev-runtime":`${g}/base.js`,"react-dom":`${g}/base.js`,"react-dom/client":`${g}/base.js`,"@jetcrab/pi-desk-sdk/react/base":`${g}/base.js`,"@jetcrab/pi-desk-sdk/react/markdown":`${g}/markdown.js`})}),d.eu("v1");let h=d.Ik({pluginName:f.tv,url:d.Yj().regex(/^\/api\/plugins\/browser-resources\/[A-Za-z0-9_-]{32,128}\/entry\.js$/,"Browser Entry URL 无效")}).strict(),i=d.Ik({}).strict(),j=d.Ik({entries:d.YO(h)}).strict(),k=Object.freeze({list:(0,e.Vc)({path:"plugins/browser-entries/list",inputSchema:i,outputSchema:j})})},18611:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{T:()=>j});var e=c(37497),f=c(55490),g=c(9570),h=a([f,g]);function i(a,b){return a.workId===b.workId&&a.sessionId===b.sessionId&&a.branchId===b.branchId}[f,g]=h.then?(await h)():h;class j{constructor(a,b){this.connection=a,this.manage=b,this.subscriptionsByWorkId=new Map,this.operationTail=Promise.resolve(),this.disposed=!1,this.routes=Object.freeze([{path:e.P6.subscribe.path,access:"ready",handle:a=>this.enqueueSubscribe(a)},{path:e.P6.send.path,access:"ready",handle:a=>this.send(a)},{path:e.P6.interrupt.path,access:"ready",handle:a=>this.interrupt(a)},{path:e.P6.compact.path,access:"ready",handle:a=>this.compact(a)},{path:e.P6.reload.path,access:"ready",handle:a=>this.reload(a)},{path:e.P6.presentationSet.path,access:"ready",handle:a=>this.setPresentation(a)},{path:e.P6.queueRestore.path,access:"ready",handle:a=>this.restoreQueue(a)},{path:e.P6.modelSet.path,access:"ready",handle:a=>this.setModel(a)},{path:e.P6.capabilityModeSet.path,access:"ready",handle:a=>this.setCapabilityMode(a)}]),this.unsubscribeMessages=this.manage.subscribeMessageEvents(a=>this.handleRuntimeEvent(a))}dispose(){this.disposed||(this.disposed=!0,this.unsubscribeMessages(),this.subscriptionsByWorkId.clear())}enqueueSubscribe(a){let b=()=>this.subscribe(a),c=this.operationTail.then(b,b);return this.operationTail=c.then(()=>void 0,()=>void 0),c}async subscribe(a){let b,c=e.P6.subscribe,d=c.inputSchema.safeParse(a.body);if(!d.success)return void this.connection.sendError(c.path,a.head.requestId,400,"聊天订阅参数无效",{key:"errors:chatSubscribeInvalid"});let g=new Map;for(let a of d.data.subscriptions)g.set(a.source.workId,this.subscriptionsByWorkId.get(a.source.workId)),this.subscriptionsByWorkId.set(a.source.workId,{source:a.source,status:"syncing",queuedEvents:[],overflowed:!1});try{b=await this.manage.prepareChatSourceSyncs(d.data.subscriptions)}catch(h){this.restoreSubscriptions(g);let b=h instanceof f.dM;b||console.error("[Pi Desk][ChatSocket] 聊天 Source 订阅初始化失败",{clientId:this.connection.clientId,connectionId:this.connection.connectionId,requestId:a.head.requestId,sources:d.data.subscriptions.map(a=>a.source),errorName:h instanceof Error?h.name:"UnknownError",errorMessage:h instanceof Error?h.message:String(h),errorStack:h instanceof Error?h.stack:void 0});let e=h instanceof Error?h.message.slice(0,32e3):null;this.connection.sendError(c.path,a.head.requestId,b?409:500,b?"聊天订阅绑定已过期":e||"聊天订阅初始化失败",b?{key:"errors:chatSubscribeExpired"}:e?void 0:{key:"errors:chatSubscribeFailed"});return}if(!this.disposed&&this.connection.isCurrent()){this.connection.sendSuccess(c,a.head.requestId,{});try{for(let a of b)await this.finishSync(a.source,a.event,a.watermark);console.info("[Pi Desk][ChatSocket] 聊天 Source 订阅完成",{clientId:this.connection.clientId,connectionId:this.connection.connectionId,sourceCount:b.length})}catch(a){console.error("[Pi Desk][ChatSocket] 聊天 Source 同步失败",{clientId:this.connection.clientId,connectionId:this.connection.connectionId,errorName:a instanceof Error?a.name:"UnknownError"}),this.connection.close(1011,"聊天消息同步失败")}}}async send(a){let b=e.P6.send,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"聊天发送参数无效",{key:"errors:chatSendInvalid"});if(Buffer.byteLength(JSON.stringify({head:a.head,body:c.data}),"utf8")>g.lr)return void this.connection.sendError(b.path,a.head.requestId,413,"聊天发送内容超过 31MB",{key:"errors:chatSendTooLarge"});try{console.info("[Pi Desk][ChatSocket] 聊天发送开始",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId,sessionId:c.data.source.sessionId,branchId:c.data.source.branchId,mode:c.data.mode});let d=await this.manage.sendChat(c.data);console.info("[Pi Desk][ChatSocket] 聊天发送已接纳",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId,tempId:d.tempId}),this.connection.sendSuccess(b,a.head.requestId,d)}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"发送聊天消息失败")}}async interrupt(a){let b=e.P6.interrupt,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"聊天打断参数无效",{key:"errors:chatInterruptInvalid"});try{await this.manage.interruptChat(c.data.source),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"打断当前响应失败")}}async compact(a){let b=e.P6.compact,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"上下文压缩参数无效",{key:"errors:chatCompactInvalid"});try{console.info("[Pi Desk][ChatSocket] 手动上下文压缩开始",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId,sessionId:c.data.source.sessionId,branchId:c.data.source.branchId}),await this.manage.compactChat(c.data.source),console.info("[Pi Desk][ChatSocket] 手动上下文压缩完成",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId}),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"压缩上下文失败")}}async reload(a){let b=e.P6.reload,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi 配置重载参数无效",{key:"errors:chatReloadInvalid"});try{console.info("[Pi Desk][ChatSocket] Pi 配置重载开始",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId,sessionId:c.data.source.sessionId,branchId:c.data.source.branchId}),await this.manage.reloadChat(c.data.source,c.data.mode),console.info("[Pi Desk][ChatSocket] Pi 配置重载完成",{clientId:this.connection.clientId,requestId:a.head.requestId,workId:c.data.source.workId}),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"重载 Pi 配置失败")}}async setPresentation(a){let b=e.P6.presentationSet,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"消息展示模式参数无效");try{await this.manage.setChatPresentation(c.data.source,c.data.mode),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"切换消息展示失败")}}async restoreQueue(a){let b=e.P6.queueRestore,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"恢复队列参数无效",{key:"errors:chatRestoreInvalid"});try{let d=await this.manage.restoreChatQueue(c.data.source),e=Buffer.byteLength(JSON.stringify({head:{op:"resp",path:b.path,requestId:a.head.requestId},body:{code:0,msg:"",data:d}}),"utf8");if(e>g.lr){console.error("[Pi Desk][ChatSocket] 队列恢复响应突破应用上限",{workId:c.data.source.workId,responseBytes:e}),this.connection.sendError(b.path,a.head.requestId,500,"恢复内容超过传输上限",{key:"errors:chatRestoreTooLarge"});return}this.connection.sendSuccess(b,a.head.requestId,d)}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"恢复全部排队消息失败")}}async setModel(a){let b=e.P6.modelSet,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"模型设置参数无效",{key:"errors:chatModelInvalid"});try{await this.manage.setChatModel(c.data),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"设置模型失败")}}async setCapabilityMode(a){let b=e.P6.capabilityModeSet,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"能力模式参数无效",{key:"errors:chatModeInvalid"});try{await this.manage.setChatCapabilityMode(c.data),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendCommandError(b.path,a.head.requestId,c,"切换能力模式失败")}}sendCommandError(a,b,c,d){if(c instanceof f.dM||c instanceof Error&&"L2ChatSourceBindingError"===c.name)return void this.connection.sendError(a,b,409,"聊天 Source 已过期",{key:"errors:sourceExpired"});if(c instanceof f.nJ||c instanceof Error&&"L2ChatLifecycleBlockedError"===c.name)return void this.connection.sendError(a,b,409,"工作会话正在替换或切换分支",{key:"errors:chatSourceBusy"});let e=c instanceof Error&&c.message?c.message:d;console.warn("[Pi Desk][ChatSocket] 聊天命令执行失败",{path:a,errorName:c instanceof Error?c.name:"UnknownError",message:e}),this.connection.sendError(a,b,400,e)}async finishSync(a,b,c){let d=b,f=c;for(;;){let b=this.subscriptionsByWorkId.get(a.workId);if(!b||!i(b.source,a))return;if(b.overflowed){b.overflowed=!1,b.queuedEvents=[];let[c]=await this.manage.prepareChatSourceSyncs([{source:a,cursor:null}]);if(!c)return;d=c.event,f=c.watermark;continue}for(this.connection.sendPush(e.P6.sourceEvent,{source:a,event:d});;){let c=b.queuedEvents.filter(a=>a.version>f);for(let d of(b.queuedEvents=[],c))this.connection.sendPush(e.P6.sourceEvent,{source:a,event:d.event}),f=d.version;if(b.overflowed)break;if(!(b.queuedEvents.length>0)){b.status="ready";return}}}}handleRuntimeEvent(a){if(this.disposed||!this.connection.isCurrent())return;let b=this.subscriptionsByWorkId.get(a.source.workId);if(b&&i(b.source,a.source)){if("source_invalidated"===a.type)return void this.subscriptionsByWorkId.delete(a.source.workId);if("syncing"===b.status){if(b.overflowed)return;if(b.queuedEvents.length>=128){b.queuedEvents=[],b.overflowed=!0;return}b.queuedEvents.push({version:a.version,event:a.event});return}this.connection.sendPush(e.P6.sourceEvent,{source:a.source,event:a.event})}}restoreSubscriptions(a){for(let[b,c]of a)c?this.subscriptionsByWorkId.set(b,c):this.subscriptionsByWorkId.delete(b)}}d()}catch(a){d(a)}})},18753:(a,b,c)=>{"use strict";let{tokenChars:d}=c(47591);function e(a,b,c){void 0===a[b]?a[b]=[c]:a[b].push(c)}a.exports={format:function(a){return Object.keys(a).map(b=>{let c=a[b];return Array.isArray(c)||(c=[c]),c.map(a=>[b].concat(Object.keys(a).map(b=>{let c=a[b];return Array.isArray(c)||(c=[c]),c.map(a=>!0===a?b:`${b}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(a){let b,c,f=Object.create(null),g=Object.create(null),h=!1,i=!1,j=!1,k=-1,l=-1,m=-1,n=0;for(;n<a.length;n++)if(l=a.charCodeAt(n),void 0===b)if(-1===m&&1===d[l])-1===k&&(k=n);else if(0!==n&&(32===l||9===l))-1===m&&-1!==k&&(m=n);else if(59===l||44===l){if(-1===k)throw SyntaxError(`Unexpected character at index ${n}`);-1===m&&(m=n);let c=a.slice(k,m);44===l?(e(f,c,g),g=Object.create(null)):b=c,k=m=-1}else throw SyntaxError(`Unexpected character at index ${n}`);else if(void 0===c)if(-1===m&&1===d[l])-1===k&&(k=n);else if(32===l||9===l)-1===m&&-1!==k&&(m=n);else if(59===l||44===l){if(-1===k)throw SyntaxError(`Unexpected character at index ${n}`);-1===m&&(m=n),e(g,a.slice(k,m),!0),44===l&&(e(f,b,g),g=Object.create(null),b=void 0),k=m=-1}else if(61===l&&-1!==k&&-1===m)c=a.slice(k,n),k=m=-1;else throw SyntaxError(`Unexpected character at index ${n}`);else if(i){if(1!==d[l])throw SyntaxError(`Unexpected character at index ${n}`);-1===k?k=n:h||(h=!0),i=!1}else if(j)if(1===d[l])-1===k&&(k=n);else if(34===l&&-1!==k)j=!1,m=n;else if(92===l)i=!0;else throw SyntaxError(`Unexpected character at index ${n}`);else if(34===l&&61===a.charCodeAt(n-1))j=!0;else if(-1===m&&1===d[l])-1===k&&(k=n);else if(-1!==k&&(32===l||9===l))-1===m&&(m=n);else if(59===l||44===l){if(-1===k)throw SyntaxError(`Unexpected character at index ${n}`);-1===m&&(m=n);let d=a.slice(k,m);h&&(d=d.replace(/\\/g,""),h=!1),e(g,c,d),44===l&&(e(f,b,g),g=Object.create(null),b=void 0),c=void 0,k=m=-1}else throw SyntaxError(`Unexpected character at index ${n}`);if(-1===k||j||32===l||9===l)throw SyntaxError("Unexpected end of input");-1===m&&(m=n);let o=a.slice(k,m);return void 0===b?e(f,o,g):(void 0===c?e(g,o,!0):h?e(g,c,o.replace(/\\/g,"")):e(g,c,o),e(f,b,g)),f}}},24202:(a,b,c)=>{"use strict";c.d(b,{dZ:()=>f});var d=c(44429),e=c(87048);function f(a,b){if("snapshot"===b.type){var c;return c=b.snapshot,a.taskId!==c.taskId||a.body?.kind!=="conversation"||c.body?.kind!=="conversation"?c:d.ui.parse({...c,body:{kind:"conversation",truncated:c.body.truncated,...(0,e.zR)(a.body,c.body.messages,c.body.temporaryMessages)}})}if("unavailable"===b.type)return null;if("text_append"===b.type){if(a.body?.kind!=="text")throw Error("Text append requires a text task detail snapshot");return{...a,body:{...a.body,text:a.body.text+b.text}}}if(a.body?.kind!=="conversation")throw Error("Conversation event requires a conversation task detail snapshot");return{...a,body:{...(0,e.FR)(a.body,b.event),kind:"conversation",truncated:a.body.truncated}}}},26272:(a,b,c)=>{"use strict";c.d(b,{V:()=>g});var d=c(77598),e=c(69375);c(37234),c(18753),c(95374),c(73),c(58773),c(74972);var f=c(42027);c(89373);class g{constructor(a,b){this.clientId=a,this.socket=b,this.connectionId=(0,d.randomUUID)(),this.inFlightRequestIds=new Set,this.requestHandler=null,this.closeListener=null,this.heartbeat=null,this.alive=!0,this.current=!0,this.started=!1,this.disposed=!1,this.handleHeartbeat=()=>{this.alive?(this.alive=!1,this.socket.ping()):this.terminate()},this.handlePong=()=>{this.alive=!0},this.handleMessage=(a,b)=>{let c;if(!this.current)return;if(b)return void this.socket.close(1003,"仅支持文本 JSON 消息");try{c=JSON.parse(Array.isArray(a)?Buffer.concat(a).toString("utf8"):a instanceof ArrayBuffer?Buffer.from(a).toString("utf8"):a.toString("utf8"))}catch{this.socket.close(1007,"JSON 格式无效");return}let d=e.tU.safeParse(c);if(!d.success)return void this.socket.close(1008,"消息信封或方向无效");let f=d.data.head.requestId;if(this.inFlightRequestIds.has(f))return void this.sendError(d.data.head.path,f,409,"requestId 正在处理中",{key:"common:duplicateRequest"});if(this.inFlightRequestIds.size>=32)return void this.sendError(d.data.head.path,f,429,"当前连接并发请求过多",{key:"common:tooManyRequests"});let g=this.requestHandler;g?(this.inFlightRequestIds.add(f),g(d.data).catch(a=>{console.error("[Pi Desk][AppSocketConnection] 请求处理失败",{clientId:this.clientId,connectionId:this.connectionId,path:d.data.head.path,errorName:a instanceof Error?a.name:"UnknownError"}),this.sendError(d.data.head.path,f,500,"服务端请求处理失败",{key:"common:serverRequestFailed"})}).finally(()=>{this.inFlightRequestIds.delete(f)})):this.sendError(d.data.head.path,f,503,"应用 WebSocket 尚未就绪",{key:"common:socketUnavailable"})},this.handleClose=(a,b)=>{let c={code:a,reason:b.toString("utf8")},d=this.closeListener;this.dispose();try{d?.(c)}catch(a){console.error("[Pi Desk][AppSocketConnection] 关闭监听器执行失败",{clientId:this.clientId,connectionId:this.connectionId,errorName:a instanceof Error?a.name:"UnknownError"})}finally{this.resolveClosed(c)}},this.handleError=a=>{console.error("[Pi Desk][AppSocketConnection] 连接错误",{clientId:this.clientId,connectionId:this.connectionId,errorName:a.name,message:a.message})},this.closedPromise=new Promise(a=>{this.resolveClosed=a})}start(a,b){if(this.started)throw Error("AppSocket connection has already started");this.started=!0,this.requestHandler=a,this.closeListener=b,this.heartbeat=setInterval(this.handleHeartbeat,3e4),this.socket.on("pong",this.handlePong),this.socket.on("message",this.handleMessage),this.socket.on("close",this.handleClose),this.socket.on("error",this.handleError)}isCurrent(){return this.current&&!this.disposed}sendSuccess(a,b,c){this.sendJson(e.hE.parse({head:{op:"resp",path:a.path,requestId:b},body:{code:0,msg:"",data:a.outputSchema.parse(c)}}))}sendError(a,b,c,d,f){this.sendJson(e.hE.parse({head:{op:"resp",path:a,requestId:b},body:{code:c,msg:d,data:null,...f?{i18n:f}:{}}}))}sendPush(a,b){this.sendJson(e.Od.parse({head:{op:"push",path:a.path},body:a.bodySchema.parse(b)}))}supersede(){!this.disposed&&this.current&&(this.current=!1,this.socket.close(e.P9,"连接已被替换"))}close(a=1e3,b="连接已关闭"){if(!this.disposed){if(this.current=!1,this.socket.readyState===f.OPEN)return void this.socket.close(a,b);this.socket.readyState!==f.CLOSED&&this.socket.terminate()}}terminate(){this.disposed||(this.current=!1,this.socket.terminate())}waitForClose(){return this.closedPromise}sendJson(a){if(this.isCurrent()&&this.socket.readyState===f.OPEN){if(this.socket.bufferedAmount>0x2000000)return void this.terminate();try{this.socket.send(JSON.stringify(a))}catch{this.terminate()}}}dispose(){this.disposed||(this.disposed=!0,this.current=!1,this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.inFlightRequestIds.clear(),this.requestHandler=null,this.closeListener=null,this.socket.off("pong",this.handlePong),this.socket.off("message",this.handleMessage),this.socket.off("close",this.handleClose),this.socket.off("error",this.handleError))}}},28026:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{B4:()=>h,UM:()=>i});var e=c(72497),f=c(6108),g=a([f]);f=(g.then?(await g)():g)[0];class j{constructor(a=(0,f.hZ)()){this.runtime=a,this.disposed=!1}setState(a,b){this.ensureActive();let c=e.tv.parse(a),d=null===b?null:e.Dz.parse(b);if(null!==d&&Buffer.byteLength(JSON.stringify(d),"utf8")>65536)throw Error("Plugin global state exceeds 64KB");let f=this.runtime.readSnapshot().plugins[c];if(null===d){if(void 0===f)return}else if(void 0!==f&&JSON.stringify(f)===JSON.stringify(d))return;this.runtime.applyInternal({key:"plugins",update:{pluginName:c,state:null===d?null:structuredClone(d)}})}releasePlugin(a){this.disposed||this.setState(a,null)}dispose(){this.disposed=!0}ensureActive(){if(this.disposed)throw Error("App Plugin State Runtime has been disposed")}}function h(){return globalThis.__piDeskAppPluginStateRuntime||(globalThis.__piDeskAppPluginStateRuntime=new j),globalThis.__piDeskAppPluginStateRuntime}function i(){let a=globalThis.__piDeskAppPluginStateRuntime;globalThis.__piDeskAppPluginStateRuntime=void 0,a?.dispose()}d()}catch(a){d(a)}})},28363:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{Y:()=>h});var e=c(36623),f=c(50906),g=a([f]);f=(g.then?(await g)():g)[0];class h{constructor(a){this.connection=a,this.disposed=!1,this.auth=new f.c(a=>{!this.disposed&&this.connection.isCurrent()&&this.connection.sendPush(e.c.state,a)}),this.routes=Object.freeze([this.route(e.c.list,async()=>({providers:await this.auth.list()})),this.route(e.c.start,async a=>(await this.auth.start(a.provider,a.loginId),{})),this.route(e.c.respond,a=>(this.auth.respond(a.loginId,a.promptId,a.value),{})),this.route(e.c.cancel,a=>(this.auth.cancel(a.loginId),{})),this.route(e.c.logout,async a=>(await this.auth.logout(a.provider),{}))])}dispose(){this.disposed||(this.disposed=!0,this.auth.dispose())}route(a,b){return{path:a.path,access:"ready",handle:async c=>{let d=a.inputSchema.safeParse(c.body);if(!d.success)return void this.connection.sendError(a.path,c.head.requestId,400,"账号操作参数无效");if(!this.disposed&&this.connection.isCurrent())try{let e=await b(d.data);!this.disposed&&this.connection.isCurrent()&&this.connection.sendSuccess(a,c.head.requestId,e)}catch(b){if(this.disposed||!this.connection.isCurrent())return;if(b instanceof f.m)return void this.connection.sendError(a.path,c.head.requestId,b.code,b.message);console.warn("[Pi Desk][ModelAuthSocket] 账号请求失败",{stage:a.path,errorName:b instanceof Error?b.name:"UnknownError"}),this.connection.sendError(a.path,c.head.requestId,500,"账号操作失败,请重试")}}}}}d()}catch(a){d(a)}})},30119:(a,b,c)=>{"use strict";c.d(b,{cx:()=>j});var d=c(36153),e=c(3329),f=c(69375),g=c(72497);let h=d.gM("scope",[d.Ik({scope:d.eu("global")}).strict(),d.Ik({scope:d.eu("session"),source:e.R}).strict()]),i=d.Ik({pluginName:g.tv,target:h,event:g.f7,data:g.Dz}).strict(),j=(0,f._G)({path:"plugins/push",bodySchema:i})},31442:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{L2AppRuntimeTargetNotFoundError:()=>i.fA,createL2AppNotificationPublisher:()=>l,createL2PluginAppRuntimeSink:()=>m,disposeL2AppRuntime:()=>n,getL2AppRuntime:()=>k});var e=c(13127),f=c(8438),g=c(5034),h=c(28026),i=c(6108),j=a([f,g,h,i]);function k(){let a=(0,i.hZ)();if(globalThis.__piDeskModeNamesBinding?.runtime!==a){globalThis.__piDeskModeNamesBinding?.dispose();let b=(0,f.O)(),c=()=>{a.applyInternal({key:"capabilityModes",update:(0,e.HE)(b.read())})};c(),globalThis.__piDeskModeNamesBinding={runtime:a,dispose:b.subscribe(c)}}return a}function l(){let a=(0,g.UM)().createPublisher();return{publish:b=>a.publish({...b,event:null}),update:(b,c)=>a.update(b,c),delete:b=>a.delete(b),dispose:()=>a.dispose()}}function m(){let a=(0,g.UM)(),b=(0,h.B4)();return{setState:(a,c)=>b.setState(a,c),publishNotification:(b,c)=>a.publishPlugin(b,c),updateNotification:(b,c,d)=>a.updatePlugin(b,c,d),deleteNotification:(b,c)=>a.deletePlugin(b,c),releasePlugin:c=>{a.releasePlugin(c),b.releasePlugin(c)}}}function n(){globalThis.__piDeskModeNamesBinding?.dispose(),globalThis.__piDeskModeNamesBinding=void 0,(0,g.HM)(),(0,h.UM)(),(0,i.s6)()}[f,g,h,i]=j.then?(await j)():j,d()}catch(a){d(a)}})},33495:(a,b,c)=>{"use strict";c.d(b,{rn:()=>m});var d=c(36153),e=c(3329),f=c(44429),g=c(69375);let h=d.Ik({source:e.R,taskId:f.mQ.nullable()}).strict(),i=d.Ik({snapshot:f.ui.nullable()}).strict(),j=d.Ik({source:e.R,taskId:f.mQ}).strict(),k=d.Ik({}).strict(),l=d.Ik({source:e.R,taskId:f.mQ,event:f.gm}).strict(),m=Object.freeze({detailWatch:(0,g.Vc)({path:"task-center/detail-watch",inputSchema:h,outputSchema:i}),interrupt:(0,g.Vc)({path:"task-center/interrupt",inputSchema:j,outputSchema:k}),detailEvent:(0,g._G)({path:"task-center/detail-event",bodySchema:l})})},36388:(a,b,c)=>{"use strict";let{kForOnEventAttribute:d,kListener:e}=c(46929),f=Symbol("kCode"),g=Symbol("kData"),h=Symbol("kError"),i=Symbol("kMessage"),j=Symbol("kReason"),k=Symbol("kTarget"),l=Symbol("kType"),m=Symbol("kWasClean");class n{constructor(a){this[k]=null,this[l]=a}get target(){return this[k]}get type(){return this[l]}}Object.defineProperty(n.prototype,"target",{enumerable:!0}),Object.defineProperty(n.prototype,"type",{enumerable:!0});class o extends n{constructor(a,b={}){super(a),this[f]=void 0===b.code?0:b.code,this[j]=void 0===b.reason?"":b.reason,this[m]=void 0!==b.wasClean&&b.wasClean}get code(){return this[f]}get reason(){return this[j]}get wasClean(){return this[m]}}Object.defineProperty(o.prototype,"code",{enumerable:!0}),Object.defineProperty(o.prototype,"reason",{enumerable:!0}),Object.defineProperty(o.prototype,"wasClean",{enumerable:!0});class p extends n{constructor(a,b={}){super(a),this[h]=void 0===b.error?null:b.error,this[i]=void 0===b.message?"":b.message}get error(){return this[h]}get message(){return this[i]}}Object.defineProperty(p.prototype,"error",{enumerable:!0}),Object.defineProperty(p.prototype,"message",{enumerable:!0});class q extends n{constructor(a,b={}){super(a),this[g]=void 0===b.data?null:b.data}get data(){return this[g]}}function r(a,b,c){"object"==typeof a&&a.handleEvent?a.handleEvent.call(a,c):a.call(b,c)}Object.defineProperty(q.prototype,"data",{enumerable:!0}),a.exports={CloseEvent:o,ErrorEvent:p,Event:n,EventTarget:{addEventListener(a,b,c={}){let f;for(let f of this.listeners(a))if(!c[d]&&f[e]===b&&!f[d])return;if("message"===a)f=function(a,c){let d=new q("message",{data:c?a:a.toString()});d[k]=this,r(b,this,d)};else if("close"===a)f=function(a,c){let d=new o("close",{code:a,reason:c.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});d[k]=this,r(b,this,d)};else if("error"===a)f=function(a){let c=new p("error",{error:a,message:a.message});c[k]=this,r(b,this,c)};else{if("open"!==a)return;f=function(){let a=new n("open");a[k]=this,r(b,this,a)}}f[d]=!!c[d],f[e]=b,c.once?this.once(a,f):this.on(a,f)},removeEventListener(a,b){for(let c of this.listeners(a))if(c[e]===b&&!c[d]){this.removeListener(a,c);break}}},MessageEvent:q}},36623:(a,b,c)=>{"use strict";c.d(b,{c:()=>n});var d=c(36153),e=c(69375);let f=d.Ik({}).strict(),g=d.Yj().trim().min(1).max(128),h=d.Yj().max(32768),i=d.Ik({url:h,label:h.optional()}).strict(),j=d.Ik({provider:g,name:h,loggedIn:d.zM(),conflict:d.Yj().nullable()}).strict(),k=d.Ik({id:d.Yj().uuid(),type:d.k5(["text","secret","select","manual_code"]),message:h,placeholder:h.optional(),options:d.YO(d.Ik({id:h,label:h,description:h.optional()}).strict()).optional()}).strict(),l=d.gM("type",[d.Ik({type:d.eu("auth_url"),url:h,instructions:h.optional()}).strict(),d.Ik({type:d.eu("device_code"),userCode:h,verificationUri:h}).strict(),d.Ik({type:d.eu("info"),message:h,links:d.YO(i).optional()}).strict(),d.Ik({type:d.eu("progress"),message:h}).strict()]),m=d.Ik({loginId:d.Yj().uuid(),provider:g,status:d.k5(["running","completed","cancelled","error"]),notice:l.nullable(),prompt:k.nullable(),message:d.Yj().nullable()}).strict(),n=Object.freeze({list:(0,e.Vc)({path:"model-auth/list",inputSchema:f,outputSchema:d.Ik({providers:d.YO(j)}).strict()}),start:(0,e.Vc)({path:"model-auth/start",inputSchema:d.Ik({loginId:d.Yj().uuid(),provider:g}).strict(),outputSchema:f}),respond:(0,e.Vc)({path:"model-auth/respond",inputSchema:d.Ik({loginId:d.Yj().uuid(),promptId:d.Yj().uuid(),value:h}).strict(),outputSchema:f}),cancel:(0,e.Vc)({path:"model-auth/cancel",inputSchema:d.Ik({loginId:d.Yj().uuid()}).strict(),outputSchema:f}),logout:(0,e.Vc)({path:"model-auth/logout",inputSchema:d.Ik({provider:g}).strict(),outputSchema:f}),state:(0,e._G)({path:"model-auth/state",bodySchema:m})})},37234:(a,b,c)=>{"use strict";c(42027);let{Duplex:d}=c(27910);function e(a){a.emit("close")}function f(){!this.destroyed&&this._writableState.finished&&this.destroy()}function g(a){this.removeListener("error",g),this.destroy(),0===this.listenerCount("error")&&this.emit("error",a)}a.exports=function(a,b){let c=!0,h=new d({...b,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return a.on("message",function(b,c){let d=!c&&h._readableState.objectMode?b.toString():b;h.push(d)||a.pause()}),a.once("error",function(a){h.destroyed||(c=!1,h.destroy(a))}),a.once("close",function(){h.destroyed||h.push(null)}),h._destroy=function(b,d){if(a.readyState===a.CLOSED){d(b),process.nextTick(e,h);return}let f=!1;a.once("error",function(a){f=!0,d(a)}),a.once("close",function(){f||d(b),process.nextTick(e,h)}),c&&a.terminate()},h._final=function(b){a.readyState===a.CONNECTING?a.once("open",function(){h._final(b)}):null!==a._socket&&(a._socket._writableState.finished?(b(),h._readableState.endEmitted&&h.destroy()):(a._socket.once("finish",function(){b()}),a.close()))},h._read=function(){a.isPaused&&a.resume()},h._write=function(b,c,d){a.readyState===a.CONNECTING?a.once("open",function(){h._write(b,c,d)}):a.send(b,d)},h.on("end",f),h.on("error",g),h}},37497:(a,b,c)=>{"use strict";c.d(b,{P6:()=>K});var d=c(36153),e=c(62695),f=c(75278),g=c(69375);let h=d.Ik({source:e.Pi,cursor:e.UR}).strict(),i=d.Ik({subscriptions:d.YO(h).min(1)}).strict().superRefine((a,b)=>{let c=new Set;for(let[d,e]of a.subscriptions.entries())c.has(e.source.workId)&&b.addIssue({code:"custom",message:"subscriptions cannot contain duplicate workId values",path:["subscriptions",d,"source","workId"]}),c.add(e.source.workId)}),j=d.Ik({}).strict(),k=d.YO(e.wR).superRefine((a,b)=>{let c=new Set;for(let[d,e]of a.entries())d>0&&e.location.index!==a[d-1].location.index+1&&b.addIssue({code:"custom",message:"chat sync message indexes must be continuous",path:[d,"location","index"]}),c.has(e.location.entryId)&&b.addIssue({code:"custom",message:"chat sync entryId values must be unique",path:[d,"location","entryId"]}),c.add(e.location.entryId)}),l=d.Ik({type:d.eu("session_sync"),mode:d.eu("full"),baseCursor:d.ch(),messages:k,temporaryMessages:d.YO(e.yI),runtime:e.wf}).strict().superRefine((a,b)=>{a.messages[0]&&0!==a.messages[0].location.index&&b.addIssue({code:"custom",message:"full sync must start at index 0",path:["messages",0,"location","index"]})}),m=d.Ik({type:d.eu("session_sync"),mode:d.eu("incremental"),baseCursor:e.DK,messages:k,temporaryMessages:d.YO(e.yI),runtime:e.wf}).strict().superRefine((a,b)=>{let c=a.messages[0];c&&c.location.index!==a.baseCursor.index+1&&b.addIssue({code:"custom",message:"incremental sync must start after baseCursor",path:["messages",0,"location","index"]})}),n=d.KC([l,m]),o=f.hS,p=f.ef,q=f.gK,r=f.PS,s=d.Ik({type:d.eu("runtime_update"),runtime:e.wf}).strict(),t=d.KC([n,o,p,q,r,s]),u=d.Ik({source:e.Pi,event:t}).strict(),v=d.k5(["auto","follow_up"]),w=d.Ik({source:e.Pi,mode:v,text:d.Yj(),images:d.YO(e.xh).max(10)}).strict().refine(a=>a.text.trim().length>0||a.images.length>0,{message:"chat input requires text or images"}),x=d.Ik({tempId:e.R3.shape.tempId}).strict(),y=d.Ik({source:e.Pi}).strict(),z=d.Ik({}).strict(),A=y.extend({mode:e.TV.optional()}).strict(),B=y.extend({mode:e.TV}).strict(),C=d.Ik({}).strict(),D=d.Ik({}).strict(),E=d.Ik({text:d.Yj(),images:d.YO(e.xh)}).strict(),F=d.Ik({source:e.Pi,model:e.w$}).strict(),G=d.Ik({}).strict(),H=d.Ik({source:e.Pi,capabilityMode:e.wf.shape.capabilityMode}).strict(),I=d.Ik({}).strict();d.k5(["chat/subscribe","chat/send","chat/interrupt","chat/reload","chat/presentation-set","chat/compact","chat/queue-restore","chat/model-set","chat/capability-mode-set"]);let J=d.eu("chat/source-event"),K=Object.freeze({subscribe:(0,g.Vc)({path:"chat/subscribe",inputSchema:i,outputSchema:j,timeoutMs:125e3}),send:(0,g.Vc)({path:"chat/send",inputSchema:w,outputSchema:x,timeoutMs:12e4}),interrupt:(0,g.Vc)({path:"chat/interrupt",inputSchema:y,outputSchema:z}),reload:(0,g.Vc)({path:"chat/reload",inputSchema:A,outputSchema:C,timeoutMs:125e3}),presentationSet:(0,g.Vc)({path:"chat/presentation-set",inputSchema:B,outputSchema:C}),compact:(0,g.Vc)({path:"chat/compact",inputSchema:y,outputSchema:D,timeoutMs:6e5}),queueRestore:(0,g.Vc)({path:"chat/queue-restore",inputSchema:y,outputSchema:E}),modelSet:(0,g.Vc)({path:"chat/model-set",inputSchema:F,outputSchema:G}),capabilityModeSet:(0,g.Vc)({path:"chat/capability-mode-set",inputSchema:H,outputSchema:I}),sourceEvent:(0,g._G)({path:J.value,bodySchema:u})})},37721:(a,b,c)=>{},42027:(a,b,c)=>{"use strict";let d=c(94735),e=c(55591),f=c(81630),g=c(91645),h=c(34631),{randomBytes:i,createHash:j}=c(55511),{Duplex:k,Readable:l}=c(27910),{URL:m}=c(79551),n=c(95374),o=c(73),p=c(58773),{isBlob:q}=c(47591),{BINARY_TYPES:r,CLOSE_TIMEOUT:s,EMPTY_BUFFER:t,GUID:u,kForOnEventAttribute:v,kListener:w,kStatusCode:x,kWebSocket:y,NOOP:z}=c(46929),{EventTarget:{addEventListener:A,removeEventListener:B}}=c(36388),{format:C,parse:D}=c(18753),{toBuffer:E}=c(52218),F=Symbol("kAborted"),G=[8,13],H=["CONNECTING","OPEN","CLOSING","CLOSED"],I=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class J extends d{constructor(a,b,c){super(),this._binaryType=r[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=t,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=J.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==a?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===b?b=[]:Array.isArray(b)||("object"==typeof b&&null!==b?(c=b,b=[]):b=[b]),function a(b,c,d,g){let h,k,l,o,p={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:s,protocolVersion:G[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...g,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(b._autoPong=p.autoPong,b._closeTimeout=p.closeTimeout,!G.includes(p.protocolVersion))throw RangeError(`Unsupported protocol version: ${p.protocolVersion} (supported versions: ${G.join(", ")})`);if(c instanceof m)h=c;else try{h=new m(c)}catch{throw SyntaxError(`Invalid URL: ${c}`)}"http:"===h.protocol?h.protocol="ws:":"https:"===h.protocol&&(h.protocol="wss:"),b._url=h.href;let q="wss:"===h.protocol,r="ws+unix:"===h.protocol;if("ws:"===h.protocol||q||r?r&&!h.pathname?k="The URL's pathname is empty":h.hash&&(k="The URL contains a fragment identifier"):k='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',k){let a=SyntaxError(k);if(0!==b._redirects)return void K(b,a);throw a}let t=q?443:80,v=i(16).toString("base64"),w=q?e.request:f.request,x=new Set;if(p.createConnection=p.createConnection||(q?M:L),p.defaultPort=p.defaultPort||t,p.port=h.port||t,p.host=h.hostname.startsWith("[")?h.hostname.slice(1,-1):h.hostname,p.headers={...p.headers,"Sec-WebSocket-Version":p.protocolVersion,"Sec-WebSocket-Key":v,Connection:"Upgrade",Upgrade:"websocket"},p.path=h.pathname+h.search,p.timeout=p.handshakeTimeout,p.perMessageDeflate&&(l=new n({...p.perMessageDeflate,isServer:!1,maxPayload:p.maxPayload}),p.headers["Sec-WebSocket-Extensions"]=C({[n.extensionName]:l.offer()})),d.length){for(let a of d){if("string"!=typeof a||!I.test(a)||x.has(a))throw SyntaxError("An invalid or duplicated subprotocol was specified");x.add(a)}p.headers["Sec-WebSocket-Protocol"]=d.join(",")}if(p.origin&&(p.protocolVersion<13?p.headers["Sec-WebSocket-Origin"]=p.origin:p.headers.Origin=p.origin),(h.username||h.password)&&(p.auth=`${h.username}:${h.password}`),r){let a=p.path.split(":");p.socketPath=a[0],p.path=a[1]}if(p.followRedirects){if(0===b._redirects){b._originalIpc=r,b._originalSecure=q,b._originalHostOrSocketPath=r?p.socketPath:h.host;let a=g&&g.headers;if(g={...g,headers:{}},a)for(let[b,c]of Object.entries(a))g.headers[b.toLowerCase()]=c}else if(0===b.listenerCount("redirect")){let a=r?!!b._originalIpc&&p.socketPath===b._originalHostOrSocketPath:!b._originalIpc&&h.host===b._originalHostOrSocketPath;a&&(!b._originalSecure||q)||(delete p.headers.authorization,delete p.headers.cookie,a||delete p.headers.host,p.auth=void 0)}p.auth&&!g.headers.authorization&&(g.headers.authorization="Basic "+Buffer.from(p.auth).toString("base64")),o=b._req=w(p),b._redirects&&b.emit("redirect",b.url,o)}else o=b._req=w(p);p.timeout&&o.on("timeout",()=>{N(b,o,"Opening handshake has timed out")}),o.on("error",a=>{null===o||o[F]||(o=b._req=null,K(b,a))}),o.on("response",e=>{let f=e.headers.location,h=e.statusCode;if(f&&p.followRedirects&&h>=300&&h<400){let e;if(++b._redirects>p.maxRedirects)return void N(b,o,"Maximum redirects exceeded");o.abort();try{e=new m(f,c)}catch(a){K(b,SyntaxError(`Invalid URL: ${f}`));return}a(b,e,d,g)}else b.emit("unexpected-response",o,e)||N(b,o,`Unexpected server response: ${e.statusCode}`)}),o.on("upgrade",(a,c,d)=>{let e;if(b.emit("upgrade",a),b.readyState!==J.CONNECTING)return;o=b._req=null;let f=a.headers.upgrade;if(void 0===f||"websocket"!==f.toLowerCase())return void N(b,c,"Invalid Upgrade header");let g=j("sha1").update(v+u).digest("base64");if(a.headers["sec-websocket-accept"]!==g)return void N(b,c,"Invalid Sec-WebSocket-Accept header");let h=a.headers["sec-websocket-protocol"];if(void 0!==h?x.size?x.has(h)||(e="Server sent an invalid subprotocol"):e="Server sent a subprotocol but none was requested":x.size&&(e="Server sent no subprotocol"),e)return void N(b,c,e);h&&(b._protocol=h);let i=a.headers["sec-websocket-extensions"];if(void 0!==i){let a;if(!l)return void N(b,c,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");try{a=D(i)}catch(a){N(b,c,"Invalid Sec-WebSocket-Extensions header");return}let d=Object.keys(a);if(1!==d.length||d[0]!==n.extensionName)return void N(b,c,"Server indicated an extension that was not requested");try{l.accept(a[n.extensionName])}catch(a){N(b,c,"Invalid Sec-WebSocket-Extensions header");return}b._extensions[n.extensionName]=l}b.setSocket(c,d,{allowSynchronousEvents:p.allowSynchronousEvents,generateMask:p.generateMask,maxBufferedChunks:p.maxBufferedChunks,maxFragments:p.maxFragments,maxPayload:p.maxPayload,skipUTF8Validation:p.skipUTF8Validation})}),p.finishRequest?p.finishRequest(o,b):o.end()}(this,a,b,c)):(this._autoPong=c.autoPong,this._closeTimeout=c.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(a){r.includes(a)&&(this._binaryType=a,this._receiver&&(this._receiver._binaryType=a))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(a,b,c){let d=new o({allowSynchronousEvents:c.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:c.maxBufferedChunks,maxFragments:c.maxFragments,maxPayload:c.maxPayload,skipUTF8Validation:c.skipUTF8Validation}),e=new p(a,this._extensions,c.generateMask);this._receiver=d,this._sender=e,this._socket=a,d[y]=this,e[y]=this,a[y]=this,d.on("conclude",P),d.on("drain",Q),d.on("error",R),d.on("message",T),d.on("ping",U),d.on("pong",V),e.onerror=X,a.setTimeout&&a.setTimeout(0),a.setNoDelay&&a.setNoDelay(),b.length>0&&a.unshift(b),a.on("close",Z),a.on("data",$),a.on("end",_),a.on("error",aa),this._readyState=J.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=J.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[n.extensionName]&&this._extensions[n.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=J.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(a,b){if(this.readyState!==J.CLOSED){if(this.readyState===J.CONNECTING)return void N(this,this._req,"WebSocket was closed before the connection was established");if(this.readyState===J.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=J.CLOSING,this._sender.close(a,b,!this._isServer,a=>{!a&&(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Y(this)}}pause(){this.readyState!==J.CONNECTING&&this.readyState!==J.CLOSED&&(this._paused=!0,this._socket.pause())}ping(a,b,c){if(this.readyState===J.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof a?(c=a,a=b=void 0):"function"==typeof b&&(c=b,b=void 0),"number"==typeof a&&(a=a.toString()),this.readyState!==J.OPEN)?O(this,a,c):(void 0===b&&(b=!this._isServer),this._sender.ping(a||t,b,c))}pong(a,b,c){if(this.readyState===J.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");("function"==typeof a?(c=a,a=b=void 0):"function"==typeof b&&(c=b,b=void 0),"number"==typeof a&&(a=a.toString()),this.readyState!==J.OPEN)?O(this,a,c):(void 0===b&&(b=!this._isServer),this._sender.pong(a||t,b,c))}resume(){this.readyState!==J.CONNECTING&&this.readyState!==J.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(a,b,c){if(this.readyState===J.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof b&&(c=b,b={}),"number"==typeof a&&(a=a.toString()),this.readyState!==J.OPEN)return void O(this,a,c);let d={binary:"string"!=typeof a,mask:!this._isServer,compress:!0,fin:!0,...b};this._extensions[n.extensionName]||(d.compress=!1),this._sender.send(a||t,d,c)}terminate(){if(this.readyState!==J.CLOSED){if(this.readyState===J.CONNECTING)return void N(this,this._req,"WebSocket was closed before the connection was established");this._socket&&(this._readyState=J.CLOSING,this._socket.destroy())}}}function K(a,b){a._readyState=J.CLOSING,a._errorEmitted=!0,a.emit("error",b),a.emitClose()}function L(a){return a.path=a.socketPath,g.connect(a)}function M(a){return a.path=void 0,a.servername||""===a.servername||(a.servername=g.isIP(a.host)?"":a.host),h.connect(a)}function N(a,b,c){a._readyState=J.CLOSING;let d=Error(c);Error.captureStackTrace(d,N),b.setHeader?(b[F]=!0,b.abort(),b.socket&&!b.socket.destroyed&&b.socket.destroy(),process.nextTick(K,a,d)):(b.destroy(d),b.once("error",a.emit.bind(a,"error")),b.once("close",a.emitClose.bind(a)))}function O(a,b,c){if(b){let c=q(b)?b.size:E(b).length;a._socket?a._sender._bufferedBytes+=c:a._bufferedAmount+=c}if(c){let b=Error(`WebSocket is not open: readyState ${a.readyState} (${H[a.readyState]})`);process.nextTick(c,b)}}function P(a,b){let c=this[y];c._closeFrameReceived=!0,c._closeMessage=b,c._closeCode=a,void 0!==c._socket[y]&&(c._socket.removeListener("data",$),process.nextTick(W,c._socket),1005===a?c.close():c.close(a,b))}function Q(){let a=this[y];a.isPaused||a._socket.resume()}function R(a){let b=this[y];void 0!==b._socket[y]&&(b._socket.removeListener("data",$),process.nextTick(W,b._socket),b.close(a[x])),b._errorEmitted||(b._errorEmitted=!0,b.emit("error",a))}function S(){this[y].emitClose()}function T(a,b){this[y].emit("message",a,b)}function U(a){let b=this[y];b._autoPong&&b.pong(a,!this._isServer,z),b.emit("ping",a)}function V(a){this[y].emit("pong",a)}function W(a){a.resume()}function X(a){let b=this[y];b.readyState!==J.CLOSED&&(b.readyState===J.OPEN&&(b._readyState=J.CLOSING,Y(b)),this._socket.end(),b._errorEmitted||(b._errorEmitted=!0,b.emit("error",a)))}function Y(a){a._closeTimer=setTimeout(a._socket.destroy.bind(a._socket),a._closeTimeout)}function Z(){let a=this[y];if(this.removeListener("close",Z),this.removeListener("data",$),this.removeListener("end",_),a._readyState=J.CLOSING,!this._readableState.endEmitted&&!a._closeFrameReceived&&!a._receiver._writableState.errorEmitted&&0!==this._readableState.length){let b=this.read(this._readableState.length);a._receiver.write(b)}a._receiver.end(),this[y]=void 0,clearTimeout(a._closeTimer),a._receiver._writableState.finished||a._receiver._writableState.errorEmitted?a.emitClose():(a._receiver.on("error",S),a._receiver.on("finish",S))}function $(a){this[y]._receiver.write(a)||this.pause()}function _(){let a=this[y];a._readyState=J.CLOSING,a._receiver.end(),this.end()}function aa(){let a=this[y];this.removeListener("error",aa),this.on("error",z),a&&(a._readyState=J.CLOSING,this.destroy())}Object.defineProperty(J,"CONNECTING",{enumerable:!0,value:H.indexOf("CONNECTING")}),Object.defineProperty(J.prototype,"CONNECTING",{enumerable:!0,value:H.indexOf("CONNECTING")}),Object.defineProperty(J,"OPEN",{enumerable:!0,value:H.indexOf("OPEN")}),Object.defineProperty(J.prototype,"OPEN",{enumerable:!0,value:H.indexOf("OPEN")}),Object.defineProperty(J,"CLOSING",{enumerable:!0,value:H.indexOf("CLOSING")}),Object.defineProperty(J.prototype,"CLOSING",{enumerable:!0,value:H.indexOf("CLOSING")}),Object.defineProperty(J,"CLOSED",{enumerable:!0,value:H.indexOf("CLOSED")}),Object.defineProperty(J.prototype,"CLOSED",{enumerable:!0,value:H.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(a=>{Object.defineProperty(J.prototype,a,{enumerable:!0})}),["open","error","close","message"].forEach(a=>{Object.defineProperty(J.prototype,`on${a}`,{enumerable:!0,get(){for(let b of this.listeners(a))if(b[v])return b[w];return null},set(b){for(let b of this.listeners(a))if(b[v]){this.removeListener(a,b);break}"function"==typeof b&&this.addEventListener(a,b,{[v]:!0})}})}),J.prototype.addEventListener=A,J.prototype.removeEventListener=B,a.exports=J},43973:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{G:()=>i});var e=c(23349),f=c(71779),g=c(25406),h=a([g]);g=(h.then?(await h)():h)[0];class i{constructor(a,b,c){this.connection=a,this.manage=b,this.appRuntime=c,this.status="new",this.dirty=!1,this.disposed=!1,this.unsubscribeWorkSessions=null,this.unsubscribeAppRuntime=null,this.routes=Object.freeze([{path:e.kM.list.path,access:"bootstrap",handle:a=>this.initialize(a)},{path:e.kM.acknowledgeCompleted.path,access:"ready",handle:a=>this.acknowledgeCompleted(a)}])}isReady(){return"ready"===this.status&&!this.disposed}dispose(){this.disposed||(this.disposed=!0,this.status="new",this.unsubscribeWorkSessions?.(),this.unsubscribeWorkSessions=null,this.unsubscribeAppRuntime?.(),this.unsubscribeAppRuntime=null)}async initialize(a){let b=e.kM.list;if("initializing"===this.status)return void this.connection.sendError(b.path,a.head.requestId,409,"工作会话正在初始化",{key:"errors:sessionsInitializing"});if(!b.inputSchema.safeParse(a.body).success)return void this.connection.sendError(b.path,a.head.requestId,400,"工作会话初始化参数无效",{key:"errors:sessionsInitializeInvalid"});this.status="initializing",this.dirty=!1,this.unsubscribeWorkSessions?.(),this.unsubscribeWorkSessions=this.manage.subscribeUpdates(a=>{if(!this.disposed&&this.connection.isCurrent()){if("initializing"===this.status){this.dirty=!0;return}"ready"===this.status&&this.connection.sendPush(e.kM.update,a)}}),this.unsubscribeAppRuntime?.(),this.unsubscribeAppRuntime=this.appRuntime.subscribe(a=>{if(!this.disposed&&this.connection.isCurrent()){if("initializing"===this.status){this.dirty=!0;return}"ready"===this.status&&this.connection.sendPush(f.R.update,a)}});try{let c,d;do if(this.dirty=!1,c=await this.manage.listWorkSessions(),d=this.appRuntime.readSnapshot(),this.disposed||!this.connection.isCurrent())return;while(this.dirty);let e={...c,appRuntime:d};this.status="ready",this.connection.sendSuccess(b,a.head.requestId,e),console.info("[Pi Desk][WorkSessionSocket] 工作会话初始化完成",{clientId:this.connection.clientId,connectionId:this.connection.connectionId,workSessionCount:e.workSessions.length,notificationCount:e.appRuntime.notifications.length,pluginStateCount:Object.keys(e.appRuntime.plugins).length})}catch(c){this.status="new",this.unsubscribeWorkSessions?.(),this.unsubscribeWorkSessions=null,this.unsubscribeAppRuntime?.(),this.unsubscribeAppRuntime=null,console.error("[Pi Desk][WorkSessionSocket] 工作会话初始化失败",{clientId:this.connection.clientId,connectionId:this.connection.connectionId,errorName:c instanceof Error?c.name:"UnknownError"}),this.connection.sendError(b.path,a.head.requestId,500,"工作会话初始化失败",{key:"errors:sessionsInitializeFailed"})}}async acknowledgeCompleted(a){let b=e.kM.acknowledgeCompleted,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"工作会话完成确认参数无效",{key:"errors:completionAckInvalid"});try{await this.manage.acknowledgeCompleted(c.data.workId),this.connection.sendSuccess(b,a.head.requestId,{workId:c.data.workId})}catch(d){let c=d instanceof g.WorkSessionNotFoundError;this.connection.sendError(b.path,a.head.requestId,c?404:500,c?"工作会话不存在":"确认工作会话完成状态失败",{key:c?"errors:sessionMissing":"errors:completionAckFailed"})}}}d()}catch(a){d(a)}})},44429:(a,b,c)=>{"use strict";c.d(b,{Ld:()=>z,NN:()=>y,gm:()=>w,mQ:()=>j,ui:()=>u});var d=c(36153),e=c(3329),f=c(56255),g=c(75278),h=c(78143),i=c(75106);let j=d.Yj().trim().min(1).max(200),k=d.Yj().trim().min(1).max(100).nullable(),l=d.Yj().trim().min(1).max(100).nullable(),m=d.Yj().trim().min(1).max(200),n=d.Ik({label:d.Yj().trim().min(1).max(64),value:d.Yj().trim().min(1).max(500)}).strict(),o=d.Yj().trim().min(1).max(300).nullable(),p=d.k5(["running","completed","failed","stopped","interrupted"]),q=d.Ik({taskId:j,taskKind:k,taskType:l,title:m,info:d.YO(n).max(12),status:p,activity:o,startedAt:i.k,endedAt:i.k.nullable()}).strict().superRefine((a,b)=>{"running"===a.status&&null!==a.endedAt&&b.addIssue({code:"custom",message:"running task requires endedAt=null",path:["endedAt"]}),"running"!==a.status&&null===a.endedAt&&b.addIssue({code:"custom",message:"terminal task requires endedAt",path:["endedAt"]})});d.Ik({tasks:d.YO(q)}).strict().superRefine((a,b)=>{let c=new Set;for(let[d,e]of a.tasks.entries())c.has(e.taskId)&&b.addIssue({code:"custom",message:"taskId values must be unique",path:["tasks",d,"taskId"]}),c.add(e.taskId)});let r=d.Ik({kind:d.eu("text"),text:d.Yj(),truncated:d.zM()}).strict(),s=f.RX.extend({kind:d.eu("conversation"),truncated:d.zM()}).strict(),t=d.KC([d.ch(),r,s]),u=d.Ik({taskId:j,canInterrupt:d.zM(),body:t}).strict(),v=g.mv,w=d.KC([d.Ik({type:d.eu("snapshot"),snapshot:u}).strict(),d.Ik({type:d.eu("text_append"),text:d.Yj().min(1)}).strict(),d.Ik({type:d.eu("conversation_event"),event:v}).strict(),d.Ik({type:d.eu("unavailable")}).strict()]),x=d.Ik({source:e.R,taskId:j,entryId:h.Rv}).strict(),y=f.XM;x.extend({imageIndex:d.ai().int().nonnegative()}).strict();let z=f.y0},45407:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{Y3:()=>q,o3:()=>p,qc:()=>r,rt:()=>n,x4:()=>o});var e=c(44429),f=c(24202),g=c(5340),h=c(32757),i=c(15819),j=c(63178),k=a([g,h,i,j]);[g,h,i,j]=k.then?(await k)():k;class n{constructor(a){this.resolveRuntime=a,this.commandTails=new Map}async watchDetail(a,b,c){let d=await this.resolveRuntime(a),e=[],g=null,h=null,i=!1,k=!1,l=d=>{if(!k){if(!i||!g||!h)return void e.push(d);try{let b=(0,j.I)(a,g,d);if(!b)return;let e=(0,f.dZ)(g,b);e&&(g=e),c(b)}catch(f){console.warn("[Pi Desk][TaskCenterRuntime] 任务详情增量无效,重建 Snapshot",{workId:a.workId,taskId:b,eventType:d.type,errorName:f instanceof Error?f.name:"UnknownError"});let e=(0,j.C)(a,h.readSnapshot());g=e,c({type:"snapshot",snapshot:e})}}};try{for(let c of(h=await d.watchTaskDetail(b,l),await this.resolveRuntime(a),g=(0,j.C)(a,h.snapshot),i=!0,e.splice(0)))l(c);return{snapshot:g,release:()=>{k||(k=!0,e.length=0,h?.release(),h=null,g=null)}}}catch(a){throw k=!0,h?.release(),m(a)}}async getMessageDetail(a,b,c){try{let d=await this.resolveRuntime(a),{index:f,entry:h}=await d.readTaskMessage(b,c),i=(0,g.Cz)(f,h.entryId,h.timestampMs,h.message,a);if(!i.fixed.hasDetail||void 0===i.detail)throw new t(c);return e.NN.parse({index:f,entryId:c,detail:i.detail})}catch(a){throw l(a)}}async getImage(a,b,c,d){try{let f=await this.resolveRuntime(a);return e.Ld.parse(await f.readTaskImage(b,c,d))}catch(a){throw l(a)}}interrupt(a,b){let c=JSON.stringify([a.workId,a.sessionId,a.branchId,b]),d=this.commandTails.get(c)??Promise.resolve(),e=async()=>{let c=await this.resolveRuntime(a);await c.interruptTask(b)},f=d.then(e,e),g=f.then(()=>void 0,()=>void 0);return this.commandTails.set(c,g),g.finally(()=>{this.commandTails.get(c)===g&&this.commandTails.delete(c)}),f.catch(a=>Promise.reject(m(a)))}}function l(a){let b=m(a);return b===a?new s(a instanceof Error?a.message:"Task detail source is unavailable"):b}function m(a){return a instanceof i.cI||a instanceof h.L9?new o(a.message):a instanceof i.JF?new p(a.message):a instanceof h.dw?new q(a.message):a instanceof h.HJ?new r(a.message):a}class o extends Error{constructor(a){super(a),this.name="L2TaskNotFoundError"}}class p extends Error{constructor(a){super(a),this.name="L2TaskNotInterruptibleError"}}class q extends Error{constructor(a){super(a),this.name="L2TaskDetailUnsupportedError"}}class r extends Error{constructor(a){super(a),this.name="L2TaskMessageNotFoundError"}}class s extends Error{constructor(a){super(a),this.name="L2TaskDetailUnavailableError"}}class t extends Error{constructor(a){super(`Task message does not provide canonical detail: ${a}`),this.name="L2TaskMessageDetailUnavailableError"}}d()}catch(a){d(a)}})},46929:a=>{"use strict";let b=["nodebuffer","arraybuffer","fragments"],c="u">typeof Blob;c&&b.push("blob"),a.exports={BINARY_TYPES:b,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:c,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},47389:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{k:()=>j});var e=c(8663),f=c(55490),g=c(45870),h=a([f]);function i(a){return JSON.stringify([a.workId,a.sessionId,a.branchId])}f=(h.then?(await h)():h)[0];class j{constructor(a,b){this.connection=a,this.manage=b,this.subscriptions=new Map,this.disposed=!1,this.releaseSources=b.subscribeMessageEvents(a=>{"source_invalidated"===a.type&&this.release(i(a.source))}),this.routes=[{path:e.H.subscribe.path,access:"ready",handle:async a=>this.subscribe(a)},{path:e.H.unsubscribe.path,access:"ready",handle:async a=>this.unsubscribe(a)},{path:e.H.respond.path,access:"ready",handle:async a=>this.respond(a)}]}dispose(){if(!this.disposed)for(let a of(this.disposed=!0,this.releaseSources(),this.subscriptions.keys()))this.release(a)}subscribe(a){if(this.disposed||!this.connection.isCurrent())return;let b=e.H.subscribe,c=b.inputSchema.safeParse(a.body);if(!c.success)return this.invalid(a);try{let{source:d}=c.data,f=this.manage.getNativeUi(d),g=i(d);this.release(g),this.subscriptions.set(g,f.subscribe(a=>{!this.disposed&&this.connection.isCurrent()&&this.connection.sendPush(e.H.event,{source:d,event:a})})),this.connection.sendSuccess(b,a.head.requestId,f.snapshot())}catch(b){this.fail(a,b)}}unsubscribe(a){if(this.disposed||!this.connection.isCurrent())return;let b=e.H.unsubscribe,c=b.inputSchema.safeParse(a.body);if(!c.success)return this.invalid(a);this.release(i(c.data.source)),this.connection.sendSuccess(b,a.head.requestId,{})}respond(a){if(this.disposed||!this.connection.isCurrent())return;let b=e.H.respond,c=b.inputSchema.safeParse(a.body);if(!c.success)return this.invalid(a);try{this.manage.getNativeUi(c.data.source).respond(c.data.response),this.connection.sendSuccess(b,a.head.requestId,{})}catch(b){this.fail(a,b)}}release(a){this.subscriptions.get(a)?.(),this.subscriptions.delete(a)}invalid(a){this.connection.sendError(a.head.path,a.head.requestId,400,"插件交互参数无效")}fail(a,b){let c=b instanceof f.dM?409:b instanceof g.H?b.code:500,d=b instanceof f.dM?"工作会话来源已变化":b instanceof Error?b.message:"插件交互失败";500===c&&console.error("[Pi Desk][NativeUI] 请求失败",{path:a.head.path,message:d}),this.connection.sendError(a.head.path,a.head.requestId,c,d)}}d()}catch(a){d(a)}})},47591:(a,b,c)=>{"use strict";let{isUtf8:d}=c(79428),{hasBlob:e}=c(46929);function f(a){let b=a.length,c=0;for(;c<b;)if((128&a[c])==0)c++;else if((224&a[c])==192){if(c+1===b||(192&a[c+1])!=128||(254&a[c])==192)return!1;c+=2}else if((240&a[c])==224){if(c+2>=b||(192&a[c+1])!=128||(192&a[c+2])!=128||224===a[c]&&(224&a[c+1])==128||237===a[c]&&(224&a[c+1])==160)return!1;c+=3}else{if((248&a[c])!=240||c+3>=b||(192&a[c+1])!=128||(192&a[c+2])!=128||(192&a[c+3])!=128||240===a[c]&&(240&a[c+1])==128||244===a[c]&&a[c+1]>143||a[c]>244)return!1;c+=4}return!0}if(a.exports={isBlob:function(a){return e&&"object"==typeof a&&"function"==typeof a.arrayBuffer&&"string"==typeof a.type&&"function"==typeof a.stream&&("Blob"===a[Symbol.toStringTag]||"File"===a[Symbol.toStringTag])},isValidStatusCode:function(a){return a>=1e3&&a<=1014&&1004!==a&&1005!==a&&1006!==a||a>=3e3&&a<=4999},isValidUTF8:f,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},d)a.exports.isValidUTF8=function(a){return a.length<24?f(a):d(a)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let b=c(93750);a.exports.isValidUTF8=function(a){return a.length<32?f(a):b(a)}}catch(a){}},50906:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{c:()=>k,m:()=>f.Q});var e=c(77598),f=c(58706),g=a([f]);f=(g.then?(await g)():g)[0];let j=new Set;function h(a){if(j.has(a))throw new f.Q(409,"该服务正在登录或退出,请等待当前操作结束");if(j.size>=32)throw new f.Q(429,"正在处理的账号操作过多,请稍后重试");j.add(a)}function i(a,b,c){console.warn("[Pi Desk][ModelAuth] 账号操作未完成",{provider:a.state.provider,loginId:a.state.loginId,stage:b,errorName:c instanceof Error?c.name:"UnknownError"})}class k{constructor(a){this.onState=a,this.active=null,this.disposed=!1,this.logoutControllers=new Set}async list(){return this.assertOpen(),(await f.I.create()).list()}async start(a,b){if(this.assertOpen(),this.active)throw new f.Q(409,"当前连接已有登录流程,请先完成或取消");h(a);let c={state:{loginId:b,provider:a,status:"running",notice:null,prompt:null,message:null},abort:new AbortController,timer:null,scheduled:null,pending:null};this.active=c,c.timer=setTimeout(()=>this.stop(c,!0),9e5);try{let b=await f.I.create(c.abort.signal),d=(await b.list(c.abort.signal)).find(b=>b.provider===a);if(!d)throw new f.Q(400,"该服务不支持账号登录");if(d.conflict)throw new f.Q(409,d.conflict);c.abort.signal.throwIfAborted(),this.assertOpen(),c.scheduled=setImmediate(()=>{c.scheduled=null,this.login(c,b)})}catch(b){if(this.release(c),j.delete(a),c.abort.signal.aborted)throw new f.Q(409,"登录流程已取消或超时");throw b}}respond(a,b,c){let d=this.getRun(a),e=d.pending;if(!e||e.id!==b)throw new f.Q(409,"该登录问题已结束,请使用当前问题");let g=d.state.prompt;if(g?.type==="select"&&!g.options?.some(a=>a.id===c))throw new f.Q(400,"请选择当前问题提供的选项");this.clearPrompt(d),e.resolve(c),this.push(d)}cancel(a){this.stop(this.getRun(a),!1)}async logout(a){this.assertOpen(),h(a);let b=new AbortController;this.logoutControllers.add(b);let c=setTimeout(()=>b.abort(),15e3);try{let c=await f.I.create(b.signal),d=(await c.list(b.signal)).find(b=>b.provider===a);if(!d)throw new f.Q(400,"该服务不支持账号登录");if(!d.loggedIn)throw new f.Q(409,"该服务没有已保存的账号登录");b.signal.throwIfAborted(),await c.logout(a,b.signal)}catch(c){if(console.warn("[Pi Desk][ModelAuth] 退出账号未完成",{provider:a,stage:"logout",errorName:c instanceof Error?c.name:"UnknownError"}),c instanceof f.Q)throw c;throw new f.Q(500,b.signal.aborted?"退出账号已取消或超时,请重新获取账号状态":"退出账号失败,请重试")}finally{clearTimeout(c),this.logoutControllers.delete(b),j.delete(a)}}dispose(){if(!this.disposed){for(let a of(this.disposed=!0,this.active&&this.stop(this.active,!1),this.logoutControllers))a.abort();this.logoutControllers.clear()}}assertOpen(){if(this.disposed)throw new f.Q(409,"账号连接已关闭")}getRun(a){this.assertOpen();let b=this.active;if(!b||b.state.loginId!==a||"running"!==b.state.status)throw new f.Q(409,"登录流程已结束或不属于当前连接");return b}push(a){this.disposed||this.onState({...a.state})}notify(a,b){"running"!==a.state.status||a.abort.signal.aborted||("progress"===b.type?(a.state.message=b.message,a.state.notice?.type!=="auth_url"&&a.state.notice?.type!=="device_code"&&(a.state.notice={type:"progress",message:b.message})):"info"===b.type?(a.state.notice={type:"info",message:b.message,...b.links?{links:b.links.map(a=>({...a}))}:{}},a.state.message=b.message):(a.state.notice="device_code"===b.type?{type:"device_code",userCode:b.userCode,verificationUri:b.verificationUri}:{...b},a.state.message=null),this.push(a))}prompt(a,b){if(a.abort.signal.aborted||"running"!==a.state.status||b.signal?.aborted)return Promise.reject(new DOMException("登录问题已取消","AbortError"));if(a.pending){let b=a.pending;this.clearPrompt(a),b.reject(new DOMException("登录问题已替换","AbortError"))}return new Promise((c,d)=>{let f=(0,e.randomUUID)(),g=()=>{a.pending?.id===f&&(this.clearPrompt(a),d(new DOMException("登录问题已取消","AbortError")),"running"===a.state.status&&this.push(a))};a.pending={id:f,resolve:c,reject:d,cleanup:()=>{a.abort.signal.removeEventListener("abort",g),b.signal?.removeEventListener("abort",g)}},a.state.prompt={id:f,type:b.type,message:b.message,..."select"===b.type?{options:b.options.map(a=>({...a}))}:{placeholder:b.placeholder}},a.abort.signal.addEventListener("abort",g,{once:!0}),b.signal?.addEventListener("abort",g,{once:!0}),this.push(a)})}clearPrompt(a){a.pending?.cleanup(),a.pending=null,a.state.prompt=null}stop(a,b){"running"===a.state.status&&(a.state.status=b?"error":"cancelled",a.state.message=b?"登录已超时,请重新开始":"登录已取消",i(a,b?"timeout":"cancel",new DOMException("登录已结束","AbortError")),this.release(a),a.abort.abort(),this.push(a),a.scheduled&&(clearImmediate(a.scheduled),a.scheduled=null,j.delete(a.state.provider)))}release(a){a.timer&&clearTimeout(a.timer),a.timer=null;let b=a.pending;this.clearPrompt(a),b?.reject(new DOMException("登录已结束","AbortError")),this.active===a&&(this.active=null)}async login(a,b){let c="login";try{this.push(a);let d=await b.login(a.state.provider,{signal:a.abort.signal,prompt:b=>this.prompt(a,b),notify:b=>this.notify(a,b)});if("running"!==a.state.status)return;d||i(a,"credential-sync",new DOMException("本地同步失败","CredentialSynchronizationError")),c="catalog",a.state.message="登录成功,正在更新模型目录",this.push(a);let e=d?"登录成功":"登录成功,但本地模型状态同步失败,请重新获取模型列表",f=new AbortController,g=AbortSignal.any([a.abort.signal,f.signal]),h=setTimeout(()=>f.abort(),15e3);try{await b.refreshCatalog(a.state.provider,g)}catch(b){i(a,c,b),e="登录成功,但模型目录刷新失败,请稍后重新获取模型列表"}finally{clearTimeout(h)}if("running"!==a.state.status)return;a.state.status="completed",a.state.message=e,this.release(a),this.push(a)}catch(b){if("running"!==a.state.status)return;i(a,c,b),a.state.status=a.abort.signal.aborted?"cancelled":"error",a.state.message=a.abort.signal.aborted?"登录已取消":"登录未完成,请重试",this.release(a),this.push(a)}finally{this.release(a),a.abort.abort(),j.delete(a.state.provider)}}}d()}catch(a){d(a)}})},52218:(a,b,c)=>{"use strict";let{EMPTY_BUFFER:d}=c(46929),e=Buffer[Symbol.species];function f(a,b,c,d,e){for(let f=0;f<e;f++)c[d+f]=a[f]^b[3&f]}function g(a,b){for(let c=0;c<a.length;c++)a[c]^=b[3&c]}function h(a){let b;return(h.readOnly=!0,Buffer.isBuffer(a))?a:(a instanceof ArrayBuffer?b=new e(a):ArrayBuffer.isView(a)?b=new e(a.buffer,a.byteOffset,a.byteLength):(b=Buffer.from(a),h.readOnly=!1),b)}if(a.exports={concat:function(a,b){if(0===a.length)return d;if(1===a.length)return a[0];let c=Buffer.allocUnsafe(b),f=0;for(let b=0;b<a.length;b++){let d=a[b];c.set(d,f),f+=d.length}return f<b?new e(c.buffer,c.byteOffset,f):c},mask:f,toArrayBuffer:function(a){return a.length===a.buffer.byteLength?a.buffer:a.buffer.slice(a.byteOffset,a.byteOffset+a.length)},toBuffer:h,unmask:g},!process.env.WS_NO_BUFFER_UTIL)try{let b=c(99407);a.exports.mask=function(a,c,d,e,g){g<48?f(a,c,d,e,g):b.mask(a,c,d,e,g)},a.exports.unmask=function(a,c){a.length<32?g(a,c):b.unmask(a,c)}}catch(a){}},58706:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{I:()=>o,Q:()=>m});var e=c(51455),f=c(76760),g=c(75430),h=a([g]);g=(h.then?(await h)():h)[0];class m extends Error{constructor(a,b){super(b),this.code=a,this.name="L4ModelAuthError"}}let n=["baseUrl","apiKey","headers","api","oauth","authHeader","compat"];async function i(a,b){let c;if(!b)return a;let d=new Promise((a,d)=>{c=()=>d(new DOMException("账号操作已取消","AbortError")),b.aborted?c():b.addEventListener("abort",c,{once:!0})});try{return await Promise.race([a,d])}finally{b.removeEventListener("abort",c)}}function j(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function k(a){return n.some(b=>void 0!==a[b])}async function l(a){let b,c;try{b=await (0,e.readFile)(a,"utf8")}catch(a){if(j(a)&&"ENOENT"===a.code)return new Set;throw new m(500,"无法读取模型配置,暂时不能进行账号操作")}try{let a=(65279===b.charCodeAt(0)?b.slice(1):b).replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g,a=>'"'===a[0]?a:"").replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g,(a,b)=>b??a);c=JSON.parse(a)}catch{throw new m(409,"模型配置格式无效,请先修正 models.json")}if(!j(c)||void 0!==c.providers&&!j(c.providers))throw new m(409,"模型配置格式无效,请先修正 models.json");let d=new Set;for(let[a,b]of Object.entries(c.providers??{})){if(!j(b))throw new m(409,"模型服务配置格式无效");(k(b)||Array.isArray(b.models)&&b.models.some(a=>j(a)&&k(a)))&&d.add(a)}return d}class o{constructor(a,b,c){this.runtime=a,this.conflicts=b,this.agentDir=c}static async create(a){let b=(0,g.getAgentDir)(),c=(0,f.join)(b,"models.json"),d=await i(l(c),a);a?.throwIfAborted();let e=await i(g.ModelRuntime.create({authPath:(0,f.join)(b,"auth.json"),modelsPath:c,refreshOnCreate:!1,allowModelNetwork:!1,signal:a}),a);return a?.throwIfAborted(),new o(e,d,b)}async list(a){let b=await i(this.runtime.listCredentials({signal:a}),a),c=new Set(b.filter(a=>"oauth"===a.type).map(a=>a.providerId));return this.runtime.getProviders().filter(a=>a.auth.oauth).map(a=>({provider:a.id,name:a.name,loggedIn:c.has(a.id),conflict:this.conflicts.has(a.id)?"同名服务已有自定义连接,会改变账号凭据的使用方式。请先将自定义连接改为独立服务 ID,再登录账号。":null}))}async login(a,b){try{return await i(this.runtime.login(a,"oauth",b,{getDeviceId:()=>g.SettingsManager.create(process.cwd(),this.agentDir).getOrCreateDeviceId()}),b.signal),!0}catch(a){if(a instanceof g.CredentialSynchronizationError&&"login"===a.operation)return!1;throw a}}async refreshCatalog(a,b){b.throwIfAborted();let c=await i(this.runtime.refresh({allowNetwork:!0,providers:[a],signal:b}),b);if(b.throwIfAborted(),c.aborted)throw Error("CatalogRefreshAborted");let d=c.errors.get(a);if(d)throw d}async logout(a,b){try{await i(this.runtime.logout(a,{signal:b}),b)}catch(a){if(a instanceof g.CredentialSynchronizationError&&"logout"===a.operation)throw new m(500,"账号已退出,但本地模型目录同步失败,请重新获取模型列表");throw a}}}d()}catch(a){d(a)}})},58773:(a,b,c)=>{"use strict";let d,{Duplex:e}=c(27910),{randomFillSync:f}=c(55511),{types:{isUint8Array:g}}=c(28354),h=c(95374),{EMPTY_BUFFER:i,kWebSocket:j,NOOP:k}=c(46929),{isBlob:l,isValidStatusCode:m}=c(47591),{mask:n,toBuffer:o}=c(52218),p=Symbol("kByteLength"),q=Buffer.alloc(4),r=8192;class s{constructor(a,b,c){this._extensions=b||{},c&&(this._generateMask=c,this._maskBuffer=Buffer.alloc(4)),this._socket=a,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=k,this[j]=void 0}static frame(a,b){let c,e,g=!1,h=2,i=!1;b.mask&&(c=b.maskBuffer||q,b.generateMask?b.generateMask(c):(8192===r&&(void 0===d&&(d=Buffer.alloc(8192)),f(d,0,8192),r=0),c[0]=d[r++],c[1]=d[r++],c[2]=d[r++],c[3]=d[r++]),i=(c[0]|c[1]|c[2]|c[3])==0,h=6),"string"==typeof a?e=(!b.mask||i)&&void 0!==b[p]?b[p]:(a=Buffer.from(a)).length:(e=a.length,g=b.mask&&b.readOnly&&!i);let j=e;e>=65536?(h+=8,j=127):e>125&&(h+=2,j=126);let k=Buffer.allocUnsafe(g?e+h:h);return(k[0]=b.fin?128|b.opcode:b.opcode,b.rsv1&&(k[0]|=64),k[1]=j,126===j?k.writeUInt16BE(e,2):127===j&&(k[2]=k[3]=0,k.writeUIntBE(e,4,6)),b.mask)?(k[1]|=128,k[h-4]=c[0],k[h-3]=c[1],k[h-2]=c[2],k[h-1]=c[3],i)?[k,a]:g?(n(a,c,k,h,e),[k]):(n(a,c,a,0,e),[k,a]):[k,a]}close(a,b,c,d){let e;if(void 0===a)e=i;else if("number"==typeof a&&m(a))if(void 0!==b&&b.length){let c=Buffer.byteLength(b);if(c>123)throw RangeError("The message must not be greater than 123 bytes");if((e=Buffer.allocUnsafe(2+c)).writeUInt16BE(a,0),"string"==typeof b)e.write(b,2);else if(g(b))e.set(b,2);else throw TypeError("Second argument must be a string or a Uint8Array")}else(e=Buffer.allocUnsafe(2)).writeUInt16BE(a,0);else throw TypeError("First argument must be a valid error code number");let f={[p]:e.length,fin:!0,generateMask:this._generateMask,mask:c,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,e,!1,f,d]):this.sendFrame(s.frame(e,f),d)}ping(a,b,c){let d,e;if("string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),d>125)throw RangeError("The data size must not be greater than 125 bytes");let f={[p]:d,fin:!0,generateMask:this._generateMask,mask:b,maskBuffer:this._maskBuffer,opcode:9,readOnly:e,rsv1:!1};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,!1,f,c]):this.getBlobData(a,!1,f,c):0!==this._state?this.enqueue([this.dispatch,a,!1,f,c]):this.sendFrame(s.frame(a,f),c)}pong(a,b,c){let d,e;if("string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),d>125)throw RangeError("The data size must not be greater than 125 bytes");let f={[p]:d,fin:!0,generateMask:this._generateMask,mask:b,maskBuffer:this._maskBuffer,opcode:10,readOnly:e,rsv1:!1};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,!1,f,c]):this.getBlobData(a,!1,f,c):0!==this._state?this.enqueue([this.dispatch,a,!1,f,c]):this.sendFrame(s.frame(a,f),c)}send(a,b,c){let d,e,f=this._extensions[h.extensionName],g=b.binary?2:1,i=b.compress;"string"==typeof a?(d=Buffer.byteLength(a),e=!1):l(a)?(d=a.size,e=!1):(d=(a=o(a)).length,e=o.readOnly),this._firstFragment?(this._firstFragment=!1,i&&f&&f.params[f._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=d>=f._threshold),this._compress=i):(i=!1,g=0),b.fin&&(this._firstFragment=!0);let j={[p]:d,fin:b.fin,generateMask:this._generateMask,mask:b.mask,maskBuffer:this._maskBuffer,opcode:g,readOnly:e,rsv1:i};l(a)?0!==this._state?this.enqueue([this.getBlobData,a,this._compress,j,c]):this.getBlobData(a,this._compress,j,c):0!==this._state?this.enqueue([this.dispatch,a,this._compress,j,c]):this.dispatch(a,this._compress,j,c)}getBlobData(a,b,c,d){this._bufferedBytes+=c[p],this._state=2,a.arrayBuffer().then(a=>{if(this._socket.destroyed){let a=Error("The socket was closed while the blob was being read");process.nextTick(t,this,a,d);return}this._bufferedBytes-=c[p];let e=o(a);b?this.dispatch(e,b,c,d):(this._state=0,this.sendFrame(s.frame(e,c),d),this.dequeue())}).catch(a=>{process.nextTick(u,this,a,d)})}dispatch(a,b,c,d){if(!b)return void this.sendFrame(s.frame(a,c),d);let e=this._extensions[h.extensionName];this._bufferedBytes+=c[p],this._state=1,e.compress(a,c.fin,(a,b)=>{this._socket.destroyed?t(this,Error("The socket was closed while data was being compressed"),d):(this._bufferedBytes-=c[p],this._state=0,c.readOnly=!1,this.sendFrame(s.frame(b,c),d),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){let a=this._queue.shift();this._bufferedBytes-=a[3][p],Reflect.apply(a[0],this,a.slice(1))}}enqueue(a){this._bufferedBytes+=a[3][p],this._queue.push(a)}sendFrame(a,b){2===a.length?(this._socket.cork(),this._socket.write(a[0]),this._socket.write(a[1],b),this._socket.uncork()):this._socket.write(a[0],b)}}function t(a,b,c){"function"==typeof c&&c(b);for(let c=0;c<a._queue.length;c++){let d=a._queue[c],e=d[d.length-1];"function"==typeof e&&e(b)}}function u(a,b,c){t(a,b,c),a.onerror(b)}a.exports=s},58922:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{p:()=>j});var e=c(33495),f=c(45407),g=c(55490),h=a([f,g]);function i(a,b){return a.workId===b.workId&&a.sessionId===b.sessionId&&a.branchId===b.branchId}[f,g]=h.then?(await h)():h;class j{constructor(a,b,c){this.connection=a,this.manage=b,this.taskCenter=c,this.currentWatch=null,this.pendingWatch=null,this.operationTail=Promise.resolve(),this.disposed=!1,this.unsubscribeSources=this.manage.subscribeMessageEvents(a=>this.handleSourceEvent(a)),this.routes=Object.freeze([{path:e.rn.detailWatch.path,access:"ready",handle:a=>this.enqueue(()=>this.watch(a))},{path:e.rn.interrupt.path,access:"ready",handle:a=>this.interrupt(a)}])}dispose(){this.disposed||(this.disposed=!0,this.unsubscribeSources(),this.pendingWatch=null,this.releaseCurrentWatch())}enqueue(a){let b=this.operationTail.then(a,a);return this.operationTail=b.then(()=>void 0,()=>void 0),b}async watch(a){let b=e.rn.detailWatch,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"任务详情参数无效");if(this.releaseCurrentWatch(),null===c.data.taskId)return void this.connection.sendSuccess(b,a.head.requestId,{snapshot:null});let d={source:c.data.source,invalidated:!1};this.pendingWatch=d;try{let e=await this.createStableWatch(c.data.source,c.data.taskId);if(this.disposed||!this.connection.isCurrent())return void e.observation.release();if(d.invalidated)throw e.observation.release(),new g.dM(d.source);this.currentWatch=e,this.connection.sendSuccess(b,a.head.requestId,{snapshot:e.observation.snapshot}),e.status="ready",this.flushQueuedEvents(e),console.info("[Pi Desk][TaskCenterSocket] 任务详情观察完成",{clientId:this.connection.clientId,workId:e.source.workId,taskId:e.taskId})}catch(c){this.sendTaskError(b.path,a.head.requestId,c,"任务详情初始化失败")}finally{this.pendingWatch===d&&(this.pendingWatch=null)}}async createStableWatch(a,b){for(;;){let c=[],d={state:null},e=await this.taskCenter.watchDetail(a,b,a=>{let b=d.state;if(!b||this.currentWatch!==b||this.disposed){c.length<128&&c.push(a);return}this.handleDetailEvent(b,a)}),f={source:a,taskId:b,observation:e,status:"syncing",queuedEvents:c,overflowed:c.length>=128};if(d.state=f,!f.overflowed)return f;e.release()}}handleDetailEvent(a,b){if(this.currentWatch===a&&!this.disposed&&this.connection.isCurrent()){if("syncing"===a.status){if(a.queuedEvents.length>=128){a.queuedEvents.length=0,a.overflowed=!0;return}a.queuedEvents.push(b);return}this.connection.sendPush(e.rn.detailEvent,{source:a.source,taskId:a.taskId,event:b}),"unavailable"===b.type&&this.releaseCurrentWatch()}}flushQueuedEvents(a){if(this.currentWatch===a){if(a.overflowed)return void this.connection.close(1011,"任务详情同步队列溢出");for(let b of a.queuedEvents.splice(0))if(this.connection.sendPush(e.rn.detailEvent,{source:a.source,taskId:a.taskId,event:b}),"unavailable"===b.type)return void this.releaseCurrentWatch()}}async interrupt(a){let b=e.rn.interrupt,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"任务打断参数无效");try{await this.taskCenter.interrupt(c.data.source,c.data.taskId),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendTaskError(b.path,a.head.requestId,c,"打断任务失败")}}sendTaskError(a,b,c,d){c instanceof g.dM?this.connection.sendError(a,b,409,"工作会话来源已变化"):c instanceof f.x4?this.connection.sendError(a,b,404,"任务不存在"):c instanceof f.o3?this.connection.sendError(a,b,409,"任务当前不可打断"):c instanceof f.Y3?this.connection.sendError(a,b,409,"任务不支持该详情"):c instanceof f.qc?this.connection.sendError(a,b,404,"任务消息不存在"):(console.warn("[Pi Desk][TaskCenterSocket] 任务操作失败",{path:a,errorName:c instanceof Error?c.name:"UnknownError",message:c instanceof Error?c.message:d}),this.connection.sendError(a,b,500,d))}handleSourceEvent(a){if("source_invalidated"!==a.type)return;this.pendingWatch&&i(this.pendingWatch.source,a.source)&&(this.pendingWatch.invalidated=!0);let b=this.currentWatch;b&&i(b.source,a.source)&&(this.connection.sendPush(e.rn.detailEvent,{source:b.source,taskId:b.taskId,event:{type:"unavailable"}}),this.releaseCurrentWatch())}releaseCurrentWatch(){let a=this.currentWatch;this.currentWatch=null,a?.observation.release()}}d()}catch(a){d(a)}})},62761:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{f4:()=>k});var e=c(17691),f=c(77598),g=c(73024),h=c(76760),i=c(36153),j=a([e]);e=(j.then?(await j)():j)[0];let l=i.Ik({passwordHash:i.Yj().regex(/^scrypt:[a-f0-9]{32}:[a-f0-9]{128}$/)}).strict().extend({username:i.Yj().trim().min(1).max(64).optional()});class m extends Error{constructor(){super("登录保护配置无法读取,请修复配置或删除 auth.json 后重新设置"),this.name="L4AuthConfigError"}}function k(){let a;try{a=(0,g.readFileSync)((0,h.join)((0,e.M)(),"auth.json"),"utf8")}catch(a){if(a instanceof Error&&"code"in a&&"ENOENT"===a.code)return null;throw new m}try{let b=l.parse(JSON.parse(a)),c=void 0===b.username?[b.passwordHash]:[b.username,b.passwordHash],d=(0,f.createHmac)("sha256",function(){let a=(0,g.readFileSync)((0,h.join)((0,e.M)(),"auth-session-key"),"utf8").trim();if(!/^[a-f0-9]{64}$/.test(a))throw new m;return a}()).update(JSON.stringify(c)).digest("hex");return{passwordHash:b.passwordHash,sessionSecret:d}}catch{throw new m}}d()}catch(a){d(a)}})},63178:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{C:()=>h,I:()=>i});var e=c(44429),f=c(5340),g=a([f]);function h(a,b){let c=null===b.body?null:"text"===b.body.kind?b.body:{kind:"conversation",messages:b.body.entries.map((b,c)=>(0,f.NA)((0,f.Cz)(c,b.entryId,b.timestampMs,b.message,a))),temporaryMessages:b.body.temporaryMessages.map(({tempId:b,message:c})=>(0,f.QS)(b,c,a)),truncated:b.body.truncated};return e.ui.parse({taskId:b.taskId,canInterrupt:b.canInterrupt,body:c})}function i(a,b,c){return"snapshot"===c.type?e.gm.parse({type:"snapshot",snapshot:h(a,c.snapshot)}):"text_append"===c.type||"unavailable"===c.type?e.gm.parse(c):function(a,b,c){if(b.body?.kind!=="conversation")throw Error("Task conversation event requires a conversation snapshot");let d=b.body;if("durable_append"===c.type)return e.gm.parse({type:"conversation_event",event:{type:"durable_append",messages:c.entries.map((b,c)=>(0,f.NA)((0,f.Cz)(d.messages.length+c,b.entryId,b.timestampMs,b.message,a)))}});if("message_start"===c.type)return e.gm.parse({type:"conversation_event",event:{type:"message_start",snapshot:(0,f.QS)(c.tempId,c.message,a)}});if("message_update"===c.type){let b=d.temporaryMessages.find(a=>a.location.tempId===c.tempId);if(!b)throw Error(`Task Temporary message was not found: ${c.tempId}`);let g=(0,f.Ht)(b,(0,f.QS)(c.tempId,c.message,a,!1,"update"));return g?e.gm.parse({type:"conversation_event",event:g}):null}return"message_commit"===c.type?e.gm.parse({type:"conversation_event",event:{type:"message_commit",location:{tempId:c.tempId},durable:{index:d.messages.length,entryId:c.entryId},fixed:{timestampMs:c.timestampMs}}}):e.gm.parse({type:"conversation_event",event:{type:"message_discard",location:{tempId:c.tempId}}})}(a,b,c.event)}f=(g.then?(await g)():g)[0],d()}catch(a){d(a)}})},71779:(a,b,c)=>{"use strict";c.d(b,{R:()=>f});var d=c(98761),e=c(69375);let f=Object.freeze({apply:(0,e.Vc)({path:"app-runtime/apply",inputSchema:d.$C,outputSchema:d.Pq}),update:(0,e._G)({path:"app-runtime/update",bodySchema:d.YT})})},72608:(a,b,c)=>{"use strict";c.d(b,{l$:()=>n,yd:()=>w});var d=c(77598),e=c(76760),f=c(75825),g=c(31421),h=c(51455),i=c(73024),j=c(48161);let k=(0,c(57975).promisify)(g.execFile),{createRequire:l}=process.getBuiltinModule("module"),m=l((0,e.join)(process.cwd(),"package.json"));class n extends Error{constructor(a,b){super(b),this.code=a,this.name="L4TerminalError"}}async function o(a){try{return await (0,h.access)(a,"win32"===process.platform?i.constants.F_OK:i.constants.X_OK),(await (0,h.stat)(a)).isFile()}catch{return!1}}async function p(a){let b=a??(0,j.homedir)();if(!(0,e.isAbsolute)(b))throw new n(400,"终端目录必须是绝对路径");try{if(!(await (0,h.stat)(b)).isDirectory())throw Error("not a directory")}catch{throw new n(400,"终端目录不存在或不是目录")}let c="/bin/sh",d=[];if("win32"===process.platform){let a=(process.env.PATH??"").split(e.delimiter).map(a=>(0,e.join)(a.replace(/^"|"$/g,""),"pwsh.exe"));for(let b of(a.push((0,e.join)(process.env.ProgramFiles??"C:/Program Files","PowerShell/7/pwsh.exe")),c=(0,e.join)(process.env.SystemRoot??"C:/Windows","System32/WindowsPowerShell/v1.0/powershell.exe"),a))if((0,e.isAbsolute)(b)&&await o(b)){c=b;break}d.push("-NoLogo","-NoProfile")}else process.env.SHELL&&(0,e.isAbsolute)(process.env.SHELL)&&await o(process.env.SHELL)&&(c=process.env.SHELL);if(!await o(c))throw new n(503,"没有可用的终端 Shell");return{cwd:b,file:c,args:d,shell:(0,e.basename)(c)}}class q{constructor(a,b,c){this.stopped=null,this.exited=!1,this.earlyInputBytes=0;try{const d=m("node-pty/package.json").version;if("1.1.0"!==d)throw Error(`不支持的 node-pty 版本:${d}`);if("win32"===process.platform&&18309>Number((0,j.release)().split(".")[2]))throw Error("系统 Windows 版本不支持稳定 ConPTY");const e=m("node-pty");if(this.pty=e.spawn(a.file,a.args,{cwd:a.cwd,cols:b,rows:c,name:"xterm-256color",env:{...process.env,TERM:"xterm-256color"},useConpty:!0,useConptyDll:!1}),"win32"===process.platform){const a=this.pty._agent;if(!a._useConpty||a._useConptyDll)throw Error("终端需要系统 ConPTY");this.workerExit=new Promise((b,c)=>{a._conoutSocketWorker._worker.once("exit",()=>b()),a._conoutSocketWorker._worker.once("error",c)}),this.workerExit.catch(()=>void 0)}else this.workerExit=null;this.processExit=new Promise(a=>{let b=this.pty.onExit(()=>{this.exited=!0,b.dispose(),a()})}),this.released=this.processExit.then(()=>this.releaseNative()),this.released.catch(a=>console.error("[Pi Desk][Terminal] 原生资源释放失败",{pid:this.pty.pid,error:a}))}catch(a){throw console.error("[Pi Desk][Terminal] PTY 加载或启动失败",{message:a instanceof Error?a.message:String(a)}),new n(503,"终端原生依赖不可用或 Shell 启动失败")}}write(a){if(this.exited)throw new n(409,"终端已经退出");let b="win32"===process.platform?this.pty:null;if(b?._isReady&&(this.earlyInputBytes=0),(b?b._agent._inSocket.writableLength+this.earlyInputBytes:this.pty._writeStream._writeQueue.reduce((a,b)=>a+b.buffer.length-b.offset,0))+Buffer.byteLength(a)>65536)throw new n(429,"终端输入缓冲已满");this.checkDeferredCapacity(),b&&!b._isReady&&(this.earlyInputBytes+=Buffer.byteLength(a)),this.pty.write(function(a){let b=[],c=0;for(let d of a.matchAll(/\x1b\[M[\x00-\xff]{3}/g)){let e=d.index;e>c&&b.push(Buffer.from(a.slice(c,e),"utf8")),b.push(Buffer.from(d[0],"latin1")),c=e+d[0].length}return 0===c?Buffer.from(a,"utf8"):(c<a.length&&b.push(Buffer.from(a.slice(c),"utf8")),Buffer.concat(b))}(a))}resize(a,b){this.checkDeferredCapacity(),this.pty.resize(a,b)}checkDeferredCapacity(){if("win32"===process.platform&&this.pty._deferreds.length>=256)throw new n(429,"终端初始化操作队列已满")}stop(){return this.stopped||(this.stopped=this.stopTree()),this.stopped}async stopTree(){let a,b=performance.now();if(!this.exited)if("win32"===process.platform)try{await k("taskkill.exe",["/PID",String(this.pty.pid),"/T","/F"],{windowsHide:!0,timeout:4e3,maxBuffer:65536})}catch(a){if(this.logStopFailure("终止进程树",b,a),!this.exited)throw a}else{let{stdout:a}=await k("ps",["-eo","pid=,ppid="],{timeout:2e3,maxBuffer:2097152}),b=a.trim().split("\n").map(a=>a.trim().split(/\s+/).map(Number)),c=new Set([this.pty.pid]),d=[],e=!0;for(;e;)for(let[a,f]of(e=!1,b))c.has(f)&&!c.has(a)&&(c.add(a),d.push(a),e=!0);for(let a of d.reverse())this.killUnix(a);this.killUnix(-this.pty.pid),this.pty.kill("SIGKILL")}let c=performance.now();try{await Promise.race([this.processExit,new Promise((b,c)=>{a=setTimeout(()=>c(Error("Shell 退出等待超时")),4e3)})])}catch(a){throw this.logStopFailure("等待 Shell 退出",b,a),a}finally{a&&clearTimeout(a)}let d=performance.now();await this.released,console.info("[Pi Desk][Terminal] 原生终端停止完成",{pid:this.pty.pid,terminateMs:Math.round(c-b),exitMs:Math.round(d-c),releaseMs:Math.round(performance.now()-d),totalMs:Math.round(performance.now()-b)})}logStopFailure(a,b,c){let d=null;try{process.kill(this.pty.pid,0),d=!0}catch(a){"ESRCH"===a.code&&(d=!1)}console.error("[Pi Desk][Terminal] 终端停止阶段失败",{pid:this.pty.pid,stage:a,elapsedMs:Math.round(performance.now()-b),processAlive:d,ptyExited:this.exited,nativeExitCode:"win32"===process.platform?this.pty._agent.exitCode??null:null,error:c})}killUnix(a){try{process.kill(a,"SIGKILL")}catch(a){if("ESRCH"!==a.code)throw a}}async releaseNative(){if("win32"!==process.platform)return;let a=this.pty._agent;a._inSocket.destroy(),a._outSocket.destroy(),a._conoutSocketWorker.dispose(),await this.workerExit}}class r{frame(a){let b=this.pending+a,c=0;for(let a=this.pending.length;a<b.length;a+=1){let d=b.charCodeAt(a);24===d||26===d?this.state="ground":"ground"===this.state?27===d?this.state="escape":155===d?this.state="csi":[144,152,157,158,159].includes(d)&&(this.osc=157===d,this.state="string"):"escape"===this.state?91===d?this.state="csi":[80,88,93,94,95].includes(d)?(this.osc=93===d,this.state="string"):d>=48&&d<=126&&(this.state="ground"):"csi"===this.state?27===d?this.state="escape":d>=64&&d<=126&&(this.state="ground"):"string"===this.state?156===d||this.osc&&7===d?this.state="ground":27===d&&(this.state="string-escape"):"string-escape"===this.state&&(92===d?this.state="ground":27!==d&&(this.state="string")),"ground"===this.state&&(c=a+1)}if(this.pending=b.slice(c),Buffer.byteLength(this.pending)>1048576)throw new n(429,"终端控制序列超出缓冲上限");return b.slice(0,c)}dispose(){this.pending=""}constructor(){this.pending="",this.state="ground",this.osc=!1}}let{createRequire:s}=process.getBuiltinModule("module"),t=s((0,e.join)(process.cwd(),"package.json"));class u{constructor(a,b,c,d){this.terminalId=a,this.onExit=c,this.framing=new r,this.listeners=new Set,this.tail=Promise.resolve(),this.queueBytes=0,this.operations=0,this.paused=!1,this.ended=!1,this.failed=!1,this.disposed=!1,this.disposing=null,this.ownerId=null,this.pendingActivations=new Set;try{const a=t("@xterm/headless"),b=t("@xterm/addon-serialize");this.screen=new a.Terminal({cols:100,rows:28,scrollback:f.XZ,allowProposedApi:!0,windowOptions:{pushTitle:!0,popTitle:!0}}),this.serializer=new b.SerializeAddon,this.screen.loadAddon(this.serializer)}catch(b){throw console.error("[Pi Desk][Terminal] 权威屏幕加载失败",{terminalId:a,error:b}),new n(503,"终端屏幕依赖不可用")}try{this.child=new q(b,this.screen.cols,this.screen.rows),console.info("[Pi Desk][Terminal] PTY 已启动",{terminalId:a,pid:this.child.pty.pid})}catch(a){throw this.screen.dispose(),a}this.subscriptions=[this.screen.onTitleChange(a=>{this.disposed||d(a)}),this.screen.onData(a=>{if(!this.ended&&!this.disposed&&!this.failed)try{this.child.write(a)}catch(a){this.fail(a)}}),this.child.pty.onData(a=>this.acceptOutput(a)),this.child.pty.onExit(({exitCode:b})=>{this.ended=!0,this.ownerId=null,this.enqueue(async()=>{await this.child.released,this.disposed||(this.emit({type:"exit",exitCode:b}),this.onExit(b),console.info("[Pi Desk][Terminal] Shell 已退出",{terminalId:a,exitCode:b}))},!1).catch(a=>this.fail(a))})]}watch(a){return this.enqueue(async()=>{if(this.ensureAvailable(),this.listeners.size>=64)throw new n(429,"终端观察连接过多");let b=this.snapshot();return this.listeners.add(a),{snapshot:b,dispose:()=>{this.listeners.delete(a)}}})}input(a){return!a||Buffer.byteLength(a)>f.Oi?Promise.reject(new n(400,"终端输入必须为 1~16KiB UTF-8")):this.enqueue(async()=>{this.ensureRunning(),this.child.write(a)})}activate(a,b,c){let d={ownerId:a,released:!1};return this.pendingActivations.add(d),this.enqueue(async()=>{this.ensureRunning(),d.released||(this.validateDimensions(b,c),this.resizeScreen(b,c),this.ownerId=a)}).finally(()=>{this.pendingActivations.delete(d)})}resize(a,b,c){return this.enqueue(async()=>{this.ensureAvailable(),this.ownerId!==a||this.ended||(this.validateDimensions(b,c),this.resizeScreen(b,c))})}releaseOwner(a){for(let b of(this.ownerId===a&&(this.ownerId=null),this.pendingActivations))b.ownerId===a&&(b.released=!0)}dispose(){return this.disposing||(this.disposing=this.disposeRuntime()),this.disposing}async disposeRuntime(){this.disposed=!0,this.ownerId=null,this.listeners.clear(),this.paused&&this.child.pty.resume();try{await this.child.stop(),await this.tail}finally{for(let a of this.subscriptions)a.dispose();this.framing.dispose(),this.screen.dispose()}}acceptOutput(a){let b;if(this.disposed||this.failed)return;try{if(Buffer.byteLength(a)>1048576)throw new n(429,"PTY 单批输出超限");b=this.framing.frame(a)}catch(a){this.fail(a);return}if(!b)return;let c=Buffer.byteLength(b);this.queueBytes+c>1048576||this.operations>=256?this.fail(new n(429,"PTY 解析队列溢出")):(this.queueBytes+=c,!this.paused&&this.queueBytes>=262144&&(this.paused=!0,this.child.pty.pause()),this.enqueue(async()=>{try{if(this.disposed)return;for(let a of function(a,b=16384){let c=[],d=0,e=0;for(let f=0;f<a.length;){let g=a.codePointAt(f),h=g<=127?1:g<=2047?2:g<=65535?3:4;e+h>b&&(c.push(a.slice(d,f)),d=f,e=0),e+=h,f+=g>65535?2:1}return d<a.length&&c.push(a.slice(d)),c}(b))await new Promise(b=>this.screen.write(a,b)),this.emit({type:"output",data:a})}finally{this.queueBytes-=c,this.paused&&this.queueBytes<=65536&&!this.disposed&&(this.paused=!1,this.child.pty.resume())}},!1).catch(a=>this.fail(a)))}enqueue(a,b=!0){if(b&&this.operations>=256)return Promise.reject(new n(429,"终端操作队列已满"));this.operations+=1;let c=this.tail.then(a);return this.tail=c.then(()=>void 0,()=>void 0).finally(()=>{this.operations-=1}),c}snapshot(){let a=f.XZ;for(;;){let b=this.serializer.serialize({scrollback:a});if(Buffer.byteLength(b)<=f.I1)return{cols:this.screen.cols,rows:this.screen.rows,data:b};if(0===a)throw new n(429,"终端当前画面超过快照上限");a=Math.floor(a/2)}}resizeScreen(a,b){(this.screen.cols!==a||this.screen.rows!==b)&&(this.child.resize(a,b),this.screen.resize(a,b),this.emit({type:"resize",cols:a,rows:b}))}validateDimensions(a,b){if(!Number.isInteger(a)||!Number.isInteger(b)||a<2||a>f.xb||b<2||b>f.tu)throw new n(400,"终端尺寸必须为 2~400 列、2~200 行")}ensureAvailable(){if(this.disposed)throw new n(503,"终端正在关闭")}ensureRunning(){if(this.ensureAvailable(),this.ended||this.failed)throw new n(409,"终端已经退出")}emit(a){for(let b of this.listeners)try{b(a)}catch(a){this.listeners.delete(b),console.warn("[Pi Desk][Terminal] 释放失败的观察者",{terminalId:this.terminalId,error:a})}}fail(a){this.failed||this.disposed||(this.failed=!0,console.error("[Pi Desk][Terminal] 终端处理失败,结束目标进程",{terminalId:this.terminalId,error:a}),this.paused&&(this.paused=!1,this.child.pty.resume()),this.child.stop().catch(a=>console.error("[Pi Desk][Terminal] 结束失败",{terminalId:this.terminalId,error:a})))}}class v{create(a){let b=performance.now();return this.enqueue(async()=>{let c=performance.now();if(this.ensureOpen(),this.list().filter(a=>"running"===a.status).length+this.releases.size>=16)throw new n(429,"运行中或尚未完成清理的终端已达 16 个上限");let e=await p(a),f=performance.now();this.ensureOpen();let g=(0,d.randomUUID)(),h=new u(g,e,a=>this.handleExit(g,a),a=>this.handleTitleChange(g,a)),i={terminalId:g,cwd:e.cwd,shell:e.shell,title:"",status:"running",exitCode:null};return this.records.set(g,{summary:i,runtime:h,titleTimer:null}),this.publish(),console.info("[Pi Desk][TerminalManage] 已创建终端",{terminalId:g,cwd:e.cwd,shell:e.shell,queueMs:Math.round(c-b),resolveMs:Math.round(f-c),startMs:Math.round(performance.now()-f),totalMs:Math.round(performance.now()-b)}),{...i}})}list(){return Array.from(this.records.values(),({summary:a})=>({...a}))}subscribeList(a){return this.ensureOpen(),this.listeners.add(a),()=>{this.listeners.delete(a)}}watch(a,b){return this.get(a).runtime.watch(b)}input(a,b){return this.get(a).runtime.input(b)}activate(a,b,c,d){return this.get(a).runtime.activate(b,c,d)}resize(a,b,c,d){return this.get(a).runtime.resize(b,c,d)}releaseOwner(a){for(let b of this.records.values())b.runtime.releaseOwner(a)}remove(a){let b=performance.now();return this.enqueue(async()=>{let c=this.get(a);this.clearTitleTimer(c),this.records.delete(a);let d=this.exitedIds.indexOf(a);-1!==d&&this.exitedIds.splice(d,1),this.release(c),this.publish(),console.info("[Pi Desk][TerminalManage] 已接纳终端关闭",{terminalId:a,elapsedMs:Math.round(performance.now()-b)})})}release(a){let b=a.summary.terminalId,c=performance.now(),d=new Promise(a=>setImmediate(a)).then(()=>a.runtime.dispose());this.releases.set(b,d),d.then(()=>{this.releases.delete(b),console.info("[Pi Desk][TerminalManage] 终端资源已释放",{terminalId:b,elapsedMs:Math.round(performance.now()-c)})},a=>{console.error("[Pi Desk][TerminalManage] 终端资源清理失败",{terminalId:b,elapsedMs:Math.round(performance.now()-c),error:a})})}dispose(){if(!this.disposing){for(let a of(this.closing=!0,this.listeners.clear(),this.records.values()))this.clearTitleTimer(a);this.disposing=this.disposeAll()}return this.disposing}async disposeAll(){await this.tail;let a=await Promise.allSettled([...this.releases.values(),...Array.from(this.records.values(),a=>a.runtime.dispose())]);this.records.clear(),this.releases.clear(),this.exitedIds.length=0;let b=a.filter(a=>"rejected"===a.status);if(b.length)throw console.error("[Pi Desk][TerminalManage] 终端集合释放失败",{errors:b.map(a=>a.reason)}),AggregateError(b.map(a=>a.reason),"终端资源未完全释放")}handleTitleChange(a,b){let c=this.records.get(a);if(!c||this.closing)return;let d=b.replace(/\p{Cc}/gu,"").slice(0,512);c.summary.title!==d&&(c.summary.title=d,c.titleTimer||(c.titleTimer=setTimeout(()=>this.publish(),50)))}clearTitleTimer(a){a.titleTimer&&clearTimeout(a.titleTimer),a.titleTimer=null}handleExit(a,b){let c=this.records.get(a);if(c&&!this.closing&&"exited"!==c.summary.status){for(c.summary={...c.summary,status:"exited",exitCode:b},this.exitedIds.push(a);this.exitedIds.length>16;){let a=this.exitedIds.shift(),b=this.records.get(a);this.records.delete(a),b&&(this.clearTitleTimer(b),this.release(b))}this.publish()}}publish(){if(this.closing)return;for(let a of this.records.values())this.clearTitleTimer(a);let a=this.list();for(let b of this.listeners)try{b(a)}catch(a){this.listeners.delete(b),console.warn("[Pi Desk][TerminalManage] 列表观察失败",{error:a})}}get(a){this.ensureOpen();let b=this.records.get(a);if(!b)throw new n(404,"终端不存在");return b}ensureOpen(){if(this.closing)throw new n(503,"终端服务正在关闭")}enqueue(a){if(this.closing)return Promise.reject(new n(503,"终端服务正在关闭"));if(this.pending>=64)return Promise.reject(new n(429,"终端集合操作队列已满"));this.pending+=1;let b=this.tail.then(a);return this.tail=b.then(()=>void 0,()=>void 0).finally(()=>{this.pending-=1}),b}constructor(){this.records=new Map,this.exitedIds=[],this.releases=new Map,this.listeners=new Set,this.tail=Promise.resolve(),this.pending=0,this.closing=!1,this.disposing=null}}function w(){return globalThis.__piDeskTerminalManage||(globalThis.__piDeskTerminalManage=new v),globalThis.__piDeskTerminalManage}},73246:(a,b,c)=>{"use strict";c.d(b,{D:()=>m});var d=c(36153),e=c(69375),f=c(75825);let g=d.Yj().uuid(),h=d.Ik({}).strict(),i=d.Ik({terminalId:g,cwd:d.Yj().min(1),shell:d.Yj().min(1),title:d.Yj().max(512),status:d.k5(["running","exited"]),exitCode:d.ai().int().nullable()}).strict(),j=d.Ik({terminals:d.YO(i).max(32)}).strict(),k=Object.freeze({list:(0,e.Vc)({path:"terminals/list",inputSchema:h,outputSchema:j}),create:(0,e.Vc)({path:"terminals/create",inputSchema:d.Ik({cwd:d.Yj().min(1).max(32768).optional()}).strict(),outputSchema:i}),remove:(0,e.Vc)({path:"terminals/remove",inputSchema:d.Ik({terminalId:g}).strict(),outputSchema:h}),watch:(0,e.Vc)({path:"terminals/watch",inputSchema:d.Ik({terminalId:g.nullable()}).strict(),outputSchema:d.Ik({snapshot:f.CR.nullable()}).strict()}),unwatch:(0,e.Vc)({path:"terminals/unwatch",inputSchema:d.Ik({terminalId:g}).strict(),outputSchema:h}),input:(0,e.Vc)({path:"terminals/input",inputSchema:d.Ik({terminalId:g,data:d.Yj().min(1).max(f.Oi)}).strict(),outputSchema:h}),activate:(0,e.Vc)({path:"terminals/activate",inputSchema:d.Ik({terminalId:g,...f.XV}).strict(),outputSchema:h}),resize:(0,e.Vc)({path:"terminals/resize",inputSchema:d.Ik({terminalId:g,...f.XV}).strict(),outputSchema:h}),update:(0,e._G)({path:"terminals/update",bodySchema:j}),event:(0,e._G)({path:"terminals/event",bodySchema:d.Ik({terminalId:g,event:f.ED}).strict()})});var l=c(72608);class m{constructor(a,b,c){this.connection=a,this.manage=b,this.isReady=c,this.disposed=!1,this.unsubscribeList=null,this.watches=new Map,this.watchTail=Promise.resolve(),this.routes=[this.route(k.list,()=>(this.unsubscribeList||(this.unsubscribeList=this.manage.subscribeList(a=>{if(!this.active())return;let b=new Set(a.map(a=>a.terminalId));for(let a of this.watches.keys())b.has(a)||this.releaseWatch(a);this.connection.sendPush(k.update,{terminals:a})})),{terminals:this.manage.list()})),this.route(k.create,({cwd:a})=>this.manage.create(a)),this.route(k.remove,async({terminalId:a})=>(await this.manage.remove(a),{})),{path:k.watch.path,access:"ready",handle:a=>this.enqueueWatch(()=>this.watch(a))},{path:k.unwatch.path,access:"ready",handle:a=>this.enqueueWatch(()=>this.unwatch(a))},this.route(k.input,async({terminalId:a,data:b})=>(await this.manage.input(a,b),{})),this.route(k.activate,async({terminalId:a,cols:b,rows:c})=>(await this.manage.activate(a,this.connection.connectionId,b,c),this.active()||this.manage.releaseOwner(this.connection.connectionId),{})),this.route(k.resize,async({terminalId:a,cols:b,rows:c})=>(await this.manage.resize(a,this.connection.connectionId,b,c),{}))]}dispose(){this.disposed||(this.disposed=!0,this.unsubscribeList?.(),this.unsubscribeList=null,this.releaseAllWatches(),this.manage.releaseOwner(this.connection.connectionId))}active(){return!this.disposed&&this.connection.isCurrent()&&this.isReady()}route(a,b){return{path:a.path,access:"ready",handle:async c=>{if(!this.active())return;let d=a.inputSchema.safeParse(c.body);if(!d.success)return void this.connection.sendError(a.path,c.head.requestId,400,"终端请求参数无效");try{let e=b(d.data),f=e instanceof Promise?await e:e;this.active()&&this.connection.sendSuccess(a,c.head.requestId,f)}catch(a){this.sendError(c,a)}}}}enqueueWatch(a){let b=this.watchTail.then(a);return this.watchTail=b.catch(()=>void 0),b}async watch(a){if(!this.active())return;let b=k.watch,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"终端观察参数无效");if(null===c.data.terminalId){this.releaseAllWatches(),this.connection.sendSuccess(b,a.head.requestId,{snapshot:null});return}if(this.releaseWatch(c.data.terminalId),this.watches.size>=32)return void this.sendError(a,new l.l$(429,"终端观察已达 32 个上限"));let d={id:c.data.terminalId,dispose:null,events:[],bytes:0,syncing:!0,overflowed:!1,rebuilding:!1,timer:null};this.watches.set(d.id,d);try{await this.prepareSnapshot(d,c=>{this.connection.sendSuccess(b,a.head.requestId,{snapshot:c})})}catch(b){this.watches.get(d.id)===d&&this.releaseWatch(d.id),this.sendError(a,b)}}async unwatch(a){if(!this.active())return;let b=k.unwatch,c=b.inputSchema.safeParse(a.body);c.success?(this.releaseWatch(c.data.terminalId),this.connection.sendSuccess(b,a.head.requestId,{})):this.connection.sendError(b.path,a.head.requestId,400,"终端观察参数无效")}valid(a){return this.watches.get(a.id)===a&&this.active()}async prepareSnapshot(a,b){a.rebuilding=!0,a.syncing=!0;try{for(;this.valid(a);){a.dispose?.(),a.dispose=null,a.events=[],a.bytes=0,a.overflowed=!1;let c=await this.manage.watch(a.id,b=>this.acceptEvent(a,b));if(!this.valid(a))return void c.dispose();if(a.dispose=c.dispose,!a.overflowed){b(c.snapshot),a.syncing=!1,this.scheduleDrain(a);return}}}finally{a.rebuilding=!1}}acceptEvent(a,b){if(!this.valid(a)||a.overflowed)return;let c=this.eventBytes(b);if(a.bytes+c>524288||a.events.length>=128){a.overflowed=!0,a.syncing=!0,a.events=[],a.bytes=0,console.warn("[Pi Desk][TerminalSocket] 观察队列溢出,重建快照",{terminalId:a.id,connectionId:this.connection.connectionId}),a.rebuilding||this.enqueueWatch(async()=>{if(this.valid(a))try{await this.prepareSnapshot(a,b=>{this.connection.sendPush(k.event,{terminalId:a.id,event:{type:"snapshot",snapshot:b}})})}catch(b){console.error("[Pi Desk][TerminalSocket] 快照重建失败",{terminalId:a.id,error:b}),this.valid(a)&&(this.releaseWatch(a.id),this.connection.close(1011,"终端画面无法同步"))}});return}a.events.push(b),a.bytes+=c,a.syncing||this.scheduleDrain(a)}scheduleDrain(a){this.valid(a)&&!a.syncing&&!a.timer&&a.events.length&&(a.timer=setTimeout(()=>{if(a.timer=null,this.valid(a)&&!a.syncing){for(let b=0;b<4&&a.events.length&&this.valid(a);b+=1){let b=a.events.shift();a.bytes-=this.eventBytes(b),this.connection.sendPush(k.event,{terminalId:a.id,event:b})}this.scheduleDrain(a)}},8))}eventBytes(a){return"output"===a.type?Buffer.byteLength(a.data):"snapshot"===a.type?Buffer.byteLength(a.snapshot.data):32}releaseWatch(a){let b=this.watches.get(a);b&&(this.watches.delete(a),b.dispose?.(),b.timer&&clearTimeout(b.timer),b.events=[],b.bytes=0)}releaseAllWatches(){for(let a of this.watches.keys())this.releaseWatch(a)}sendError(a,b){if(this.active()){if(b instanceof l.l$)return void this.connection.sendError(a.head.path,a.head.requestId,b.code,b.message);console.error("[Pi Desk][TerminalSocket] 终端请求失败",{path:a.head.path,connectionId:this.connection.connectionId,error:b}),this.connection.sendError(a.head.path,a.head.requestId,500,"终端操作失败")}}}},74344:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{c:()=>r});var e=c(93951),f=c(50520),g=c(76217),h=c(18331),i=c(63210),j=c(42035),k=c(55490),l=c(6676),m=c(78922),n=c(36361),o=c(64007),p=c(99667),q=a([f,k,l,n,p]);[f,k,l,n,p]=q.then?(await q)():q;class r{constructor(a,b,c){this.connection=a,this.manage=b,this.disposed=!1,this.unsubscribeManagement=(0,f.getL2PluginManagement)().subscribe(()=>{!this.disposed&&c()&&this.connection.isCurrent()&&this.connection.sendPush(e.LC,{})}),this.routes=Object.freeze([{path:g.OY.invoke.path,access:"ready",handle:a=>this.invoke(a)},{path:h.bm.list.path,access:"ready",handle:a=>this.listBrowserEntries(a)},{path:i.QV.commandsList.path,access:"ready",handle:a=>this.listCommands(a)},{path:i.QV.commandExecute.path,access:"ready",handle:a=>this.executeCommand(a)},{path:i.QV.toolsList.path,access:"ready",handle:a=>this.listTools(a)},{path:i.QV.bashExecute.path,access:"ready",handle:a=>this.executeBash(a)},{path:i.QV.bashAbort.path,access:"ready",handle:a=>this.abortBash(a)}])}dispose(){this.disposed||(this.disposed=!0,this.unsubscribeManagement())}async invoke(a){let b=g.OY.invoke,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"插件调用参数无效");try{let d="global"===c.data.scope?await (0,n.getL4PiGlobalPluginRuntime)().invoke(c.data.pluginName,c.data.method,c.data.input):await this.manage.invokeSessionPluginMethod(c.data);this.connection.sendSuccess(b,a.head.requestId,d)}catch(d){this.sendInvokeError(b.path,a.head.requestId,d,c.data.pluginName,c.data.method)}}async listBrowserEntries(a){let b=h.bm.list;if(!b.inputSchema.safeParse(a.body).success)return void this.connection.sendError(b.path,a.head.requestId,400,"插件入口参数无效");try{let c=await (0,n.getL4PiGlobalPluginRuntime)().listBrowserEntries(),d=(0,m.IC)().replace(c);this.connection.sendSuccess(b,a.head.requestId,{entries:d.map(a=>({pluginName:a.entry.pluginName,url:a.url}))})}catch(c){console.error("[Pi Desk][PluginSocket] 查询 Browser Entry 失败",{errorName:c instanceof Error?c.name:"UnknownError",message:c instanceof Error?c.message:String(c)}),this.connection.sendError(b.path,a.head.requestId,500,"查询插件入口失败")}}async listCommands(a){let b=i.QV.commandsList,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi 命令参数无效");try{this.connection.sendSuccess(b,a.head.requestId,await this.manage.listNativeCommands(c.data))}catch(c){this.sendNativeError(b.path,a.head.requestId,c,"查询 Pi 命令失败")}}async executeCommand(a){let b=i.QV.commandExecute,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi 命令参数无效");try{await this.manage.executeNativeCommand(c.data),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendNativeError(b.path,a.head.requestId,c,"执行 Pi 命令失败")}}async listTools(a){let b=i.QV.toolsList,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi Tool 参数无效");try{this.connection.sendSuccess(b,a.head.requestId,await this.manage.listNativeTools(c.data))}catch(c){this.sendNativeError(b.path,a.head.requestId,c,"查询 Pi Tool 失败")}}async executeBash(a){let b=i.QV.bashExecute,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi Bash 参数无效");try{this.connection.sendSuccess(b,a.head.requestId,await this.manage.executeDirectBash(c.data))}catch(c){this.sendNativeError(b.path,a.head.requestId,c,"执行 Pi Bash 失败")}}async abortBash(a){let b=i.QV.bashAbort,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"Pi Bash 参数无效");try{await this.manage.abortDirectBash(c.data),this.connection.sendSuccess(b,a.head.requestId,{})}catch(c){this.sendNativeError(b.path,a.head.requestId,c,"中止 Pi Bash 失败")}}sendNativeError(a,b,c,d){c instanceof k.dM?this.connection.sendError(a,b,409,"工作会话来源已变化"):c instanceof k.nJ?this.connection.sendError(a,b,409,"工作会话正在变更"):c instanceof l.X9?this.connection.sendError(a,b,404,"Pi 命令不存在"):c instanceof l.yT?this.connection.sendError(a,b,409,"当前工作会话已有 Bash 正在执行"):(console.warn("[Pi Desk][PluginSocket] Native Pi 调用失败",{path:a,errorName:c instanceof Error?c.name:"UnknownError",message:c instanceof Error?c.message:String(c)}),this.connection.sendError(a,b,500,c instanceof Error&&c.message?c.message:d))}sendInvokeError(a,b,c,d,e){c instanceof k.dM?this.connection.sendError(a,b,409,"工作会话来源已变化"):c instanceof k.nJ?this.connection.sendError(a,b,409,"工作会话正在变更"):c instanceof p.y||c instanceof Error&&"L4PiPluginRuntimeBusyError"===c.name?this.connection.sendError(a,b,409,"插件正在重载"):c instanceof o.Tk||c instanceof Error&&"L4PiPluginMethodNotFoundError"===c.name?this.connection.sendError(a,b,404,"插件方法不存在"):c instanceof o.Pu?"input"===c.direction?this.connection.sendError(a,b,413,"插件调用数据超过 2MB"):(console.warn("[Pi Desk][PluginSocket] 插件方法输出超过限制",{pluginName:d,method:e,path:a,errorName:c.name}),this.connection.sendError(a,b,500,`插件方法执行失败:${d}/${e} 返回数据超过 2MB,请缩小查询范围或减少返回内容`)):(0,j.LO)(c)?this.connection.sendError(a,b,c.code,c.message):(console.warn("[Pi Desk][PluginSocket] 插件方法执行失败",{pluginName:d,method:e,path:a,errorName:c instanceof Error?c.name:"UnknownError",message:c instanceof Error?c.message:"Unknown plugin method error"}),this.connection.sendError(a,b,500,"插件方法执行失败"))}}d()}catch(a){d(a)}})},74972:(a,b,c)=>{"use strict";let{tokenChars:d}=c(47591);a.exports={parse:function(a){let b=new Set,c=-1,e=-1,f=0;for(;f<a.length;f++){let g=a.charCodeAt(f);if(-1===e&&1===d[g])-1===c&&(c=f);else if(0!==f&&(32===g||9===g))-1===e&&-1!==c&&(e=f);else if(44===g){if(-1===c)throw SyntaxError(`Unexpected character at index ${f}`);-1===e&&(e=f);let d=a.slice(c,e);if(b.has(d))throw SyntaxError(`The "${d}" subprotocol is duplicated`);b.add(d),c=e=-1}else throw SyntaxError(`Unexpected character at index ${f}`)}if(-1===c||-1!==e)throw SyntaxError("Unexpected end of input");let g=a.slice(c,f);if(b.has(g))throw SyntaxError(`The "${g}" subprotocol is duplicated`);return b.add(g),b}}},75825:(a,b,c)=>{"use strict";c.d(b,{CR:()=>k,ED:()=>l,I1:()=>i,Oi:()=>h,XV:()=>j,XZ:()=>g,tu:()=>f,xb:()=>e});var d=c(36153);let e=400,f=200,g=2e3,h=16384,i=8388608,j={cols:d.ai().int().min(2).max(e),rows:d.ai().int().min(2).max(f)},k=d.Ik({...j,data:d.Yj().max(i)}).strict(),l=d.gM("type",[d.Ik({type:d.eu("snapshot"),snapshot:k}).strict(),d.Ik({type:d.eu("output"),data:d.Yj().min(1).max(65536)}).strict(),d.Ik({type:d.eu("resize"),...j}).strict(),d.Ik({type:d.eu("exit"),exitCode:d.ai().int()}).strict()])},76217:(a,b,c)=>{"use strict";c.d(b,{OY:()=>l});var d=c(36153),e=c(3329),f=c(69375);let g=d.Yj().trim().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),h=d.g1(d.Yj(),d.Pq()),i=d.Ik({pluginName:g,method:g,scope:d.eu("global"),input:h}).strict(),j=d.Ik({pluginName:g,method:g,scope:d.eu("session"),source:e.R,input:h}).strict(),k=d.gM("scope",[i,j]),l=Object.freeze({invoke:(0,f.Vc)({path:"plugins/invoke",inputSchema:k,outputSchema:h})})},78922:(a,b,c)=>{"use strict";c.d(b,{IC:()=>h,J:()=>i});var d=c(77598),e=c(57075);class f extends Error{constructor(a,b){super(`Plugin Browser resource was not found: ${a}/${b}`),this.name="L4PiPluginBrowserResourceNotFoundError"}}class g{replace(a){let b=new Set(a.map(a=>a.pluginName));if(b.size!==a.length)throw Error("Browser Entry 清单包含重复插件");if(a.reduce((a,b)=>a+b.snapshot.size,0)>0x8000000)throw Error("Browser 活动资源超过容量上限");for(let[a,c]of this.recordsByPlugin)b.has(a)||(this.recordsByPlugin.delete(a),this.retire(c));let c=a.map(a=>{let b=this.recordsByPlugin.get(a.pluginName),c=b?.resourceKey===a.resourceKey&&b.entryPath===a.entryPath?b:{pluginName:a.pluginName,resourceGroup:(0,d.randomBytes)(24).toString("base64url"),resourceKey:a.resourceKey,entryPath:a.entryPath,snapshot:a.snapshot,retiredAt:null};return b!==c&&(b&&this.retire(b),this.recordsByPlugin.set(a.pluginName,c),this.recordsByGroup.set(c.resourceGroup,c)),{resourceGroup:c.resourceGroup,url:`/api/plugins/browser-resources/${c.resourceGroup}/entry.js`,entry:a}});return this.prune(),c}async read(a,b){this.prune();let c=this.recordsByGroup.get(a),d=!(!b||b.length>4096||b.startsWith("/")||b.includes("\\")||b.includes("\0"))&&b.endsWith(".js")&&b.split("/").every(a=>""!==a&&"."!==a&&".."!==a)?c?.snapshot.modules.get(b):void 0;if(!d)throw new f(a,b);return{stream:e.Readable.toWeb(e.Readable.from([d.content])),size:d.content.length,etag:d.etag}}dispose(){this.pruneTimer&&clearTimeout(this.pruneTimer),this.pruneTimer=null,this.recordsByPlugin.clear(),this.recordsByGroup.clear()}retire(a){a.retiredAt??=Date.now()}prune(){this.pruneTimer&&clearTimeout(this.pruneTimer),this.pruneTimer=null;let a=Date.now(),b=[...this.recordsByGroup.values()].filter(a=>null!==a.retiredAt).sort((a,b)=>a.retiredAt-b.retiredAt),c=b.reduce((a,b)=>a+b.snapshot.size,0),d=b.length;for(let e of b)(a-e.retiredAt>=6e4||d>32||c>0x4000000)&&(this.recordsByGroup.delete(e.resourceGroup),c-=e.snapshot.size,d-=1);let e=b.find(a=>this.recordsByGroup.has(a.resourceGroup));e&&(this.pruneTimer=setTimeout(()=>this.prune(),Math.max(1,e.retiredAt+6e4-a)),this.pruneTimer.unref())}constructor(){this.recordsByPlugin=new Map,this.recordsByGroup=new Map,this.pruneTimer=null}}function h(){return globalThis.__piDeskPluginBrowserResourceRegistry||(globalThis.__piDeskPluginBrowserResourceRegistry=new g),globalThis.__piDeskPluginBrowserResourceRegistry}function i(){globalThis.__piDeskPluginBrowserResourceRegistry?.dispose(),globalThis.__piDeskPluginBrowserResourceRegistry=void 0}},79271:(a,b,c)=>{"use strict";c.d(b,{m:()=>r});var d=c(76760),e=c(36153),f=c(69375),g=c(72497);let h=e.Yj().trim().min(1).max(32768),i=e.Ik({text:e.Yj(),truncated:e.zM()}).strict(),j=e.KC([e.Ik({type:e.eu("text_append"),text:e.Yj().min(1)}).strict(),e.Ik({type:e.eu("snapshot"),snapshot:i}).strict(),e.Ik({type:e.eu("unavailable")}).strict()]),k=e.Ik({pluginName:g.tv,path:h}).strict(),l=e.Ik({snapshot:i}).strict(),m=e.Ik({}).strict(),n=e.Ik({pluginName:g.tv,path:h,event:j}).strict(),o=Object.freeze({watch:(0,f.Vc)({path:"plugins/logs/watch",inputSchema:k,outputSchema:l}),unwatch:(0,f.Vc)({path:"plugins/logs/unwatch",inputSchema:k,outputSchema:m}),event:(0,f._G)({path:"plugins/logs/event",bodySchema:n})});var p=c(78555);function q(a,b){return JSON.stringify([a,b])}class r{constructor(a){this.connection=a,this.watches=new Map,this.operationTail=Promise.resolve(),this.disposed=!1,this.routes=Object.freeze([{path:o.watch.path,access:"ready",handle:a=>this.enqueue(()=>this.watch(a))},{path:o.unwatch.path,access:"ready",handle:a=>this.enqueue(()=>this.unwatch(a))}])}dispose(){if(!this.disposed){for(let a of(this.disposed=!0,this.watches.values()))a.observation.release();this.watches.clear()}}enqueue(a){let b=this.operationTail.then(a,a);return this.operationTail=b.then(()=>void 0,()=>void 0),b}async watch(a){let b=o.watch,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"日志观察参数无效");if(!(0,d.isAbsolute)(c.data.path))return void this.connection.sendError(b.path,a.head.requestId,400,"日志路径必须是服务端绝对路径");let e=q(c.data.pluginName,c.data.path),f=this.watches.get(e);if(f)return void this.connection.sendSuccess(b,a.head.requestId,{snapshot:f.observation.readSnapshot()});if(this.watches.size>=16)return void this.connection.sendError(b.path,a.head.requestId,409,"当前页面观察的日志过多");try{let d=await this.createStableWatch(e,c.data.pluginName,c.data.path);if(this.disposed||!this.connection.isCurrent())return void d.observation.release();this.watches.set(e,d),this.connection.sendSuccess(b,a.head.requestId,{snapshot:d.observation.snapshot}),d.status="ready",this.flushQueuedEvents(d),console.info("[Pi Desk][PluginLogSocket] 日志观察完成",{clientId:this.connection.clientId,pluginName:d.pluginName,path:d.path})}catch(d){console.warn("[Pi Desk][PluginLogSocket] 初始化日志观察失败",{pluginName:c.data.pluginName,path:c.data.path,errorName:d instanceof Error?d.name:"UnknownError",message:d instanceof Error?d.message:String(d)}),this.connection.sendError(b.path,a.head.requestId,500,"读取日志失败")}}async createStableWatch(a,b,c){for(;;){let d=[],e={state:null},f=await (0,p.i)().observe(c,b=>{let c=e.state;if(!c||this.watches.get(a)!==c||this.disposed){d.length<128&&d.push(b);return}this.handleEvent(c,b)}),g={key:a,pluginName:b,path:c,observation:f,status:"syncing",queuedEvents:d,overflowed:d.length>=128};if(e.state=g,!g.overflowed)return g;f.release()}}async unwatch(a){let b=o.unwatch,c=b.inputSchema.safeParse(a.body);c.success?(0,d.isAbsolute)(c.data.path)?(this.releaseWatch(q(c.data.pluginName,c.data.path)),this.connection.sendSuccess(b,a.head.requestId,{})):this.connection.sendError(b.path,a.head.requestId,400,"日志路径必须是服务端绝对路径"):this.connection.sendError(b.path,a.head.requestId,400,"日志解除观察参数无效")}handleEvent(a,b){if(this.watches.get(a.key)===a&&!this.disposed&&this.connection.isCurrent()){if("syncing"===a.status){if(a.queuedEvents.length>=128){a.queuedEvents.length=0,a.overflowed=!0;return}a.queuedEvents.push(b);return}this.connection.sendPush(o.event,{pluginName:a.pluginName,path:a.path,event:b}),"unavailable"===b.type&&this.releaseWatch(a.key)}}flushQueuedEvents(a){if(this.watches.get(a.key)===a){if(a.overflowed){this.connection.sendPush(o.event,{pluginName:a.pluginName,path:a.path,event:{type:"snapshot",snapshot:a.observation.readSnapshot()}}),a.queuedEvents.length=0,a.overflowed=!1;return}for(let b of a.queuedEvents.splice(0))if(this.connection.sendPush(o.event,{pluginName:a.pluginName,path:a.path,event:b}),"unavailable"===b.type)return void this.releaseWatch(a.key)}}releaseWatch(a){let b=this.watches.get(a);b&&(this.watches.delete(a),b.observation.release())}}},80273:(a,b,c)=>{"use strict";c.d(b,{aJ:()=>g,nV:()=>h});var d=c(77598);let e=/^(\d+)\.([a-f0-9]{64})$/;function f(a){return(0,d.createHash)("sha256").update(a,"utf8").digest()}function g(a,b,c=Date.now()){var h,i;if(!a||!b)return!1;let j=e.exec(a);if(!j)return!1;let k=Number(j[1]);return!!Number.isSafeInteger(k)&&!(k<c)&&(h=j[2],i=(0,d.createHmac)("sha256",b).update(`Pi Desk web session:${k}`,"utf8").digest("hex"),(0,d.timingSafeEqual)(f(h),f(i)))}function h(a,b){if(a)for(let c of a.split(";")){let a=c.indexOf("=");if(!(a<0)&&c.slice(0,a).trim()===b)try{return decodeURIComponent(c.slice(a+1).trim())}catch{break}}}},81607:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{U:()=>h});var e=c(71779),f=c(31442),g=a([f]);f=(g.then?(await g)():g)[0];class h{constructor(a,b){this.connection=a,this.runtime=b,this.routes=Object.freeze([{path:e.R.apply.path,access:"ready",handle:a=>this.apply(a)}])}dispose(){}async apply(a){let b=e.R.apply,c=b.inputSchema.safeParse(a.body);if(!c.success)return void this.connection.sendError(b.path,a.head.requestId,400,"App Runtime 更新参数无效");try{await this.runtime.applyClient(c.data),this.connection.sendSuccess(b,a.head.requestId,{})}catch(d){let c=d instanceof f.L2AppRuntimeTargetNotFoundError;this.connection.sendError(b.path,a.head.requestId,c?404:500,c?"App Runtime 目标不存在":"App Runtime 更新失败")}}}d()}catch(a){d(a)}})},81882:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{Oe:()=>k,yJ:()=>l});var e=c(80273),f=c(62761),g=c(9763),h=c(5034),i=c(67841);c(37721);var j=a([f,g,h,i]);[f,g,h,i]=j.then?(await j)():j;let l="pi-desk-session";function k(a){var b;return b=(0,f.f4)(),null===b||(0,e.aJ)((0,e.nV)(a,l),b.sessionSecret)}d()}catch(a){d(a)}})},84048:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.d(b,{k:()=>q});var e=c(30119),f=c(26272),g=c(81607),h=c(18611),i=c(79271),j=c(47389),k=c(28363),l=c(74344),m=c(58922),n=c(73246),o=c(43973),p=a([g,h,j,k,l,m,o]);[g,h,j,k,l,m,o]=p.then?(await p)():p;class q{constructor(a,b,c,d,e,p,q,r){this.authToken=c,this.onClose=r,this.routes=new Map,this.disposed=!1,this.connection=new f.V(b,a),this.workSessions=new o.G(this.connection,d,e),this.appRuntime=new g.U(this.connection,e),this.chat=new h.T(this.connection,d),this.plugins=new l.c(this.connection,d,()=>this.workSessions.isReady()),this.nativeUi=new j.k(this.connection,d),this.modelAuth=new k.Y(this.connection),this.pluginLogs=new i.m(this.connection),this.taskCenter=new m.p(this.connection,d,p),this.terminals=new n.D(this.connection,q,()=>this.workSessions.isReady()),this.registerRoutes(this.workSessions.routes),this.registerRoutes(this.appRuntime.routes),this.registerRoutes(this.chat.routes),this.registerRoutes(this.plugins.routes),this.registerRoutes(this.nativeUi.routes),this.registerRoutes(this.modelAuth.routes),this.registerRoutes(this.pluginLogs.routes),this.registerRoutes(this.taskCenter.routes),this.registerRoutes(this.terminals.routes)}start(){this.connection.start(a=>this.handleRequest(a),a=>{this.dispose(),this.onClose(this,a)}),console.info("[Pi Desk][AppSocketSession] 应用连接已建立",{clientId:this.connection.clientId,connectionId:this.connection.connectionId})}supersede(){this.disposeControllers(),this.connection.supersede()}close(a,b){this.disposeControllers(),this.connection.close(a,b)}terminate(){this.disposeControllers(),this.connection.terminate()}waitForClose(){return this.connection.waitForClose()}pushPlugin(a){!this.disposed&&this.workSessions.isReady()&&this.connection.sendPush(e.cx,a)}registerRoutes(a){for(let b of a){if(this.routes.has(b.path))throw Error(`Duplicate WebSocket route: ${b.path}`);this.routes.set(b.path,b)}}async handleRequest(a){let b=this.routes.get(a.head.path);b?"ready"!==b.access||this.workSessions.isReady()?await b.handle(a):this.connection.sendError(a.head.path,a.head.requestId,409,"工作会话尚未初始化",{key:"errors:sessionsNotReady"}):this.connection.sendError(a.head.path,a.head.requestId,404,"未知 WebSocket 路径",{key:"errors:socketUnknownPath"})}disposeControllers(){this.plugins.dispose(),this.nativeUi.dispose(),this.modelAuth.dispose(),this.pluginLogs.dispose(),this.taskCenter.dispose(),this.terminals.dispose(),this.chat.dispose(),this.appRuntime.dispose(),this.workSessions.dispose()}dispose(){this.disposed||(this.disposed=!0,this.disposeControllers())}}d()}catch(a){d(a)}})},89373:(a,b,c)=>{"use strict";let d=c(94735),e=c(81630),{Duplex:f}=c(27910),{createHash:g}=c(55511),h=c(18753),i=c(95374),j=c(74972),k=c(42027),{CLOSE_TIMEOUT:l,GUID:m,kWebSocket:n}=c(46929),o=/^[+/0-9A-Za-z]{22}==$/;class p extends d{constructor(a,b){if(super(),null==(a={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:262144,maxFragments:16384,maxPayload:0x6400000,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:l,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:k,...a}).port&&!a.server&&!a.noServer||null!=a.port&&(a.server||a.noServer)||a.server&&a.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=a.port?(this._server=e.createServer((a,b)=>{let c=e.STATUS_CODES[426];b.writeHead(426,{"Content-Length":c.length,"Content-Type":"text/plain"}),b.end(c)}),this._server.listen(a.port,a.host,a.backlog,b)):a.server&&(this._server=a.server),this._server){const a=this.emit.bind(this,"connection");this._removeListeners=function(a,b){for(let c of Object.keys(b))a.on(c,b[c]);return function(){for(let c of Object.keys(b))a.removeListener(c,b[c])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(b,c,d)=>{this.handleUpgrade(b,c,d,a)}})}!0===a.perMessageDeflate&&(a.perMessageDeflate={}),a.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=a,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(a){if(2===this._state){a&&this.once("close",()=>{a(Error("The server is not running"))}),process.nextTick(q,this);return}if(a&&this.once("close",a),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(q,this);else{let a=this._server;this._removeListeners(),this._removeListeners=this._server=null,a.close(()=>{q(this)})}}shouldHandle(a){if(this.options.path){let b=a.url.indexOf("?");if((-1!==b?a.url.slice(0,b):a.url)!==this.options.path)return!1}return!0}handleUpgrade(a,b,c,d){b.on("error",r);let e=a.headers["sec-websocket-key"],f=a.headers.upgrade,g=+a.headers["sec-websocket-version"];if("GET"!==a.method)return void t(this,a,b,405,"Invalid HTTP method");if(void 0===f||"websocket"!==f.toLowerCase())return void t(this,a,b,400,"Invalid Upgrade header");if(void 0===e||!o.test(e))return void t(this,a,b,400,"Missing or invalid Sec-WebSocket-Key header");if(13!==g&&8!==g)return void t(this,a,b,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});if(!this.shouldHandle(a))return void s(b,400);let k=a.headers["sec-websocket-protocol"],l=new Set;if(void 0!==k)try{l=j.parse(k)}catch(c){t(this,a,b,400,"Invalid Sec-WebSocket-Protocol header");return}let m=a.headers["sec-websocket-extensions"],n={};if(this.options.perMessageDeflate&&void 0!==m){let c=new i({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let a=h.parse(m);a[i.extensionName]&&(c.accept(a[i.extensionName]),n[i.extensionName]=c)}catch(c){t(this,a,b,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:a.headers[`${8===g?"sec-websocket-origin":"origin"}`],secure:!!(a.socket.authorized||a.socket.encrypted),req:a};if(2===this.options.verifyClient.length)return void this.options.verifyClient(f,(f,g,h,i)=>{if(!f)return s(b,g||401,h,i);this.completeUpgrade(n,e,l,a,b,c,d)});if(!this.options.verifyClient(f))return s(b,401)}this.completeUpgrade(n,e,l,a,b,c,d)}completeUpgrade(a,b,c,d,e,f,j){if(!e.readable||!e.writable)return e.destroy();if(e[n])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return s(e,503);let k=g("sha1").update(b+m).digest("base64"),l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${k}`],o=new this.options.WebSocket(null,void 0,this.options);if(c.size){let a=this.options.handleProtocols?this.options.handleProtocols(c,d):c.values().next().value;a&&(l.push(`Sec-WebSocket-Protocol: ${a}`),o._protocol=a)}if(a[i.extensionName]){let b=a[i.extensionName].params,c=h.format({[i.extensionName]:[b]});l.push(`Sec-WebSocket-Extensions: ${c}`),o._extensions=a}this.emit("headers",l,d),e.write(l.concat("\r\n").join("\r\n")),e.removeListener("error",r),o.setSocket(e,f,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(o),o.on("close",()=>{this.clients.delete(o),this._shouldEmitClose&&!this.clients.size&&process.nextTick(q,this)})),j(o,d)}}function q(a){a._state=2,a.emit("close")}function r(){this.destroy()}function s(a,b,c,d){c=c||e.STATUS_CODES[b],d={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(c),...d},a.once("finish",a.destroy),a.end(`HTTP/1.1 ${b} ${e.STATUS_CODES[b]}\r
2
+ `+Object.keys(d).map(a=>`${a}: ${d[a]}`).join("\r\n")+"\r\n\r\n"+c)}function t(a,b,c,d,e,f){if(a.listenerCount("wsClientError")){let d=Error(e);Error.captureStackTrace(d,t),a.emit("wsClientError",d,c,b)}else s(c,d,e,f)}a.exports=p},93750:()=>{},94296:(a,b,c)=>{"use strict";c.a(a,async(a,d)=>{try{c.r(b),c.d(b,{getL1AppSocketRuntime:()=>r});var e=c(47757),f=c(81882),g=c(80273),h=c(50520),i=c(31442),j=c(25406),k=c(78922),l=c(36361),m=c(33448),n=c(16050),o=c(72608),p=c(84048),q=a([e,f,h,i,j,l,m,n,p]);[e,f,h,i,j,l,m,n,p]=q.then?(await q)():q;class s{constructor(){this.sessionsByClientId=new Map,this.manage=(0,j.getL2WorkSessionManage)(),this.appRuntime=(0,i.getL2AppRuntime)(),this.taskCenter=(0,n.K)(),this.terminals=(0,o.yd)(),this.manage.subscribePluginPushEvents(a=>this.pushPlugin(a))}accept(a,b,c){let d=this.sessionsByClientId.get(b),e=new p.k(a,b,(0,g.nV)(c,f.yJ),this.manage,this.appRuntime,this.taskCenter,this.terminals,(a,c)=>{this.sessionsByClientId.get(b)===a&&this.sessionsByClientId.delete(b),console.info("[Pi Desk][AppSocketRuntime] 应用连接已断开",{clientId:b,connectionId:a.connection.connectionId,code:c.code})});this.sessionsByClientId.set(b,e);try{e.start()}catch(a){throw d?this.sessionsByClientId.set(b,d):this.sessionsByClientId.delete(b),e.terminate(),a}d?.supersede()}async closeByAuthToken(a,b,c){let d=[];for(let[e,f]of this.sessionsByClientId)f.authToken===a&&(this.sessionsByClientId.delete(e),f.close(b,c),d.push(f));await Promise.all(d.map(a=>a.waitForClose()))}async closeAll(a,b){let c=[...this.sessionsByClientId.values()];for(let d of(this.sessionsByClientId.clear(),c))d.close(a,b);await Promise.all(c.map(a=>a.waitForClose()))}terminateAll(){let a=[...this.sessionsByClientId.values()];for(let b of(this.sessionsByClientId.clear(),a))b.terminate()}connectionCount(){return this.sessionsByClientId.size}pushPlugin(a){for(let b of this.sessionsByClientId.values())b.pushPlugin(a)}async disposePlugins(){(0,e.disposeL4PiDeskCommands)(),(0,h.disposeL2PluginManagement)(),await (0,l.disposeL4PiGlobalPluginRuntime)(),(0,k.J)(),(0,i.disposeL2AppRuntime)()}async disposeTerminals(){await this.terminals.dispose()}async disposeWorkSessions(){await (0,m.wz)()}}function r(){return globalThis.__piDeskAppSocketRuntime||(globalThis.__piDeskAppSocketRuntime=new s),globalThis.__piDeskAppSocketRuntime}d()}catch(a){d(a)}})},95374:(a,b,c)=>{"use strict";let d,e=c(74075),f=c(52218),g=c(7586),{kStatusCode:h}=c(46929),i=Buffer[Symbol.species],j=Buffer.from([0,0,255,255]),k=Symbol("permessage-deflate"),l=Symbol("total-length"),m=Symbol("callback"),n=Symbol("buffers"),o=Symbol("error");class p{constructor(a){this._options=a||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._maxPayload=0|this._options.maxPayload,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,d||(d=new g(void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10))}static get extensionName(){return"permessage-deflate"}offer(){let a={};return this._options.serverNoContextTakeover&&(a.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(a.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(a.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?a.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(a.client_max_window_bits=!0),a}accept(a){return a=this.normalizeParams(a),this.params=this._isServer?this.acceptAsServer(a):this.acceptAsClient(a),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let a=this._deflate[m];this._deflate.close(),this._deflate=null,a&&a(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(a){let b=this._options,c=a.find(a=>(!1!==b.serverNoContextTakeover||!a.server_no_context_takeover)&&(!a.server_max_window_bits||!1!==b.serverMaxWindowBits&&("number"!=typeof b.serverMaxWindowBits||!(b.serverMaxWindowBits>a.server_max_window_bits)))&&("number"!=typeof b.clientMaxWindowBits||("number"==typeof a.client_max_window_bits?!(b.clientMaxWindowBits>a.client_max_window_bits):!!a.client_max_window_bits)));if(!c)throw Error("None of the extension offers can be accepted");return b.serverNoContextTakeover&&(c.server_no_context_takeover=!0),b.clientNoContextTakeover&&(c.client_no_context_takeover=!0),"number"==typeof b.serverMaxWindowBits&&(c.server_max_window_bits=b.serverMaxWindowBits),"number"==typeof b.clientMaxWindowBits?c.client_max_window_bits=b.clientMaxWindowBits:(!0===c.client_max_window_bits||!1===b.clientMaxWindowBits)&&delete c.client_max_window_bits,c}acceptAsClient(a){let b=a[0];if(!1===this._options.clientNoContextTakeover&&b.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(b.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&b.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(b.client_max_window_bits=this._options.clientMaxWindowBits);return b}normalizeParams(a){return a.forEach(a=>{Object.keys(a).forEach(b=>{let c=a[b];if(c.length>1)throw Error(`Parameter "${b}" must have only a single value`);if(c=c[0],"client_max_window_bits"===b){if(!0!==c){let a=+c;if(!Number.isInteger(a)||a<8||a>15)throw TypeError(`Invalid value for parameter "${b}": ${c}`);c=a}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${b}": ${c}`)}else if("server_max_window_bits"===b){let a=+c;if(!Number.isInteger(a)||a<8||a>15)throw TypeError(`Invalid value for parameter "${b}": ${c}`);c=a}else if("client_no_context_takeover"===b||"server_no_context_takeover"===b){if(!0!==c)throw TypeError(`Invalid value for parameter "${b}": ${c}`)}else throw Error(`Unknown parameter "${b}"`);a[b]=c})}),a}decompress(a,b,c){d.add(d=>{this._decompress(a,b,(a,b)=>{d(),c(a,b)})})}compress(a,b,c){d.add(d=>{this._compress(a,b,(a,b)=>{d(),c(a,b)})})}_decompress(a,b,c){let d=this._isServer?"client":"server";if(!this._inflate){let a=`${d}_max_window_bits`,b="number"!=typeof this.params[a]?e.Z_DEFAULT_WINDOWBITS:this.params[a];this._inflate=e.createInflateRaw({...this._options.zlibInflateOptions,windowBits:b}),this._inflate[k]=this,this._inflate[l]=0,this._inflate[n]=[],this._inflate.on("error",s),this._inflate.on("data",r)}this._inflate[m]=c,this._inflate.write(a),b&&this._inflate.write(j),this._inflate.flush(()=>{let a=this._inflate[o];if(a){this._inflate.close(),this._inflate=null,c(a);return}let e=f.concat(this._inflate[n],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[n]=[],b&&this.params[`${d}_no_context_takeover`]&&this._inflate.reset()),c(null,e)})}_compress(a,b,c){let d=this._isServer?"server":"client";if(!this._deflate){let a=`${d}_max_window_bits`,b="number"!=typeof this.params[a]?e.Z_DEFAULT_WINDOWBITS:this.params[a];this._deflate=e.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:b}),this._deflate[l]=0,this._deflate[n]=[],this._deflate.on("data",q)}this._deflate[m]=c,this._deflate.write(a),this._deflate.flush(e.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let a=f.concat(this._deflate[n],this._deflate[l]);b&&(a=new i(a.buffer,a.byteOffset,a.length-4)),this._deflate[m]=null,this._deflate[l]=0,this._deflate[n]=[],b&&this.params[`${d}_no_context_takeover`]&&this._deflate.reset(),c(null,a)})}}function q(a){this[n].push(a),this[l]+=a.length}function r(a){(this[l]+=a.length,this[k]._maxPayload<1||this[l]<=this[k]._maxPayload)?this[n].push(a):(this[o]=RangeError("Max payload size exceeded"),this[o].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[o][h]=1009,this.removeListener("data",r),this.reset())}function s(a){(this[k]._inflate=null,this[o])?this[m](this[o]):(a[h]=1007,this[m](a))}a.exports=p},99407:()=>{}};