@crewx/sdk 0.9.0-rc.20 → 0.9.0-rc.201

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 (411) hide show
  1. package/README.md +1 -1
  2. package/dist/account/auth-client.d.ts +61 -0
  3. package/dist/account/auth-json-v2.d.ts +1 -0
  4. package/dist/account/auth-json.d.ts +30 -0
  5. package/dist/account/config.d.ts +37 -0
  6. package/dist/account/env-bootstrap.d.ts +11 -0
  7. package/dist/account/errors.d.ts +24 -0
  8. package/dist/account/index.d.ts +12 -0
  9. package/dist/account/index.js +2 -0
  10. package/dist/account/session-manager.d.ts +47 -0
  11. package/dist/activity-log/builder.d.ts +59 -6
  12. package/dist/agent/agent-list-view.d.ts +19 -0
  13. package/dist/agent-interceptor/chain.d.ts +25 -0
  14. package/dist/agent-interceptor/index.d.ts +6 -0
  15. package/dist/agent-interceptor/model-runner.d.ts +19 -0
  16. package/dist/agent-interceptor/program-runner.d.ts +13 -0
  17. package/dist/agent-interceptor/protocol.d.ts +68 -0
  18. package/dist/agent-interceptor/run-stop.d.ts +3 -0
  19. package/dist/agent-interceptor/schema.d.ts +267 -0
  20. package/dist/agent-interceptor/types.d.ts +88 -0
  21. package/dist/app/app-files/args.d.ts +12 -0
  22. package/dist/app/app-files/errors.d.ts +6 -0
  23. package/dist/app/app-files/index.d.ts +35 -0
  24. package/dist/app/app-files/lock.d.ts +26 -0
  25. package/dist/app/app-files/root.d.ts +22 -0
  26. package/dist/app/app-files/store.d.ts +48 -0
  27. package/dist/app/app-files/write.child.d.ts +1 -0
  28. package/dist/app/app.d.ts +168 -0
  29. package/dist/app/backend-env.d.ts +3 -0
  30. package/dist/app/content-media-types.d.ts +2 -0
  31. package/dist/app/context.d.ts +2 -0
  32. package/dist/app/entry.d.ts +9 -0
  33. package/dist/app/frame.d.ts +55 -0
  34. package/dist/app/index.d.ts +20 -0
  35. package/dist/app/index.js +13 -0
  36. package/dist/app/job-bridge.child.d.ts +1 -0
  37. package/dist/app/job-bridge.d.ts +67 -0
  38. package/dist/app/job-bridge.drain.child.d.ts +1 -0
  39. package/dist/app/job-bridge.example.d.ts +11 -0
  40. package/dist/app/job-contract.d.ts +40 -0
  41. package/dist/app/job-wire.d.ts +149 -0
  42. package/dist/app/protocol.d.ts +9 -0
  43. package/dist/app/runtime.d.ts +23 -0
  44. package/dist/app/schedule-contract.d.ts +59 -0
  45. package/dist/app/tool-mode.d.ts +3 -0
  46. package/dist/app-artifact-policy/check.d.ts +2 -0
  47. package/dist/app-artifact-policy/contract.d.ts +54 -0
  48. package/dist/app-artifact-policy/helper.d.ts +15 -0
  49. package/dist/app-artifact-policy/index.d.ts +3 -0
  50. package/dist/app-artifact-policy/index.js +18 -0
  51. package/dist/app-artifact-policy/paths.d.ts +24 -0
  52. package/dist/app-artifact-policy/scan.d.ts +47 -0
  53. package/dist/app-ui/index.d.ts +95 -0
  54. package/dist/app-ui/index.js +1 -0
  55. package/dist/attachment-receive/index.d.ts +76 -0
  56. package/dist/attachment-receive/index.js +2 -0
  57. package/dist/boxing/box.types.d.ts +4 -0
  58. package/dist/config/canonicalize-agent-options.d.ts +2 -0
  59. package/dist/config/default-agent-models.d.ts +11 -0
  60. package/dist/config/global-settings.d.ts +33 -0
  61. package/dist/config/migrate-grok-mode.d.ts +6 -0
  62. package/dist/config/model-compat.d.ts +31 -0
  63. package/dist/config/models.generated.d.ts +38 -0
  64. package/dist/config/models.remote.d.ts +1 -0
  65. package/dist/config/overdrive.d.ts +7 -0
  66. package/dist/config/pricing.d.ts +6 -3
  67. package/dist/config/pricing.generated.d.ts +4 -0
  68. package/dist/config/pricing.types.d.ts +4 -0
  69. package/dist/config/timeout.config.d.ts +4 -0
  70. package/dist/config/wi-boards.d.ts +19 -0
  71. package/dist/context/GoalLoader.d.ts +6 -0
  72. package/dist/context-budget/continuity.d.ts +64 -0
  73. package/dist/context-budget/fixed-slot-shrink.d.ts +97 -0
  74. package/dist/context-budget/index.d.ts +168 -0
  75. package/dist/conversation/index.d.ts +1 -1
  76. package/dist/conversation/sqlite-provider.d.ts +6 -3
  77. package/dist/conversation/to-template-messages.d.ts +9 -0
  78. package/dist/conversation/types.d.ts +86 -1
  79. package/dist/desktop/command-runner.d.ts +4 -0
  80. package/dist/desktop/default-adapters.d.ts +4 -0
  81. package/dist/desktop/global-install.d.ts +19 -0
  82. package/dist/desktop/index.d.ts +3 -0
  83. package/dist/desktop/index.js +3 -0
  84. package/dist/desktop/install.d.ts +5 -0
  85. package/dist/desktop/lnk.d.ts +22 -0
  86. package/dist/desktop/manifest.d.ts +21 -0
  87. package/dist/desktop/types.d.ts +67 -0
  88. package/dist/desktop/version.d.ts +1 -0
  89. package/dist/desktop/windows-paths.d.ts +21 -0
  90. package/dist/desktop/wrapper.d.ts +18 -0
  91. package/dist/esm/account/index.js +2 -0
  92. package/dist/esm/app/index.js +13 -0
  93. package/dist/esm/app-artifact-policy/index.js +18 -0
  94. package/dist/esm/attachment-receive/index.js +2 -0
  95. package/dist/esm/desktop/index.js +3 -0
  96. package/dist/esm/history-snapshot/index.js +16 -0
  97. package/dist/esm/index.js +1362 -224
  98. package/dist/esm/node/index.js +2 -0
  99. package/dist/esm/plugins/index.js +532 -214
  100. package/dist/esm/process/index.js +1 -0
  101. package/dist/esm/publish/index.js +2 -0
  102. package/dist/esm/repository/index.js +792 -207
  103. package/dist/esm/skills/index.js +2 -0
  104. package/dist/esm/testing/index.js +1 -1
  105. package/dist/events/types.d.ts +44 -0
  106. package/dist/facade/Crewx.d.ts +78 -5
  107. package/dist/facade/task-ticket.d.ts +14 -0
  108. package/dist/highlight/thread-highlight-prompt.d.ts +2 -0
  109. package/dist/highlight/thread-highlighter.d.ts +326 -0
  110. package/dist/history-snapshot/index.d.ts +82 -0
  111. package/dist/history-snapshot/index.js +16 -0
  112. package/dist/index.browser.d.ts +26 -1
  113. package/dist/index.browser.js +6 -2
  114. package/dist/index.d.ts +165 -18
  115. package/dist/index.js +1362 -224
  116. package/dist/internal/console-decoder.d.ts +38 -0
  117. package/dist/internal/windows-spawn.d.ts +10 -0
  118. package/dist/layout/types.d.ts +18 -1
  119. package/dist/lifecycle/process-lease.d.ts +80 -0
  120. package/dist/lifecycle/process-owner.d.ts +20 -0
  121. package/dist/lifecycle/task-heartbeat.d.ts +41 -0
  122. package/dist/lifecycle/task-stop.d.ts +112 -0
  123. package/dist/lifecycle/update-admission.d.ts +45 -0
  124. package/dist/local-server/base-url.d.ts +18 -0
  125. package/dist/local-server/index.d.ts +8 -0
  126. package/dist/local-server/opencode.d.ts +8 -0
  127. package/dist/local-server/probe.d.ts +3 -0
  128. package/dist/local-server/runtime.d.ts +26 -0
  129. package/dist/local-server/types.d.ts +43 -0
  130. package/dist/mcp-app/agent-access.d.ts +33 -0
  131. package/dist/mcp-app/app-handoff.d.ts +109 -0
  132. package/dist/mcp-app/app-icon-read.d.ts +7 -0
  133. package/dist/mcp-app/app-job-bridge.d.ts +30 -0
  134. package/dist/mcp-app/app-job-bridge.example.d.ts +36 -0
  135. package/dist/mcp-app/app-job.d.ts +168 -0
  136. package/dist/mcp-app/app-schedule.d.ts +85 -0
  137. package/dist/mcp-app/apps-context.d.ts +32 -0
  138. package/dist/mcp-app/bundle-provenance.d.ts +3 -0
  139. package/dist/mcp-app/candidate-registration.d.ts +4 -0
  140. package/dist/mcp-app/card-handler.d.ts +7 -0
  141. package/dist/mcp-app/catalog.d.ts +7 -0
  142. package/dist/mcp-app/content-channel.d.ts +86 -0
  143. package/dist/mcp-app/content-declarations.d.ts +31 -0
  144. package/dist/mcp-app/dev-checks.d.ts +31 -0
  145. package/dist/mcp-app/diagnostic-reason.d.ts +3 -0
  146. package/dist/mcp-app/discovery.d.ts +164 -0
  147. package/dist/mcp-app/errors.d.ts +7 -0
  148. package/dist/mcp-app/index.d.ts +46 -0
  149. package/dist/mcp-app/installed-app-ref.d.ts +25 -0
  150. package/dist/mcp-app/model-context.d.ts +29 -0
  151. package/dist/mcp-app/node-app-discovery-fs.d.ts +23 -0
  152. package/dist/mcp-app/product-bundle-assets.d.ts +27 -0
  153. package/dist/mcp-app/product-bundle-loader.d.ts +53 -0
  154. package/dist/mcp-app/projection.d.ts +14 -0
  155. package/dist/mcp-app/prompt-cards.d.ts +28 -0
  156. package/dist/mcp-app/registry.d.ts +28 -0
  157. package/dist/mcp-app/skill-backend.d.ts +141 -0
  158. package/dist/mcp-app/state-set.d.ts +9 -0
  159. package/dist/mcp-app/types.d.ts +501 -0
  160. package/dist/mcp-app/view-call.d.ts +7 -0
  161. package/dist/mcp-app/workspace-app-assets.d.ts +42 -0
  162. package/dist/mcp-app/workspace-app-scan-cache.d.ts +27 -0
  163. package/dist/mcp-app/workspace-snapshot.d.ts +81 -0
  164. package/dist/migrations/0011_far_black_tarantula.sql +1 -0
  165. package/dist/migrations/0012_blue_turbo.sql +23 -0
  166. package/dist/migrations/0013_hesitant_adam_destine.sql +15 -0
  167. package/dist/migrations/0014_organic_mongu.sql +73 -0
  168. package/dist/migrations/0015_panoramic_gorilla_man.sql +71 -0
  169. package/dist/migrations/0016_fuzzy_hemingway.sql +14 -0
  170. package/dist/migrations/0017_project_stage_sdk_migration.sql +29 -0
  171. package/dist/migrations/0018_bored_jackal.sql +33 -0
  172. package/dist/migrations/0019_backfill_task_thread_ids.sql +74 -0
  173. package/dist/migrations/0020_useful_iron_lad.sql +55 -0
  174. package/dist/migrations/0021_dashing_peter_quill.sql +51 -0
  175. package/dist/migrations/0022_wandering_bucky.sql +1 -0
  176. package/dist/migrations/0023_red_payback.sql +1 -0
  177. package/dist/migrations/0024_storage_metadata.sql +262 -0
  178. package/dist/migrations/0025_task_heartbeat.sql +8 -0
  179. package/dist/migrations/0025_thread_app_instance_ledger.sql +2 -0
  180. package/dist/migrations/0026_mcp_action_source.sql +47 -0
  181. package/dist/migrations/0027_task_stop_scope_cleanup.sql +5 -0
  182. package/dist/migrations/0027_ui_instance_active_unique.sql +2 -0
  183. package/dist/migrations/0029_nice_rhino.sql +1 -0
  184. package/dist/migrations/0031_petite_arclight.sql +6 -0
  185. package/dist/migrations/0032_ui_instance_opened_by.sql +1 -0
  186. package/dist/migrations/0033_thread_creator_boundary_guard.sql +38 -0
  187. package/dist/migrations/0034_keen_fallen_one.sql +36 -0
  188. package/dist/migrations/0035_request_log_daily.sql +11 -0
  189. package/dist/migrations/0036_ui_definition_archive.sql +8 -0
  190. package/dist/migrations/0037_ui_instance_agent_open_request.sql +1 -0
  191. package/dist/migrations/0038_task_rating.sql +3 -0
  192. package/dist/migrations/0039_aspiring_purifiers.sql +9 -0
  193. package/dist/migrations/0040_task_provider_inputs.sql +53 -0
  194. package/dist/migrations/0041_tranquil_vivisector.sql +54 -0
  195. package/dist/migrations/0042_breezy_blue_shield.sql +31 -0
  196. package/dist/migrations/0043_nervous_darkstar.sql +1 -0
  197. package/dist/migrations/0044_military_galactus.sql +8 -0
  198. package/dist/migrations/0045_task_pid_started_at.sql +1 -0
  199. package/dist/migrations/0046_acoustic_karnak.sql +49 -0
  200. package/dist/migrations/0047_doc_sync_connect_requests.sql +18 -0
  201. package/dist/migrations/0048_smart_gertrude_yorkes.sql +47 -0
  202. package/dist/migrations/meta/0011_snapshot.json +1342 -0
  203. package/dist/migrations/meta/0012_snapshot.json +1494 -0
  204. package/dist/migrations/meta/0013_snapshot.json +1592 -0
  205. package/dist/migrations/meta/0014_snapshot.json +1975 -0
  206. package/dist/migrations/meta/0015_snapshot.json +2315 -0
  207. package/dist/migrations/meta/0016_snapshot.json +2419 -0
  208. package/dist/migrations/meta/0017_snapshot.json +2419 -0
  209. package/dist/migrations/meta/0018_snapshot.json +2570 -0
  210. package/dist/migrations/meta/0020_snapshot.json +2895 -0
  211. package/dist/migrations/meta/0021_snapshot.json +3031 -0
  212. package/dist/migrations/meta/0022_snapshot.json +3039 -0
  213. package/dist/migrations/meta/0023_snapshot.json +3047 -0
  214. package/dist/migrations/meta/0029_snapshot.json +3206 -0
  215. package/dist/migrations/meta/0031_snapshot.json +3251 -0
  216. package/dist/migrations/meta/0034_snapshot.json +3473 -0
  217. package/dist/migrations/meta/0035_snapshot.json +3547 -0
  218. package/dist/migrations/meta/0036_snapshot.json +3591 -0
  219. package/dist/migrations/meta/0037_snapshot.json +3598 -0
  220. package/dist/migrations/meta/0038_snapshot.json +3626 -0
  221. package/dist/migrations/meta/0039_snapshot.json +3684 -0
  222. package/dist/migrations/meta/0040_snapshot.json +3759 -0
  223. package/dist/migrations/meta/0041_snapshot.json +4156 -0
  224. package/dist/migrations/meta/0042_snapshot.json +4383 -0
  225. package/dist/migrations/meta/0043_snapshot.json +4390 -0
  226. package/dist/migrations/meta/0044_snapshot.json +4435 -0
  227. package/dist/migrations/meta/0045_snapshot.json +4442 -0
  228. package/dist/migrations/meta/0046_snapshot.json +4733 -0
  229. package/dist/migrations/meta/0047_snapshot.json +4832 -0
  230. package/dist/migrations/meta/0048_snapshot.json +5128 -0
  231. package/dist/migrations/meta/_journal.json +266 -0
  232. package/dist/node/index.d.ts +1 -0
  233. package/dist/node/index.js +2 -0
  234. package/dist/paths.d.ts +1 -0
  235. package/dist/plugin/types.d.ts +1 -0
  236. package/dist/plugins/index.d.ts +1 -1
  237. package/dist/plugins/index.js +532 -214
  238. package/dist/plugins/sqlite-tracing.d.ts +46 -0
  239. package/dist/process/index.d.ts +2 -0
  240. package/dist/process/index.js +1 -0
  241. package/dist/process/process-control.d.ts +74 -0
  242. package/dist/prompt/tag-names.d.ts +22 -0
  243. package/dist/provider/acp/adapter.d.ts +37 -2
  244. package/dist/provider/acp/adapters/antigravity-account.d.ts +4 -0
  245. package/dist/provider/acp/completion-observer.d.ts +24 -0
  246. package/dist/provider/acp/connection.d.ts +69 -3
  247. package/dist/provider/acp/index.d.ts +3 -3
  248. package/dist/provider/acp/meta.d.ts +11 -0
  249. package/dist/provider/acp/register.d.ts +1 -0
  250. package/dist/provider/acp/runtime.d.ts +1 -0
  251. package/dist/provider/acp/types.d.ts +31 -4
  252. package/dist/provider/bridge.browser.d.ts +3 -0
  253. package/dist/provider/bridge.d.ts +25 -3
  254. package/dist/provider/classify-task-error.d.ts +2 -0
  255. package/dist/provider/claude-agent-env.d.ts +1 -0
  256. package/dist/provider/cli/adapter.types.d.ts +26 -2
  257. package/dist/provider/cli/adapters/agent-call.util.d.ts +1 -1
  258. package/dist/provider/cli/adapters/antigravity-stream.d.ts +27 -0
  259. package/dist/provider/cli/adapters/antigravity.d.ts +1 -0
  260. package/dist/provider/cli/adapters/cli-knob.util.d.ts +7 -0
  261. package/dist/provider/cli/adapters/codex-item.d.ts +1 -0
  262. package/dist/provider/cli/adapters/event-timestamp.util.d.ts +1 -0
  263. package/dist/provider/cli/adapters/grok.d.ts +2 -0
  264. package/dist/provider/cli/adapters/index.d.ts +5 -0
  265. package/dist/provider/cli/index.d.ts +3 -2
  266. package/dist/provider/cli/meta.d.ts +5 -0
  267. package/dist/provider/cli/protocol-envelope.d.ts +3 -0
  268. package/dist/provider/errors.d.ts +5 -1
  269. package/dist/provider/idle-watchdog.d.ts +19 -0
  270. package/dist/provider/models.d.ts +17 -12
  271. package/dist/provider/order.d.ts +1 -1
  272. package/dist/provider/parse-usage.d.ts +6 -0
  273. package/dist/provider/provider-selection.d.ts +8 -0
  274. package/dist/provider/redact-technical-message.d.ts +1 -0
  275. package/dist/provider/task-error.types.d.ts +17 -0
  276. package/dist/provider-account/accounts.d.ts +15 -0
  277. package/dist/provider-account/antigravity-acp/auth.d.ts +29 -0
  278. package/dist/provider-account/antigravity-acp/browser.d.ts +4 -0
  279. package/dist/provider-account/antigravity-acp/install.d.ts +42 -0
  280. package/dist/provider-account/antigravity-acp/lease.d.ts +23 -0
  281. package/dist/provider-account/antigravity-acp/lifecycle.d.ts +76 -0
  282. package/dist/provider-account/antigravity-acp/manifest.d.ts +76 -0
  283. package/dist/provider-account/antigravity-acp/profile.d.ts +4 -0
  284. package/dist/provider-account/capabilities.d.ts +6 -0
  285. package/dist/provider-account/index.d.ts +13 -0
  286. package/dist/provider-account/registry.d.ts +30 -0
  287. package/dist/provider-account/types.d.ts +47 -0
  288. package/dist/publish/constants.d.ts +6 -0
  289. package/dist/publish/errors.d.ts +7 -0
  290. package/dist/publish/index.d.ts +55 -0
  291. package/dist/publish/index.js +2 -0
  292. package/dist/publish/manifest.d.ts +47 -0
  293. package/dist/publish/marketplace-api.constants.d.ts +1 -0
  294. package/dist/publish/pack.d.ts +6 -0
  295. package/dist/publish/scan.d.ts +10 -0
  296. package/dist/publish/secrets.d.ts +6 -0
  297. package/dist/publish/upload.d.ts +19 -0
  298. package/dist/remote/execution-profile.d.ts +9 -0
  299. package/dist/remote/index.d.ts +1 -0
  300. package/dist/remote/types.d.ts +28 -0
  301. package/dist/repository/agent-send-history.repository.d.ts +23 -0
  302. package/dist/repository/agent-suggestion.repository.d.ts +34 -0
  303. package/dist/repository/base-sqlite-repository.d.ts +1 -0
  304. package/dist/repository/common-code.repository.d.ts +45 -0
  305. package/dist/repository/db.d.ts +13 -1
  306. package/dist/repository/index.d.ts +62 -6
  307. package/dist/repository/index.js +792 -207
  308. package/dist/repository/logs-db.d.ts +12 -0
  309. package/dist/repository/notification.repository.d.ts +58 -0
  310. package/dist/repository/project.repository.d.ts +90 -0
  311. package/dist/repository/public-task-answer.d.ts +24 -0
  312. package/dist/repository/request-log-mover.d.ts +70 -0
  313. package/dist/repository/request-log.repository.d.ts +7 -3
  314. package/dist/repository/run-columns.d.ts +10 -0
  315. package/dist/repository/run-history.repository.d.ts +112 -0
  316. package/dist/repository/schedule-run.repository.d.ts +103 -0
  317. package/dist/repository/sidebar-tab.repository.d.ts +86 -0
  318. package/dist/repository/storage-metadata.repository.d.ts +64 -0
  319. package/dist/repository/task-log-migration.d.ts +74 -0
  320. package/dist/repository/task-log.repository.d.ts +47 -0
  321. package/dist/repository/task-status.d.ts +21 -0
  322. package/dist/repository/task.repository.d.ts +330 -8
  323. package/dist/repository/thread-history.repository.d.ts +193 -0
  324. package/dist/repository/thread-origin-verdict.d.ts +27 -0
  325. package/dist/repository/thread-title.types.d.ts +29 -0
  326. package/dist/repository/thread.repository.d.ts +134 -5
  327. package/dist/repository/usage-backfill.d.ts +62 -0
  328. package/dist/repository/usage-from-logs.d.ts +22 -0
  329. package/dist/repository/workflow-anchor-kinds.d.ts +4 -0
  330. package/dist/repository/workspace.repository.d.ts +3 -0
  331. package/dist/route/decide.d.ts +54 -0
  332. package/dist/route/eligibility.d.ts +11 -0
  333. package/dist/route/errors.d.ts +11 -0
  334. package/dist/route/index.d.ts +14 -0
  335. package/dist/route/runner.d.ts +15 -0
  336. package/dist/route/sqlite-store.d.ts +17 -0
  337. package/dist/route/store.d.ts +45 -0
  338. package/dist/route/strategies.d.ts +4 -0
  339. package/dist/route/types.d.ts +212 -0
  340. package/dist/schema/agent-send-history.d.ts +85 -0
  341. package/dist/schema/agent-suggestions.d.ts +199 -0
  342. package/dist/schema/common-codes.d.ts +216 -0
  343. package/dist/schema/doc-sync-connect-requests.d.ts +140 -0
  344. package/dist/schema/doc-sync-links.d.ts +481 -0
  345. package/dist/schema/index.d.ts +21 -0
  346. package/dist/schema/model-routes.d.ts +581 -0
  347. package/dist/schema/notifications.d.ts +303 -0
  348. package/dist/schema/projects.d.ts +610 -0
  349. package/dist/schema/request-log-daily.d.ts +151 -0
  350. package/dist/schema/run-column-backfill.d.ts +81 -0
  351. package/dist/schema/schedule-runs.d.ts +451 -0
  352. package/dist/schema/sidebar-tabs.d.ts +466 -0
  353. package/dist/schema/storage-metadata.d.ts +181 -0
  354. package/dist/schema/task-log-events.d.ts +119 -0
  355. package/dist/schema/task-provider-inputs.d.ts +100 -0
  356. package/dist/schema/tasks.d.ts +1172 -1
  357. package/dist/schema/thread-creator-unverified.d.ts +45 -0
  358. package/dist/schema/thread-history.d.ts +734 -0
  359. package/dist/schema/threads.d.ts +59 -0
  360. package/dist/schema/ui-action-receipts.d.ts +358 -0
  361. package/dist/schema/ui-definition-archive.d.ts +63 -0
  362. package/dist/schema/ui-instance-repins.d.ts +222 -0
  363. package/dist/schema/ui-instances.d.ts +324 -0
  364. package/dist/schema/workspaces.d.ts +17 -0
  365. package/dist/skills/index.d.ts +15 -0
  366. package/dist/skills/index.js +2 -0
  367. package/dist/skills/types.d.ts +18 -0
  368. package/dist/task-log/anchor-child-tasks.d.ts +7 -0
  369. package/dist/task-log/delegation-trailer.d.ts +34 -0
  370. package/dist/template/engine.d.ts +2 -2
  371. package/dist/template/helpers/exec.browser.d.ts +4 -3
  372. package/dist/template/helpers/exec.d.ts +4 -3
  373. package/dist/template/helpers/format-conversation.d.ts +1 -0
  374. package/dist/template/types.d.ts +20 -0
  375. package/dist/testing/index.js +1 -1
  376. package/dist/types/index.d.ts +3493 -93
  377. package/dist/types/task-log.types.d.ts +6 -1
  378. package/dist/ui-card/index.d.ts +2 -0
  379. package/dist/ui-card/legacy-card-parser.d.ts +11 -0
  380. package/dist/ui-instance/definition.d.ts +6 -0
  381. package/dist/ui-instance/errors.d.ts +18 -0
  382. package/dist/ui-instance/index.d.ts +11 -0
  383. package/dist/ui-instance/json.d.ts +19 -0
  384. package/dist/ui-instance/lineage.d.ts +24 -0
  385. package/dist/ui-instance/runtime.d.ts +19 -0
  386. package/dist/ui-instance/store.d.ts +216 -0
  387. package/dist/ui-instance/types.d.ts +384 -0
  388. package/dist/ui-plugin/app-icon.d.ts +50 -0
  389. package/dist/ui-plugin/app-manifest.d.ts +64 -0
  390. package/dist/ui-plugin/csp.d.ts +28 -0
  391. package/dist/ui-plugin/index.d.ts +8 -0
  392. package/dist/ui-plugin/limits.d.ts +27 -0
  393. package/dist/ui-plugin/manifest.d.ts +3 -0
  394. package/dist/ui-plugin/types.d.ts +220 -0
  395. package/dist/ui-plugin/validator.d.ts +18 -0
  396. package/dist/utils/crewx-executable.d.ts +76 -0
  397. package/dist/utils/crewx-home.d.ts +1 -0
  398. package/dist/utils/env-defaults.d.ts +3 -0
  399. package/dist/utils/id.d.ts +1 -1
  400. package/dist/utils/local-identity.d.ts +2 -0
  401. package/dist/utils/runner-env.d.ts +3 -0
  402. package/dist/utils/timestamp.d.ts +1 -0
  403. package/dist/utils/workspace.d.ts +1 -0
  404. package/dist/wi/create.d.ts +48 -0
  405. package/dist/wi/select.d.ts +20 -0
  406. package/package.json +83 -3
  407. package/templates/agents/default.yaml +311 -128
  408. package/templates/documents/crewx-manual.md +138 -138
  409. package/templates/documents/crewx-quick-guide.md +8 -7
  410. package/templates/workflows/wi-default-flow.yaml +65 -0
  411. package/templates/workflows/wi-plan-flow.yaml +140 -0
@@ -0,0 +1 @@
1
+ import {spawnSync,spawn}from'child_process';var O=3e3;var b=2e3,g=25,L=100;function R(e){return e instanceof Error?e:e===void 0?void 0:new Error(String(e))}function y(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function S(e){return Number.isSafeInteger(e)&&e>0}function J(e){let r=e.trim();if(!r)return "";let n=/^(?:"([^"]+)"|'([^']+)')/.exec(r);return n?.[1]??n?.[2]??r.split(/\s+/,1)[0]??""}function B(e,r,n){let t=n==="win32"?e.toLowerCase():e,o=n==="win32"?r.toLowerCase():r;if(!o.trim())return false;if(o==="agy"){let s=J(e).split(/[\\/]/).pop()??"",i=n==="win32"?s.toLowerCase():s;return i==="agy"||n==="win32"&&(i==="agy.exe"||i==="agy.cmd")}return t.includes(o)}function h(e,r,n){return r.some(t=>B(e,t,n))}function x(e,r){try{let n=spawnSync(e,r,{encoding:"utf8",timeout:O,windowsHide:!0});return {status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",error:n.error}}catch(n){return {status:null,stdout:"",stderr:"",error:R(n)}}}function V(e,r){return new Promise(n=>{let t;try{t=spawn(e,r,{windowsHide:!0});}catch(a){n({status:null,stdout:"",stderr:"",error:R(a)});return}let o="",s="",i=false,u,m=setTimeout(()=>{try{t.kill();}catch{}u({status:null,stdout:o,stderr:s,error:new Error(`Command timed out after ${O}ms`)});},O);u=a=>{i||(i=true,clearTimeout(m),n(a));},t.stdout?.setEncoding("utf8"),t.stderr?.setEncoding("utf8"),t.stdout?.on("data",a=>{o+=String(a);}),t.stderr?.on("data",a=>{s+=String(a);}),t.once("error",a=>{u({status:null,stdout:o,stderr:s,error:a});}),t.once("close",a=>{u({status:a,stdout:o,stderr:s});});})}async function I(e,r,n){return n.runCommandAsync?n.runCommandAsync(e,r):n.runCommand?n.runCommand(e,r):V(e,r)}function G(e){return new Promise(r=>{setTimeout(r,Math.max(0,e));})}function E(){return new Promise(e=>{setImmediate(e);})}function w(e,r=process.kill){try{return r(e,0),"alive"}catch(n){return y(n)==="ESRCH"?"not_found":y(n)==="EPERM"?"alive":"unknown"}}function j(e,r){if(!S(e))return {status:"unknown"};let n=r.platform??process.platform,t=r.runCommand??x,o=n==="win32"?"powershell.exe":"ps",s=n==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${e}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(e),"-o","command="],i;try{i=t(o,s);}catch{return {status:"unknown"}}if(i.error||i.status!==0)return {status:"unknown"};let u=i.stdout.trim();return u?{status:"found",commandLine:u}:{status:"not_found"}}function z(e,r){let n=w(-e,r),t=w(e,r);return n==="alive"||t==="alive"?"alive":n==="unknown"||t==="unknown"?"unknown":"not_found"}async function v(e,r,n,t){let o=Math.max(0,n),s=Math.max(1,t.pollIntervalMs??g),i=Date.now()+o,u,m=o===0,a=t.sleep?Promise.resolve().then(()=>t.sleep(o)).then(()=>{},()=>{}):new Promise(c=>{u=setTimeout(c,o);});a.then(()=>{m=true;});try{for(await E();;){let c=z(e,r);if(c==="not_found")return c;let f=i-Date.now();if(m||f<=0)return c;await Promise.race([a,G(Math.min(s,f))]);}}finally{u!==void 0&&clearTimeout(u);}}async function k(e,r,n,t,o){let s=await v(e,r,o.hardConfirmMs??L,{...o,sleep:void 0});return s==="not_found"?n?{status:"not_found",pid:e,method:t}:{status:"terminated",pid:e,method:t}:s==="alive"?{status:"failed",pid:e,method:t,error:"Process is still running after termination attempt"}:{status:"failed",pid:e,method:t,error:"Unable to verify process termination"}}function q(e,r,n={}){let t=j(e,n);if(t.status!=="found")return t.status;let o=n.platform??process.platform;return h(t.commandLine,r,o)?"owned":"not_owned"}async function Y(e,r,n={}){if(!S(e))return "unknown";let t=n.platform??process.platform,o=t==="win32"?"powershell.exe":"ps",s=t==="win32"?["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${e}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write([string]$p.CommandLine) }`]:["-p",String(e),"-o","command="],i;try{i=await I(o,s,n);}catch{return "unknown"}if(i.error||i.status!==0)return "unknown";let u=i.stdout.trim();return u?h(u,r,t)?"owned":"not_owned":"not_found"}var Z=3e3,Q=/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/,ee=/^\s*(\d+)\s+(\S+)\s+(\S+)\s*$/,ne=/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-]\d{3})$/;function A(e){let r=Q.exec(e.trim());if(!r)return;let[,n="0",t="0",o="0",s="0"]=r;return ((Number(n)*24+Number(t))*60+Number(o))*60+Number(s)}function U(e){let r=e.trim(),n=ne.exec(r);if(n){let[,o,s,i,u,m,a,c,f]=n;return Date.UTC(Number(o),Number(s)-1,Number(i),Number(u),Number(m),Number(a),Math.trunc(Number(c)/1e3))-Number(f)*6e4}let t=Date.parse(r);return Number.isFinite(t)?t:void 0}function D(e,r){return r==="win32"?{command:"powershell.exe",args:["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",`$p = Get-CimInstance -ClassName Win32_Process -Filter 'ProcessId = ${e}' -ErrorAction Stop; if ($null -ne $p) { [Console]::Write($p.CreationDate.ToUniversalTime().ToString('o')) }`]}:{command:"ps",args:["-p",String(e),"-o","pgid=","-o","etime=","-o","stat="]}}function $(e,r,n){if(e.error)return {status:"unknown"};let t=e.stdout.trim();if(!t)return e.status===0||e.status===1?{status:"not_found"}:{status:"unknown"};if(e.status!==0)return {status:"unknown"};if(r==="win32"){let i=U(t);return i===void 0?{status:"unknown"}:{status:"found",startedAtMs:i,groupId:null}}let o=ee.exec(t),s=o?A(o[2]):void 0;return !o||s===void 0?{status:"unknown"}:o[3].startsWith("Z")?{status:"unknown"}:{status:"found",startedAtMs:n-s*1e3,groupId:Number(o[1])}}function re(e,r={}){if(!S(e))return {status:"unknown"};let n=r.platform??process.platform,{command:t,args:o}=D(e,n),s=r.runCommand??x,i;try{i=s(t,o);}catch{return {status:"unknown"}}return $(i,n,Date.now())}async function te(e,r={}){if(!S(e))return {status:"unknown"};let n=r.platform??process.platform,{command:t,args:o}=D(e,n),s;try{s=await I(t,o,r);}catch{return {status:"unknown"}}return $(s,n,Date.now())}async function oe(e,r={}){let n=r.platform??process.platform,t=n==="win32"?"taskkill":"process-group",o=l=>({status:"failed",pid:e,method:t,error:l});if(!S(e))return o("Invalid process ID");let s=r.kill??process.kill,i=w(e,s);if(i==="not_found")return {status:"not_found",pid:e,method:t};if(i!=="alive")return o("Unable to determine whether the process is alive");if(n==="win32"){let l;try{l=await I("taskkill",["/PID",String(e),"/T","/F"],r);}catch(P){l={status:null,stdout:"",stderr:"",error:R(P)};}let p=w(e,s);return p==="not_found"?l.status===0&&!l.error?{status:"terminated",pid:e,method:t}:{status:"not_found",pid:e,method:t}:o(p==="alive"?"Process is still running after termination attempt":"Unable to verify process termination")}let u,m=r.signal??"SIGKILL";try{s(-e,m);}catch(l){u=l;}if(m==="SIGKILL")return k(e,s,u,t,r);if(await v(e,s,r.graceMs??b,r)==="not_found")return u?{status:"not_found",pid:e,method:t}:{status:"terminated",pid:e,method:t};let c;try{s(-e,"SIGKILL");}catch(l){c=l;}let f=await k(e,s,c,t,r);return f.status==="terminated"?f:f.status==="not_found"?u?f:{status:"terminated",pid:e,method:t}:o(f.error??"Process termination failed")}var K=1e3,se=["SIGTERM","SIGINT","SIGHUP","SIGKILL"],ie=6e4,ue=100,ae=3e4,ce=1e3;function C(e,r,n){return Number.isFinite(e)&&e>=r&&e<=n}function de(e){return Number.isSafeInteger(e)&&e>1&&e!==process.pid}function N(e,r){try{return r(-e,0),"alive"}catch(n){let t=y(n);return t==="ESRCH"?"not_found":t==="EPERM"?"denied":"unknown"}}function M(e,r,n){try{return n(-e,r),"sent"}catch(t){let o=y(t);return o==="ESRCH"?"empty":o==="EPERM"?"denied":"failed"}}function _(){return performance.now()}async function T(e,r,n,t){let o=_()+n;for(;;){await E();let s=N(e,r);if(s==="not_found")return s;let i=o-_();if(i<=0)return s;await G(Math.min(t,i));}}async function me(e,r,n,t){for(;;){await E();let o=N(e,r);if(o==="not_found"||o==="alive")return o;let s=n-_();if(s<=0)return o;await G(Math.min(t,s));}}function d(e,r,n,t){return {status:r,groupId:e,...n?{lastSignal:n}:{},...t?{errorKind:t}:{}}}async function le(e,r={}){let n=r.signal??"SIGTERM",t=r.graceMs??b,o=r.hardConfirmMs??K,s=r.pollIntervalMs??g;if(!de(e))return d(e,"failed",void 0,"invalid_group_id");if(!se.includes(n)||!C(t,0,ie)||!C(o,ue,ae)||!C(s,1,ce))return d(e,"failed",void 0,"invalid_option");if((r.platform??process.platform)==="win32")return d(e,"unsupported",void 0,"unsupported_platform");let u=r.kill??process.kill,m=N(e,u);if(m==="not_found")return d(e,"exited");let a=t;if(m==="denied"&&n!=="SIGKILL"&&t>0){let p=_()+t,P=await me(e,u,p,s);if(P==="not_found")return d(e,"exited");if(P!=="alive")return d(e,"failed",void 0,P==="denied"?"probe_denied":"probe_failed");a=Math.max(0,p-_());}else if(m!=="alive")return d(e,"failed",void 0,m==="denied"?"probe_denied":"probe_failed");let c;if(n!=="SIGKILL"){let p=M(e,n,u);if(p==="empty")return d(e,"exited");if(p!=="sent")return d(e,"failed",void 0,p==="denied"?"signal_denied":"signal_failed");c=n;let P=await T(e,u,a,s);if(P==="not_found")return d(e,"exited",c);if(P!=="alive")return d(e,"failed",c,P==="denied"?"probe_denied":"probe_failed")}let f=M(e,"SIGKILL",u);if(f==="empty")return d(e,"exited",c);if(f!=="sent")return d(e,"failed",c,f==="denied"?"signal_denied":"signal_failed");c="SIGKILL";let l=await T(e,u,o,s);return l==="not_found"?d(e,"exited",c):l==="alive"?d(e,"failed",c,"still_running"):d(e,"failed",c,l==="denied"?"probe_denied":"probe_failed")}export{K as OWNED_GROUP_KILL_CONFIRM_MS,Z as PROCESS_START_TIME_TOLERANCE_MS,g as UNIX_PROCESS_POLL_INTERVAL_MS,L as UNIX_SIGKILL_CONFIRM_MS,b as UNIX_SIGTERM_GRACE_MS,q as checkProcessOwnership,Y as checkProcessOwnershipAsync,A as parseProcessElapsedSeconds,U as parseWindowsCreationDate,w as probeProcessLiveness,re as readProcessIdentity,te as readProcessIdentityAsync,le as terminateOwnedProcessGroup,oe as terminateProcessTree};
@@ -0,0 +1,2 @@
1
+ import*as pe from'path';import {resolve,relative,sep,isAbsolute,join}from'path';import'url';import*as $i from'crypto';import {createHash}from'crypto';import {isIP}from'net';import*as te from'fs';import {constants,readFileSync,existsSync,statSync,readdirSync}from'fs';import {realpath,stat,readdir,open,lstat}from'fs/promises';import*as ws from'js-yaml';import {load}from'js-yaml';import*as Vs from'os';import*as Hs from'tar';import {gunzipSync,gzipSync}from'zlib';var F=(e,n)=>()=>(e&&(n=e(e=0)),n);var m=F(()=>{});var C,zn=F(()=>{m();C=class extends Error{constructor(t,i=t,o){super(i);this.code=t;this.currentRevision=o;}code;currentRevision;name="UiRuntimeError"};});function Ct(e){return na.test(e)||ta.test(e)}function Ie(){throw new C("INPUT_INVALID","JSON value is not projection-safe")}function sa(e){let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Rt(e,n,t,i,o,r){if(n>i&&Ie(),e===null||typeof e=="string"||typeof e=="boolean")return typeof e=="string"&&(ia.test(e)||ra.test(e)&&!da(o,r)||oa.test(e))&&Ie(),e;if(typeof e=="number")return Number.isFinite(e)||Ie(),e;(typeof e!="object"||e===void 0||typeof e=="function"||typeof e=="bigint")&&Ie();let s=e;t.has(s)&&Ie(),t.add(s);try{if(Array.isArray(e))return e.map(c=>Rt(c,n+1,t,i,o,r));sa(s)||Ie();let a={};for(let[c,d]of Object.entries(e))Ct(c)&&Ie(),a[c]=Rt(d,n+1,t,i,[...o,c],r);return a}finally{t.delete(s);}}function ge(e,n=0,t=[]){(!Number.isInteger(n)||n<0||n>ca)&&Ie(),(!Array.isArray(t)||t.some(o=>typeof o!="string"))&&Ie();let i=Rt(e,0,new Set,aa+n,[],t);return (i===null||Array.isArray(i)||typeof i!="object")&&Ie(),i}function on(e,n){if(!e||!n)return false;let t=e.split("."),i=n.split(".");return t.length>=i.length&&i.every((o,r)=>t[r]===o)}function da(e,n){if(e.length===0)return false;let t=e.join(".");return n.some(i=>on(t,i))}function rn(e){try{let n=JSON.stringify(e);return n===void 0&&Ie(),n}catch{Ie();}}function wt(e){return Array.isArray(e)?e.map(wt):e!==null&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(n=>[n,wt(e[n])])):e}function ie(e){return rn(wt(e))}function Ut(e){return Buffer.byteLength(e,"utf8")}var na,ta,ia,oa,ra,aa,ca,Ue=F(()=>{m();zn();na=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,ta=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i,ia=/<\/?[A-Za-z][^>]*>/,oa=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,ra=/^(?:https?|file|ftp|ws|wss):\/\//i;aa=8,ca=4;});var Ki=F(()=>{m();Ue();});var $n,kt=F(()=>{m();$n=["text/plain","application/json"];});var Xi=F(()=>{m();kt();});function sn(e){return la.has(e)||ua.test(e)||fa.test(e)}var Yi,la,ua,fa,Gn,_n,Me,xt,vt,jt,Ft,Vt,We=F(()=>{m();Yi=["__proto__","prototype","constructor","proof","token","secret","password","cookie","authorization","private_key","private-key","stack","exception","plugin_text","url","uri","endpoint","path","filename","filepath","cwd","shell","directory","dir","folder"],la=new Set(Yi),ua=/(?:proof|token|secret|password|cookie|authorization|private[_-]?key|stack|exception|plugin[_-]?text)/i,fa=/(?:url|uri|endpoint|path|file(?:name|path)?|cwd|shell|directory|dir|folder)$/i;Gn=/^[A-Za-z0-9_]+$/,_n=/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/,Me=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,xt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,vt=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,jt=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/,Ft=["blue","violet","emerald","amber","rose","sky","slate","indigo"],Vt=["inline","panel"];});function Bt(e){return typeof e=="string"&&$n.includes(e)}var qi=F(()=>{m();kt();We();});function Jn(e){if(!Ht(e))return false;let n=Object.keys(e);return !(n.some(t=>t!=="in"&&t!=="out")||n.length===0||Object.hasOwn(e,"in")&&!ya(e.in)||Object.hasOwn(e,"out")&&!Aa(e.out))}function ya(e){return Ht(e)?Object.keys(e).every(t=>t==="mediaType"||t==="required")&&Object.hasOwn(e,"mediaType")&&Bt(e.mediaType)&&(!Object.hasOwn(e,"required")||typeof e.required=="boolean"):false}function Aa(e){return Ht(e)?Object.keys(e).every(t=>t==="mediaType"||t==="range")&&Object.hasOwn(e,"mediaType")&&Bt(e.mediaType)&&(!Object.hasOwn(e,"range")||typeof e.range=="boolean"):false}function Ht(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var zt=F(()=>{m();Xi();qi();new TextDecoder("utf-8",{fatal:true,ignoreBOM:true});});function Kn(e){return Ia.includes(e)}function Xn(e){return Number.isSafeInteger(e)&&e>=Wn.min&&e<=Wn.max}var Ia,Wn,Zi,$t=F(()=>{m();Ia=[5,15,30,60],Wn=Object.freeze({min:15e3,max:6e5,default:3e5}),Zi=1;});function qn(e){return Number.isSafeInteger(e)&&e>=Yn.min&&e<=Yn.max}function Zn(e){return ga.includes(e)}var Yn,Qi,ga,Gt=F(()=>{m();Yn=Object.freeze({min:6e4,max:18e5,default:6e5}),Qi=1,ga=["start","status","cancel"];});function fe(e){let t=e.renderer!==void 0||e.surfaces!==void 0||e.stateProjection!==void 0||e.dataPaths!==void 0||e.usage!==void 0||e.detailPanel!==void 0||e.displayModes!==void 0||e.summaryProjection!==void 0||e.downloads!==void 0||e.legacy!==void 0||Object.values(e.actions).some(o=>o.resultProjection!==void 0)?{id:e.id,version:e.version,...e.renderer===void 0?{}:{renderer:e.renderer},...e.surfaces===void 0?{}:{surfaces:e.surfaces},...e.stateProjection===void 0?{}:{stateProjection:e.stateProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.legacy===void 0?{}:{legacy:e.legacy},...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},...e.downloads===void 0?{}:{downloads:e.downloads},...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},actions:e.actions}:e.sourceHash===void 0?{id:e.id,version:e.version,actions:e.actions}:{id:e.id,version:e.version,sourceHash:e.sourceHash,actions:e.actions},i=ge(t);return createHash("sha256").update(ie(i)).digest("hex")}function Wt(e){return `${e.id}\0${e.version}`}function me(e){if(!/^\d+$/.test(String(e.version))||e.version<1||e.id.length<1||e.id.length>128)throw new C("DEFINITION_UNSUPPORTED","UI definition is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!ha.test(e.sourceHash)))throw new C("DEFINITION_UNSUPPORTED","UI definition source hash is invalid");if(!/^[0-9a-f]{64}$/.test(e.hash)||fe(e)!==e.hash)throw new C("DEFINITION_UNSUPPORTED","UI definition hash is invalid");for(let[n,t]of Object.entries(e.actions)){if(!n||!Array.isArray(t.capabilities)||t.capabilities.some(i=>!Ea(i)))throw new C("DEFINITION_UNSUPPORTED","UI action declaration is invalid");if(t.confirmation!==void 0&&t.confirmation!=="none"&&t.confirmation!=="native")throw new C("DEFINITION_UNSUPPORTED","UI action confirmation is invalid");if(t.mutation!==void 0&&typeof t.mutation!="boolean")throw new C("DEFINITION_UNSUPPORTED","UI action mutation policy is invalid");if(t.inputKeys&&(!Array.isArray(t.inputKeys)||t.inputKeys.some(i=>typeof i!="string"||!i)))throw new C("DEFINITION_UNSUPPORTED","UI action input declaration is invalid");if(t.dataInputs!==void 0&&(!Array.isArray(t.dataInputs)||new Set(t.dataInputs).size!==t.dataInputs.length||t.dataInputs.some(i=>typeof i!="string"||!i||t.inputKeys!==void 0&&!t.inputKeys.includes(i))))throw new C("DEFINITION_UNSUPPORTED","UI action data input declaration is invalid");if(t.resultProjection&&Jt(t.resultProjection),t.schedule!==void 0&&(!Kn(t.schedule.everyMinutes)||!Xn(t.schedule.timeoutMs)))throw new C("DEFINITION_UNSUPPORTED","UI action schedule declaration is invalid");if(t.job!==void 0&&(typeof t.job!="object"||Object.keys(t.job).some(i=>i!=="deadlineMs")||!qn(t.job.deadlineMs)))throw new C("DEFINITION_UNSUPPORTED","UI action job declaration is invalid");if(t.jobAccess!==void 0&&(!Array.isArray(t.jobAccess)||t.jobAccess.length===0||new Set(t.jobAccess).size!==t.jobAccess.length||!t.jobAccess.every(Zn)||t.job!==void 0))throw new C("DEFINITION_UNSUPPORTED","UI action job control declaration is invalid");if(t.content!==void 0&&!Jn(t.content))throw new C("DEFINITION_UNSUPPORTED","UI action content declaration is invalid");if(t.env!==void 0&&(!Array.isArray(t.env)||t.env.length===0||new Set(t.env).size!==t.env.length||t.env.some(i=>i!=="CREWX_APP_INSTANCE_ID"&&i!=="CREWX_THREAD_ID")))throw new C("DEFINITION_UNSUPPORTED","UI action environment declaration is invalid")}if(e.renderer!==void 0&&(!e.renderer||e.renderer.length>128))throw new C("DEFINITION_UNSUPPORTED","UI definition renderer is invalid");if(e.surfaces&&(!Array.isArray(e.surfaces)||e.surfaces.some(n=>!n||n.length>64)))throw new C("DEFINITION_UNSUPPORTED","UI definition surfaces are invalid");if(e.usage!==void 0&&e.usage!=="card"&&e.usage!=="window")throw new C("DEFINITION_UNSUPPORTED","UI definition usage is invalid");if(e.detailPanel!==void 0&&typeof e.detailPanel!="boolean")throw new C("DEFINITION_UNSUPPORTED","UI definition detailPanel is invalid");if(e.displayModes&&(!Array.isArray(e.displayModes)||e.displayModes.length===0||new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(n=>n!=="inline"&&n!=="floating"&&n!=="focused")))throw new C("DEFINITION_UNSUPPORTED","UI definition displayModes are invalid");if(e.usage==="card"&&e.displayModes!==void 0)throw new C("DEFINITION_UNSUPPORTED","Card definitions cannot declare displayModes");if(e.usage==="window"&&e.detailPanel!==void 0)throw new C("DEFINITION_UNSUPPORTED","Window definitions cannot declare detailPanel");if(e.stateProjection&&Jt(e.stateProjection),e.summaryProjection){Jt(e.summaryProjection);let n=new Set(e.stateProjection?.allow??[]);if(e.summaryProjection.allow.some(t=>!n.has(t)))throw new C("DEFINITION_UNSUPPORTED","UI summary projection exceeds state projection")}if(e.legacy!==void 0){if(!e.legacy||typeof e.legacy!="object"||Array.isArray(e.legacy)||Object.keys(e.legacy).some(o=>!["readTool","actionTool","hostTools","agentAccess"].includes(o)))throw new C("DEFINITION_UNSUPPORTED","UI legacy metadata is invalid");let n=new Set;for(let[o,r]of [["readTool",e.legacy.readTool],["actionTool",e.legacy.actionTool]])if(r!==void 0){if(_a(r,o==="readTool"),n.has(r.name))throw new C("DEFINITION_UNSUPPORTED","UI legacy tool names collide");n.add(r.name);}let t=e.legacy.hostTools;if(t!==void 0){if(!t||typeof t!="object"||Array.isArray(t))throw new C("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");let o={"doc.open":"crewx_app_html_viewer_open","pty.connect":"crewx_app_terminal_connect"};for(let[r,s]of Object.entries(t)){if(!Object.hasOwn(o,r)||o[r]!==s||typeof s!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(s)||n.has(s))throw new C("DEFINITION_UNSUPPORTED","UI legacy host tools are invalid");n.add(s);}}let i=e.legacy.agentAccess;if(i!==void 0&&(!i||typeof i!="object"||Array.isArray(i)||Object.entries(i).some(([o,r])=>!o||!Object.hasOwn(e.actions,o)||r!=="allowed"&&r!=="denied")))throw new C("DEFINITION_UNSUPPORTED","UI legacy agent access is invalid");if(e.legacy.actionTool!==void 0&&(!i||Object.keys(i).length===0))throw new C("DEFINITION_UNSUPPORTED","UI legacy action tool requires its complete agent access map")}if(e.downloads!==void 0&&e.downloads!==true)throw new C("DEFINITION_UNSUPPORTED","UI definition downloads is invalid");if(e.dataPaths!==void 0){let n=new Set(["__proto__","prototype","constructor"]);if(!Array.isArray(e.dataPaths)||e.dataPaths.length>16||new Set(e.dataPaths).size!==e.dataPaths.length||e.dataPaths.some(t=>typeof t!="string"||!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(t)||t.split(".").some(i=>n.has(i))||!(e.stateProjection?.allow??[]).some(i=>on(t,i))))throw new C("DEFINITION_UNSUPPORTED","UI definition dataPaths are invalid")}}function _a(e,n){if(!e||typeof e!="object"||Array.isArray(e))throw new C("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");let t=e,i=["name","description","inputSchema","textFallback","visibility"],o=Object.hasOwn(t,"fixedResult");if(Object.keys(t).some(r=>!i.includes(r)&&!(n&&r==="fixedResult"))||i.some(r=>!Object.hasOwn(t,r))||typeof t.name!="string"||!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(t.name)||typeof t.description!="string"||t.description.trim().length===0||t.description.length>8192||typeof t.textFallback!="string"||t.textFallback.trim().length===0||t.textFallback.length>16384||!t.inputSchema||typeof t.inputSchema!="object"||Array.isArray(t.inputSchema)||!Array.isArray(t.visibility)||t.visibility.length===0||t.visibility.some(r=>r!=="model"&&r!=="app")||new Set(t.visibility).size!==t.visibility.length)throw new C("DEFINITION_UNSUPPORTED","UI legacy tool metadata is invalid");try{let r=ge(t.inputSchema);if(r.type!==void 0&&r.type!=="object")throw new Error("schema type");if(o){if(!n)throw new Error("fixed result location");let s=t.fixedResult;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("fixed result");let a=s;if(Object.keys(a).sort().join(",")!=="argsPolicy,structuredContent"||a.argsPolicy!=="empty-only"&&a.argsPolicy!=="ignore"||!a.structuredContent||typeof a.structuredContent!="object"||Array.isArray(a.structuredContent))throw new Error("fixed result");let c=ge(a.structuredContent);if(Ut(rn(c))>4*1024)throw new Error("fixed result size")}}catch{throw new C("DEFINITION_UNSUPPORTED","UI legacy tool metadata is not projection-safe")}}function Jt(e){if(!Array.isArray(e.allow)||e.allow.some(n=>!/^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/.test(n)))throw new C("DEFINITION_UNSUPPORTED","UI projection policy is invalid")}function Ea(e){return e.length>0&&e.length<=128&&e!=="*"&&e!=="all"&&!/[/*]/.test(e)}var ha,Ke=F(()=>{m();Ue();zn();zt();$t();Gt();ha=/^[0-9a-f]{64}$/;});var G,ke,Kt=F(()=>{m();G="dist/tools.json",ke="dist/main.mjs";});var Le,eo,oe,an=F(()=>{m();Le="view.call",eo="crewxImage",oe="window";});function no(e){if(!Array.isArray(e)||e.length===0)return false;let n=new Set;for(let t of e){if(!Ta.some(i=>i===t)||n.has(t))return false;n.add(t);}return true}var Ta,to=F(()=>{m();Ta=["CREWX_APP_INSTANCE_ID","CREWX_THREAD_ID"];});function W(e){throw new Xt(e)}function Ua(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function ka(e,n){let t=Object.getOwnPropertyDescriptor(e,n);return (!t||!("value"in t))&&W("CSP_ORIGIN_INVALID"),t.value}function Qn(e,n){if(!Object.prototype.hasOwnProperty.call(e,n))return [];let t=ka(e,n);Array.isArray(t)||W("CSP_ORIGIN_INVALID"),Reflect.ownKeys(t).some(r=>typeof r!="string"||r!=="length"&&!/^(?:0|[1-9][0-9]*)$/.test(r))&&W("CSP_ORIGIN_INVALID");let o=[];for(let r=0;r<t.length;r+=1)(!Object.prototype.hasOwnProperty.call(t,r)||typeof t[r]!="string")&&W("CSP_ORIGIN_INVALID"),o.push(t[r]);return Object.keys(t).length!==t.length&&W("CSP_ORIGIN_INVALID"),o}function xa(e){let n;try{n=JSON.stringify(e);}catch{W("CSP_ORIGIN_INVALID");}return n===void 0&&W("CSP_ORIGIN_INVALID"),new TextEncoder().encode(n).byteLength}function ro(e,n){/\s|\\/u.test(e)&&W("CSP_ORIGIN_INVALID");let t=La.exec(e);t||W("CSP_ORIGIN_INVALID");let i=t[1].toLowerCase(),o=t[2];(o.includes("@")||o.includes("%")||o.includes("*"))&&W("CSP_ORIGIN_INVALID"),(o.startsWith("[")?Oa:Ra).test(o)||W("CSP_ORIGIN_INVALID"),i==="wss"&&n!=="connectDomains"&&W("CSP_ORIGIN_INVALID");let s;try{s=new URL(e);}catch{W("CSP_ORIGIN_INVALID");}(s.protocol!==`${i}:`||s.username!==""||s.password!==""||s.search!==""||s.hash!=="")&&W("CSP_ORIGIN_INVALID");let a=s.hostname.toLowerCase();if((!a||a.includes("%"))&&W("CSP_ORIGIN_INVALID"),!a.startsWith("[")){let d=a.endsWith(".")?a.slice(0,-1):a;(d.length===0||d.length>253)&&W("CSP_ORIGIN_INVALID"),d.split(".").some(p=>p.length>63||!wa.test(p))&&W("CSP_ORIGIN_INVALID");}let c=s.origin;return (c==="null"||!c.startsWith(`${i}://`))&&W("CSP_ORIGIN_INVALID"),{origin:c,hostname:a}}function va(e){let n=e.split(".").map(Number);return ((n[0]*256+n[1])*256+n[2])*256+n[3]}function so(e,n,t){let i=4294967295<<32-t>>>0;return (e&i)===(n&i)}function po(e){let n=va(e);return so(n,3221225472,24)?n!==3221225481&&n!==3221225482:Ca.some(([t,i])=>so(n,t,i))}function ja(e){let n=e.indexOf("::"),t=(n<0?e:e.slice(0,n)).split(":").filter(Boolean),i=n<0?[]:e.slice(n+2).split(":").filter(Boolean);return (n<0?t:[...t,...Array(8-t.length-i.length).fill("0"),...i]).reduce((r,s)=>r<<16n|BigInt(Number.parseInt(s,16)),0n)}function Fa(e){let n=ja(e),t=Number(n>>112n),i=Number(n>>96n&0xffffn);if(n>>32n===0xffffn){let o=Number(n&0xffffffffn);return po([o>>>24&255,o>>>16&255,o>>>8&255,o&255].join("."))}return t<8192||t>16383||t===8193&&i<=511||t===8193&&i===3512||t===8194||t===16383&&i<=4095}function Va(e,n){let t=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,i=isIP(t);if(i===4)return po(t);if(i===6)return Fa(t);let o=e.toLowerCase().replace(/\.$/,"");return !o||!o.includes(".")||n.has(o)?true:Ma.some(r=>o===r||o.endsWith(`.${r}`))}function ao(e){return Object.freeze([...new Set(e.map(n=>n.origin))].sort())}function co(e){return JSON.stringify({baseUriDomains:[],connectDomains:e.connectDomains,declared:e.declared,frameDomains:e.frameDomains,resourceDomains:[]})}function lo(e,n={}){if(e===void 0){let y=co({declared:false,connectDomains:[],frameDomains:[]});return Object.freeze({declared:false,connectDomains:Object.freeze([]),frameDomains:Object.freeze([]),resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(y,"utf8").digest("hex")})}Ua(e)||W("CSP_ORIGIN_INVALID");let t=Reflect.ownKeys(e);t.some(y=>typeof y!="string")&&W("CSP_ORIGIN_INVALID"),t.some(y=>!Sa.has(y))&&W("CSP_AXIS_UNKNOWN");let i=Qn(e,"connectDomains"),o=Qn(e,"frameDomains"),r=Qn(e,"resourceDomains"),s=Qn(e,"baseUriDomains");(r.length>0||s.length>0)&&W("CSP_AXIS_UNSUPPORTED"),(xa(e)>Pa||i.length>oo||o.length>oo||i.length+o.length>Na||[...i,...o].some(y=>new TextEncoder().encode(y).byteLength>Da))&&W("CSP_LIMIT_EXCEEDED");let c=i.map(y=>ro(y,"connectDomains")),d=o.map(y=>ro(y,"frameDomains")),l=new Set((n.runtimeHostnames??[]).map(y=>y.toLowerCase().replace(/\.$/,"")));[...c,...d].some(y=>Va(y.hostname,l))&&W("CSP_ORIGIN_FORBIDDEN");let p={declared:true,connectDomains:ao(c),frameDomains:ao(d)},f=co(p);return Object.freeze({...p,resourceDomains:Object.freeze([]),baseUriDomains:Object.freeze([]),cspHash:createHash("sha256").update(f,"utf8").digest("hex")})}var Pa,oo,Na,Da,Sa,Ma,La,Oa,Ra,wa,Ca,Xt,uo=F(()=>{m();Pa=4096,oo=16,Na=32,Da=512,Sa=new Set(["connectDomains","frameDomains","resourceDomains","baseUriDomains"]),Ma=["localhost","local","internal","home.arpa","test","example","invalid","onion","lan","corp","home","intranet","private","localdomain"],La=/^(https|wss):\/\/([^/?#]+)$/i,Oa=/^\[[^\]]+\](?::[0-9]+)?$/,Ra=/^[^:\[\]]+(?::[0-9]+)?$/,wa=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Ca=[[0,8],[1681915904,10],[167772160,8],[2130706432,8],[2851995648,16],[2886729728,12],[3221225984,24],[3227017984,24],[3232235520,16],[3323068416,15],[3325256704,24],[3405803776,24],[3758096384,4],[4026531840,4]],Xt=class extends Error{constructor(t){super(t);this.code=t;}code;name="UiPluginCspNormalizationError"};});function Tn(e,n){return n===void 0||n===""?e:e===""?n:n.startsWith("[")?`${e}${n}`:`${e}.${n}`}function u(e,n=e,t,i){throw new de(e,n,t,i)}function $(e,n){try{return n()}catch(t){throw t instanceof de?t.withPathPrefix(e):t}}function J(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function w(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function _c(e,n){let t={};for(let[i,o]of Object.entries(e))n.includes(i)||(t[i]=o);return t}function X(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e).find(s=>!i.has(s));o!==void 0&&u("MANIFEST_INVALID","MANIFEST_INVALID",o,"unknown-key");let r=n.find(s=>!w(e,s));r!==void 0&&u("MANIFEST_INVALID","MANIFEST_INVALID",r,"missing-key");}function it(e,n=false,t=false,i=false){return $a.test(e)||!i&&Ja.test(e)||Ga.test(e)||t&&fo.test(e)||Wa.test(e)&&!(n&&/^\s*data:/i.test(e)&&!fo.test(e))}function tt(e,n=new Set,t=0,i=false,o=false,r=""){if(typeof e=="string"){it(e,i,o)&&u("UNSAFE_VALUE","UNSAFE_VALUE",r,"unsafe-value");return}if(!(e===null||typeof e!="object")){(t>8||n.has(e))&&u("MANIFEST_INVALID","MANIFEST_INVALID",r),n.add(e);try{if(Array.isArray(e)){e.forEach((s,a)=>tt(s,n,t+1,!1,!1,Tn(r,`[${a}]`)));return}J(e)||u("MANIFEST_INVALID","MANIFEST_INVALID",r);for(let[s,a]of Object.entries(e))tt(a,n,t+1,i&&t===0&&(s==="name"||s==="description"),o,Tn(r,s));}finally{n.delete(e);}}}function Oe(e,n){let t=e[n];return typeof t!="string"&&u("MANIFEST_INVALID"),t}function Ee(e,n,t){let i=e[n];return (!Number.isSafeInteger(i)||i<t)&&u("MANIFEST_INVALID"),i}function Yt(e){return za.test(e)||u("MANIFEST_INVALID"),e}function cn(e){return Ha.test(e)||u("TOKEN_INVALID"),e}function Ec(e){return So.test(e)||u("MANIFEST_INVALID"),e}function Tc(e){J(e)||u("MANIFEST_INVALID");let n={};for(let[t,i]of Object.entries(e)){let o=Ec(t);J(i)||u("MANIFEST_INVALID");let r=i.type;if(r==="text"){X(i,["type","maxLength"]),n[o]={type:r,maxLength:Ee(i,"maxLength",1)};continue}if(r==="text-list"){X(i,["type","max","itemMaxLength"]),n[o]={type:r,max:Ee(i,"max",0),itemMaxLength:Ee(i,"itemMaxLength",1)};continue}if(r==="step-list"){X(i,["type","min","max","labelMaxLength","detailMaxLength"]);let s=Ee(i,"min",0),a=Ee(i,"max",1);s>a&&u("MANIFEST_INVALID"),n[o]={type:r,min:s,max:a,labelMaxLength:Ee(i,"labelMaxLength",1),detailMaxLength:Ee(i,"detailMaxLength",1)};continue}typeof r=="string"&&u("SCHEMA_TYPE_UNSUPPORTED"),u("MANIFEST_INVALID");}return n}function bc(e,n,t){let i=e[n];(!i||i.type!==t)&&u("MANIFEST_INVALID");}function et(e,n,t){let i=Oe(e,"field");return So.test(i)||u("MANIFEST_INVALID"),bc(n,i,t),i}function Pc(e,n){J(e)||u("MANIFEST_INVALID");let t=e.primitive;switch(typeof t!="string"&&u("MANIFEST_INVALID"),hc.includes(t)||u("PRIMITIVE_UNKNOWN"),t){case "card-shell":return X(e,["primitive"]),{primitive:t};case "meta-banner":return X(e,["primitive","badgeToken","noticeToken"]),{primitive:t,badgeToken:cn(Oe(e,"badgeToken")),noticeToken:cn(Oe(e,"noticeToken"))};case "heading":return X(e,["primitive","field"]),{primitive:t,field:et(e,n,"text")};case "labeled-text":return X(e,["primitive","titleToken","field","variant"]),e.variant!=="callout"&&u("MANIFEST_INVALID"),{primitive:t,titleToken:cn(Oe(e,"titleToken")),field:et(e,n,"text"),variant:"callout"};case "step-flow":return X(e,["primitive","titleToken","field"]),{primitive:t,titleToken:cn(Oe(e,"titleToken")),field:et(e,n,"step-list")};case "text-list":{X(e,["primitive","titleToken","field"],["emptyToken","hideWhenEmpty"]);let i={primitive:t,titleToken:cn(Oe(e,"titleToken")),field:et(e,n,"text-list")};return w(e,"emptyToken")&&(i.emptyToken=cn(Oe(e,"emptyToken"))),w(e,"hideWhenEmpty")&&(typeof e.hideWhenEmpty!="boolean"&&u("MANIFEST_INVALID"),i.hideWhenEmpty=e.hideWhenEmpty),i}}return u("MANIFEST_INVALID")}function Nc(e,n){return Array.isArray(e)||u("MANIFEST_INVALID"),e.map(t=>Pc(t,n))}function q(e="v2 manifest exceeds a contract limit",n,t){return u("LIMIT_EXCEEDED",e,n,t)}function he(e="initial state is not projection-safe"){return u("INITIAL_STATE_INVALID",e)}function yo(e,n){return (typeof e!="string"||e.length===0||e.length>4096||e.trim().length===0||fc.test(e)||yc.test(e))&&u("MANIFEST_INVALID",`${n} is invalid`),(it(e,true,true)||Ka.test(e)||Xa.test(e)||Ya.test(e))&&u("UNSAFE_VALUE",`${n} contains an unsafe value`),e}function qt(e,n){return (typeof e!="string"||!Me.test(e))&&u("MANIFEST_INVALID",`${n} is invalid`),e}function Dc(e){return (typeof e!="string"||!xt.test(e)||e==="*"||e==="all")&&u("MANIFEST_INVALID","action capability is invalid"),e}function Mo(e){return (typeof e!="string"||!uc.test(e))&&u("MANIFEST_INVALID","resource hash is invalid"),e}function Zt(e,n=new Set,t=0,i=""){if(typeof e=="string"){e.length>4096&&q("v2 manifest string is too long",i,"string-too-long");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||u("MANIFEST_INVALID","v2 manifest contains a non-finite number",i,"non-finite-number");return}(e===void 0||typeof e=="function"||typeof e=="bigint")&&u("MANIFEST_INVALID","v2 manifest contains a non-JSON value",i,"non-json-value"),typeof e!="object"&&u("MANIFEST_INVALID","MANIFEST_INVALID",i),t>8&&q("v2 manifest nesting is too deep",i,"too-deep"),n.has(e)&&u("MANIFEST_INVALID","v2 manifest contains a cycle",i,"cycle"),n.add(e);try{if(Array.isArray(e)){e.length>128&&q("v2 manifest array is too long",i,"array-too-long"),e.forEach((o,r)=>Zt(o,n,t+1,Tn(i,`[${r}]`)));return}J(e)||u("MANIFEST_INVALID","v2 manifest contains a non-plain object",i,"non-plain-object");for(let[o,r]of Object.entries(e))Zt(r,n,t+1,Tn(i,o));}finally{n.delete(e);}}}function Lo(e){return (typeof e!="string"||e.length>4096||!_n.test(e))&&(typeof e=="string"&&e.length>4096&&q("projection path is too long"),u("MANIFEST_INVALID","projection paths must be canonical exact paths")),e.split(".").some(t=>sn(t)||t===eo)&&u("MANIFEST_INVALID","projection paths cannot address reserved state keys"),e}function Qt(e){J(e)||u("MANIFEST_INVALID","projection policy must be an object"),X(e,["allow"]),Array.isArray(e.allow)||u("MANIFEST_INVALID","projection allow must be an array"),e.allow.length>128&&q("projection allowlist is too long");let n=[],t=new Set;for(let i of e.allow){let o=Lo(i);t.has(o)&&u("MANIFEST_INVALID","projection allowlist contains a duplicate path"),t.add(o),n.push(o);}return {allow:n}}function Sc(e,n){if(e===void 0)return;Array.isArray(e)||u("MANIFEST_INVALID","dataPaths must be an array"),e.length>Ac&&q("dataPaths exceed the v2 limit");let t=[],i=new Set;for(let o of e){let r=Lo(o);i.has(r)&&u("MANIFEST_INVALID","dataPaths contain a duplicate path"),n.some(s=>on(r,s))||u("MANIFEST_INVALID","dataPaths must be projection-allowed"),i.add(r),t.push(r);}return t}function Mc(e){Array.isArray(e)||u("MANIFEST_INVALID","deviceFeatures must be an array",void 0,"array"),e.length>Ic&&u("MANIFEST_INVALID","deviceFeatures allow at most 16 names",void 0,"too-many-items");let n=[],t=new Set;for(let[i,o]of e.entries()){let r=`[${i}]`;typeof o!="string"&&u("MANIFEST_INVALID","a device feature name must be a string",r,"string"),o.length===0&&u("MANIFEST_INVALID","a device feature name must not be empty",r,"empty"),o.length>gc&&u("MANIFEST_INVALID","a device feature name is at most 32 characters",r,"too-long"),mc.test(o)||u("MANIFEST_INVALID","a device feature name starts with a lowercase letter and holds only letters and digits",r,"format"),t.has(o)&&u("MANIFEST_INVALID","deviceFeatures contain a duplicate name",r,"duplicate-item"),t.add(o),n.push(o);}return n}function Lc(e){if(e!==false)return e!==true&&u("MANIFEST_INVALID","downloads must be true or false",void 0,"boolean"),true}function Oc(e){return typeof e!="boolean"&&u("MANIFEST_INVALID","desktopOnly must be true or false",void 0,"boolean"),e}function Rc(e){return (!J(e)||e.view!==true||Object.keys(e).some(n=>n!=="view"&&n!=="entry"))&&u("MANIFEST_INVALID",'share must be { "view": true } or { "view": true, "entry": "<path>" }',void 0,"share-shape"),w(e,"entry")?{view:true,entry:Cc(e.entry)}:{view:true}}function Cc(e){typeof e!="string"&&u("MANIFEST_INVALID","share.entry must be a string","entry","entry-shape");let n=(i,o)=>u("MANIFEST_INVALID",`share.entry ${o}`,"entry",i);e.length===0&&n("empty","must not be empty"),e.length>Ao&&n("too-long",`must be at most ${Ao} characters`),e.startsWith("/")&&n("absolute","must be relative to the App folder");let t=e.split("/");t.length>Io&&n("too-many-segments",`must have at most ${Io} segments`);for(let i of t)i.length===0&&n("empty-segment","must not contain an empty segment"),(i==="."||i==="..")&&n("dot-segment",'must not contain "." or ".." segments'),wc.test(i)||n("segment-shape",'segments start with an ASCII letter or digit, then use only letters, digits, ".", "_" and "-"');return t[t.length-1].endsWith(".html")||n("extension","must name a file ending in .html"),e}function Uc(e){return (!J(e)||Object.keys(e).length!==1||typeof e.root!="string")&&u("MANIFEST_INVALID",'files must be exactly { "root": "<workspace folder>" }',void 0,"files-shape"),{root:Fc(e.root)}}function Fc(e){let n=e.normalize("NFC"),t=(r,s)=>u("MANIFEST_INVALID",`files.root ${s}`,"root",r);n.length===0&&t("empty","must not be empty"),jc.test(n)&&t("forbidden-character","must not contain control characters, backslash or colon"),(n.startsWith("/")||n.startsWith("~"))&&t("absolute","must be relative to the workspace"),Array.from(n).length>go&&t("too-long",`must be at most ${go} characters`);let i=n.split("/"),o=i[0].toLowerCase().replace(/[. ]+$/,"");vc.includes(o)&&t("reserved-folder","must not start in an App code folder or a tool folder"),i.length<kc&&t("too-shallow","must name a folder inside a top-level folder, such as docs/trips"),i.length>mo&&t("too-many-segments",`must have at most ${mo} segments`);for(let r of i)r.length===0&&t("empty-segment","must not contain an empty segment"),(r==="."||r==="..")&&t("dot-segment",'must not contain "." or ".." segments'),Array.from(r).length>ho&&t("segment-too-long",`segments must be at most ${ho} characters`),xc.test(r)||t("segment-shape",'segments must start with a letter or digit and contain only letters, digits, combining marks, "_" or "-"');return n}function dn(e,n,t=Number.MAX_SAFE_INTEGER){return (!Number.isSafeInteger(e)||e<0||e>t)&&u("MANIFEST_INVALID",`${n} is invalid`),e}function _o(e,n){return (typeof e!="number"||!Number.isFinite(e))&&u("MANIFEST_INVALID",`${n} is invalid`),e}function ei(e,n=0,t=new Set){if(typeof e=="string")return (e.length>4096||it(e))&&u("UNSAFE_VALUE","schema enum contains an unsafe string"),e;if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||u("MANIFEST_INVALID","schema enum contains a non-finite number"),e;(n>8||typeof e!="object"||e===void 0)&&q("schema enum is too deep"),t.has(e)&&u("MANIFEST_INVALID","schema enum contains a cycle"),t.add(e);try{if(Array.isArray(e))return e.length>128&&q("schema enum array is too long"),e.map(o=>ei(o,n+1,t));J(e)||u("MANIFEST_INVALID","schema enum contains a non-plain object");let i={};for(let[o,r]of Object.entries(e))sn(o)&&u("MANIFEST_INVALID","schema enum contains a reserved key"),i[o]=ei(r,n+1,t);return i}finally{t.delete(e);}}function Vc(e,n){if(e===void 0)return;Array.isArray(e)||u("MANIFEST_INVALID","schema required must be an array"),e.length>64&&q("schema required list is too long");let t=[],i=new Set;for(let o of e)(typeof o!="string"||!_n.test(o))&&u("MANIFEST_INVALID","schema required contains an invalid key"),o.length>4096&&q("schema required key is too long"),i.has(o)&&u("MANIFEST_INVALID","schema required contains a duplicate key"),n&&!Object.prototype.hasOwnProperty.call(n,o)&&u("MANIFEST_INVALID","schema required references an undeclared property"),i.add(o),t.push(o);return t}function Bc(e,n){let t=n?_n:Gn;return e.length>4096&&q("schema property name is too long"),(!t.test(e)||e.split(".").some(i=>sn(i)))&&u("MANIFEST_INVALID","schema property name is invalid"),e}function ni(e,n=0,t=false){J(e)||u("MANIFEST_INVALID","action inputSchema must be an object"),n>8&&q("action inputSchema is too deep");let i=e.type;i!=="object"&&i!=="string"&&i!=="number"&&i!=="integer"&&i!=="boolean"&&i!=="array"&&i!=="null"&&(typeof i=="string"&&u("SCHEMA_TYPE_UNSUPPORTED","action inputSchema type is unsupported"),u("MANIFEST_INVALID","action inputSchema type is required"));let o=["type","enum"];i==="string"&&o.push("minLength","maxLength"),i==="array"&&o.push("minItems","maxItems","items"),i==="object"&&o.push("minProperties","maxProperties","properties","required","additionalProperties"),(i==="number"||i==="integer")&&o.push("minimum","maximum"),X(e,["type"],o.filter(a=>a!=="type"));let r={type:i};if(w(e,"enum")&&(Array.isArray(e.enum)||u("MANIFEST_INVALID","schema enum must be an array"),e.enum.length>128&&q("schema enum is too long"),r.enum=e.enum.map(a=>ei(a))),i==="string"&&(w(e,"minLength")&&(r.minLength=dn(e.minLength,"schema minLength",4096)),w(e,"maxLength")&&(r.maxLength=dn(e.maxLength,"schema maxLength",4096)),r.minLength!==void 0&&r.maxLength!==void 0&&r.minLength>r.maxLength&&u("MANIFEST_INVALID","schema string length bounds are inverted")),(i==="number"||i==="integer")&&(w(e,"minimum")&&(r.minimum=_o(e.minimum,"schema minimum")),w(e,"maximum")&&(r.maximum=_o(e.maximum,"schema maximum")),r.minimum!==void 0&&r.maximum!==void 0&&r.minimum>r.maximum&&u("MANIFEST_INVALID","schema numeric bounds are inverted")),i==="array"&&(w(e,"minItems")&&(r.minItems=dn(e.minItems,"schema minItems",128)),w(e,"maxItems")&&(r.maxItems=dn(e.maxItems,"schema maxItems",128)),r.minItems!==void 0&&r.maxItems!==void 0&&r.minItems>r.maxItems&&u("MANIFEST_INVALID","schema array length bounds are inverted"),w(e,"items")&&(r.items=ni(e.items,n+1,false))),i==="object"){let a;if(w(e,"properties")){J(e.properties)||u("MANIFEST_INVALID","schema properties must be an object");let d=Object.entries(e.properties);d.length>64&&q("schema properties are too many"),a={};for(let[l,p]of d){let f=Bc(l,t);a[f]=ni(p,n+1,false);}r.properties=a;}w(e,"minProperties")&&(r.minProperties=dn(e.minProperties,"schema minProperties",64)),w(e,"maxProperties")&&(r.maxProperties=dn(e.maxProperties,"schema maxProperties",64)),r.minProperties!==void 0&&r.maxProperties!==void 0&&r.minProperties>r.maxProperties&&u("MANIFEST_INVALID","schema object property bounds are inverted");let c=Vc(e.required,a);c!==void 0&&(r.required=c),w(e,"additionalProperties")&&(e.additionalProperties!==false&&u("MANIFEST_INVALID","schema additionalProperties must be false"),r.additionalProperties=false);}let s=JSON.stringify(r);return (s===void 0||Buffer.byteLength(s,"utf8")>2097152)&&q("action inputSchema subtree is too large"),r}function Hc(e){let n=ni(e,0,true);return (n.type!=="object"||!n.properties)&&u("MANIFEST_INVALID","action inputSchema must declare object properties"),n}function zc(e){if(J(e)||u("MANIFEST_INVALID","action backend must be an object"),e.type==="core"){X(e,sc);let n=e.handler;return (typeof n!="string"||!vt.test(n))&&u("MANIFEST_INVALID","core backend handler is invalid"),{type:"core",handler:n}}if(e.type==="skill"&&w(e,"entry"))return X(e,dc),e.entry!==ke&&u("MANIFEST_INVALID",`skill backend entry must be ${ke}`),{type:"skill",entry:ke};if(e.type==="skill"){X(e,ac,cc),(!Array.isArray(e.command)||e.command.length===0||e.command.length>16)&&u("MANIFEST_INVALID","skill backend command is invalid");let n=[];for(let i of e.command)(typeof i!="string"||i.length===0||i.length>256||!jt.test(i))&&u("MANIFEST_INVALID","skill backend command token is invalid"),n.push(i);let t=w(e,"env")?Xc(e.env):void 0;return {type:"skill",command:n,...t===void 0?{}:{env:t}}}u("MANIFEST_INVALID","action backend type is unsupported");}function $c(e){J(e)||u("MANIFEST_INVALID","action must be an object"),X(e,ec,nc),w(e,"_meta")&&$("_meta",()=>Oo(e._meta));let n=$("actionId",()=>qt(e.actionId,"actionId"));Ct(n)&&u("MANIFEST_INVALID",`actionId "${n}" is not projection-safe`,"actionId");let t=$("capability",()=>Dc(e.capability)),i=e.mutation;typeof i!="boolean"&&u("MANIFEST_INVALID","action mutation must be boolean","mutation");let o=$("inputSchema",()=>Hc(e.inputSchema)),r;if(w(e,"dataInputs")){Array.isArray(e.dataInputs)||u("MANIFEST_INVALID","action dataInputs must be an array","dataInputs");let y=o.properties,g=new Set,_=[];for(let E of e.dataInputs)(typeof E!="string"||!w(y,E)||g.has(E))&&u("MANIFEST_INVALID","action dataInputs must be unique declared properties","dataInputs"),g.add(E),_.push(E);r=_;}let s=$("resultProjection",()=>Qt(e.resultProjection)),a=$("backend",()=>zc(e.backend)),c;w(e,"content")&&((a.type!=="skill"||!Jn(e.content))&&u("MANIFEST_INVALID","action content declaration is invalid","content"),c=Yc(e.content));let d;if(w(e,"confirmation")){let y=e.confirmation;y!=="none"&&y!=="native"&&u("MANIFEST_INVALID","action confirmation is invalid","confirmation"),d=y;}let l;w(e,"schedule")&&(l=$("schedule",()=>Kc(e.schedule,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let p;w(e,"job")&&(l!==void 0&&u("MANIFEST_INVALID","an action is either the scheduled run or a job, not both","job"),p=$("job",()=>Wc(e.job,{backend:a,inputSchema:o,hasContent:c!==void 0,hasDataInputs:r!==void 0,confirmation:d})));let f;return w(e,"jobAccess")&&(p!==void 0&&u("MANIFEST_INVALID","an action is either the job or a job control, not both","jobAccess"),f=$("jobAccess",()=>Jc(e.jobAccess,{backend:a,hasContent:c!==void 0}))),{actionId:n,capability:t,mutation:i,inputSchema:o,resultProjection:s,backend:a,...c===void 0?{}:{content:c},...r===void 0?{}:{dataInputs:r},...d===void 0?{}:{confirmation:d},...l===void 0?{}:{schedule:l},...p===void 0?{}:{job:p},...f===void 0?{}:{jobAccess:f}}}function Gc(e,n,t){e.backend.type!=="core"||e.backend.handler!==Le||((n??oe)!==oe&&u("MANIFEST_INVALID","view.call is only available to screen Apps",`${t}.backend.handler`),e.mutation!==false&&u("MANIFEST_INVALID","view.call must be read-only",`${t}.mutation`),e.confirmation!=="none"&&u("MANIFEST_INVALID","view.call requires confirmation none",`${t}.confirmation`),(e.content!==void 0||e.schedule!==void 0||e.job!==void 0||e.jobAccess!==void 0)&&u("MANIFEST_INVALID","view.call cannot declare content, jobs, or schedules",t),e.resultProjection===void 0&&u("MANIFEST_INVALID","view.call requires resultProjection",`${t}.resultProjection`));}function Jc(e,n){return (n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==ke)&&u("MANIFEST_INVALID","jobAccess needs a tool-mode action","jobAccess"),n.hasContent&&u("MANIFEST_INVALID","a job control action takes no content","jobAccess"),(!Array.isArray(e)||e.length===0)&&u("MANIFEST_INVALID","jobAccess must list at least one operation","jobAccess"),(new Set(e).size!==e.length||!e.every(Zn))&&u("MANIFEST_INVALID","jobAccess must name each operation once: start, status or cancel","jobAccess"),Object.freeze([...e])}function Wc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==ke)&&u("MANIFEST_INVALID","job needs a tool-mode action","job"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&u("MANIFEST_INVALID","a job action takes no content, dataInputs or native confirmation","job"),(n.inputSchema.required??[]).length>0&&u("MANIFEST_INVALID","a job action input must accept {}","inputSchema.required"),J(e)||u("MANIFEST_INVALID","job must be an object","job"),X(e,[],oc);let t=w(e,"deadlineMs")?e.deadlineMs:Yn.default;return qn(t)||u("MANIFEST_INVALID","job deadlineMs is invalid","job.deadlineMs"),{deadlineMs:t}}function Kc(e,n){(n.backend.type!=="skill"||!("entry"in n.backend)||n.backend.entry!==ke)&&u("MANIFEST_INVALID","schedule needs a tool-mode action","schedule"),(n.hasContent||n.hasDataInputs||n.confirmation!==void 0&&n.confirmation!=="none")&&u("MANIFEST_INVALID","a scheduled action takes no content, dataInputs or native confirmation","schedule"),(n.inputSchema.required??[]).length>0&&u("MANIFEST_INVALID","a scheduled action input must accept {}","inputSchema.required"),J(e)||u("MANIFEST_INVALID","schedule must be an object","schedule"),X(e,tc,ic),Kn(e.everyMinutes)||u("MANIFEST_INVALID","schedule everyMinutes is invalid","schedule.everyMinutes");let t=w(e,"timeoutMs")?e.timeoutMs:Wn.default;return Xn(t)||u("MANIFEST_INVALID","schedule timeoutMs is invalid","schedule.timeoutMs"),{everyMinutes:e.everyMinutes,timeoutMs:t}}function Xc(e){return no(e)||u("MANIFEST_INVALID","skill backend env is invalid"),Object.freeze([...e])}function Yc(e){return Object.freeze({...e.in===void 0?{}:{in:Object.freeze({...e.in})},...e.out===void 0?{}:{out:Object.freeze({...e.out})}})}function qc(e){return J(e)||u("INITIAL_STATE_INVALID","initialState must be an object"),X(e,pc,lc),e.path!=="ui/state.json"&&u("MANIFEST_INVALID","initialState path is not fixed"),w(e,"hash")?{path:"ui/state.json",hash:Mo(e.hash)}:{path:"ui/state.json"}}function Zc(e){let n=["wasm","terminal","htmlDocuments","appBrowser"];return (!J(e)||Object.keys(e).length===0||Object.keys(e).some(t=>!n.includes(t)||e[t]!==true))&&u("MANIFEST_INVALID","runtime must contain only known capability flags set to true"),{...e.wasm===true?{wasm:true}:{},...e.terminal===true?{terminal:true}:{},...e.htmlDocuments===true?{htmlDocuments:true}:{},...e.appBrowser===true?{appBrowser:true}:{}}}function Qc(e,n){let t;try{t=lo(e);}catch(i){let o=i!==null&&typeof i=="object"&&"code"in i&&typeof i.code=="string"?i.code:"CSP_ORIGIN_INVALID";return u("MANIFEST_INVALID",o,void 0,o.toLowerCase().replace(/_/g,"-"))}if(t.frameDomains.length>0&&u("MANIFEST_INVALID","external origins in csp are not enabled in this rollout",void 0,"csp-not-enabled"),t.connectDomains.length!==0)return n?.terminal===true&&u("MANIFEST_INVALID","runtime.terminal cannot be combined with csp.connectDomains","connectDomains","terminal-with-connect-domains"),Object.freeze({connectDomains:t.connectDomains})}function ed(e,n){tt(J(e)?_c(e,["csp","downloads","files","share"]):e,new Set,0,true,true),Zt(e),J(e)||u("MANIFEST_INVALID"),X(e,Za,Qa),w(e,"_meta")&&$("_meta",()=>Oo(e._meta)),e.manifestVersion!==2&&u("MANIFEST_INVALID");let t;w(e,"runtime")&&(t=$("runtime",()=>Zc(e.runtime)));let i;w(e,"csp")&&(i=$("csp",()=>Qc(e.csp,t)));let o=$("pluginId",()=>qt(e.pluginId,"pluginId")),r=$("definitionId",()=>qt(e.definitionId,"definitionId")),s=$("version",()=>Ee(e,"version",1)),a=$("name",()=>yo(e.name,"name")),c=$("description",()=>yo(e.description,"description")),d;w(e,"icon")&&((typeof e.icon!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.icon))&&u("MANIFEST_INVALID","icon is invalid","icon"),d=e.icon);let l;w(e,"tone")&&((typeof e.tone!="string"||!Ft.includes(e.tone))&&u("MANIFEST_INVALID","tone is invalid","tone"),l=e.tone),e.entry!=="ui/index.html"&&u("MANIFEST_INVALID","entry path is not fixed","entry","fixed-value");let p;w(e,"entryHash")&&(p=$("entryHash",()=>Mo(e.entryHash)));let f;w(e,"initialState")&&(f=$("initialState",()=>qc(e.initialState)));let y;w(e,"usage")&&(e.usage!=="card"&&e.usage!=="window"&&u("MANIFEST_INVALID","usage is invalid","usage"),y=e.usage);let g;w(e,"detailPanel")&&(typeof e.detailPanel!="boolean"&&u("MANIFEST_INVALID","detailPanel is invalid","detailPanel"),g=e.detailPanel);let _;if(w(e,"displayModes")){((y??oe)!==oe||!Array.isArray(e.displayModes)||e.displayModes.length===0)&&u("MANIFEST_INVALID","displayModes are only valid for window Apps","displayModes");let j=new Set(["inline","floating","focused"]);(new Set(e.displayModes).size!==e.displayModes.length||e.displayModes.some(ue=>typeof ue!="string"||!j.has(ue)))&&u("MANIFEST_INVALID","displayModes are invalid","displayModes"),_=e.displayModes;}(y??oe)===oe&&g!==void 0&&u("MANIFEST_INVALID","detailPanel is card-only","detailPanel");let E=n.mode??"local";E!=="local"&&E!=="installed"&&E!=="published"&&u("MANIFEST_INVALID","manifest mode is invalid"),E!=="local"&&p===void 0&&u("MANIFEST_INVALID","installed manifests require entryHash","entryHash","required-when-installed"),E!=="local"&&f!==void 0&&f.hash===void 0&&u("MANIFEST_INVALID","installed manifests require initialState.hash","initialState.hash","required-when-installed"),(!Array.isArray(e.surfaces)||e.surfaces.length===0)&&u("MANIFEST_INVALID","surfaces are invalid","surfaces"),e.surfaces.length>2&&q("surfaces exceed the v2 limit","surfaces","too-many-items");let k=[],x=new Set;for(let j of e.surfaces)(typeof j!="string"||!Vt.includes(j))&&u("MANIFEST_INVALID","surface is unsupported","surfaces"),x.has(j)&&u("MANIFEST_INVALID","surfaces contain a duplicate","surfaces","duplicate-item"),x.add(j),k.push(j);J(e.size)||u("MANIFEST_INVALID","size must be an object","size"),$("size",()=>X(e.size,["height"]));let T=$("size",()=>Ee(e.size,"height",1));T>720&&q("size.height exceeds the v2 limit","size.height","too-large");let U=$("stateProjection",()=>Qt(e.stateProjection)),H=e.summaryProjection===void 0?void 0:$("summaryProjection",()=>Qt(e.summaryProjection));H!==void 0&&H.allow.some(j=>!U.allow.includes(j))&&u("MANIFEST_INVALID","summaryProjection must be a subset of stateProjection.allow","summaryProjection");let N=$("dataPaths",()=>Sc(e.dataPaths,U.allow)),D=w(e,"deviceFeatures")?$("deviceFeatures",()=>Mc(e.deviceFeatures)):void 0,L=w(e,"downloads")?$("downloads",()=>Lc(e.downloads)):void 0,I=w(e,"share")?$("share",()=>Rc(e.share)):void 0,A=w(e,"files")?$("files",()=>Uc(e.files)):void 0,h=w(e,"desktopOnly")?$("desktopOnly",()=>Oc(e.desktopOnly)):void 0;Array.isArray(e.actions)||u("MANIFEST_INVALID","actions must be an array","actions"),e.actions.length>32&&q("actions exceed the v2 limit","actions","too-many-items");let b=[],B=new Set,v=0,Y=0;for(let[j,ue]of e.actions.entries()){let _e=`actions[${j}]`,Se=$(_e,()=>$c(ue));if(Gc(Se,y,_e),B.has(Se.actionId)&&u("MANIFEST_INVALID","actions contain a duplicate actionId",`${_e}.actionId`,"duplicate-item"),Se.schedule!==void 0&&(v+=1,v>Zi&&u("MANIFEST_INVALID","an App declares at most one scheduled action",`${_e}.schedule`,"duplicate-item")),Se.job!==void 0&&(Y+=1,Y>Qi&&u("MANIFEST_INVALID","an App declares at most one job action",`${_e}.job`,"duplicate-item")),Se.backend.type==="core"&&Se.backend.handler==="state.set"){Se.mutation||u("MANIFEST_INVALID","state.set actions must be mutations",`${_e}.mutation`);for(let ea of Object.keys(Se.inputSchema.properties))U.allow.includes(ea)||u("MANIFEST_INVALID","state.set input paths must be projection-allowed",`${_e}.inputSchema.properties`);}B.add(Se.actionId),b.push(Se);}return {manifestVersion:2,pluginId:o,definitionId:r,version:s,name:a,description:c,...d===void 0?{}:{icon:d},...l===void 0?{}:{tone:l},entry:"ui/index.html",...p===void 0?{}:{entryHash:p},...t===void 0?{}:{runtime:t},...i===void 0?{}:{csp:i},...f===void 0?{}:{initialState:f},...y===void 0?{}:{usage:y},...g===void 0?{}:{detailPanel:g},..._===void 0?{}:{displayModes:_},surfaces:k,size:{height:T},stateProjection:U,...H===void 0?{}:{summaryProjection:H},...N===void 0?{}:{dataPaths:N},...D===void 0?{}:{deviceFeatures:D},...L===void 0?{}:{downloads:L},...I===void 0?{}:{share:I},...A===void 0?{}:{files:A},...h===void 0?{}:{desktopOnly:h},actions:b}}function Oo(e){J(e)||u("MANIFEST_INVALID","_meta must be an object");let n=JSON.stringify(e);(n===void 0||Buffer.byteLength(n,"utf8")>rc)&&q("_meta exceeds the 4 KiB limit",void 0,"meta-too-large");}function nd(e){let n={},t={};for(let r of e.actions){n[r.actionId]={capabilities:[r.capability],inputKeys:Object.keys(r.inputSchema.properties??{}),...r.backend.type==="core"&&r.backend.handler===Le?{mutation:r.mutation}:{},...r.dataInputs===void 0?{}:{dataInputs:r.dataInputs},resultProjection:r.resultProjection,...r.confirmation===void 0?{}:{confirmation:r.confirmation},...r.content===void 0?{}:{content:r.content},...r.schedule===void 0?{}:{schedule:r.schedule},...r.job===void 0?{}:{job:r.job},...r.jobAccess===void 0?{}:{jobAccess:r.jobAccess},...r.backend.type!=="skill"||r.backend.env===void 0?{}:{env:r.backend.env}};let s=r.backend.type==="skill"||r.backend.type==="core"&&(r.backend.handler==="state.set"||r.backend.handler===Le);t[r.actionId]={actionId:r.actionId,mutation:r.mutation,backend:r.backend,launchPolicy:s?"allowed":"denied",...s?{}:{denialCode:"EXEC_DENIED"}};}let i={id:e.definitionId,version:e.version,renderer:"sandbox-html",...e.usage===void 0?{}:{usage:e.usage},...e.detailPanel===void 0?{}:{detailPanel:e.detailPanel},...e.displayModes===void 0?{}:{displayModes:e.displayModes},surfaces:e.surfaces,stateProjection:e.stateProjection,...e.summaryProjection===void 0?{}:{summaryProjection:e.summaryProjection},...e.dataPaths===void 0?{}:{dataPaths:e.dataPaths},...e.downloads===void 0?{}:{downloads:e.downloads},actions:n},o={entry:{path:"ui/index.html",...e.entryHash===void 0?{}:{hash:e.entryHash}},...e.initialState===void 0?{}:{initialState:e.initialState}};return {manifest:e,definition:i,handlers:t,resources:o}}function ti(e,n,t,i,o,r){if(typeof e=="string"){let s=o.length>0&&r.some(a=>on(o.join("."),a));return (e.length>4096||it(e,false,false,s))&&he("state contains an unsafe string"),e}if(e===null||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)||he("state contains a non-finite number"),e;(e===void 0||typeof e!="object"||typeof e=="function"||typeof e=="bigint")&&he("state contains a non-JSON value"),t>8&&he("state is too deep"),n.has(e)&&he("state contains a cycle"),n.add(e);try{let s;if(Array.isArray(e))e.length>128&&he("state array is too long"),s=e.map(c=>ti(c,n,t+1,2097152,o,r));else {J(e)||he("state contains a non-plain object");let c={};for(let[d,l]of Object.entries(e))(d.length>4096||!Gn.test(d)||sn(d))&&(d.length>4096&&he("state key is too long"),he("state contains a reserved or invalid key")),c[d]=ti(l,n,t+1,2097152,[...o,d],r);s=c;}let a=JSON.stringify(s);return (a===void 0||Buffer.byteLength(a,"utf8")>i)&&he("state subtree is too large"),s}finally{n.delete(e);}}function oi(e,n=[]){J(e)||he("initial state must be a JSON object");let t=ti(e,new Set,0,2097152,[],n);return (t===null||Array.isArray(t)||typeof t!="object")&&he(),t}function td(e,n={}){tt(e),J(e)||u("MANIFEST_INVALID"),X(e,qa),e.manifestVersion!==1&&u("MANIFEST_INVALID");let t=Yt(Oe(e,"pluginId")),i=Yt(Oe(e,"definitionId")),o=Ee(e,"version",1),r=Ee(e,"primitiveSet",1),s=n.supportedPrimitiveSet??Ba;(!Number.isSafeInteger(s)||s<1)&&u("MANIFEST_INVALID"),r>s&&u("PRIMITIVE_SET_UNSUPPORTED"),J(e.activation)||u("MANIFEST_INVALID"),X(e.activation,["kind","language"]),e.activation.kind!=="fenced-code"&&u("MANIFEST_INVALID");let a=Yt(Oe(e.activation,"language")),c=Tc(e.schema),d=Nc(e.layout,c);return {manifestVersion:1,pluginId:t,definitionId:i,version:o,primitiveSet:r,activation:{kind:"fenced-code",language:a},schema:c,layout:d}}function id(e,n={}){return J(e)||u("MANIFEST_INVALID"),Object.hasOwn(e,"lineage")&&u("MANIFEST_INVALID","lineage is only allowed in product bundle indexes"),e.manifestVersion===2?ed(e,n):td(e,n)}function Ye(e,n={}){try{return id(e,n)}catch(t){if(t instanceof de)throw t;return u("MANIFEST_INVALID")}}function bn(e,n={}){let t=Ye(e,n);return t.manifestVersion===2?nd(t):t}var Ba,Ha,za,So,$a,Ga,Ja,Wa,fo,Ka,Xa,Ya,qa,Za,Qa,ec,nc,tc,ic,oc,rc,sc,ac,cc,dc,pc,lc,uc,fc,yc,Ac,Ic,gc,mc,hc,de,Ao,Io,wc,go,kc,mo,ho,xc,vc,jc,ri=F(()=>{m();an();Ue();zt();to();Kt();$t();Gt();uo();We();Ba=1,Ha=/^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9]+)+$/,za=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,So=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,$a=/<\/?[A-Za-z][^>]*>/,Ga=/^(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)/,Ja=/^(?:https?|file|ftp|ws|wss):\/\//i,Wa=/^\s*(?:javascript|data):/i,fo=/data:[^,\s]*,/i,Ka=/(?:https?|file|ftp|ws|wss):\/\//i,Xa=/javascript:/i,Ya=/(?:^[\s]*|[\s"'(=])(?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/)(?=[^\s"'<>])[^\s"'<>]*/,qa=["manifestVersion","pluginId","definitionId","version","primitiveSet","activation","schema","layout"],Za=["manifestVersion","pluginId","definitionId","version","name","description","entry","surfaces","size","stateProjection","actions"],Qa=["_meta","icon","tone","entryHash","runtime","csp","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","deviceFeatures","downloads","share","files","desktopOnly"],ec=["actionId","capability","mutation","inputSchema","resultProjection","backend"],nc=["confirmation","dataInputs","content","schedule","job","jobAccess","_meta"],tc=["everyMinutes"],ic=["timeoutMs"],oc=["deadlineMs"],rc=4*1024,sc=["type","handler"],ac=["type","command"],cc=["env"],dc=["type","entry"],pc=["path"],lc=["hash"],uc=/^[0-9a-f]{64}$/,fc=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/,yc=/[\r\n]/,Ac=16,Ic=16,gc=32,mc=/^[a-z][A-Za-z0-9]{0,31}$/,hc=["card-shell","meta-banner","heading","labeled-text","step-flow","text-list"],de=class e extends Error{constructor(t,i=t,o,r){super(i);this.code=t;this.path=o;this.rule=r;}code;path;rule;name="UiPluginValidationError";withPathPrefix(t){return new e(this.code,this.message,Tn(t,this.path),this.rule)}};Ao=200,Io=3,wc=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;go=200,kc=2,mo=4,ho=100,xc=/^[\p{L}\p{N}][\p{L}\p{N}\p{M}_-]*$/u,vc=[".git",".crewx","node_modules","apps","skills"],jc=/[\u0000-\u001f\u007f-\u009f\\:<>"|?*]/;});function xo(e){return typeof e=="string"&&e.length<=rd&&od.test(e)}function V(e,n,t,i,o){throw new Re(e,{path:n,rule:t,...i===void 0?{}:{message:i},...o===void 0?{}:{file:o}})}function re(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function Z(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Pe(e){let n=`_meta["${He}"]`;return e===void 0||e===""?n:e.startsWith("[")?`${n}${e}`:`${n}.${e}`}function dd(e){return e.toLowerCase().replace(/_/g,"-")}function pd(e){if(e===void 0||e==="")return "";let n=/^([^.[]+)(.*)$/.exec(e);if(!n)return Pe(e);let[,t,i]=n;switch(t){case "pluginId":return `name${i}`;case "name":return `display_name${i}`;case "description":return `description${i}`;case "_meta":return `_meta${i}`;case "version":return Pe("definitionVersion");case "definitionId":return Pe("definitionId");default:return Pe(`${t}${i}`)}}function vo(e,n,t){return {path:t(e.path),rule:e.rule??dd(e.code),...e.message!==e.code?{message:e.message}:{},file:n}}function jo(e){return JSON.parse(JSON.stringify(e))}function ci(e,n,t=0,i=new Set){if(typeof e=="string"){e.length>4096&&V("LIMIT_EXCEEDED",n,"string-too-long"),(sd.test(e)||ad.test(e)||cd.test(e))&&V("UNSAFE_VALUE",n,"unsafe-value");return}if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){Number.isFinite(e)||V("MANIFEST_INVALID",n,"non-finite-number");return}typeof e!="object"&&V("MANIFEST_INVALID",n,"non-json-value"),t>8&&V("LIMIT_EXCEEDED",n,"too-deep"),i.has(e)&&V("MANIFEST_INVALID",n,"cycle"),i.add(e);try{if(Array.isArray(e)){e.length>128&&V("LIMIT_EXCEEDED",n,"array-too-long"),e.forEach((o,r)=>ci(o,`${n}[${r}]`,t+1,i));return}re(e)||V("MANIFEST_INVALID",n,"non-plain-object");for(let[o,r]of Object.entries(e))ci(r,n===""?o:`${n}.${o}`,t+1,i);}finally{i.delete(e);}}}function Te(e,n){return (typeof e!="string"||e.length===0)&&V("MANIFEST_INVALID",n,"string"),e}function ln(e,n){return re(e)||V("MANIFEST_INVALID",n,"object"),e}function ld(e,n){Array.isArray(e)||V("MANIFEST_INVALID",n,"array"),e.forEach((t,i)=>Te(t,`${n}[${i}]`));}function ud(e,n){typeof e!="boolean"&&V("MANIFEST_INVALID",n,"boolean");}function Pn(e,n,t,i){for(let o of Object.keys(e))!t.includes(o)&&!i.includes(o)&&V("MANIFEST_INVALID",`${n}.${o}`,"unknown-key");for(let o of t)Z(e,o)||V("MANIFEST_INVALID",`${n}.${o}`,"missing-key");}function fd(e,n){if(e!=="icon")switch(ci(n,e),e){case "long_description":case "homepage":case "documentation":case "support":case "license":Te(n,e);return;case "author":{let t=ln(n,e);Pn(t,e,["name"],["email","url"]);for(let i of Object.keys(t))Te(t[i],`${e}.${i}`);return}case "repository":{let t=ln(n,e);Pn(t,e,[],["type","url"]);for(let i of Object.keys(t))Te(t[i],`${e}.${i}`);return}case "icons":{Array.isArray(n)||V("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=ln(t,o);Pn(r,o,["src","size"],["theme"]),Te(r.src,`${o}.src`),Te(r.size,`${o}.size`),Z(r,"theme")&&Te(r.theme,`${o}.theme`);});return}case "screenshots":case "keywords":case "privacy_policies":ld(n,e);return;case "tools":{Array.isArray(n)||V("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=ln(t,o);Pn(r,o,["name"],["description"]),Te(r.name,`${o}.name`),Z(r,"description")&&Te(r.description,`${o}.description`);});return}case "prompts":{Array.isArray(n)||V("MANIFEST_INVALID",e,"array"),n.forEach((t,i)=>{let o=`${e}[${i}]`,r=ln(t,o);Pn(r,o,["name","text"],["description","arguments"]),Te(r.name,`${o}.name`),Te(r.text,`${o}.text`);});return}case "tools_generated":case "prompts_generated":ud(n,e);return;case "localization":case "compatibility":case "user_config":ln(n,e);return;default:V("MANIFEST_INVALID",e,"unknown-key");}}function ot(e){return typeof e=="string"&&Me.test(e)?e:void 0}function Fo(e){return Number.isSafeInteger(e)&&e>=1?e:void 0}function yd(e){let n=ot(e.name);if(n===void 0)return;let t=e._meta,i=re(t)?t[He]:void 0,o=re(i)?i:{},r=Z(o,"definitionId")?ot(o.definitionId):n,s=Z(o,"definitionVersion")?Fo(o.definitionVersion):1;return {pluginId:n,...r===void 0?{}:{definitionId:r},...s===void 0?{}:{definitionVersion:s}}}function Ad(e){let n=ot(e.pluginId);if(n===void 0)return;let t=ot(e.definitionId),i=Fo(e.version);return {pluginId:n,...t===void 0?{}:{definitionId:t},...i===void 0?{}:{definitionVersion:i}}}function li(e){try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));if(!re(n))return !1;let t=n._meta;return re(t)&&Z(t,He)}catch{return false}}function Id(e,n){if(e===le)return n.builtinOnly===true;let t=n._meta,i=re(t)?t[He]:void 0;return re(i)&&i.builtinOnly===true}function gd(e,n){Z(e,"server")&&V("MANIFEST_INVALID","server","server-unsupported","phase 1 runs CrewX-owned Apps only");for(let a of Object.keys(e))di.includes(a)||V("MANIFEST_INVALID",a,"unknown-key");for(let a of pi)Z(e,a)||V("MANIFEST_INVALID",a,"missing-key");e.manifest_version!==si&&V("MANIFEST_INVALID","manifest_version","unsupported-version",`manifest_version must be "${si}"`),xo(e.version)||V("MANIFEST_INVALID","version","semver","version must be a semver.org version such as 0.1.0");let t=e._meta;re(t)||V("MANIFEST_INVALID","_meta","object"),Z(t,He)||V("MANIFEST_INVALID",Pe(),"missing-key");let i=t[He];re(i)||V("MANIFEST_INVALID",Pe(),"object");for(let a of Object.keys(i))ai.includes(a)||ko.includes(a)||V("MANIFEST_INVALID",Pe(a),"unknown-key");for(let a of ai)a==="actions"&&n!==void 0||Z(i,a)||V("MANIFEST_INVALID",Pe(a),"missing-key");if(n!==void 0&&Z(i,"actions")&&V("MANIFEST_INVALID",Pe("actions"),"two-truths",`actions are declared in both ${K} and ${G}; a server.ts App keeps them in the tools file only`),md(i.actions),Z(i,"definitionVersion")){let a=i.definitionVersion;(!Number.isSafeInteger(a)||a<1)&&V("MANIFEST_INVALID",Pe("definitionVersion"),"positive-integer");}let o={};for(let a of Uo)Z(e,a)&&(fd(a,e[a]),o[a]=jo(e[a]));let r={};for(let[a,c]of Object.entries(t))a!==He&&(r[a]=c);let s={manifestVersion:2,pluginId:e.name,definitionId:Z(i,"definitionId")?i.definitionId:e.name,version:Z(i,"definitionVersion")?i.definitionVersion:1,name:e.display_name,description:e.description};for(let[a,c]of Object.entries(i))a==="definitionId"||a==="definitionVersion"||(s[a]=c);return n!==void 0&&(s.actions=n.map(a=>{let{viewCall:c,...d}=a;return {...d,backend:c===true?{type:"core",handler:"view.call"}:{type:"skill",entry:ke}}})),Object.keys(r).length>0&&(s._meta=r),{v2Input:s,...Object.keys(r).length>0?{vendorMeta:r}:{},passthrough:o}}function md(e){Array.isArray(e)&&e.forEach((n,t)=>{let i=re(n)?n.backend:void 0;re(i)&&Z(i,"entry")&&V("MANIFEST_INVALID",Pe(`actions[${t}].backend.entry`),"entry-not-authorable",`an action in ${K} cannot name an entry; a server.ts App declares its actions in ${G}`);});}function hd(e,n,t){re(e)||V("MANIFEST_INVALID","","not-object","manifest.json must be a JSON object",K);let i;try{i=gd(e,t);}catch(s){throw s instanceof Re?new Re(s.code,{...s.reason,file:K}):s}let o;try{let s=Ye(i.v2Input,{mode:n.mode??"local"});s.manifestVersion!==2&&V("MANIFEST_INVALID","","v2-required"),o=s;}catch(s){throw s instanceof de?new Re(s.code,vo(s,K,pd)):s}let r=e.tools;if(Array.isArray(r)){let s=new Set(o.actions.map(a=>a.actionId));r.forEach((a,c)=>{let d=a.name;if(!s.has(d))throw new Re("MANIFEST_INVALID",{path:`tools[${c}].name`,rule:"tool-not-action",message:"every tools[].name must be an action id",file:K})});}return {file:K,manifest:o,v2Input:i.v2Input,releaseVersion:e.version,...Object.keys(i.passthrough).length>0?{mcpb:i.passthrough}:{}}}function _d(e,n){try{let t=Ye(e,{mode:n.mode??"local"});if(t.manifestVersion!==2)throw new Re("MANIFEST_INVALID",{path:"manifestVersion",rule:"v2-required",message:"a workspace App requires manifestVersion 2",file:le});return {file:le,manifest:t,v2Input:e}}catch(t){throw t instanceof de?new Re(t.code,vo(t,le,i=>i??"")):t}}function un(e){return fe(bn(e).definition)}function wo(e){let{entryHash:n,initialState:t,...i}=e,o={...i};return t!==void 0&&(o.initialState={path:t.path}),jo(o)}function Ed(e,n){let t=wo(e),i=wo(n);return [...new Set([...Object.keys(t),...Object.keys(i)])].sort().filter(r=>ie(t[r]??null)!==ie(i[r]??null))}function Td(e,n){return e.entryHash!==void 0&&n.entryHash!==void 0&&e.entryHash!==n.entryHash||e.initialState?.hash!==void 0&&n.initialState?.hash!==void 0&&e.initialState.hash!==n.initialState.hash}function bd(e,n){let t=Ed(e,n),i=Td(e,n),o="";try{let r=un(e),s=un(n);i=i||r!==s,o=` (definition hash ${r.slice(0,12)} vs ${s.slice(0,12)})`;}catch{i=true;}t.length===0&&!i||V("MANIFEST_DUAL_MISMATCH","","dual-manifest-mismatch",`${K} and ${le} normalize to different definitions${o}`+(t.length>0?`; differing fields: ${t.join(", ")}`:""));}function be(e,n,t="MANIFEST_INVALID",i){return {code:t,reason:{path:e,rule:n,...i===void 0?{}:{message:i},file:G},files:[]}}function Co(e){return {...be("","tools-needs-manifest-json","MANIFEST_INVALID",`${G} is read with ${K} only`),files:e}}function Pd(e,n){if(e.byteLength>n)return {failure:be("","file-too-large","LIMIT_EXCEEDED")};let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));}catch{return {failure:be("","invalid-json")}}if(!re(t))return {failure:be("","not-object","MANIFEST_INVALID",`${G} must be a JSON object`)};for(let o of Object.keys(t))if(o!=="schemaVersion"&&o!=="actions")return {failure:be(o,"unknown-key")};for(let o of ["schemaVersion","actions"])if(!Z(t,o))return {failure:be(o,"missing-key")};if(t.schemaVersion!==1)return {failure:be("schemaVersion","unsupported-version","MANIFEST_INVALID",`schemaVersion must be ${1}`)};let i=t.actions;if(!Array.isArray(i))return {failure:be("actions","array")};for(let[o,r]of i.entries()){if(!re(r))return {failure:be(`actions[${o}]`,"object")};if(Z(r,"backend"))return {failure:be(`actions[${o}].backend`,"tools-backend","MANIFEST_INVALID",`an action in ${G} cannot carry a backend`)};if(Z(r,"viewCall")&&r.viewCall!==true)return {failure:be(`actions[${o}].viewCall`,"view-call-marker","MANIFEST_INVALID","viewCall must be the exact marker true")}}return {actions:i}}function Nd(e,n){let t=n.maxBytes??262144,i=[],o=new TextDecoder("utf-8",{fatal:true});for(let r of ee){let s=e[r];if(s===void 0)continue;if(s.byteLength>t)return {parsed:i,failure:{code:"LIMIT_EXCEEDED",reason:{path:"",rule:"file-too-large",file:r},files:[r]}};let a;try{a=JSON.parse(o.decode(s));}catch{return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"invalid-json",file:r},files:[r]}}}if(!re(a))return {parsed:i,failure:{code:"MANIFEST_INVALID",reason:{path:"",rule:"not-object",message:`${r} must be a JSON object`,file:r},files:[r]}};i.push({file:r,raw:a});}return {parsed:i}}function $e(e,n={}){let{parsed:t,failure:i}=Nd(e,n),o=ee.filter(y=>e[y]!==void 0);if(i!==void 0)return {ok:false,rejection:i,parseFailure:true,builtinOnly:false};let r=e[G],s=r===void 0?void 0:Pd(r,n.maxBytes??262144);if(t.length===0)return {ok:false,rejection:s===void 0?{code:"MANIFEST_INVALID",reason:{path:"",rule:"no-manifest-file",message:"neither manifest.json nor ui-plugin.json is present"},files:[]}:Co(o),parseFailure:true,builtinOnly:false};let a=t[0],c=a.file===K?yd(a.raw):Ad(a.raw),d=t.some(y=>Id(y.file,y.raw)),l;if(s!==void 0){let y=t.some(g=>g.file===K)?s.failure:Co(o);if(y!==void 0)return {ok:false,rejection:y,parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};l=s.actions;}let p=[];try{for(let y of t)p.push(y.file===K?hd(y.raw,n,l):_d(y.raw,n));p.length===2&&bd(p[0].manifest,p[1].manifest);}catch(y){if(y instanceof Re)return {ok:false,rejection:{code:y.code,reason:y.reason,files:y.code==="MANIFEST_DUAL_MISMATCH"?[...ee]:y.reason.file===void 0||y.reason.file===G?o:[y.reason.file]},parseFailure:false,...c===void 0?{}:{identity:c},builtinOnly:d};throw y}let f=p[0];return {ok:true,...f,identity:c??{pluginId:f.manifest.pluginId},files:o}}var K,le,ee,si,He,di,pi,Uo,ai,ko,od,rd,sd,ad,cd,Re,rt=F(()=>{m();Ke();Ue();Kt();We();ri();K="manifest.json",le="ui-plugin.json",ee=[K,le],si="0.3",He="dev.crewx",di=Object.freeze(["manifest_version","name","display_name","version","description","long_description","author","repository","homepage","documentation","support","icon","icons","screenshots","localization","server","tools","tools_generated","prompts","prompts_generated","keywords","license","privacy_policies","compatibility","user_config","_meta"]),pi=Object.freeze(["manifest_version","name","display_name","version","description","_meta"]),Uo=Object.freeze(di.filter(e=>e!=="server"&&!pi.includes(e))),ai=Object.freeze(["entry","surfaces","size","stateProjection","actions"]),ko=Object.freeze(["definitionId","definitionVersion","icon","tone","entryHash","runtime","initialState","usage","detailPanel","displayModes","summaryProjection","dataPaths","focusedAiDataPaths","csp","deviceFeatures","downloads","share","files","desktopOnly"]),od=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,rd=256,sd=/<\/?[A-Za-z][^>]*>/,ad=/^\s*javascript:/i,cd=/data:[^,\s]*,/i;Re=class extends Error{constructor(t,i){super(`${t}: ${i.path||"<file>"} (${i.rule})`);this.code=t;this.reason=i;}code;reason};});function Jo(e){if(e===void 0)return {kind:"none"};if(typeof e!="string")return {kind:"invalid",reason:"bad-path"};if(Md.test(e))return {kind:"url",declared:e};if(!Rd(e))return {kind:"invalid",reason:"bad-path",declared:e};let n=e.lastIndexOf("."),t=n<0?void 0:Dd.get(e.slice(n+1).toLowerCase());return t===void 0?{kind:"invalid",reason:"bad-type",declared:e}:{kind:"file",path:e,contentType:t}}function Rd(e){return e.length===0||e.length>512||e.startsWith("/")||e.includes("\\")||e.includes("\0")?false:e.split("/").every(n=>n!==""&&n!=="."&&n!=="..")}async function Nn(e,n){let t=Jo(e);if(t.kind==="none")return {diagnostics:[]};if(t.kind==="url")return {diagnostics:[{code:"ICON_NOT_FILE",severity:"warning",declared:t.declared}]};if(t.kind==="invalid")return {diagnostics:[ui(t.reason,t.declared)]};let i=await n(t.path);if(typeof i=="string")return {diagnostics:[ui(i,t.path)]};let o=Wo(t.contentType,i);if(!o.ok)return {diagnostics:[ui(o.reason,t.path)]};let r={path:t.path,contentType:t.contentType,byteLength:i.byteLength,bytes:i},s=o.square===false?[{code:"ICON_NOT_SQUARE",severity:"warning",declared:t.path}]:[];return {file:r,diagnostics:s}}function ui(e,n){return {code:"ICON_INVALID",severity:"error",reason:e,...n===void 0?{}:{declared:n}}}function Wo(e,n){if(n.byteLength>262144)return {ok:false,reason:"too-large"};if(e==="image/png")return !zo(n,Ld)||Bd(n,12,16)!=="IHDR"||n.byteLength<24?{ok:false,reason:"bytes-mismatch"}:{ok:true,square:Ho($o(n,16),$o(n,20))};if(e==="image/jpeg"){if(!zo(n,Od))return {ok:false,reason:"bytes-mismatch"};let t=Fd(n);return {ok:true,square:t===void 0?void 0:Ho(t.width,t.height)}}return wd(n)}function wd(e){let n;try{n=Sd.decode(e);}catch{return {ok:false,reason:"bytes-mismatch"}}return vd(n)?{ok:false,reason:"unsafe-svg"}:Cd.test(n)?{ok:true,square:jd(n)}:{ok:false,reason:"bytes-mismatch"}}function vd(e){if(Ud.some(n=>n.test(e)))return true;for(let n of e.matchAll(kd))if(!(n[1]??n[2]??n[3]??"").startsWith("#"))return true;for(let n of e.matchAll(xd))if(Vo.lastIndex=n.index??0,!Vo.test(e))return true;return false}function jd(e){let n=/<svg\b[^>]*>/i.exec(e)?.[0];if(n===void 0)return;let t=Ko(n,"viewBox");if(t!==void 0){let r=t.trim().split(/[\s,]+/).map(Number);return r.length===4&&r.every(Number.isFinite)?r[2]===r[3]:void 0}let i=Bo(n,"width"),o=Bo(n,"height");return i===void 0||o===void 0?void 0:i===o}function Ko(e,n){let t=new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(e);return t?.[1]??t?.[2]}function Bo(e,n){let t=Ko(e,n),i=t===void 0?null:/^\s*(\d+(?:\.\d+)?)(?:px)?\s*$/.exec(t);return i===null?void 0:Number(i[1])}function Fd(e){let n=2;for(;n+4<=e.byteLength;){if(e[n]!==255)return;let t=e[n+1];if(t===255){n+=1;continue}if(t===216||t===1||t>=208&&t<=215){n+=2;continue}if(t===217)return;let i=e[n+2]<<8|e[n+3];if(i<2)return;if(Vd(t))return n+9>e.byteLength?void 0:{height:Go(e,n+5),width:Go(e,n+7)};n+=2+i;}}function Vd(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}function Ho(e,n){if(!(e<=0||n<=0))return e===n}function zo(e,n){return e.byteLength>=n.length&&n.every((t,i)=>e[i]===t)}function Bd(e,n,t){return String.fromCharCode(...e.subarray(n,t))}function $o(e,n){return (e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0}function Go(e,n){return e[n]<<8|e[n+1]}var Dd,Sd,Md,Ld,Od,Cd,Ud,kd,xd,Vo,fi=F(()=>{m();Dd=new Map([["svg","image/svg+xml"],["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"]]),Sd=new TextDecoder("utf-8",{fatal:true}),Md=/^[A-Za-z][A-Za-z0-9+.-]*:/,Ld=[137,80,78,71,13,10,26,10],Od=[255,216,255];Cd=/^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<svg(?=[\s/>])/,Ud=[/<script/i,/[\s"'/]on[a-z]+\s*=/i,/<foreignobject/i,/<!doctype/i,/<!entity/i,/<(?:iframe|embed|object)\b/i,/@import/i],kd=/(?:^|[\s"'/])(?:xlink:)?href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi,xd=/url\(/gi,Vo=/url\(\s*["']?#/iy;});var yi=F(()=>{m();Ki();rt();fi();ri();We();});function S(e,n=e){throw new we(e,n)}var we,at=F(()=>{m();we=class extends Error{constructor(t,i=t){super(i);this.code=t;}code;name="McpAppContractError"};});var sr=F(()=>{m();});var ar=F(()=>{m();Ke();Ue();at();sr();});function dr(e,n){return cr.add(e),n!==void 0&&Qd.set(e,n),e}function fn(e){return e!==null&&typeof e=="object"&&cr.has(e)}var cr,Qd,ct=F(()=>{m();cr=new WeakSet,Qd=new WeakMap;});function Ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ii(e,n,t=[]){let i=new Set([...n,...t]),o=Object.keys(e);return n.every(r=>Object.hasOwn(e,r))&&o.every(r=>i.has(r))}function ur(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))ur(n);return Object.freeze(e)}function se(e){throw new Ce("LINEAGE_INVALID",e)}function sp(e){throw new Ce("LINEAGE_STALE",e)}function fr(e){if(!Ln(e)||!Ii(e,tp,ip)||!Ln(e.actions))return se("Lineage definition shape is invalid");for(let n of Object.values(e.actions))if(!Ln(n)||!Ii(n,op,rp))return se("Lineage action definition shape is invalid");return e}function ap(e){if(!Ln(e)||!Ii(e,ep,np))return se("Lineage entry shape is invalid");if(!Number.isSafeInteger(e.version)||e.version<1||typeof e.hash!="string"||!pr.test(e.hash))return se("Lineage entry identity is invalid");if(e.sourceHash!==void 0&&(typeof e.sourceHash!="string"||!pr.test(e.sourceHash)))return se("Lineage source hash is invalid");if(e.compat!==void 0&&e.compat!=="break")return se("Lineage compatibility marker is invalid");let n=fr(e.definition);if(n.version!==e.version)return se("Lineage version does not match its definition");if(e.sourceHash!==void 0&&n.sourceHash!==e.sourceHash)return se("Lineage source hash does not match its definition");let t;try{t=fe(n),me({...n,hash:e.hash});}catch{return se("Lineage definition is invalid")}return t!==e.hash?se("Lineage definition hash does not match"):ur({version:e.version,hash:e.hash,definition:n,...e.sourceHash===void 0?{}:{sourceHash:e.sourceHash},...e.compat===void 0?{}:{compat:e.compat}})}function lr(e){return e.stateProjection?.allow??[]}function cp(e,n){let t=[],i=new Set(lr(n));lr(e).some(a=>!i.has(a))&&t.push("S1_STATE_PROJECTION");let o=new Set(n.dataPaths??[]);(e.dataPaths??[]).some(a=>!o.has(a))&&t.push("S2_DATA_PATHS");for(let[a,c]of Object.entries(e.actions)){let d=n.actions[a];if(d&&(c.confirmation??"native")==="native"&&(d.confirmation??"native")!=="native"){t.push("S3_ACTION_CONFIRMATION");break}}Object.keys(e.legacy?.agentAccess??{}).some(a=>!Object.hasOwn(n.actions,a))&&t.push("S4_LEGACY_AGENT_ACTIONS");let s=e.summaryProjection?.allow;if(s!==void 0){let a=new Set(n.summaryProjection?.allow??[]);s.some(c=>!a.has(c))&&t.push("S5_SUMMARY_PROJECTION");}return t}function dp(e,n){return ie(e)===ie(n)}function gi(e,n){if(!Array.isArray(e)||e.length===0)return se("Definition lineage is missing");if(!Ln(n)||typeof n.hash!="string")return se("Current definition is invalid");let t,i;try{let{hash:a,...c}=n;i=fr(c),t={...i,hash:a},me(t);}catch{return se("Current definition is invalid")}let o=e.map(ap),r=o[0].definition.id;if(o.some(a=>a.definition.id!==r))return se("Lineage definition ids do not match");if(o.some((a,c)=>c>0&&a.version<=o[c-1].version))return se("Lineage generations are not in increasing version order");if(o.some((a,c)=>o.findIndex(d=>d.hash===a.hash)!==c))return se("Lineage contains a duplicate hash");let s=o[o.length-1];if(s.version!==t.version||s.hash!==t.hash||s.definition.id!==t.id||!dp(s.definition,i))return sp("The last lineage generation does not match the current package");if(t.legacy!==void 0){let a=new Set(Object.keys(t.actions)),c=new Set;for(let l of o)if(l.sourceHash===void 0)for(let p of Object.keys(l.definition.actions))a.has(p)&&c.add(p);let d=Object.keys(t.legacy.agentAccess??{});if(d.length!==c.size||d.some(l=>!c.has(l))){let l="S4_LEGACY_AGENT_ACCESS_COMPLETE";throw new Ce("LINEAGE_INVALID",`Lineage compatibility failed: ${l}`,[l])}}for(let a=0;a<o.length-1;a+=1){if(o.slice(a,-1).some(l=>l.compat==="break"))continue;let d=cp(o[a].definition,t);if(d.length>0)throw new Ce("LINEAGE_INVALID",`Lineage compatibility failed: ${d.join(", ")}`,d)}return Object.freeze({entries:Object.freeze(o),current:t})}var Ce,pr,ep,np,tp,ip,op,rp,mi=F(()=>{m();Ke();Ue();Ce=class extends Error{constructor(t,i=t,o=[]){super(i);this.code=t;this.violations=o;}code;violations;name="UiDefinitionLineageError"},pr=/^[0-9a-f]{64}$/,ep=["version","hash","definition"],np=["sourceHash","compat"],tp=["id","version","actions"],ip=["sourceHash","usage","detailPanel","displayModes","renderer","surfaces","stateProjection","dataPaths","summaryProjection","downloads","legacy"],op=["capabilities"],rp=["inputKeys","mutation","dataInputs","confirmation","resultProjection","content","env","schedule","job","jobAccess"];});var yr,Ar,Ir,gr,mr=F(()=>{m();yr="text/html;profile=mcp-app",Ar=["crewx_app_terminal_connect","crewx_app_html_viewer_open","crewx_app_browser","crewx_files_list","crewx_files_read","crewx_files_write","crewx_docs_share"],Ir=["crewx_listWorkspaces","crewx_queryAgent","crewx_executeAgent","crewx_getTaskResult","crewx_listTasks","crewx_listAgents","callBrowser","openTab","listTabs","closeTab"],gr="text/html";});function On(e){return typeof e=="string"&&pp.includes(e)}function dt(e,n){return e==="card"&&n?.type==="core"&&On(n.handler)}var pp,pt=F(()=>{m();pp=Object.freeze(["card.secret-env"]);});function hr(e,n=[],t){if(e.content!==void 0||e.confirmation!=="none")return "denied";let i=lp();return i&&Object.hasOwn(i,e.actionId)?i[e.actionId]:e.backend?.type==="core"&&e.backend.handler.startsWith("host.")?"denied":e.backend?.type==="core"&&e.backend.handler===Le?(e.usage??oe)===oe&&e.mutation===false&&e.resultProjection!==void 0&&Array.isArray(e.resultProjection.allow)&&e.env===void 0&&e.job===void 0&&e.jobAccess===void 0&&e.schedule===void 0?"allowed":"denied":e.backend?.type==="core"&&e.backend.handler==="state.set"?"allowed":e.backend?.type==="core"&&On(e.backend.handler)||e.backend?.type==="skill"?"approval_required":e.backend===void 0&&n.includes(e.actionId)?"allowed":"denied"}function lp(e){return;}var _r=F(()=>{m();an();Ke();ct();pt();});function _p(e){return Cn.has(e)&&(e.initialState===void 0||Cn.has(e.initialState))}function Nr(e,n,t,i){let o=i===void 0?void 0:Object.freeze({hash:i.hash,bytes:Object.freeze(i.bytes)}),r=Object.freeze({mimeType:gr,entryHash:e,html:n,bytes:Object.freeze(t),...o===void 0?{}:{initialState:o}});return o!==void 0&&Cn.add(o),Cn.add(r),r}function Ep(e){let n=[];return e?.terminal===true&&n.push({name:"crewx_app_terminal_connect",description:"Open a local-only terminal session for this App.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"A local terminal connection is ready for this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ye}),e?.htmlDocuments===true&&n.push({name:"crewx_app_html_viewer_open",description:"List workspace HTML documents or open one through a short-lived Host capability.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"},operation:{type:"string",enum:["list","open"]},documentId:{type:"string"}},required:["threadId","instanceId","operation"],additionalProperties:false},textFallback:"Workspace HTML documents are available through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ye}),e?.appBrowser===true&&n.push({name:"crewx_app_browser",description:"Grant this App a native Desktop browser window. Browser commands use the custom Host RPC, not this tool.",inputSchema:{type:"object",properties:{workspace:{type:"string"},threadId:{type:"string"},instanceId:{type:"string"}},required:["threadId","instanceId"],additionalProperties:false},textFallback:"Desktop browser access is granted to this App. Browser commands use the custom Host RPC ui/crewx-app-browser.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ye}),n}function Tp(e){let n=[];return e?.appFiles===true&&n.push({name:"crewx_files_list",description:"List the .md files of this App on the phone, sorted by ref, at most 200 per page. Pass `next` as `after` for the next page.",inputSchema:{type:"object",properties:{prefix:{type:"string",description:'A folder such as "workouts/". Omit for every file.'},after:{type:"string",description:"Return only refs after this one (the `next` of the previous page)."}},additionalProperties:false},textFallback:"The markdown files of this App are listed through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ye},{name:"crewx_files_read",description:"Read one .md file: its text and its version (sha256 of the UTF-8 bytes).",inputSchema:{type:"object",properties:{ref:{...hi}},required:["ref"],additionalProperties:false},textFallback:"A markdown file of this App is read through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ye},{name:"crewx_files_write",description:"Write one .md file (at most 256 KiB). expectedVersion null creates it and fails if it exists; a version string replaces it only if the file still has that version.",inputSchema:{type:"object",properties:{ref:{...hi},text:{type:"string",maxLength:256*1024},expectedVersion:{type:["string","null"],description:"null = create only, or the version the file had when you read it."}},required:["ref","text","expectedVersion"],additionalProperties:false},textFallback:"A markdown file of this App is written through this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ye}),e?.resultShare===true&&n.push({name:"crewx_docs_share",description:"Open the Host share sheet for one markdown file of this App; resolves when the sheet closes.",inputSchema:{type:"object",properties:{ref:{...hi}},required:["ref"],additionalProperties:false},textFallback:"The Host share sheet opens for a markdown file of this App.",visibility:Object.freeze(["app"]),kind:"host",resourceBinding:ye}),n}function Ge(e,n,t){return (typeof e!="string"||!br.test(e))&&S(n,`${t} must be a safe identifier`),e}function Rn(e,n,t){let i=e??t;return (typeof i!="string"||i.trim().length===0||i.length>yp)&&S("TOOL_INVALID",`${n} must be a meaningful description`),i}function Ei(e){return (typeof e!="string"||e.length===0||e.length>yn||!/<html(?:\s|>)/i.test(e)||!/<\/html\s*>/i.test(e))&&S("HTML_INVALID","MCP App HTML must be a non-empty HTML document"),e}function wn(e,n=0){try{let t=ge(e,n);return t.type!==void 0&&t.type!=="object"&&S("TOOL_INVALID","MCP App inputSchema must describe an object"),t}catch(t){if(t instanceof we)throw t;S("TOOL_INVALID","MCP App inputSchema must be projection-safe JSON");}}function bp(e){return (typeof e!="string"||e.trim().length===0||e.length>Ap)&&S("TOOL_INVALID","MCP App tools require a meaningful text fallback"),e}function Pp(e){e===void 0&&S("TOOL_INVALID","MCP App tool visibility is required");let n=[...e];return (n.length===0||n.some(t=>t!=="model"&&t!=="app")||new Set(n).size!==n.length)&&S("TOOL_INVALID","MCP App tool visibility must contain model and/or app once"),n}function Sr(e){return (typeof e!="string"||!Pr.test(e))&&S("RESOURCE_URI_INVALID","MCP App resource URI is not a registered ui:// URI"),e}function Mr(e){let n=Ge(e.appId,"APP_ID_INVALID","Local App id"),t=Rn(e.name,"Local App name",n),i=Rn(e.description,"Local App description",`${t} interactive view`),o=yt(e.definition),r=Ei(e.html),s=lt(e.entryHash,"Local App entry hash"),a=e.entryBytes===void 0?Array.from(new TextEncoder().encode(r)):ft(e.entryBytes,"Local App entry bytes");(ut(a)!==s||Rr(a)!==r)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let c=Np(e),d=[];Array.isArray(e.actions)||S("TOOL_INVALID","Local App actions must be an array");for(let T of e.actions){let U=Ge(T.actionId,"TOOL_ID_INVALID","Local App action id");(d.includes(U)||!Object.prototype.hasOwnProperty.call(o.actions,U))&&S("TOOL_INVALID",`Local App action is not declared by the UI definition: ${U}`),d.push(U);}let l=Ge(e.readToolName,"TOOL_ID_INVALID","Local App read tool name"),p=e.actionToolName===void 0?void 0:Ge(e.actionToolName,"TOOL_ID_INVALID","Local App action tool name");d.length===0&&p!==void 0&&S("TOOL_INVALID","A static local App cannot register an action tool"),d.length>0&&p===void 0&&S("TOOL_INVALID","A stateful local App requires an action tool name"),p!==void 0&&p===l&&S("TOOL_ID_CONFLICT",`Local App read and action tools share a name: ${l}`);let f=[...Ep(e.runtime),...Tp(e.hostTools)];f.some(T=>T.name===l||T.name===p)&&S("TOOL_ID_CONFLICT","Local App read or action tool conflicts with a requested Host capability");let y={name:l,description:`${t} current state`,inputSchema:hp,textFallback:`${t} current state is available through its open instance.`,visibility:Object.freeze(["model","app"]),kind:"read",resourceBinding:ye},g=[Object.freeze(y)];if(g.push(...f.map(T=>Object.freeze(T))),p!==void 0){let T={name:p,description:`${t} actions`,inputSchema:Ti(e.actions),textFallback:`${t} action requests are handled by the open App instance.`,visibility:Object.freeze(["app"]),kind:"action",resourceBinding:ye,actionIds:Object.freeze([...d])};g.push(Object.freeze(T));}let _=[],E=new Set(g.map(T=>T.name));if(p!==void 0)for(let T of e.actions){let U=`${p}__${T.actionId}`;if(U.length>128||!br.test(U)){_.push(Object.freeze({toolName:U,actionId:T.actionId,reason:"name_too_long"}));continue}if(E.has(U)){_.push(Object.freeze({toolName:U,actionId:T.actionId,reason:"name_collision"}));continue}let H=hr({actionId:T.actionId,confirmation:o.actions[T.actionId]?.confirmation,content:o.actions[T.actionId]?.content,usage:o.usage,mutation:o.actions[T.actionId]?.mutation,resultProjection:o.actions[T.actionId]?.resultProjection,env:o.actions[T.actionId]?.env,job:o.actions[T.actionId]?.job,jobAccess:o.actions[T.actionId]?.jobAccess,schedule:o.actions[T.actionId]?.schedule,backend:T.backend},e.modelActions),N=Object.freeze([...Op(H,o.usage,T.backend)]),D={name:U,description:`${U} action`,inputSchema:wn(T.inputSchema),textFallback:`${U} action requests are handled by the open App instance.`,visibility:N,kind:"action",resourceBinding:ye,actionId:T.actionId,actionIds:Object.freeze([T.actionId]),_meta:Object.freeze({ui:Object.freeze({visibility:N})})};g.push(Object.freeze(D)),E.add(U);}let k=Nr(s,r,a,c===void 0?void 0:{hash:c.hash,bytes:[...c.bytes]}),x={appId:n,name:t,description:i,...e.icon===void 0?{}:{icon:wr(e.icon)},...e.tone===void 0?{}:{tone:Cr(e.tone)},builtinOnly:false,definition:o,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},...e.share===void 0?{}:{share:Object.freeze({...e.share})},...e.files===void 0?{}:{files:Object.freeze({...e.files})},resourceBinding:ye,resource:k,tools:Object.freeze(g),toolDiagnostics:Object.freeze(_)};return ne(x)}function Lr(e={}){return new _i(e)}function Ti(e){if(e.length===0)return wn({type:"object",properties:{},additionalProperties:false});let n=e.map(i=>i.actionId),t=new Map;for(let i of e)t.set(i.actionId,wn(i.inputSchema));return wn(Dp(n,t),Dr)}function Np(e){let n=e.definition.dataPaths??[];if(e.initialStateBytes===void 0){e.initialStateHash!==void 0&&S("STATE_INVALID","Initial state hash has no bytes"),e.initialState!==void 0&&ge(e.initialState,0,n);return}e.initialStateHash===void 0&&S("STATE_INVALID","Initial state bytes require a hash");let t=lt(e.initialStateHash,"Initial state hash"),i=ft(e.initialStateBytes,"Initial state bytes");ut(i)!==t&&S("STATE_INVALID","Initial state bytes do not match the hash");let o;try{let r=new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(i));o=ge(JSON.parse(r),0,n);}catch{S("STATE_INVALID","Initial state bytes are not projection-safe JSON");}return e.initialState!==void 0&&ie(o)!==ie(ge(e.initialState,0,n))&&S("STATE_INVALID","Initial state bytes do not match the state value"),{hash:t,bytes:Object.freeze([...i])}}function Dp(e,n){let t=e.map(i=>({type:"object",properties:{actionId:{type:"string",const:i},input:n.get(i)??{type:"object"}},required:["actionId","input"],additionalProperties:false}));return Object.freeze({type:"object",oneOf:Object.freeze(t),properties:Object.freeze({actionId:Object.freeze({type:"string",enum:Object.freeze([...e])}),input:Object.freeze({type:"object"})}),required:Object.freeze(["actionId","input"]),additionalProperties:false})}function Sp(e){let n=Un(e),t=Ge(n.appId,"APP_ID_INVALID","MCP App id"),i=Ei(n.html);Sr(n.uiUri);let o=n.definition===void 0?void 0:yt(n.definition),r=e.provenance;r!==void 0&&(!fn(r)||r.appId!==t||r.definitionId!==o?.id||r.version!==o?.version||r.definitionHash!==o?.hash)&&S("TOOL_INVALID","Product App built-in registration provenance is not verified");let s=Object.freeze(n.tools.map(d=>ne(Un(d)))),a=ne({...n,appId:t,html:i,...o===void 0?{}:{definition:o},...r===void 0?{}:{provenance:r},tools:s}),c=ne({uri:a.uiUri,mimeType:yr,text:i,...a.csp===void 0?{}:{_meta:{ui:{csp:a.csp}}}});return ne({appId:t,name:a.name,description:a.description,...a.icon===void 0?{}:{icon:a.icon},...a.tone===void 0?{}:{tone:a.tone},builtinOnly:a.builtinOnly,uiUri:a.uiUri,...o===void 0?{}:{definition:o},resourceBinding:Object.freeze({kind:"mcp",uri:a.uiUri}),resource:c,tools:s,descriptor:a})}function Mp(e){(e.resourceBinding.kind!=="instance"||e.builtinOnly!==false)&&S("STATE_INVALID","Local App registration binding is invalid"),Object.prototype.hasOwnProperty.call(e,"uiUri")&&S("STATE_INVALID","Local App registration cannot contain uiUri");let n=Ge(e.appId,"APP_ID_INVALID","Local App id"),t=yt(e.definition),i=e.provenance;i!==void 0&&(!fn(i)||i.appId!==n||i.definitionId!==t.id||i.version!==t.version||i.definitionHash!==t.hash)&&S("TOOL_INVALID","Product App local registration provenance is not verified");let o=Lp(e.resource),r=e.tools.map(a=>{Ge(a.name,"TOOL_ID_INVALID","Local App tool name"),Rn(a.description,"Local App tool description","Local App tool"),bp(a.textFallback);let c=wn(a.inputSchema,a.kind==="action"&&!("actionId"in a)?Dr:0);if((a.resourceBinding.kind!=="instance"||Object.prototype.hasOwnProperty.call(a,"resourceUri"))&&S("TOOL_INVALID","Local App tools cannot carry an MCP resource URI"),a.kind==="host")return (!mp.has(a.name)||a.visibility.length!==1||a.visibility[0]!=="app"||Object.prototype.hasOwnProperty.call(a,"actionId"))&&S("TOOL_INVALID","Local App Host tools must use an allow-listed name and app-only visibility"),ne({...a,inputSchema:c,visibility:Object.freeze(["app"])});if(a.kind==="action"){if("actionId"in a){let l=Ge(a.actionId,"TOOL_ID_INVALID","Local App action id");Object.prototype.hasOwnProperty.call(t.actions,l)||S("TOOL_INVALID","Local App action tool references an undeclared action");let p=Pp(a._meta.ui.visibility);return JSON.stringify(p)!==JSON.stringify(a.visibility)&&S("TOOL_INVALID","Local App action metadata visibility must match the tool visibility"),ne({...a,actionId:l,actionIds:Object.freeze([l]),inputSchema:c,visibility:p,_meta:{ui:{visibility:p}}})}let d=[...a.actionIds];return (d.length===0||d.some(l=>!Object.prototype.hasOwnProperty.call(t.actions,l)))&&S("TOOL_INVALID","Local App action tool references an undeclared action"),ne({...a,inputSchema:c,actionIds:Object.freeze(d)})}return ne({...a,inputSchema:c})}),s=ne({appId:n,name:Rn(e.name,"Local App name",e.appId),description:Rn(e.description,"Local App description",e.name),...e.icon===void 0?{}:{icon:wr(e.icon)},...e.tone===void 0?{}:{tone:Cr(e.tone)},builtinOnly:false,definition:t,...e.runtime===void 0?{}:{runtime:Object.freeze({...e.runtime})},...e.deviceFeatures===void 0?{}:{deviceFeatures:Object.freeze([...e.deviceFeatures])},...e.downloads===void 0?{}:{downloads:e.downloads},...e.share===void 0?{}:{share:Object.freeze({...e.share})},...e.files===void 0?{}:{files:Object.freeze({...e.files})},...i===void 0?{}:{provenance:i},resourceBinding:ye,resource:o,tools:Object.freeze(r),toolDiagnostics:Object.freeze([...e.toolDiagnostics??[]])});return Er.has(e)?e:(Er.add(s),s)}function Lp(e){let n=Ei(e.html),t=lt(e.entryHash,"Local App entry hash");if(_p(e))return e;let i=ft(e.bytes,"Local App entry bytes");(ut(i)!==t||Rr(i)!==n)&&S("HTML_INVALID","Local App entry bytes do not match the HTML hash");let o=e.initialState===void 0?void 0:{hash:lt(e.initialState.hash,"Initial state hash"),bytes:ft(e.initialState.bytes,"Initial state bytes")};return o&&ut(o.bytes)!==o.hash&&S("STATE_INVALID","Initial state bytes do not match the hash"),Nr(t,n,i,o)}function Op(e,n,t){if(dt(n,t))return ["model"];if(t?.type==="core"&&t.handler===Le)return ["model"];let i=t?.type==="core"&&On(t.handler);return e==="denied"||i?["app"]:["model","app"]}function Rp(e){return ne({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:false,definition:Or(e.definition),...e.provenance===void 0?{}:{provenance:e.provenance},entryHash:e.resource.entryHash,resourceBinding:ye,tools:e.tools})}function wp(e){return ne({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},builtinOnly:e.builtinOnly,uiUri:e.uiUri,...e.definition===void 0?{}:{definition:Or(e.definition)},resourceBinding:Object.freeze({kind:"mcp",uri:e.uiUri}),tools:e.tools})}function yt(e){try{if(Object.isFrozen(e))return me(e),ne(e);let n=Un(e);return me(n),ne(n)}catch(n){if(n instanceof we)throw n;S("STATE_INVALID","UI definition is not a valid immutable definition");}}function Or(e){return ne({id:e.id,version:e.version,hash:e.hash})}function Cp(e){return e!==null&&typeof e=="object"&&typeof e.id=="string"&&Number.isSafeInteger(e.version)&&typeof e.hash=="string"}function Tr(e,n,t){return `${e}\0${n}\0${t}`}function lt(e,n){return (typeof e!="string"||!fp.test(e))&&S("SERIALIZATION_INVALID",`${n} is invalid`),e}function ut(e){return createHash("sha256").update(Uint8Array.from(e)).digest("hex")}function ft(e,n){return (!Array.isArray(e)||e.some(t=>!Number.isInteger(t)||t<0||t>255))&&S("SERIALIZATION_INVALID",`${n} is invalid`),[...e]}function Rr(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(Uint8Array.from(e))}catch{S("SERIALIZATION_INVALID","UTF-8 bytes are invalid");}}function wr(e){return (typeof e!="string"||!Ip.test(e))&&S("TOOL_INVALID","MCP App icon is invalid"),e}function Cr(e){return (typeof e!="string"||!gp.has(e))&&S("TOOL_INVALID","MCP App tone is invalid"),e}function Un(e,n=new Map){if(e===null||typeof e!="object")return e;let t=e;if(n.has(t)&&S("SERIALIZATION_INVALID","MCP App value contains a cycle"),Array.isArray(e)){let r=[];n.set(t,r);for(let s of e)r.push(Un(s,n));return n.delete(t),r}let i;try{i=Object.getPrototypeOf(e);}catch{S("SERIALIZATION_INVALID","MCP App value cannot be cloned");}i!==Object.prototype&&i!==null&&S("SERIALIZATION_INVALID","MCP App value must be plain JSON");let o={};n.set(t,o);for(let[r,s]of Object.entries(e))Object.defineProperty(o,r,{configurable:true,enumerable:true,value:Un(s,n),writable:true});return n.delete(t),o}function ne(e,n=new Set){if(e===null||typeof e!="object"||n.has(e)||Cn.has(e))return e;n.add(e);for(let t of Object.values(e))ne(t,n);return Object.freeze(e),e}var br,Pr,fp,yn,yp,Ap,Ip,gp,mp,ye,hp,Cn,Er,hi,Dr,_i,At=F(()=>{m();ar();Ke();Ue();ct();at();mi();mr();an();_r();pt();br=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/,Pr=/^ui:\/\/crewx\/([A-Za-z][A-Za-z0-9._-]{0,127})\/([0-9a-f]{12})$/,fp=/^[0-9a-f]{64}$/,yn=8*1024*1024,yp=8*1024,Ap=16*1024,Ip=/^[a-z][a-z0-9-]{0,63}$/,gp=new Set(["blue","violet","emerald","amber","rose","sky","slate","indigo"]),mp=new Set(Ar),new Set(Ir),ye=Object.freeze({kind:"instance"}),hp=Object.freeze({type:"object",properties:Object.freeze({}),additionalProperties:false}),Cn=new WeakSet,Er=new WeakSet;hi={type:"string",description:'Relative path in NFC, 1 to 3 segments joined by "/", each [\\p{L}\\p{N}][\\p{L}\\p{N}\\p{M}_-]{0,99}, the last ending in ".md". At most 200 code points.'};Dr=4;_i=class{builtinApps;localApps;builtinDescriptors;builtinTools;mcpResources=new Map;localById=new Map;registrationById=new Map;launcherById=new Map;definitionByKey=new Map;handlerByKey=new Map;mcpToolByName=new Map;localToolByName=new Map;constructor(n){let t=n.builtins??n.builtin,i=[],o=[],r=[],s=new Set,a=new Set;for(let p of t?.listMcpApps()??[]){let f=Sp(p);s.has(f.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),s.add(f.appId);let y=f.tools;for(let g of y)a.has(g.name)&&S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${g.name}`),a.add(g.name),this.mcpToolByName.set(g.name,g),r.push(g);this.mcpResources.set(f.resource.uri,f.resource),i.push(f),o.push(f.descriptor);}let c=(n.localApps??n.locals??[]).map(Mp),d=new Set(c.flatMap(p=>p.tools.filter(f=>!(f.kind==="action"&&"actionId"in f)).map(f=>f.name))),l=[];for(let p of c){let f=p;s.has(f.appId)&&S("APP_ID_CONFLICT",`MCP App id is already registered: ${f.appId}`),s.add(f.appId);let y=[],g=[...f.toolDiagnostics??[]];for(let _ of f.tools){if(a.has(_.name)){if(_.kind==="host"&&this.localToolByName.get(_.name)?.kind==="host"){y.push(_);continue}if(_.kind==="action"&&"actionId"in _){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}S("TOOL_ID_CONFLICT",`MCP App tool name is already registered: ${_.name}`);}if(_.kind==="action"&&"actionId"in _&&d.has(_.name)){g.push(Object.freeze({toolName:_.name,actionId:_.actionId,reason:"name_collision"}));continue}a.add(_.name),this.localToolByName.set(_.name,_),y.push(_);}(y.length!==f.tools.length||g.length!==(f.toolDiagnostics?.length??0))&&(f=ne({...f,tools:Object.freeze(y),toolDiagnostics:Object.freeze(g)})),l.push(f),this.localById.set(f.appId,f);}for(let p of i)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,wp(p)),p.definition&&this.addDefinition(p.definition);for(let p of l)this.registrationById.set(p.appId,p),this.launcherById.set(p.appId,Rp(p)),this.addDefinition(p.definition);for(let p of n.definitions??[])this.addDefinition(p);for(let p of n.handlers??[])this.addHandler(p);this.builtinApps=Object.freeze(i),this.localApps=Object.freeze(l),this.builtinDescriptors=Object.freeze(o),this.builtinTools=Object.freeze(r);}getMcpApp(n){return this.builtinApps.find(t=>t.appId===n)?.descriptor??null}listMcpApps(){return this.builtinDescriptors}listMcpAppTools(){return this.builtinTools}resolveMcpAppTool(n){return this.mcpToolByName.get(n)??null}resolveMcpAppResource(n){return typeof n!="string"||!Pr.test(n)?null:this.mcpResources.get(n)??null}requireMcpAppResource(n){Sr(n);let t=this.mcpResources.get(n);return t||S("RESOURCE_NOT_FOUND",`MCP App resource is not registered: ${n}`),t}listLocalMcpApps(){return this.localApps}getLocalMcpApp(n){return this.localById.get(n)??null}listLocalMcpAppTools(){return Object.freeze([...this.localToolByName.values()])}resolveLocalMcpAppTool(n){return this.localToolByName.get(n)??null}resolveLocalMcpAppResource(n,t){let i=this.localById.get(n);return !i||t!==void 0&&i.definition.hash!==t?null:i.resource}listRegistrations(){return Object.freeze([...this.builtinApps,...this.localApps])}getRegistration(n){return this.registrationById.get(n)??null}listLaunchers(){return Object.freeze([...this.launcherById.values()].filter(n=>{let t=this.registrationById.get(n.appId),i=t?"descriptor"in t?t.descriptor.provenance:t.provenance:void 0,o=fn(i)&&i.launcher===false;return t?.definition?.usage!=="card"&&!o}))}listCardApps(){return Object.freeze([...this.launcherById.values()].filter(n=>this.registrationById.get(n.appId)?.definition?.usage==="card"))}getLauncher(n){return this.launcherById.get(n)??null}resolveDefinition(n){if(!Cp(n))return null;let t=this.definitionByKey.get(Wt(n));if(!t||t.hash!==n.hash)return null;try{return fe(t)===t.hash?t:null}catch{return null}}resolveActionHandler(n,t,i){return typeof n!="string"||typeof i!="string"||!Number.isSafeInteger(t)?null:this.handlerByKey.get(Tr(n,t,i))??null}addDefinition(n){let t=yt(n),i=Wt(t),o=this.definitionByKey.get(i);o&&o.hash!==t.hash&&S("STATE_INVALID",`UI definition generation conflicts: ${i}`),o||this.definitionByKey.set(i,t);}addHandler(n){(!n||typeof n.definitionId!="string"||typeof n.actionId!="string"||!Number.isSafeInteger(n.version)||n.version<1||typeof n.handle!="function")&&S("STATE_INVALID","UI action handler registration is invalid");let t=Tr(n.definitionId,n.version,n.actionId);this.handlerByKey.has(t)&&S("TOOL_INVALID",`Duplicate UI action handler registration: ${t}`),this.handlerByKey.set(t,Object.freeze({...n}));}};});function Up(e,n){let t=Mr({appId:e.appId,name:e.name,description:e.description,...e.icon===void 0?{}:{icon:e.icon},...e.tone===void 0?{}:{tone:e.tone},...e.normalized.manifest.runtime===void 0?{}:{runtime:e.normalized.manifest.runtime},...e.normalized.manifest.deviceFeatures===void 0?{}:{deviceFeatures:e.normalized.manifest.deviceFeatures},...e.normalized.manifest.downloads===void 0?{}:{downloads:e.normalized.manifest.downloads},...e.normalized.manifest.share===void 0?{}:{share:e.normalized.manifest.share},...e.normalized.manifest.files===void 0?{}:{files:e.normalized.manifest.files},definition:e.definition,html:e.html,entryHash:e.entryHash,entryBytes:e.entryBytes,initialState:e.initialState,...e.initialStateHash===void 0?{}:{initialStateHash:e.initialStateHash},...e.initialStateBytes===void 0?{}:{initialStateBytes:e.initialStateBytes},readToolName:e.toolNames.read,...e.toolNames.action===void 0?{}:{actionToolName:e.toolNames.action},actions:e.normalized.manifest.actions.map(o=>({actionId:o.actionId,inputSchema:o.inputSchema,backend:o.backend})),...{}});return e.provenance===void 0?t:Object.freeze({...t,provenance:e.provenance})}function Ur(e){let n=e.normalized.manifest.actions;if(n.some(i=>i.backend.type==="skill")&&n.some(i=>i.backend.type==="core"))throw new Error("Mixed workspace App execution models");let t=Up(e);Lr({localApps:[t],definitions:[e.definition]});}var kr=F(()=>{m();At();});function kp(e){if(e===null||typeof e!="object"||!(xr in e))throw new TypeError("scanCache must be created by createWorkspaceAppScanCache");return e[xr]}function vr(e,n){let t=kp(e),i=t.rootIdentity;return i!==void 0&&(i.dev!==n.dev||i.ino!==n.ino||i.realPath!==n.realPath)&&(t.candidates.clear(),t.assetCatalogs.clear(),t.preparedCandidates.clear(),t.lastCandidateScanUnchanged=void 0,t.lastCandidateKeys=void 0,t.scanStartedAtNs=void 0,t.lastAssetCatalogsUnchanged=void 0,t.lastSnapshot=void 0,t.lastSnapshotBuildInputs=void 0,t.lastSnapshotCandidates=void 0,t.lastSnapshotCatalogFingerprint=void 0),t.rootIdentity=n,t}var xr,jr=F(()=>{m();xr=Symbol("crewx.workspace-app-scan-cache.state");});function Ae(e){let n=typeof e=="object"&&e!==null&&"code"in e?String(e.code):"";return n==="ENOENT"?new M("NOT_FOUND"):n==="ELOOP"?new M("PATH_ESCAPED"):n==="EFBIG"||n==="EOVERFLOW"?new M("LIMIT_EXCEEDED"):n==="EACCES"||n==="EPERM"||n==="ENOTDIR"?new M("READ_DENIED"):new M("READ_DENIED")}function Fp(e){if(typeof e!="string"||e.length===0||!isAbsolute(e))throw new M("READ_DENIED")}function bi(e){if(typeof e!="string"||isAbsolute(e)||/[\\\u0000]/.test(e))throw new M("PATH_ESCAPED");if(e==="")return [];let n=e.split("/");if(n.some(t=>t.length===0||t==="."||t===".."))throw new M("PATH_ESCAPED");return n}function ht(e,n){let t=relative(e,n);return t===""||t!==".."&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)}function In(e){return {dev:e.dev,ino:e.ino,size:e.size,mtimeNs:e.mtimeNs,ctimeNs:e.ctimeNs}}function Si(e,n){return e.dev===n.dev&&e.ino===n.ino}function Mi(e,n){return Si(e,n)&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}async function It(e){Fp(e);let n,t;try{n=await realpath(e),t=await stat(n,{bigint:!0});}catch(i){throw Ae(i)}if(!t.isDirectory())throw new M("READ_DENIED");return {realRoot:n,identity:In(t)}}async function Br(e,n,t){if(t.length<2||t[0]!=="apps"&&t[0]!=="skills")return;let i,o;try{if(i=resolve(e,t[0],t[1]),o=await realpath(i),!(await stat(o,{bigint:!0})).isDirectory())throw new M("READ_DENIED")}catch(r){throw r instanceof M?r:Ae(r)}if(!ht(n,o))throw new M("PATH_ESCAPED");return o}async function gt(e,n,t,i){let o,r,s;try{o=await lstat(e,{bigint:!0}),r=await realpath(e),s=await stat(r,{bigint:!0});}catch(a){throw Ae(a)}if(!ht(n,r)||t!==void 0&&!ht(t,r))throw new M("PATH_ESCAPED");if(!o.isFile()||!s.isFile())throw new M("READ_DENIED");if(!Si(i,o)||!Si(i,s)||i.dev!==s.dev)throw new M("PATH_ESCAPED")}async function An(e,n){let t,i;try{t=await realpath(e),i=await stat(t,{bigint:!0});}catch{throw new M("PATH_ESCAPED")}if(t!==n.realRoot||!Mi(n.identity,In(i)))throw new M("PATH_ESCAPED")}function Vp(e){return e.isSymbolicLink()?{name:e.name,kind:"symlink"}:e.isDirectory()?{name:e.name,kind:"directory"}:e.isFile()?{name:e.name,kind:"file"}:{name:e.name,kind:"other"}}var M,Di,jp,Vr,_t,Hr,Oi=F(()=>{m();M=class extends Error{constructor(t){super(t);this.code=t;}code;name="AppDiscoveryFsError"},Di=constants.O_NOFOLLOW,jp=constants.O_NONBLOCK,Vr=constants.O_RDONLY|(Di??0)|(jp??0);_t=class{async getRootIdentity(n){let t=await It(n);return await An(n,t),{dev:t.identity.dev,ino:t.identity.ino,realPath:t.realRoot}}async listDirectory(n,t){let i=bi(t),o=await It(n),r=resolve(n,...i),s,a;try{s=await realpath(r),a=await stat(s,{bigint:!0});}catch(c){let d=Ae(c);if(d.code==="NOT_FOUND")return [];throw d}if(!ht(o.realRoot,s)||!a.isDirectory())throw new M("PATH_ESCAPED");try{let c=await readdir(s,{withFileTypes:!0,encoding:"utf8"});return await An(n,o),c.map(Vp)}catch(c){let d=Ae(c);if(d.code==="NOT_FOUND")return [];throw d}}async readdir(n,t){return this.listDirectory(n,t)}async readDirectory(n,t){return this.listDirectory(n,t)}async readVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(Di===void 0)throw new M("UNSUPPORTED");let o=bi(t),r=await It(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await open(s,Vr);}catch(d){throw Ae(d)}try{let d;try{let g=await c.stat({bigint:!0});d=In(g);}catch(g){throw Ae(g)}if(d.size>BigInt(i))throw new M("LIMIT_EXCEEDED");if(d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await An(n,r);let l=await Br(n,r.realRoot,o);await gt(s,r.realRoot,l,d);let p=new Uint8Array(new ArrayBuffer(Number(d.size))),f=0;for(;f<p.byteLength;){let g;try{g=(await c.read(p,f,p.byteLength-f,f)).bytesRead;}catch(_){throw Ae(_)}if(g<=0)throw new M("IDENTITY_CHANGED");f+=g;}let y;try{let g=await c.stat({bigint:!0});y=In(g);}catch(g){throw Ae(g)}if(!Mi(d,y))throw new M("IDENTITY_CHANGED");return await gt(s,r.realRoot,l,y),await An(n,r),new Uint8Array(p)}finally{await c.close().catch(()=>{});}}async fingerprintVerifiedFile(n,t,i){if(!Number.isSafeInteger(i)||i<0)throw new M("READ_DENIED");if(Di===void 0)throw new M("UNSUPPORTED");let o=bi(t),r=await It(n),s=resolve(n,...o),a=relative(n,s);if(a===".."||a.startsWith(`..${sep}`)||isAbsolute(a))throw new M("PATH_ESCAPED");let c;try{c=await open(s,Vr);}catch(d){throw Ae(d)}try{let d;try{let f=await c.stat({bigint:!0});d=In(f);}catch(f){throw Ae(f)}if(d.size>BigInt(i)||d.size>BigInt(Number.MAX_SAFE_INTEGER))throw new M("LIMIT_EXCEEDED");await An(n,r);let l=await Br(n,r.realRoot,o);await gt(s,r.realRoot,l,d);let p;try{let f=await c.stat({bigint:!0});p=In(f);}catch(f){throw Ae(f)}if(!Mi(d,p))throw new M("IDENTITY_CHANGED");return await gt(s,r.realRoot,l,p),await An(n,r),{...p,candidateRealPath:l??r.realRoot}}catch(d){throw d instanceof M?d:Ae(d)}finally{await c.close().catch(()=>{});}}async readFileVerified(n,t,i){return this.readVerifiedFile(n,t,i)}},Hr=new _t;});function jn(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function $r(e){return typeof e=="string"&&Me.test(e)?e:void 0}function Wp(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Ze(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function Kp(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function Xp(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function Yp(e){return Gp.decode(e)}function qp(e){return JSON.parse(Yp(e))}function Gr(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function Zp(e){if(e instanceof M)return Gr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return Gr(n)}}function ve(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Qp(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function el(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function Jr(e,n,t,i){let o=Qp(e);if(!o)throw new M("READ_DENIED");return Xp(await o.call(e,n,t,i))}async function Ci(e,n,t){let i=el(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(Kp).filter(r=>r!==null)}function nl(e,n,t,i){return Object.freeze({code:e,...{},source:n,relativePath:t})}function tl(e){if(!jn(e))throw new TypeError("productBundle.reservedIds must be an object with appIds and definitionIds arrays");try{let n=Reflect.ownKeys(e);if(n.length!==2||!n.includes("appIds")||!n.includes("definitionIds"))throw new TypeError("productBundle.reservedIds must contain exactly appIds and definitionIds");let t=(i,o)=>{if(!Array.isArray(i))throw new TypeError("productBundle.reservedIds."+o+" must be an array");let r=[];for(let s=0;s<i.length;s+=1){let a=i[s];if(typeof a!="string"||a.length===0)throw new TypeError("productBundle.reservedIds."+o+" must contain non-empty strings");r.push(a);}return Object.freeze([...new Set(r)].sort(Ze))};return Object.freeze({appIds:t(e.appIds,"appIds"),definitionIds:t(e.definitionIds,"definitionIds")})}catch(n){throw n instanceof TypeError?n:new TypeError("productBundle.reservedIds must be a valid reservation object")}}function il(e,n){return e.appIds.length===n.appIds.length&&e.appIds.every((t,i)=>t===n.appIds[i])&&e.definitionIds.length===n.definitionIds.length&&e.definitionIds.every((t,i)=>t===n.definitionIds[i])}function Tt(e){return Object.freeze({appIds:Object.freeze([...new Set(e.map(n=>n.appId))].sort(Ze)),definitionIds:Object.freeze([...new Set(e.map(n=>n.definition.id))].sort(Ze))})}function Et(e,n){let t=Object.keys(e).sort(Ze),i=[...n].sort(Ze);return t.length===i.length&&t.every((o,r)=>o===i[r])}function Wr(e){if(typeof e!="string"||e.length===0||e.startsWith("/")||/[\\\u0000]/.test(e))return;let n=e.split("/");if(!n.some(t=>t.length===0||t==="."||t===".."))return n}function ol(e){let n;try{n=qp(e);}catch{return}if(!jn(n)||!Et(n,["version","packages"])||n.version!==1||!Array.isArray(n.packages)||n.packages.length>Ui)return;let t=new Set,i=new Set,o=0,r=[];for(let s of n.packages){if(!jn(s))return;let a=["packageDir","appId","definition","files"],c=Object.hasOwn(s,"lineage"),d=Object.hasOwn(s,"launcher"),l=[...c?["lineage"]:[],...d?["launcher"]:[]];if(!Et(s,[...a,...l])||d&&s.launcher!==false)return;let p=Wr(s.packageDir),f=$r(s.appId);if(!p||p.length!==2||p[0]!=="apps"||!Wp(p[1])||!f||t.has(s.packageDir)||!jn(s.definition)||!Et(s.definition,["id","version","hash"]))return;let y=$r(s.definition.id),g=s.definition.version,_=s.definition.hash;if(!y||!Number.isSafeInteger(g)||g<1||typeof _!="string"||!wi.test(_)||!Array.isArray(s.files)||s.files.length<2||s.files.length>ki)return;let E=new Set,k=[];for(let x of s.files){if(!jn(x)||!Et(x,["path","sha256"]))return;let T=Wr(x.path);if(!T||typeof x.sha256!="string"||!wi.test(x.sha256))return;let U=T.join("/"),H=`${s.packageDir}/${U}`;if(E.has(U)||i.has(H))return;E.add(U),i.add(H),k.push(Object.freeze({path:U,sha256:x.sha256}));}if(!ee.some(x=>E.has(x))||!E.has("ui/index.html")||(o+=k.length,o>Hp))return;t.add(s.packageDir),r.push(Object.freeze({packageDir:s.packageDir,...d?{launcher:false}:{},appId:f,definition:Object.freeze({id:y,version:g,hash:_}),lineage:Array.isArray(s.lineage)?s.lineage:[],files:Object.freeze(k.sort((x,T)=>Ze(x.path,T.path)))}));}return Object.freeze({version:1,packages:Object.freeze(r)})}function qe(e){let n=Zp(e);return n==="PATH_ESCAPED"||n==="IDENTITY_CHANGED"||n==="TOCTOU"?"PATH_ESCAPED":n==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":"BUNDLE_INTEGRITY"}async function rl(e,n,t,i,o){let r=[],s=async(a,c)=>{if(!ve(i,o))throw new M("LIMIT_EXCEEDED");if(c>2)throw new M("LIMIT_EXCEEDED");let d=await Ci(e,n,a);for(let l of d){if(typeof l.name!="string"||l.name.length===0||l.name==="."||l.name===".."||/[\\/\u0000]/.test(l.name))throw new M("PATH_ESCAPED");let p=`${a}/${l.name}`;if(l.kind==="file"){if(r.push(p.slice(t.length+1)),r.length>ki)throw new M("LIMIT_EXCEEDED")}else if(l.kind==="directory")await s(p,c+1);else throw l.kind==="symlink"?new M("PATH_ESCAPED"):new M("READ_DENIED")}};return await s(t,0),r.sort(Ze)}function sl(e){return ee.includes(e)?262144:e==="ui/index.html"?yn:e==="ui/state.json"?2097152:e.startsWith("ui/assets/")?$p:zp}async function Kr(e,n,t,i){if(e===void 0)return {packages:[],diagnostics:[],incomplete:false,reservedIds:Jp};let o=tl(e.reservedIds),r=[],s=(I,A,h)=>nl(I,"bundled",A),a=(I=[],A=false,h)=>({...h===void 0?{}:{indexHash:h},packages:I,diagnostics:r,incomplete:A,reservedIds:o});if(typeof e.root!="string"||e.root.length===0||typeof e.expectedIndexHash!="string"||!wi.test(e.expectedIndexHash))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let c;try{c=await Jr(n,e.root,"bundle-index.json",Bp);}catch(I){return r.push(s(qe(I),"bundle-index.json")),a()}let d=createHash("sha256").update(c).digest("hex");if(d!==e.expectedIndexHash)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();let l=ol(c);if(l===void 0)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a();if(!il(Tt(l.packages),o))return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a([],false,d);if(!ve(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let p;try{p=await Ci(n,e.root,"");}catch(I){return r.push(s(qe(I),"bundle-index.json")),a(l.packages.map(A=>({indexEntry:A,failureCode:qe(I)})),false,d)}if(!ve(t,i))return r.push(s("LIMIT_EXCEEDED","bundle-index.json")),a(l.packages.map(I=>({indexEntry:I,failureCode:"LIMIT_EXCEEDED"})),true,d);let f=p.find(I=>I.name==="bundle-index.json"&&I.kind==="file"),y=p.find(I=>I.name==="apps"&&I.kind==="directory"),g=I=>l.packages.map(A=>({indexEntry:A,failureCode:I}));if(!f)return r.push(s("BUNDLE_INTEGRITY","bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d);let _=p.filter(I=>I.name!=="bundle-index.json"&&I.name!=="apps");if(_.length>0){let I=_.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return r.push(s(I,"bundle-index.json")),a(g("BUNDLE_INTEGRITY"),false,d)}if(p.some(I=>I.name==="apps"&&I.kind!=="directory"))return r.push(s("PATH_ESCAPED","apps")),a(g("PATH_ESCAPED"),false,d);let E=[];if(y)try{E=await Ci(n,e.root,"apps");}catch(I){return r.push(s(qe(I),"apps")),a(g(qe(I)),false,d)}if(!ve(t,i)||E.length>Ui)return r.push(s("LIMIT_EXCEEDED","apps")),a(g("LIMIT_EXCEEDED"),true,d);let k=new Map(l.packages.map(I=>[I.packageDir.slice(5),I])),x=E.filter(I=>!k.has(I.name));for(let I of x)r.push(s(I.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY",`apps/${I.name}`));if(x.length>0){let I=x.some(A=>A.kind==="symlink")?"PATH_ESCAPED":"BUNDLE_INTEGRITY";return a(g(I),false,d)}let T=new Set,U=new Map,H=new Map;for(let I of l.packages){let A=U.get(I.appId)??[];A.push(I),U.set(I.appId,A);let h=`${I.definition.id}\0${String(I.definition.version)}`,b=H.get(h)??[];b.push(I),H.set(h,b);}for(let I of [...U.values(),...H.values()])if(I.length>1)for(let A of I)T.add(A);let N=[],D=c.byteLength,L=false;for(let I of l.packages){if(!ve(t,i)){L=true,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let A;try{let B=I.lineage[I.lineage.length-1];if(!B)throw new Ce("LINEAGE_INVALID","Definition lineage is missing");if(B.definition.id!==I.definition.id||B.version!==I.definition.version||B.hash!==I.definition.hash)throw new Ce("LINEAGE_STALE","Last lineage generation does not match bundle identity");A=gi(I.lineage,{...B.definition,hash:B.hash}).entries;}catch(B){let v=B instanceof Ce?B.code:"LINEAGE_INVALID";r.push(s(v,I.packageDir)),N.push({indexEntry:I,failureCode:v});continue}let h=E.find(B=>B.name===I.packageDir.slice(5));if(!y||!h){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}if(h.kind!=="directory"){N.push({indexEntry:I,failureCode:h.kind==="symlink"?"PATH_ESCAPED":"BUNDLE_INTEGRITY"});continue}let b;try{let B=await rl(n,e.root,I.packageDir,t,i);if(!ve(t,i)){L=!0,N.push({indexEntry:I,failureCode:"LIMIT_EXCEEDED"});continue}let v=I.files.map(j=>j.path);if(B.length!==v.length||B.some((j,ue)=>j!==v[ue])){N.push({indexEntry:I,failureCode:"BUNDLE_INTEGRITY"});continue}b=new Map;let Y;for(let j of I.files){if(!ve(t,i)){Y="LIMIT_EXCEEDED",L=!0;break}if(D>=Ri){Y="LIMIT_EXCEEDED";break}let ue;try{ue=await Jr(n,e.root,`${I.packageDir}/${j.path}`,sl(j.path));}catch(_e){Y=qe(_e);break}if(!ve(t,i)){Y="LIMIT_EXCEEDED",L=!0;break}if(D+ue.byteLength>Ri){D=Ri,Y="LIMIT_EXCEEDED";break}if(D+=ue.byteLength,createHash("sha256").update(ue).digest("hex")!==j.sha256){Y="BUNDLE_INTEGRITY";break}b.set(j.path,ue);}if(Y!==void 0){N.push({indexEntry:I,failureCode:Y});continue}}catch(B){ve(t,i)||(L=true),N.push({indexEntry:I,failureCode:qe(B)});continue}N.push({indexEntry:I,lineage:A,files:b,...T.has(I)?{failureCode:"DUPLICATE_ID"}:{}});}return a(N,L,d)}var Bp,Ui,ki,Hp,zp,$p,Ri,wi,Gp,Jp,xi=F(()=>{m();mi();We();rt();At();Oi();Bp=256*1024,Ui=64,ki=128,Hp=Ui*ki,zp=2*1024*1024,$p=8*1024*1024,Ri=32*1024*1024,wi=/^[0-9a-f]{64}$/,Gp=new TextDecoder("utf-8",{fatal:true}),Jp=Object.freeze({appIds:Object.freeze([]),definitionIds:Object.freeze([])});});function cl(e){if(typeof e!="string"||!Me.test(e))throw new TypeError("pluginId must be a safe UI plugin identifier");let n=`${vi}${e}`.length+7<=128?e:`hash_${createHash("sha256").update(e,"utf8").digest("hex")}`;return {read:`${vi}${n}_read`,action:`${vi}${n}_action`}}function Yr(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;try{let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}catch{return false}}function pl(e,n){return n.length===0||n==="."||n===".."||/[\\/\u0000]/.test(n)?e==="skills"?"skills":"apps":`${e==="skills"?"skills":"apps"}/${n}`}function ll(e){return e.length>0&&e!=="."&&e!==".."&&!/[\\/\u0000]/.test(e)}function Vn(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function as(e){if(typeof e=="string")return {name:e,kind:"directory"};if(e===null||typeof e!="object")return null;let n=e;if(typeof n.name!="string")return null;if(n.kind==="file"||n.kind==="directory"||n.kind==="symlink"||n.kind==="other")return {name:n.name,kind:n.kind};if(n.type==="file"||n.type==="directory"||n.type==="symlink"||n.type==="other")return {name:n.name,kind:n.type};let t=n.isDirectory;if(typeof t=="function"&&t.call(e))return {name:n.name,kind:"directory"};let i=n.isSymbolicLink;if(typeof i=="function"&&i.call(e))return {name:n.name,kind:"symlink"};let o=n.isFile;return typeof o=="function"&&o.call(e)?{name:n.name,kind:"file"}:{name:n.name,kind:"other"}}function ul(e){if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("filesystem port returned an invalid byte array")}function cs(e){return dl.decode(e)}function fl(e){return JSON.parse(cs(e))}function yl(e){if(e===void 0)return;let n=e.definitionId!==void 0&&e.definitionVersion!==void 0?`${e.definitionId}\0${String(e.definitionVersion)}`:void 0;return {pluginId:e.pluginId,...n===void 0?{}:{definitionKey:n}}}function bt(e,n,t,i,o){let r={code:e,...i===void 0?{}:{pluginId:i},source:n,relativePath:t,...o?.reason===void 0?{}:{reason:Object.freeze({...o.reason})},...o?.files===void 0?{}:{files:Object.freeze([...o.files])}};return Object.freeze(r)}function qr(e){switch(e){case "ENOENT":return "NOT_FOUND";case "ELOOP":case "EXDEV":return "PATH_ESCAPED";case "EFBIG":case "EOVERFLOW":return "LIMIT_EXCEEDED";case "EACCES":case "EPERM":case "ENOTDIR":return "READ_DENIED";default:return e}}function ae(e){if(e instanceof M)return qr(e.code);if(e!==null&&typeof e=="object"&&"code"in e){let n=e.code;if(typeof n=="string")return qr(n)}}function en(e,n){return e==="PATH_ESCAPED"||e==="IDENTITY_CHANGED"||e==="TOCTOU"?"PATH_ESCAPED":e==="LIMIT_EXCEEDED"?"LIMIT_EXCEEDED":n==="manifest"&&e==="NOT_FOUND"?"MANIFEST_MISSING":n==="entry"?"ENTRY_INVALID":n==="initial"?"INITIAL_STATE_INVALID":"MANIFEST_INVALID"}function Zr(e){return {reason:e.reason,...e.code==="MANIFEST_DUAL_MISMATCH"?{files:e.files}:{}}}function Qr(e){return e==="MANIFEST_DUAL_MISMATCH"?e:ds(e)}function Al(e){return ds(e.code)}function ds(e){switch(e){case "MANIFEST_INVALID":case "PRIMITIVE_UNKNOWN":case "PRIMITIVE_SET_UNSUPPORTED":case "SCHEMA_TYPE_UNSUPPORTED":case "TOKEN_INVALID":case "UNSAFE_VALUE":return "MANIFEST_INVALID";case "LIMIT_EXCEEDED":return "LIMIT_EXCEEDED";case "INITIAL_STATE_INVALID":return "INITIAL_STATE_INVALID";default:return ps("UiPluginValidationError",e)}}function ps(e,n){throw new Error(`Unmapped ${e} code: ${String(n)}`)}function ls(e){switch(e){case "APP_ID_INVALID":case "TOOL_ID_INVALID":case "RESOURCE_URI_INVALID":case "TOOL_INVALID":case "SERIALIZATION_INVALID":return "MANIFEST_INVALID";case "APP_ID_CONFLICT":case "TOOL_ID_CONFLICT":return "DUPLICATE_ID";case "RESOURCE_NOT_FOUND":case "HTML_INVALID":return "ENTRY_INVALID";case "STATE_INVALID":case "STATE_PROJECTION_INVALID":case "BUTTON_INVALID":return "INITIAL_STATE_INVALID";default:return ps("McpAppContractError",e)}}function je(e,n){let t=n();return Number.isFinite(t)&&Number.isFinite(e)&&t-e<=5e3}function Il(e){return {pluginId:e.appId,definitionKey:`${e.definition.id}\0${String(e.definition.version)}`}}function gl(e,n){let t=n.get("package.json");if(t!==void 0)try{let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t));if(Yr(o)){let r=o.bin,s=typeof r=="string"?r:Yr(r)?Object.values(r).find(a=>typeof a=="string"):void 0;for(let a of [s,o.main]){if(typeof a!="string")continue;let c=ml(a);if(c&&n.has(c))return c}}}catch{}return [`${e.slice(e.lastIndexOf("/")+1)}.js`,"index.js","main.js"].find(o=>n.has(o))}function ml(e){if(e.startsWith("/")||e.includes("\\")||e.includes("\0"))return;let n=e.split("/").filter(t=>t!==".");if(!(n.length===0||n.some(t=>t.length===0||t==="..")))return n.join("/")}function hl(){return globalThis.performance?.now()??Date.now()}function Qe(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let n of Object.values(e))Qe(n);return Object.freeze(e)}function es(e){return Object.freeze(Array.from(e))}async function Bn(e,n,t,i){if(n.pinnedFiles!==void 0){let a=n.pinnedFiles.get(t);if(a===void 0)throw new M("NOT_FOUND");if(a.byteLength>i)throw new M("LIMIT_EXCEEDED");return new Uint8Array(a)}let o=`${n.relativePath}/${t}`,r=n.scanContext,s=e.fingerprintVerifiedFile;if(r===void 0||!r.cacheable||typeof s!="function")return os(e,n.root,o,i);try{let a=r.priorFingerprints.get(o)??await s.call(e,r.workspaceRoot,o,i);r.candidateRealPath=a.candidateRealPath;let c=await os(e,n.root,o,i),d=await s.call(e,r.workspaceRoot,o,i);return r.candidateRealPath=d.candidateRealPath,fs(a,d)&&d.size===BigInt(c.byteLength)&&!ys(d,r.scanStartedAtNs)?r.files.set(o,{relativePath:o,byteLimit:i,fingerprint:d}):r.cacheable=!1,c}catch(a){let c=!t.includes("/")&&ae(a)==="NOT_FOUND"&&r.directoryListings.some(l=>l.relativePath===n.relativePath&&!Pt(l.key,t)),d=t===G&&ae(a)==="NOT_FOUND"&&El(r.directoryListings,n.relativePath);throw !c&&!d&&(r.cacheable=false),a}}async function _l(e,n,t){if(n.pinnedFiles!==void 0)return {iconDiagnostics:[]};let i=await Nn(t,async r=>{try{return await Bn(e,n,r,262144)}catch(s){let a=ae(s);return a==="NOT_FOUND"?"missing":a==="LIMIT_EXCEEDED"?"too-large":"bad-path"}}),o=i.file;return {...o===void 0?{}:{iconFile:{path:o.path,sha256:createHash("sha256").update(o.bytes).digest("hex"),contentType:o.contentType,byteLength:o.byteLength}},iconDiagnostics:i.diagnostics}}function El(e,n){let t=e.find(o=>o.relativePath===n);if(t===void 0)return false;if(!Pt(t.key,"dist"))return true;let i=e.find(o=>o.relativePath===`${n}/dist`);return i!==void 0&&!Pt(i.key,"tools.json")}function us(e,n){return JSON.stringify([e.realPath,n.source,n.relativePath])}async function bl(e,n,t,i,o,r,s,a){let c=e.fingerprintVerifiedFile,d=us(t,i),l=o.candidates.get(d),p=i.relativePath,f;try{f=await is(e,n,p);}catch(L){if(ae(L)!=="NOT_FOUND")throw L}let y=f===void 0?void 0:{relativePath:p,key:f};if(y!==void 0&&(i.source==="apps"||i.source==="skills")&&!ee.some(L=>Pt(y.key,L)))return je(s,a)?l!==void 0&&l.candidate===void 0&&l.candidateRealPath===void 0&&l.files.length===0&&l.directoryListings.length===1&&l.directoryListings[0]?.relativePath===y.relativePath&&l.directoryListings[0]?.key===y.key&&(i.source==="apps"?l.diagnostic?.code==="MANIFEST_MISSING":l.diagnostic===void 0)&&typeof c=="function"?{memo:l}:typeof c!="function"?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze([y]),priorFingerprints:new Map,files:new Map,cacheable:true}}:{timeLimitReached:true};let g=async L=>{if(L==="")return y;let I=`${i.relativePath}${L}`;try{let A=await is(e,n,I);return A===void 0?void 0:{relativePath:I,key:A}}catch(A){if(ae(A)==="NOT_FOUND")return;throw A}},_=await Promise.all(ns.map(g)),E=await Promise.all(Tl.map(g));if(!je(s,a))return {timeLimitReached:true};let k=typeof c=="function"&&_.every(L=>L!==void 0),x=_.filter(L=>L!==void 0),T=[...x,...E.filter(L=>L!==void 0)],U=new Map,H=l!==void 0&&k,N;if(l!==void 0&&typeof c=="function"){let L=await Promise.all(l.files.map(async I=>{if(!je(s,a))return {kind:"time",file:I};try{let A=await c.call(e,n,I.relativePath,I.byteLimit);return {kind:"fingerprint",file:I,current:A}}catch(A){return ae(A)==="NOT_FOUND"?{kind:"missing",file:I}:{kind:"error",file:I,error:A}}}));if(L.some(I=>I.kind==="time"))return {timeLimitReached:true};for(let I of L){if(I.kind==="error")throw I.error;if(I.kind==="missing"){H=false;continue}if(I.kind!=="fingerprint")continue;let{file:A,current:h}=I;U.set(A.relativePath,h),N??=h.candidateRealPath,(h.candidateRealPath!==l.candidateRealPath||!fs(h,A.fingerprint)||ys(h,r))&&(H=false);}}let D=l!==void 0&&l.directoryListings.length===T.length&&l.directoryListings.every((L,I)=>L.relativePath===T[I]?.relativePath&&L.key===T[I]?.key);return l!==void 0&&k&&D&&H&&N===l.candidateRealPath?{memo:l}:!k||x.length!==ns.length?{}:{context:{state:o,cacheKey:d,workspaceRoot:n,scanStartedAtNs:r,directoryListings:Object.freeze(T),priorFingerprints:U,files:new Map,...N===void 0?{}:{candidateRealPath:N},cacheable:true}}}function Pt(e,n){try{let t=JSON.parse(e);return Array.isArray(t)&&t.some(i=>Array.isArray(i)&&i[0]===n)}catch{return true}}async function is(e,n,t){let i=As(e);if(typeof i!="function")return;let o=await i.call(e,n,t);if(!Array.isArray(o)||o.some(s=>typeof s=="string"))return;let r=o.map(as);if(!r.some(s=>s===null))return JSON.stringify(r.slice().sort((s,a)=>Vn(s.name,a.name)||Vn(s.kind,a.kind)).map(s=>[s.name,s.kind]))}function fs(e,n){return e.dev===n.dev&&e.ino===n.ino&&e.size===n.size&&e.mtimeNs===n.mtimeNs&&e.ctimeNs===n.ctimeNs}function ys(e,n){let t=e.mtimeNs-n;return t>=-ts&&t<=ts}function ji(e){let n=e.scanContext,t=e.source==="skills"&&e.candidate===void 0&&e.diagnostic===void 0&&n?.files.size===0,i=e.source==="apps"&&e.candidate===void 0&&e.diagnostic?.code==="MANIFEST_MISSING"&&n?.files.size===0,o=t||i;if(n===void 0||!n.cacheable||n.candidateRealPath===void 0&&!o||n.files.size===0&&!o)return;let r=Object.freeze({...!o&&n.candidateRealPath!==void 0?{candidateRealPath:n.candidateRealPath}:{},directoryListings:n.directoryListings,files:Object.freeze([...n.files.values()]),...e.candidate===void 0?{}:{candidate:e.candidate},...e.diagnostic===void 0?{}:{diagnostic:e.diagnostic},...e.identity===void 0?{}:{identity:e.identity},...e.provenance===void 0?{}:{provenance:e.provenance}});n.state.candidates.set(n.cacheKey,r);}function Pl(e,n,t){let i=createHash("sha256"),o=new TextEncoder().encode(ie(e)),r=s=>{let a=new Uint8Array(8);new DataView(a.buffer).setBigUint64(0,BigInt(s)),i.update(a);};return r(o.byteLength),i.update(o),r(n.byteLength),i.update(n),r(t.byteLength),i.update(t),i.digest("hex")}function Nl(e,n){let t={...e.definition,sourceHash:n},i;try{i=fe(t);}catch(r){throw r instanceof C&&r.code==="INPUT_INVALID"?new de("MANIFEST_INVALID","normalized definition is invalid"):r}let o={...t,hash:i};try{me(o);}catch{throw new de("MANIFEST_INVALID","normalized definition is invalid")}return o}function Dl(e,n){return e.actions.some(t=>t.backend.type==="core"&&t.backend.handler!=="state.set"&&!(t.backend.handler===Le&&(n??oe)===oe)&&!dt(n,t.backend))}function Sl(e){if(typeof e.readVerifiedFile=="function")return e.readVerifiedFile;if(typeof e.readFileVerified=="function")return e.readFileVerified}function As(e){if(typeof e.listDirectory=="function")return e.listDirectory;if(typeof e.readDirectory=="function")return e.readDirectory;if(typeof e.readdir=="function")return e.readdir}async function os(e,n,t,i){let o=Sl(e);if(!o)throw new M("READ_DENIED");return ul(await o.call(e,n,t,i))}async function Ml(e,n,t){let i=As(e);if(!i)throw new M("READ_DENIED");let o=await i.call(e,n,t);if(!Array.isArray(o))throw new M("READ_DENIED");return o.map(as).filter(r=>r!==null)}function Ll(e){let n=[];for(let t of [e.reserved,e.builtin])t&&n.push(t);return e.builtins&&"listMcpApps"in e.builtins?n.push(rs(e.builtins)):e.builtins&&n.push(e.builtins),e.builtinCatalog&&n.push(rs(e.builtinCatalog)),n.push({...e.reservedAppIds===void 0?{}:{appIds:e.reservedAppIds},...e.reservedDefinitionIds===void 0?{}:{definitionIds:e.reservedDefinitionIds},...e.reservedToolNames===void 0?{}:{toolNames:e.reservedToolNames}}),n}function rs(e){let n=[],t=[],i=[];for(let o of e.listMcpApps())typeof o.appId=="string"&&n.push(o.appId),o.definition&&typeof o.definition.id=="string"&&t.push(o.definition.id);for(let o of e.listMcpAppTools())typeof o.name=="string"&&i.push(o.name);return {appIds:n,definitionIds:t,toolNames:i}}function Ne(e,n){e.diagnostic||(e.diagnostic=bt(n,e.source,e.relativePath,e.identity?.pluginId));}function Ol(e,n){let t=new Set,i=new Map;for(let r of e){let s=r.identity?.pluginId;if(s===void 0)continue;let a=i.get(s)??[];a.push(r),i.set(s,a);}for(let r of i.values()){if(r.length<2)continue;let s=r.filter(c=>c.provenance!==void 0);if(s.length>0){let c=r.find(d=>n.has(d));if(c){for(let d of s)t.add(d);for(let d of r)d!==c&&d.provenance===void 0&&Ne(d,"RESERVED_ID");continue}for(let d of r)d.provenance===void 0&&Ne(d,"RESERVED_ID");if(s.length>1)for(let d of s)Ne(d,"DUPLICATE_ID");continue}let a=r.filter(c=>c.source==="apps");if(a.length>1){for(let c of a)Ne(c,"DUPLICATE_ID");for(let c of r.filter(d=>d.source==="skills"))Ne(c,"DUPLICATE_ID");}else for(let c of r.filter(d=>d.source==="skills"))Ne(c,"DUPLICATE_ID");}let o=new Map;for(let r of e){if(r.diagnostic?.code==="RESERVED_ID"||t.has(r)||r.provenance===void 0&&!n.has(r)&&i.get(r.identity?.pluginId??"")?.some(c=>c.provenance!==void 0))continue;let s=r.identity?.definitionKey;if(s===void 0)continue;let a=o.get(s)??[];a.push(r),o.set(s,a);}for(let r of o.values())if(r.length>1)for(let s of r)Ne(s,"DUPLICATE_ID");return t}function Rl(e,n,t){let i=new Set,o=new Set,r=new Set,s=new Set([...t.appIds,...n.productBundleReservationMetadata?.reservedAppIds??[]]),a=new Set([...t.definitionIds,...n.productBundleReservationMetadata?.reservedDefinitionIds??[]]);for(let l of Ll(n)){for(let p of l.appIds??[])typeof p=="string"&&i.add(p);for(let p of l.definitionIds??[])typeof p=="string"&&o.add(p);for(let p of l.toolNames??[])typeof p=="string"&&r.add(p);}for(let l of e){let p=l.candidate;if(!p)continue;if(i.has(p.pluginId)||o.has(p.definitionId)){Ne(l,"RESERVED_ID");continue}[p.toolNames.read,p.toolNames.action].filter(y=>y!==void 0).some(y=>r.has(y))&&Ne(l,"DUPLICATE_ID");}let c=[...e.filter(l=>l.provenance!==void 0&&l.diagnostic===void 0).flatMap(l=>l.candidate?[l.candidate]:[]),...(n.productBundleReservationMetadata?.candidates??[]).filter(l=>n.productBundleReservationMetadata?.indexHash!==void 0&&l.provenance?.indexHash===n.productBundleReservationMetadata.indexHash)],d=new Set;for(let l of e){let p=l.candidate;if(!(!p||l.diagnostic||l.source!=="apps"||l.provenance!==void 0)&&e.filter(f=>f.source==="apps"&&f.identity?.pluginId===p.pluginId).length===1&&c.some(f=>f.pluginId===p.pluginId)&&!(a.has(p.definitionId)&&!c.some(f=>f.pluginId===p.pluginId&&f.definitionId===p.definitionId))&&!c.some(f=>f.pluginId!==p.pluginId&&f.definitionId===p.definitionId)&&!e.some(f=>f.identity?.pluginId!==p.pluginId&&f.identity?.definitionKey===`${p.definitionId}\0${p.version}`&&f.diagnostic?.code!=="RESERVED_ID"))try{Ur(p),d.add(l);}catch(f){Ne(l,f instanceof we?ls(f.code):"EXEC_DENIED");}}for(let l of e){let p=l.candidate;p&&l.provenance===void 0&&!d.has(l)&&(s.has(p.pluginId)||a.has(p.definitionId))&&Ne(l,"RESERVED_ID");}return d}function wl(e){return [...e].sort((n,t)=>{let i=Xr.indexOf(n.source)-Xr.indexOf(t.source);return i!==0?i:Vn(n.relativePath,t.relativePath)})}function z(e,n,t){e.diagnostic=bt(n,e.source,e.relativePath,e.identity?.pluginId,t);}async function ss(e,n,t){let i=$e(t,{mode:"local"});if(!i.ok&&i.parseFailure){z(n,Qr(i.rejection.code),Zr(i.rejection));return}let o=yl(i.identity);if(n.bundleIdentity===void 0)n.identity=o;else if(o?.pluginId!==n.bundleIdentity.appId||o.definitionKey!==`${n.bundleIdentity.definitionId}\0${String(n.bundleIdentity.version)}`){z(n,"BUNDLE_INTEGRITY");return}if(!i.ok&&i.builtinOnly){z(n,"RESERVED_ID");return}if(!i.ok){z(n,Qr(i.rejection.code),Zr(i.rejection));return}let r=i.manifest,s={pluginId:r.pluginId,definitionKey:`${r.definitionId}\0${String(r.version)}`};if(n.bundleIdentity===void 0&&(n.identity=s),r.actions.length>0)try{Ti(r.actions.map(v=>({actionId:v.actionId,inputSchema:v.inputSchema})));}catch(v){if(v instanceof we){z(n,ls(v.code));return}throw v}let a;try{a=await Bn(e,n,"ui/index.html",yn);}catch(v){z(n,en(ae(v),"entry"));return}if(a.byteLength>yn){z(n,"LIMIT_EXCEEDED");return}let c;try{c=cs(a);}catch{z(n,"ENTRY_INVALID");return}if(a.byteLength===0||c.length===0){z(n,"ENTRY_INVALID");return}let d=createHash("sha256").update(a).digest("hex");if(r.entryHash!==void 0&&r.entryHash!==d){z(n,"ENTRY_INVALID");return}let l={},p,f;if(r.initialState!==void 0){try{p=await Bn(e,n,"ui/state.json",2097152);}catch(v){z(n,en(ae(v),"initial"));return}if(p.byteLength>2097152){z(n,"LIMIT_EXCEEDED");return}try{let v=fl(p),Y=r.dataPaths??[],j=oi(v,Y);l=ge(j,0,Y),rn(l);}catch{z(n,"INITIAL_STATE_INVALID");return}if(f=createHash("sha256").update(p).digest("hex"),r.initialState.hash!==void 0&&r.initialState.hash!==f){z(n,"INITIAL_STATE_INVALID");return}}let y={...r,entryHash:d,...r.initialState===void 0?{}:{initialState:{path:"ui/state.json",hash:f}}},g=bn(y),_=Pl(y,a,p??new Uint8Array),E;try{E=Nl(g,_);}catch(v){if(v instanceof de){z(n,Al(v));return}throw v}let k;if(n.bundleLineage!==void 0){let v=n.bundleLineage[n.bundleLineage.length-1];if(!v){z(n,"LINEAGE_INVALID");return}let{legacy:Y,...j}=v.definition,{hash:ue,..._e}=E;if(ie(j)!==ie(_e)){z(n,"LINEAGE_STALE");return}if(Y!==void 0&&(E={...E,legacy:Y}),Y!==void 0)try{E={...E,hash:fe(E)},me(E);}catch{z(n,"LINEAGE_INVALID");return}k=n.bundleLineage;}if(n.bundleIdentity!==void 0&&n.bundleIdentity.appId!==r.pluginId){z(n,"BUNDLE_INTEGRITY");return}if(n.bundleIdentity!==void 0&&(n.bundleIdentity.definitionId!==E.id||n.bundleIdentity.version!==E.version||n.bundleIdentity.definitionHash!==E.hash)){z(n,"LINEAGE_STALE");return}let x=await _l(e,n,i.mcpb?.icon),T=cl(r.pluginId),U=r.actions.length===0?{read:T.read}:T,H=Qe(g),N=Qe(y),D=Qe(E),L=Qe({...g.handlers}),I=es(a),A=p===void 0?void 0:es(p),h=Object.freeze({...n.provenance===void 0?{}:{provenance:n.provenance},entry:Object.freeze({path:"ui/index.html",hash:d,bytes:I}),...A===void 0?{}:{initialState:Object.freeze({path:"ui/state.json",hash:f,bytes:A})}}),b={appId:r.pluginId,pluginId:r.pluginId,definitionId:r.definitionId,version:r.version,...i.releaseVersion===void 0?{}:{releaseVersion:i.releaseVersion},manifestFile:i.file,...i.mcpb===void 0?{}:{mcpb:Qe(i.mcpb)},relativePath:n.relativePath,manifest:N,normalized:H,name:r.name,description:r.description,...r.icon===void 0?{}:{icon:r.icon},...r.tone===void 0?{}:{tone:r.tone},...x.iconFile===void 0?{}:{iconFile:Object.freeze({...x.iconFile})},...x.iconDiagnostics.length===0?{}:{iconDiagnostics:Object.freeze([...x.iconDiagnostics])},definition:D,handlers:L,resources:h,html:c,entryBytes:I,entryHash:d,initialState:Qe(l),...A===void 0?{}:{initialStateBytes:A},...f===void 0?{}:{initialStateHash:f},sourceHash:_,toolNames:Object.freeze(U)},B=n.provenance===void 0?{...b,source:n.source}:{...b,provenance:n.provenance,lineage:k??[]};n.candidate=Object.freeze(B),Dl(r,E.usage)&&z(n,"EXEC_DENIED");}async function Is(e,n){let t={};for(let i of ee)try{t[i]=await Bn(e,n,i,262144);}catch(o){if(ae(o)==="NOT_FOUND")continue;return {files:t,failure:en(ae(o),"manifest")}}if(t[K]!==void 0)try{t[G]=await Bn(e,n,G,262144);}catch(i){if(ae(i)!=="NOT_FOUND")return {files:t,failure:en(ae(i),"manifest")}}return {files:t}}function Fi(e){return ee.some(n=>e[n]!==void 0)}async function Cl(e,n){let{files:t,failure:i}=await Is(e,n);if(i!==void 0){z(n,i);return}let o=t[K];return o!==void 0&&!li(o)&&(delete t[K],delete t[G]),Fi(t)?t:void 0}function Ul(e,n,t,i=al,o=false,r=new Set){let s=wl(e),a=Ol(s,r),c=Object.freeze(s.filter(f=>f.candidate!==void 0&&f.diagnostic===void 0&&!a.has(f)).map(f=>f.candidate)),d=Object.freeze(s.filter(f=>f.diagnostic!==void 0).map(f=>f.diagnostic)),l=o?Object.freeze({...t===void 0?{}:{indexHash:t},candidates:Object.freeze(s.filter(f=>f.source==="bundled"&&f.diagnostic===void 0&&t!==void 0&&f.candidate?.provenance?.indexHash===t).map(f=>f.candidate)),diagnostics:Object.freeze(d.filter(f=>f.source==="bundled").map(f=>Object.freeze({...f}))),reservedAppIds:Object.freeze([...i.appIds]),reservedDefinitionIds:Object.freeze([...i.definitionIds])}):void 0,p={apps:c,diagnostics:d,complete:n===void 0,...n===void 0?{}:{incompleteReason:n},...t===void 0?{}:{productBundleIndexHash:t},...l===void 0?{}:{productBundleSnapshotMetadata:l}};return Object.defineProperty(p,"candidates",{configurable:false,enumerable:false,get:()=>c}),Object.freeze(p)}function kl(e){if(e===null||typeof e!="object"&&typeof e!="function")return false;let n=e;return typeof n.readVerifiedFile=="function"||typeof n.readFileVerified=="function"||typeof n.listDirectory=="function"||typeof n.readDirectory=="function"||typeof n.readdir=="function"}function xl(e,n){if(kl(e))return {fs:e,options:{}};let t=e??n??{};return {fs:t.filesystem??t.fileSystem??t.fs??Hr,options:t}}async function gs(e,n,t){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");let{fs:i,options:o}=xl(n,t),r=o.clock??hl,s=r(),a=await Kr(o.productBundle,i,s,r),c=r(),d=BigInt(Date.now())*1000000n,l=[],p=0,f,y=false,g,_;if(o.scanCache!==void 0&&typeof i.getRootIdentity=="function"&&typeof i.fingerprintVerifiedFile=="function")try{_=await i.getRootIdentity(e),g=vr(o.scanCache,_),g.scanStartedAtNs=d;}catch(N){if(ae(N)!=="NOT_FOUND")throw N}let E=g!==void 0&&o.productBundle===void 0&&a.packages.length===0&&a.diagnostics.length===0,k=new Set,x=true;l.push(...a.diagnostics.map(N=>({source:N.source,root:o.productBundle?.root??e,name:"",relativePath:N.relativePath,diagnostic:N})));let T=a.reservedIds;a.incomplete&&(f="time_limit");for(let N of a.packages){if(!je(c,r)){y=true,f="time_limit";break}let D=N.indexEntry,L=D.packageDir,I=N.files===void 0?void 0:gl(L,N.files),A=a.indexHash===void 0?void 0:dr(Object.freeze({kind:"bundled",launcher:D.launcher!==false,indexHash:a.indexHash,packageDir:L,appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash,files:D.files}),I),h={source:"bundled",root:o.productBundle?.root??e,name:L.slice(5),relativePath:L,...A===void 0?{}:{provenance:A},...N.files===void 0?{}:{pinnedFiles:N.files},...N.lineage===void 0?{}:{bundleLineage:N.lineage},bundleIdentity:{appId:D.appId,definitionId:D.definition.id,version:D.definition.version,definitionHash:D.definition.hash},identity:Il(D)};if(l.push(h),p+=1,N.failureCode!==void 0){z(h,N.failureCode);continue}if(N.files?.has(G)===true){z(h,"EXEC_DENIED",{reason:{path:"",rule:"bundled-tool-mode-unsupported",file:G}});continue}let b={};for(let B of ee){let v=N.files?.get(B);v!==void 0&&(b[B]=v);}if(!Fi(b)){z(h,"BUNDLE_INTEGRITY");continue}if(await ss(i,h,b),!je(c,r)){y=true,f="time_limit";break}}let U=[{source:"apps",directory:"apps"},{source:"skills",directory:"skills"}];e:for(let N of U){let{source:D,directory:L}=N,I;try{I=await Ml(i,e,L);}catch(h){if(ae(h)==="NOT_FOUND")continue;E=false,x=false,l.push({source:D,root:e,name:"",relativePath:D,diagnostic:bt(en(ae(h),"manifest"),D,D)});continue}let A=I.filter(h=>h.kind==="directory"||h.kind==="symlink").filter(h=>ll(h.name)).map(h=>({source:D,root:e,name:h.name,relativePath:pl(D,h.name)})).sort((h,b)=>Vn(h.relativePath,b.relativePath));for(let h of A){let b={...h};if(l.push(b),_!==void 0?k.add(us(_,b)):E=false,!je(c,r)){y=true,f="time_limit";break e}let B;if(g!==void 0&&_!==void 0){try{let j=await bl(i,e,_,b,g,d,c,r);if(j.timeLimitReached){y=!0,f="time_limit";break e}b.scanContext=j.context,B=j.memo;}catch(j){E=false,z(b,en(ae(j),"manifest"));continue}B===void 0&&(E=false);}if(B!==void 0){if(b.candidate=B.candidate,b.diagnostic=B.diagnostic,b.identity=B.identity,D==="skills"&&B.candidate===void 0&&B.diagnostic===void 0)continue;if(p>=64){z(b,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){z(b,"LIMIT_EXCEEDED");continue}if(p+=1,!je(c,r)){y=true,f="time_limit";break e}continue}let v;if(D==="skills"&&(v=await Cl(i,b),v===void 0)){b.diagnostic===void 0&&ji(b);continue}if(p>=64){z(b,"LIMIT_EXCEEDED");continue}if(h.relativePath.split("/").length-1>2){z(b,"LIMIT_EXCEEDED");continue}if(!je(c,r)){y=true,f="time_limit";break e}if(p+=1,v===void 0){let j=await Is(i,b);if(j.failure!==void 0||!Fi(j.files)){z(b,j.failure??en("NOT_FOUND","manifest")),ji(b);continue}v=j.files;}if(await ss(i,b,v),ji(b),!je(c,r)){y=true,f="time_limit";break e}}}if(g!==void 0&&_!==void 0){let N=[...k].sort(Vn),D=g.lastCandidateKeys,L=D!==void 0&&D.length===N.length&&D.every((A,h)=>A===N[h]);if(E=E&&L,x&&!y&&f===void 0)for(let A of g.candidates.keys())try{JSON.parse(A)[0]===_.realPath&&!k.has(A)&&g.candidates.delete(A);}catch{g.candidates.delete(A);}let I=[...g.candidates.keys()].filter(A=>{try{return JSON.parse(A)[0]===_.realPath}catch{return false}});E=E&&I.length===k.size&&I.every(A=>k.has(A))&&!y&&f===void 0,g.lastCandidateScanUnchanged=E,x&&!y&&f===void 0&&(g.lastCandidateKeys=Object.freeze(N));}y&&l.push({source:"apps",root:e,name:"",relativePath:"apps",diagnostic:bt("DISCOVERY_TIME_LIMIT","apps","apps")});let H=Rl(l,o,T);return Ul(l,f,a.indexHash,T,o.productBundle!==void 0,H)}var al,vi,Xr,dl,ns,Tl,ts,ms=F(()=>{m();Ke();zn();Ue();an();yi();fi();We();At();kr();pt();at();jr();Oi();ct();xi();xi();al=Tt([]),vi="crewx_local_app_";Xr=["bundled","apps","skills"],dl=new TextDecoder("utf-8",{fatal:true});ns=["","/ui"],Tl=["/dist"],ts=2000000000n;});m();yi();m();an();m();var Yo="SKILL.md",Jd=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;function qo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Wd(e){return e.isDirectory()||e.isSymbolicLink()}function tr(e){try{return existsSync(e)&&statSync(e).isDirectory()}catch{return false}}function Ai(e){let n;try{n=readFileSync(e,"utf8");}catch{return {frontmatter:{},readable:false,valid:false,hasFrontmatter:false}}let t=n.match(Jd);if(!t)return {frontmatter:{},readable:true,valid:true,hasFrontmatter:false};try{let i=load(t[1]??"");if(!qo(i))return {frontmatter:{},readable:!0,valid:!1,hasFrontmatter:!0};let o=qo(i.metadata)?i.metadata:void 0;return {frontmatter:{...typeof i.name=="string"?{name:i.name}:{},...typeof(o?.version??i.version)=="string"?{version:o?.version??i.version}:{},...typeof i.description=="string"?{description:i.description}:{}},readable:!0,valid:!0,hasFrontmatter:!0}}catch{return {frontmatter:{},readable:true,valid:false,hasFrontmatter:true}}}function Kd(e){return [join(e,Yo),join(e,"skill",Yo)]}function Zo(e,n){if(!tr(e))return null;for(let t of Kd(e)){if(!existsSync(t))continue;let o=Ai(t).frontmatter;return {name:o.name??n,...o.version===void 0?{}:{version:o.version},...o.description===void 0?{}:{description:o.description},skillMdPath:t,dir:e}}return null}function Qo(e){try{return readdirSync(e,{withFileTypes:!0}).filter(Wd)}catch{return []}}function er(e,n,t){!e||n.has(e.name)||(n.add(e.name),t.push(e));}function ir(e){let n=[],t=new Set;for(let i of e)if(tr(i))for(let o of Qo(i)){if(o.name.startsWith("@")){let r=join(i,o.name);for(let s of Qo(r))er(Zo(join(r,s.name),s.name),t,n);continue}er(Zo(join(i,o.name),o.name),t,n);}return n.sort((i,o)=>i.name.localeCompare(o.name))}m();rt();var Xd=/^[A-Za-z0-9_$.[\]"-]{0,200}$/,Yd=/^[a-z][a-z0-9-]{0,63}$/,qd="<unknown>";function Zd(e){return typeof e=="string"&&(ee.includes(e)||e===G)}function or(e){if(typeof e!="object"||e===null)return;let{file:n,path:t,rule:i}=e;if(!(typeof i!="string"||!Yd.test(i)))return {...Zd(n)?{file:n}:{},path:typeof t=="string"&&Xd.test(t)?t:qd,rule:i}}function rr(e){if(!Array.isArray(e))return;let n=ee.filter(t=>e.includes(t));return n.length>0?n:void 0}ms();var jl=/^[A-Za-z][A-Za-z0-9._-]{0,127}$/;function St(e){let n="screenHash"in e?e.screenHash:void 0,i=("skillHash"in e?e.skillHash:void 0)??(e.relativePath!==void 0&&e.fileBytes!==void 0?Fl(e.relativePath,e.fileBytes):void 0);if(n!==void 0&&i!==void 0){let o=JSON.stringify({screenHash:n,skillHash:i});return createHash("sha256").update(o,"utf8").digest("hex")}if(n!==void 0)return n;if(i!==void 0)return i;throw new TypeError("App definition hash input must contain a screenHash or skill bytes")}function Fl(e,n){let t=new TextEncoder().encode(Mt(e)),i=Vl(n),o=new Uint8Array(t.byteLength+1+i.byteLength);return o.set(t,0),o[t.byteLength]=0,o.set(i,t.byteLength+1),createHash("sha256").update(o).digest("hex")}function Vl(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(Array.isArray(e)&&e.every(n=>Number.isInteger(n)&&n>=0&&n<=255))return Uint8Array.from(e);throw new TypeError("fileBytes must be UTF-8 text or bytes")}function Mt(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))throw new TypeError("relative path must be package-relative");let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");if(!n||n.split("/").some(t=>t===".."))throw new TypeError("relative path must stay inside the package");return n}function Nt(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function Es(e,n){let t=relative(e,n).split(sep).join("/");return !t||t===".."||t.startsWith("../")||isAbsolute(t)?null:Mt(t)}function Bl(e){return e==="apps"||e.startsWith("apps/")?"apps":e==="skills"||e.startsWith("skills/")?"skills":e==="node_modules"||e.startsWith("node_modules/")?"node_modules":null}function Ts(e){return Object.freeze({packageRoot:e})}function Hl(e){return Object.freeze({id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??oe,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}})}function bs(e){return {capabilities:Object.freeze([...e]),origin:"local",ownership:"unknown",shareability:"unknown",sharingAvailability:"unavailable"}}function zl(e,n){let t=e.candidate,i=t.provenance!==void 0,o=n&&!i?["screen","skill"]:["screen"],r=Hl(t),s=St(n?{screenHash:r.hash,skillHash:n.skillHash}:{screenHash:r.hash}),a=t.description||n?.skill.description||"",c=t.releaseVersion??String(t.version),d={appId:t.pluginId,name:t.name,description:a,version:c,...bs(o),definition:r,...n===void 0||i?{}:{skillName:n.skill.name},...i?{provenance:t.provenance}:{localDefinitionRef:Ts(e.packageRoot)},definitionHash:s,...t.manifest.csp===void 0?{}:{connectDomains:Object.freeze([...t.manifest.csp.connectDomains])}};return {...i?{}:{packageRoot:e.packageRoot},source:i?"bundled":t.source,appId:d.appId,capabilities:o,summary:Object.freeze(d)}}function $l(e){let n=Gl(e.skill.name),t={appId:n,name:e.skill.name,description:e.skill.description??"",...e.skill.version===void 0?{}:{version:e.skill.version},...bs(["skill"]),skillName:e.skill.name,localDefinitionRef:Ts(e.packageRoot),definitionHash:St({skillHash:e.skillHash})};return {packageRoot:e.packageRoot,source:e.source,appId:n,capabilities:["skill"],summary:Object.freeze(t)}}function Gl(e){return `skill.${e.replace(/^@/,"").replace(/\//g,".").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,122)||"unnamed"}`}function Q(e,n,t,i,o){let r=or(o?.reason),s=rr(o?.files);return Object.freeze({code:e,source:n,relativePath:Jl(t),...i===void 0?{}:{appId:i},...r===void 0?{}:{reason:r},...s===void 0?{}:{files:s}})}function Jl(e){if(typeof e!="string"||e.length===0||isAbsolute(e)||/[\\\u0000]/.test(e))return "<unknown>";let n=e.split("/").filter(t=>t.length>0&&t!==".").join("/");return n.split("/").some(t=>t==="..")?"<unknown>":n}function Ps(e){return Q(e.code,e.source,e.relativePath,e.pluginId,e)}function Wl(e,n){let t=Es(e,n.dir);if(!t)return {diagnostic:Q("PATH_ESCAPED","node_modules","node_modules")};let i=Bl(t);if(!i)return {diagnostic:Q("PATH_ESCAPED","node_modules",t)};let o=Ai(n.skillMdPath);if(!o.readable)return {diagnostic:Q("SKILL_READ_FAILED",i,t)};if(!o.valid)return {diagnostic:Q("SKILL_INVALID",i,t)};let r=Kl(n.dir,n.skillMdPath);if(!r)return {diagnostic:Q("PATH_ESCAPED",i,t)};try{let s=new Uint8Array(readFileSync(n.skillMdPath));return {skill:n,packageRoot:t,relativeSkillPath:r,skillHash:St({relativePath:r,fileBytes:s}),source:i}}catch{return {diagnostic:Q("SKILL_READ_FAILED",i,t)}}}function Kl(e,n){let t=relative(e,n).split(sep).join("/");try{return Mt(t)}catch{return null}}function Xl(e){if(!jl.test(e.appId))return {diagnostic:Q("BUILTIN_INVALID","builtin",`builtin/${e.appId||"unknown"}`)};let n=e.definition===void 0?void 0:{id:e.definition.id,version:e.definition.version,hash:e.definition.hash,usage:e.definition.usage??oe,...e.definition.detailPanel===void 0?{}:{detailPanel:e.definition.detailPanel},...e.definition.displayModes===void 0?{}:{displayModes:e.definition.displayModes},...e.definition.summaryProjection===void 0?{}:{summaryProjection:e.definition.summaryProjection}},t=n?.hash??createHash("sha256").update(JSON.stringify({appId:e.appId,name:e.name,description:e.description}),"utf8").digest("hex"),i={appId:e.appId,name:e.name,description:e.description,...n===void 0?{}:{version:String(n.version),definition:n},capabilities:["screen"],origin:"builtin",ownership:"unknown",shareability:"forbidden",sharingAvailability:"unavailable",definitionHash:t};return {source:"builtin",appId:e.appId,summary:Object.freeze(i)}}function Yl(e){return e.builtinCatalog}function ql(e){let n=e.packageRoot??e.relativePath??e.packageRootPath;if(n===void 0)return null;try{return Mt(n)}catch{return null}}function Zl(e){let n=e.marketplaceContentId;return typeof n=="string"&&n.length>0?n:void 0}function Ql(e,n,t){let i=n.installed??[],o=new Map;for(let s of i){let a=ql(s);if(!a){t.push(Q("INSTALLED_IDENTITY_MISMATCH","installed","installed"));continue}let c=o.get(a);if(c&&JSON.stringify(c)!==JSON.stringify(s)){t.push(Q("INSTALLED_IDENTITY_MISMATCH","installed",a));continue}o.set(a,s);}let r=new Map;for(let s of e)s.packageRoot!==void 0&&r.set(s.packageRoot,s);for(let[s,a]of o){let c=r.get(s);if(!c){t.push(Q("INSTALLED_MISSING","installed",s,a.appId));continue}let d=Zl(a);if(!d){t.push(Q("INSTALLED_CONTENT_ID_MISSING","installed",s,a.appId));continue}if(a.appId!==void 0&&a.appId!==c.appId||a.definitionHash!==void 0&&a.definitionHash!==c.summary.definitionHash){t.push(Q("INSTALLED_IDENTITY_MISMATCH","installed",s,a.appId));continue}let l={...c.summary,origin:"installed",...a.slug===void 0?{}:{slug:a.slug},marketplaceContentId:d},p=e.indexOf(c);p>=0&&(e[p]={...c,summary:Object.freeze(l)});}}function eu(e,n){let t=new Map;for(let o of e){let r=t.get(o.appId)??[];r.push(o),t.set(o.appId,r);}let i=new Set;for(let o of t.values()){if(o.length<2)continue;let r=o.some(s=>s.source==="builtin")?"builtin":o.some(s=>s.source==="bundled")?"bundled":void 0;if(r==="bundled"){let s=o.filter(a=>a.source==="apps"&&a.summary.definition!==void 0);if(s.length===1){for(let a of o)a.source==="bundled"?i.add(a):a!==s[0]&&(i.add(a),n.push(Q("RESERVED_ID",a.source,Dt(a),a.appId)));continue}}if(r!==void 0){let s=o.filter(a=>a.source===r);for(let a of o.filter(c=>c.source!==r))i.add(a),n.push(Q("RESERVED_ID",a.source,Dt(a),a.appId));if(s.length>1)for(let a of s)i.add(a),n.push(Q("DUPLICATE_ID",a.source,Dt(a),a.appId));continue}for(let s of o)i.add(s),n.push(Q("DUPLICATE_ID",s.source,Dt(s),s.appId));}return e.filter(o=>!i.has(o))}function Dt(e){return e.packageRoot??e.summary.provenance?.packageDir??`builtin/${e.appId}`}function nu(e,n){return e.filter(t=>!(t.code==="MANIFEST_MISSING"&&n.has(t.relativePath))).map(Ps)}function tu(e){return e.filesystem}function iu(e,n){let t=tu(e),i=e.registeredProductBundle;return {...t===void 0?{}:{filesystem:t},...e.productBundle===void 0?{}:{productBundle:e.productBundle},...n===void 0?{}:{builtinCatalog:n},...i===void 0?{}:{productBundleReservationMetadata:i}}}async function Ns(e,n={}){if(typeof e!="string"||e.length===0)throw new TypeError("workspaceRoot must be explicit");if(n.productBundle!==void 0&&n.registeredProductBundle!==void 0)throw new TypeError("registeredProductBundle cannot be combined with product bundle discovery");let t=Yl(n),i=await gs(e,iu(n,t)),o=n.registeredProductBundle??i.productBundleSnapshotMetadata,r=[join(e,"skills"),join(e,"node_modules"),join(e,"apps")],s=[],a=[],c=[],d=new Set;for(let A of r)for(let h of ir([A])){let b=Es(e,h.dir);(b===null||!d.has(b))&&(c.push(h),b!==null&&d.add(b));}for(let A of c){let h=Wl(e,A);"diagnostic"in h?s.push(h.diagnostic):a.push(h);}let l=new Map,p=n.registeredProductBundle?.indexHash,f=(n.registeredProductBundle?.candidates??[]).filter(A=>p!==void 0&&A.provenance?.indexHash===p),y=[...new Set([...i.apps??i.candidates??[],...i.productBundleSnapshotMetadata?.candidates??[]]),...f],g=new Set(f),_=new Set(p===void 0?[]:(t?.listMcpApps()??[]).filter(A=>A.provenance?.indexHash===p).map(A=>A.appId));for(let A of y){if(g.has(A)&&A.provenance?.indexHash===p&&_.has(A.appId))continue;let h=A.provenance===void 0?`workspace\0${A.relativePath}`:`bundled\0${A.provenance.indexHash}\0${A.provenance.packageDir}`;l.set(h,{candidate:A,packageRoot:A.relativePath});}let E=new Map(a.map(A=>[A.packageRoot,A])),k=[];for(let A of l.values()){let h=A.candidate.provenance===void 0?E.get(A.packageRoot):void 0,b=zl(A,h);k.push({...b.packageRoot===void 0?{}:{packageRoot:b.packageRoot},source:b.source,appId:b.appId,summary:b.summary});}let x=new Set([...l.values()].filter(A=>A.candidate.provenance===void 0).map(A=>A.packageRoot)),T=o===void 0?new Set:new Set(i.diagnostics.filter(A=>A.code==="RESERVED_ID"&&A.source!=="bundled").map(A=>A.relativePath)),U=new Set(o?.reservedAppIds??[]);for(let A of a){let h=$l(A);if(!(x.has(A.packageRoot)||T.has(A.packageRoot))){if(U.has(h.appId)){s.push(Q("RESERVED_ID",A.source,A.packageRoot,h.appId));continue}k.push({packageRoot:h.packageRoot,source:h.source,appId:h.appId,summary:h.summary});}}let H=[...nu(i.diagnostics,new Set(a.map(A=>A.packageRoot))),...s,...n.registeredProductBundle?.diagnostics.filter(A=>A.source==="bundled").map(Ps)??[]],N=[];if(t)for(let A of t.listMcpApps()){let h=Xl(A);"diagnostic"in h?H.push(h.diagnostic):N.push(h);}let D=eu([...k,...N],H);Ql(D,n,H);let L=D.map(A=>A.summary).sort((A,h)=>Nt(A.appId,h.appId)),I=[...H].sort((A,h)=>Nt(A.relativePath,h.relativePath)||Nt(A.code,h.code)||Nt(A.appId??"",h.appId??""));return Object.freeze({items:Object.freeze(L),diagnostics:Object.freeze(I)})}m();m();m();function ou(e){let n=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),i=e.split("/").map(o=>o==="**"?".*":o.split("*").map(n).join("[^/]*"));return new RegExp(`^${i.join("\\/")}$`)}function gn(e,n){try{return ou(n).test(e)}catch{return false}}function Lt(e,...n){let t=e.split("/");if(t.length<n.length)return false;let i=t.length-n.length;return n.every((o,r)=>gn(t[i+r],o))}function ru(e,n){return e.split("/").some(t=>gn(t,n))}var Ds=[{label:".env*",test:e=>gn(e,".env*")},{label:".git/",test:(e,n,t)=>t&&e===".git"},{label:"memory/",test:(e,n,t)=>t&&e==="memory"},{label:"*.key",test:e=>gn(e,"*.key")},{label:"*.pem",test:e=>gn(e,"*.pem")},{label:"auth.json",test:e=>e==="auth.json"},{label:"node_modules/",test:(e,n,t)=>t&&e==="node_modules"},{label:"conversations/",test:(e,n,t)=>t&&e==="conversations"},{label:".crewx/threads/",test:(e,n,t)=>t&&Lt(n,".crewx","threads")},{label:".crewx/crewx.db",test:(e,n,t)=>!t&&Lt(n,".crewx","crewx.db")},{label:".crewx/*.log",test:(e,n,t)=>!t&&Lt(n,".crewx","*.log")},{label:".crewx/publish/",test:(e,n,t)=>t&&Lt(n,".crewx","publish")},{label:".crewx/",test:(e,n)=>ru(n,".crewx")}];function mn(e,n,t){for(let i of Ds)if(i.test(e,n,t))return i.label;return null}m();var Fe=class extends Error{constructor(t,i){super(`publish: [${t}]${i?` ${i}`:""}`);this.code=t;}code;name="PublishError"};function P(e,n){return new Fe(e,n)}function Ss(e,n){if(!n||/[\\\u0000]/.test(n)||pe.posix.isAbsolute(n)||n.split("/").some(y=>!y||y==="."||y===".."))throw P("PACKAGE_PATH_TRAVERSAL","package root must be a safe workspace-relative path");let t=pe.resolve(e),i=pe.resolve(t,...n.split("/"));if(!i.startsWith(`${t}${pe.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","package root escaped the workspace");function o(y,g){let _;try{_=te.lstatSync(y);}catch{throw P("PACKAGE_FILE_INVALID",`package directory is missing: ${g}`)}if(_.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${g}`);if(!_.isDirectory())throw P("PACKAGE_FILE_INVALID",`not a package directory: ${g}`)}o(t,".");let r=t,s="",a=null;for(let y of n.split("/"))r=pe.join(r,y),s=s?`${s}/${y}`:y,o(r,s),a??=mn(y,s,true);let c=[],d=[];function l(y,g){o(y,g);let _=te.readdirSync(y,{withFileTypes:true});for(let E of _){let k=`${g}/${E.name}`,x=pe.join(y,E.name);if(E.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${k}`);let T=mn(E.name,k,E.isDirectory());T?d.push({path:k,rule:T}):E.isDirectory()?l(x,k):E.isFile()&&c.push(k);}}a?d.push({path:n,rule:a}):l(i,n);let p=new TextEncoder,f=(y,g)=>Buffer.compare(p.encode(y),p.encode(g));return c.sort(f),d.sort((y,g)=>f(y.path,g.path)),{included:c,excluded:d}}function Ms(e){let n=[],t=[];function i(o,r,s){let a;try{a=te.readdirSync(o,{withFileTypes:!0});}catch{return}a.sort((c,d)=>c.name.localeCompare(d.name));for(let c of a){let d=r?`${r}/${c.name}`:c.name,l=pe.join(o,c.name);if(c.isSymbolicLink()){let p;try{p=te.statSync(l);}catch{t.push({path:d,rule:"symlink"});continue}if(p.isDirectory()){t.push({path:d,rule:s??"symlink-dir"});continue}let f=s??mn(c.name,d,false);f?t.push({path:d,rule:f}):t.push({path:d,rule:"symlink"});continue}if(c.isDirectory()){let p=s??mn(c.name,d,true);i(l,d,p);continue}if(c.isFile()){let p=s??mn(c.name,d,false);p?t.push({path:d,rule:p}):n.push(d);}}}return i(e,"",null),n.sort(),t.sort((o,r)=>o.path<r.path?-1:o.path>r.path?1:0),{included:n,excluded:t}}m();var su=[{rule:"token-prefix",regex:/\b(?:sk-|ghp_|xoxb-)[A-Za-z0-9_-]{10,}/},{rule:"private-key",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----/},{rule:"aws-access-key",regex:/\bAKIA[0-9A-Z]{16}\b/}];function au(e){return e.includes(0)}function zi(e,n,t){let i=[];for(let o of n){let r=pe.join(e,o),s;try{let c=t?.get(o);s=c===void 0?te.readFileSync(r):Buffer.from(c);}catch{continue}if(au(s))continue;s.toString("utf8").split(/\r\n|\r|\n/).forEach((c,d)=>{for(let{rule:l,regex:p}of su)p.test(c)&&i.push({path:o,line:d+1,rule:l});});}return i}m();var Rs=/^[a-z0-9-]+$/,cu=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,du=/^[A-Za-z_][A-Za-z0-9_]*$/;function pu(e){let n=pe.join(e,"crewx.yaml");if(!te.existsSync(n))return {};let t;try{t=ws.load(te.readFileSync(n,"utf8"));}catch{return {}}if(!t||typeof t!="object")return {};let i=t.metadata;if(!i||typeof i!="object")return {};let o=i;return {name:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,description:typeof o.description=="string"?o.description:void 0,requiredEnv:o.requiredEnv,crewxMinVersion:typeof o.crewxMinVersion=="string"?o.crewxMinVersion:void 0}}function lu(e){return $i.createHash("sha256").update(e).digest("hex")}function Cs(e){let n;try{n=te.lstatSync(e);}catch{throw P("PACKAGE_FILE_INVALID",`file is not readable: ${pe.basename(e)}`)}if(n.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!n.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return $i.createHash("sha256").update(new Uint8Array(te.readFileSync(e))).digest("hex")}function uu(e,n){let t=new TextEncoder().encode(e),i=new TextEncoder().encode(n),o=Math.min(t.byteLength,i.byteLength);for(let r=0;r<o;r+=1){let s=t[r]-i[r];if(s!==0)return s}return t.byteLength-i.byteLength}function Us(e){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||pe.posix.isAbsolute(e)||e.split("/").some(n=>n===".."||n.length===0))throw P("PACKAGE_PATH_TRAVERSAL","manifest file path must be a non-empty POSIX relative path")}function fu(e){if(!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(e))throw P("APP_PACKAGE_ROOT_INVALID","packageRoot must be apps/<safe-id> or skills/<safe-id>")}function ks(e){if(!cu.test(e))throw new Error(`publish: invalid version "${e}" \u2014 must be semver (e.g. 1.0.0)`)}function xs(e,n,t={}){let i=pu(e),o=i.name??pe.basename(e);if(!Rs.test(o))throw new Error(`publish: invalid name "${o}" \u2014 must match ${Rs} (lowercase letters, numbers, hyphen only)`);let r=t.version??i.version;if(!r)throw new Error("publish: version is required \u2014 set crewx.yaml metadata.version or pass opts.version");ks(r);let s=Array.isArray(i.requiredEnv)?i.requiredEnv:[],a=[];for(let l of s){if(typeof l!="string"||!du.test(l))throw new Error(`publish: requiredEnv must contain names only (no values), got "${String(l)}"`);a.push(l);}let c=n.map(l=>(Us(l),{path:l,sha256:Cs(pe.join(e,l))})).sort((l,p)=>l.path<p.path?-1:l.path>p.path?1:0),d={name:o,version:r,type:"template",description:i.description??"",files:c,requiredEnv:a};return i.crewxMinVersion&&(d.crewxMinVersion=i.crewxMinVersion),d}function yu(e){let n=e.toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw P("APP_PACKAGE_ROOT_INVALID","appId cannot produce a marketplace name");return n}function vs(e,n){if(fu(n.packageRoot),!n.version)throw new Error("publish: version is required for App publishing \u2014 pass opts.version");if(ks(n.version),typeof n.description!="string")throw new Error("publish: App description must be a string");let t=[...new Set(n.capabilities)].sort();if(t.length===0||t.some(s=>s!=="screen"&&s!=="skill"))throw new Error("publish: App capabilities must contain screen or skill");let i=`${n.packageRoot}/`;if(t.includes("screen")){if(typeof n.definitionId!="string"||n.definitionId.length===0)throw P("APP_UI_MANIFEST_INVALID","screen App manifests require definitionId");let s=n.includedFiles.includes(`${i}manifest.json`),a=n.includedFiles.includes(`${i}ui-plugin.json`);if(!s&&!a)throw P("APP_UI_MANIFEST_INVALID","screen App is missing manifest.json or ui-plugin.json");if(s&&!a)throw P("APP_UI_MANIFEST_INVALID","a manifest.json App must also ship a generated ui-plugin.json");if(!n.includedFiles.includes(`${i}ui/index.html`))throw P("APP_UI_MANIFEST_INVALID","screen App is missing ui/index.html")}if(t.includes("skill")&&!n.includedFiles.includes(`${i}SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");let o=new Set,r=n.includedFiles.map(s=>{if(Us(s),!s.startsWith(i))throw P("PACKAGE_PATH_TRAVERSAL","App manifest file is outside packageRoot");let a=n.generatedFiles?.get(s);return a!==void 0&&o.add(s),{path:s,sha256:a===void 0?Cs(pe.join(e,s)):lu(a),...a===void 0?{}:{generated:true}}}).sort((s,a)=>uu(s.path,a.path));if(o.size>0&&(o.size!==1||!o.has(`${i}ui-plugin.json`)))throw new Error("publish: only the generated ui-plugin.json may be present in an App package");return {manifestVersion:1,name:yu(n.appId),version:n.version,type:"app",description:n.description,appId:n.appId,...n.definitionId===void 0?{}:{definitionId:n.definitionId},...n.definitionHash===void 0?{}:{definitionHash:n.definitionHash},capabilities:t,packageRoot:n.packageRoot,files:r,requiredEnv:[]}}m();function js(e){return $i.createHash("sha256").update(e).digest("hex")}function zs(e,n){if(typeof n!="string"||n.length===0||n.includes("\\")||n.includes("\0")||pe.posix.isAbsolute(n)||n.split("/").some(o=>o===".."||o.length===0))throw P("PACKAGE_PATH_TRAVERSAL","archive paths must be non-empty POSIX relative paths");let t=pe.resolve(e),i=pe.resolve(t,...n.split("/"));if(i!==t&&!i.startsWith(`${t}${pe.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","archive path escaped its root");return i}function Fs(e,n){let t=zs(e,n),i;try{i=te.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID","manifest file is missing")}if(i.isSymbolicLink())throw P("PACKAGE_SYMLINK","symlink content is not publishable");if(!i.isFile())throw P("PACKAGE_FILE_INVALID","only regular files are publishable");return new Uint8Array(te.readFileSync(t))}async function $s(e,n,t={}){let i=pe.join(e,".crewx","publish");te.mkdirSync(i,{recursive:true});let o=pe.join(i,`${n.name}-${n.version}.tgz`),r=pe.join(i,`.${n.name}-${n.version}.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp.tgz`),s=te.mkdtempSync(pe.join(Vs.tmpdir(),"crewx-publish-"));try{let a=new Set,c=[];for(let d of n.files){if(a.has(d.path))throw P("PACKAGE_PATH_TRAVERSAL","manifest contains duplicate file paths");a.add(d.path);let l=t.generatedFiles?.get(d.path);if(d.generated===!0&&l===void 0)throw P("PACKAGE_GENERATED_FILE_MISSING","generated manifest file bytes are missing");if(t.sourceFileHashes?.has(d.path)){let y=Fs(e,d.path);if(t.sourceFileHashes.get(d.path)!==js(y))throw P("PACKAGE_STAGED_BYTES_MISMATCH","workspace source changed before staging")}let p=l??Fs(e,d.path);if(js(p)!==d.sha256)throw P("PACKAGE_STAGED_BYTES_MISMATCH",`staged bytes differ for ${d.path}`);let f=zs(s,d.path);te.mkdirSync(pe.dirname(f),{recursive:!0}),te.writeFileSync(f,new Uint8Array(p)),c.push(d.path);}te.writeFileSync(pe.join(s,"manifest.json"),JSON.stringify(n,null,2)),await Hs.create({gzip:!0,file:r,cwd:s,portable:!0,noMtime:!0},["manifest.json",...c]),te.renameSync(r,o);}finally{try{te.rmSync(r,{force:!0});}catch{}te.rmSync(s,{recursive:true,force:true});}return o}m();m();var hn="/api/v1";var gu=201,mu=200,hu=409,Gi=401,Gs={APP_NAME_CONFLICT:"APP_NAME_CONFLICT",CONTENT_SUSPENDED:"PUBLISH_CONTENT_SUSPENDED",CONTENT_REJECTED:"CONTENT_REJECTED",APP_VERSION_MUST_INCREASE:"APP_VERSION_MUST_INCREASE",APP_VERSION_INVALID:"APP_VERSION_INVALID"};function _u(){return process.env.WI013_FAKE_UPLOAD==="1"}function Eu(e){let n=gunzipSync(new Uint8Array(e)),t=gzipSync(new Uint8Array(n),{level:1});if(Buffer.compare(new Uint8Array(t),new Uint8Array(e))===0)throw new Error("publish: [E_MALFORMED] Re-gzipped upload bytes are identical to the original \u2014 tamper is a no-op");return t}function Tu(e){return e.replace(/\/+$/,"")}async function Hn(e){try{return await e.json()}catch{return null}}function Js(e,n,t){let i=e;if(!i||i.success!==true||i.data===void 0)throw new Error(`publish: [E_MALFORMED] ${n} response envelope is malformed (expected { success: true, data }) \u2014 HTTP ${t}`);return i.data}function bu(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.contentId=="string"&&n.contentId.length>0)return n.contentId;if(!n.data||typeof n.data!="object"||Array.isArray(n.data))return;let t=n.data;return typeof t.contentId=="string"&&t.contentId.length>0?t.contentId:void 0}function Pu(e){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e;if(typeof n.slug=="string"&&n.slug.length>0)return n.slug;if(!n.data||typeof n.data!="object"||Array.isArray(n.data))return;let t=n.data;return typeof t.slug=="string"&&t.slug.length>0?t.slug:void 0}function Ws(e,n){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e,i=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:void 0,o=[t.code,t.message,i?.code,i?.message];for(let r of o){if(typeof r!="string"||!Object.prototype.hasOwnProperty.call(Gs,r))continue;let s=r,a=s==="APP_NAME_CONFLICT"?`marketplace name is already in use: ${n}`:void 0;return P(Gs[s],a)}}async function Nu(e){if(!e.baseUrl.trim())throw new Error("publish: [E_ENV_MISSING] Marketplace base URL is required");if(!e.accessToken.trim())throw new Error("publish: [E_AUTH_EXPIRED] A valid bearer token is required");let n=Tu(e.baseUrl),t=e.accessPolicy??"private",i=e.manifest.name,o=e.manifest.type==="app"?e.manifest:void 0,r=o!==void 0,s=o?.appId,a;try{a=await fetch(`${n}${hn}/publisher/items`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({slug:i,displayName:i,description:e.manifest.description,type:e.manifest.type,version:e.manifest.version,accessPolicy:t,...s===void 0?{}:{appId:s}})});}catch{throw new Error("publish: [E_NETWORK] Submit request failed (network)")}let c=await Hn(a),d=bu(c),l=Pu(c),p=r&&l!==void 0?l:i,f;if(a.status===gu)f="created";else if(r&&a.status===mu){if(d===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App republish did not return an opaque contentId");f="existing";}else if(a.status===hu){if(r)throw Ws(c,i)??P("APP_NAME_CONFLICT",`marketplace name is already in use: ${i}`);f="existing";}else throw a.status===Gi?new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)"):new Error(`publish: [E_HTTP] Submit request failed \u2014 HTTP ${a.status}`);let y="not-needed",g=null;if(f==="existing"&&!r){let D;try{D=await fetch(`${n}${hn}/publisher/items`,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});}catch{throw new Error("publish: [E_NETWORK] Publisher items request failed (network)")}let L=await Hn(D);if(D.status!==200)throw new Error(`publish: [E_HTTP] Publisher items request failed \u2014 HTTP ${D.status}`);let A=Js(L,"publisher items",D.status)?.items;if(!Array.isArray(A))throw new Error(`publish: [E_MALFORMED] Publisher items response is malformed (expected data.items[]) \u2014 HTTP ${D.status}`);let h=A.find(b=>!b||typeof b!="object"?false:b.slug===i);if(!h||typeof h.version!="string")throw new Error(`publish: [E_MALFORMED] Publisher items response does not contain slug "${i}" \u2014 HTTP ${D.status}`);if(g=h.version,g!==e.manifest.version){let b;try{b=await fetch(`${n}${hn}/publisher/items/${encodeURIComponent(i)}`,{method:"PUT",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({version:e.manifest.version})});}catch{throw new Error("publish: [E_NETWORK] Version update request failed (network)")}if(!b.ok)throw await Hn(b),b.status===Gi?new Error(`publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP ${b.status})`):b.status===403?new Error(`publish: [E_FORBIDDEN] Version update is forbidden; only the item owner can update an existing item (HTTP ${b.status})`):new Error(`publish: [E_HTTP] Version update failed \u2014 HTTP ${b.status}`);y="applied";}}let _=te.readFileSync(e.tgzPath),E=_u()?Eu(_):_,k=new FormData;k.set("archive",new Blob([new Uint8Array(E)],{type:"application/gzip"}),`${p}-${e.manifest.version}.tgz`);let x=r&&d!==void 0?d:i,T;try{T=await fetch(`${n}${hn}/publisher/items/${encodeURIComponent(x)}/upload`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`},body:k});}catch{throw new Error("publish: [E_NETWORK] Upload request failed (network)")}if(T.status===Gi)throw new Error("publish: [E_AUTH_EXPIRED] Authentication is expired or missing \u2014 please log in again (HTTP 401)");if(!T.ok){let D=await Hn(T);if(r){let L=Ws(D,p);if(L)throw L}throw new Error(`publish: [E_HTTP] Upload request failed \u2014 HTTP ${T.status}`)}let U=await Hn(T),H=Js(U,"upload",T.status),N=typeof H.contentId=="string"&&H.contentId.length>0?H.contentId:d;if(r&&N===void 0)throw P("PUBLISH_CONTENT_ID_MISSING","App upload did not return an opaque contentId");return {slug:p,version:e.manifest.version,...N===void 0?{}:{contentId:N},artifactChecksum:H.artifactChecksum,artifactSizeBytes:H.artifactSizeBytes,submitOutcome:f,versionUpdate:y,serverVersionBefore:g}}var Du=1e4,Su=100*1024*1024;function Ji(e){return $i.createHash("sha256").update(e).digest("hex")}function Mu(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function Je(e,n){if(!n||n.includes("\\")||n.includes("\0")||pe.posix.isAbsolute(n)||n.split("/").some(r=>r===".."||r.length===0))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path is not a safe relative path");let t=pe.resolve(e,...n.split("/")),i=pe.resolve(e);if(t!==i&&!t.startsWith(`${i}${pe.sep}`))throw P("PACKAGE_PATH_TRAVERSAL","workspace file path escaped the workspace root");let o;try{o=te.lstatSync(t);}catch{throw P("PACKAGE_FILE_INVALID",`workspace file is missing: ${n}`)}if(o.isSymbolicLink())throw P("PACKAGE_SYMLINK",`symlink is not publishable: ${n}`);if(!o.isFile())throw P("PACKAGE_FILE_INVALID",`not a regular file: ${n}`);return new Uint8Array(te.readFileSync(t))}async function Lu(e,n,t){let i=`${n}/${K}`;if(!t.includes(i))return [];let o={[K]:Je(e,i)},r=`${n}/${G}`;t.includes(r)&&(o[G]=Je(e,r));let s=$e(o,{mode:"local"});if(!s.ok)return [];let{diagnostics:a}=await Nn(s.mcpb?.icon,async d=>{let l=`${n}/${d}`;return t.includes(l)?Je(e,l):"missing"}),c=a.find(d=>d.code==="ICON_INVALID");if(c!==void 0)throw P("ICON_INVALID",`${c.reason??"invalid"} at ${c.declared??"icon"}`);return a.flatMap(d=>d.code==="ICON_INVALID"?[]:[{code:d.code,path:d.declared??"icon"}])}function Xs(e,n,t){let i=e??n;if(!Number.isSafeInteger(i)||i<=0)throw new Fe("PACKAGE_SIZE_LIMIT",`${t} must be a positive integer`);return i}function qs(e,n,t,i){let o=Xs(t.maxFileCount??t.maxFiles,Du,"max file count"),r=Xs(t.maxTotalBytes??t.maxBytes,Su,"max total bytes");if(n.length>o)throw new Fe("PACKAGE_SIZE_LIMIT",`package exceeds file count limit (${o})`);let s=0;for(let a of n){let c=i?.get(a);if(c!==void 0?s+=c.byteLength:s+=Je(e,a).byteLength,s>r)throw new Fe("PACKAGE_SIZE_LIMIT",`package exceeds byte limit (${r})`)}}function Ou(e){return e.appId!==void 0||e.expectedDefinitionHash!==void 0}function Ru(e){let n=e.appId!==void 0,t=e.expectedDefinitionHash!==void 0;if(!n&&t)throw P("APP_ID_REQUIRED","appId is required with expectedDefinitionHash");if(n&&!t)throw P("APP_DEFINITION_HASH_REQUIRED","expectedDefinitionHash is required with appId");if(!n||!t)throw P("APP_ID_REQUIRED")}function wu(e,n){let t=e.filter(i=>i.appId===n);if(t.length===0)throw P("APP_NOT_FOUND",`no publishable App matches ${n}`);if(t.length!==1)throw P("APP_AMBIGUOUS",`more than one App matches ${n}`);return t[0]}function Cu(e){let n=e.localDefinitionRef?.packageRoot;if(!n||!/^(?:apps|skills)\/[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(n))throw P("APP_PACKAGE_ROOT_INVALID","selected App is not rooted in apps/<safe-id> or skills/<safe-id>");return n}function Wi(e){let{path:n,rule:t}=e.reason;return `${e.code} at ${n===""?"<file>":n} (${t})`+(e.files.length>0?` [${e.files.join(", ")}]`:"")}function Uu(e,n,t){let i=$e({[le]:t},{mode:"published"});if(!i.ok)throw P("APP_UI_MANIFEST_INVALID",`generated ${le} does not read: ${Wi(i.rejection)}`);if(un(i.manifest)!==un(n))throw P("APP_UI_MANIFEST_INVALID",`generated ${le} normalizes to a different definition hash than the source`);let o=e[K];if(o===void 0)return;let r=e[G],s=$e({[K]:o,[le]:t,...r===void 0?{}:{[G]:r}},{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",Wi(s.rejection))}function ku(e,n,t,i){let o={};for(let y of ee){let g=`${t}/${y}`;i.includes(g)&&(o[y]=Je(e,g));}let r=`${t}/${G}`;if(o[K]!==void 0&&i.includes(r)&&(o[G]=Je(e,r)),Object.keys(o).length===0)throw P("APP_UI_MANIFEST_INVALID","selected screen App has no package manifest.json or ui-plugin.json");let s=$e(o,{mode:"local"});if(!s.ok)throw P("APP_UI_MANIFEST_INVALID",Wi(s.rejection));if(s.manifest.pluginId!==n.appId)throw P("APP_DEFINITION_CONFLICT",`${s.file} identity no longer matches the selected App`);let a=o[le],c=a===void 0?void 0:Ji(a),d=`${t}/ui/index.html`;if(!i.includes(d))throw P("APP_UI_MANIFEST_INVALID","screen entry is outside package scope");let l=Ji(Je(e,d)),p=JSON.parse(JSON.stringify(s.v2Input));if(p.entryHash=l,Object.prototype.hasOwnProperty.call(p,"initialState")){let y=p.initialState;if(!Mu(y)||y.path!=="ui/state.json")throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState must reference ui/state.json inside the package");let g=`${t}/ui/state.json`;if(!i.includes(g))throw P("APP_INITIAL_STATE_OUT_OF_SCOPE","initialState reference is outside the selected package");let _=Je(e,g);p.initialState={...y,hash:Ji(_)};}let f;try{let y=Ye(p,{mode:"published"});f=new Uint8Array(Buffer.from(JSON.stringify(y),"utf8"));}catch(y){throw y instanceof de?P("APP_UI_MANIFEST_INVALID",y.code):P("APP_UI_MANIFEST_INVALID")}return Uu(o,s.manifest,f),{bytes:f,...c===void 0?{}:{legacySourceHash:c}}}async function xu(e,n){let{included:t,excluded:i}=Ms(e);qs(e,t,n);let o=xs(e,t,{version:n.version}),r=zi(e,t);return {plan:{manifest:o,included:t,excluded:i,secretFindings:r},archiveOptions:{}}}async function vu(e,n){Ru(n);let t=await Ns(e),i=wu(t.items,n.appId);if(i.definitionHash!==n.expectedDefinitionHash)throw P("APP_DEFINITION_CONFLICT",`definitionHash changed for ${n.appId}`);let o=Cu(i),{included:r,excluded:s}=Ss(e,o),a=await Lu(e,o,r),c=new Map,d=new Map;if(i.capabilities.includes("screen")){let y=ku(e,i,o,r),g=`${o}/${le}`;if(c.set(g,y.bytes),y.legacySourceHash!==void 0)d.set(g,y.legacySourceHash);else {r.push(g);let _=new TextEncoder;r.sort((E,k)=>Buffer.compare(_.encode(E),_.encode(k)));}}if(i.capabilities.includes("skill")&&!r.includes(`${o}/SKILL.md`))throw P("APP_SKILL_MISSING","skill capability requires package-root SKILL.md");qs(e,r,n,c);let l={appId:i.appId,version:n.version??"",description:i.description,capabilities:i.capabilities,packageRoot:o,...i.definition?.id===void 0?{}:{definitionId:i.definition.id},definitionHash:i.definitionHash,includedFiles:r,generatedFiles:c},p=vs(e,l),f=zi(e,r,c);return {plan:{manifest:p,included:r,excluded:s,secretFindings:f,warnings:a},archiveOptions:{generatedFiles:c,sourceFileHashes:d}}}async function Zs(e,n){let t=pe.resolve(e);if(Ou(n))return vu(t,n);if(n.expectedDefinitionHash!==void 0)throw P("APP_ID_REQUIRED");return xu(t,n)}async function tg(e,n={}){return (await Zs(e,n)).plan}function ju(e){let n=e.map(t=>`${t.path}:${t.line} (${t.rule})`).join(", ");throw new Fe("PUBLISH_SECRET_FINDINGS",`aborted \u2014 secret findings must be resolved before packing: ${n}`)}async function Qs(e,n={}){let t=pe.resolve(e),i=await Zs(t,n);i.plan.secretFindings.length>0&&ju(i.plan.secretFindings);let o=await $s(t,i.plan.manifest,i.archiveOptions);return {manifest:i.plan.manifest,tgzPath:o}}async function ig(e,n={}){return Qs(e,n)}async function og(e,n){let t=await Qs(e,n);if(t.manifest.type!=="app")throw new Error("publish: App pack unexpectedly produced a template manifest");return t}
2
+ export{Su as DEFAULT_PUBLISH_MAX_BYTES,Du as DEFAULT_PUBLISH_MAX_FILES,Ds as EXCLUDE_RULES,hn as MARKETPLACE_API_PREFIX,Fe as PublishError,og as packApp,Qs as packPublish,ig as packTemplate,tg as planPublish,Nu as uploadToMarketplace};