@salesforce/afv-skills 1.67.0 → 1.69.0

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 (258) hide show
  1. package/README.md +55 -5
  2. package/package.json +1 -1
  3. package/skills/afcc-setup-coordinate/SKILL.md +348 -0
  4. package/skills/afcc-setup-coordinate/assets/console-app/AFCC_Service_Console.app-meta.xml +19 -0
  5. package/skills/afcc-setup-coordinate/assets/console-app/Admin.profile-meta.xml +8 -0
  6. package/skills/afcc-setup-coordinate/assets/console-app/Standard.profile-meta.xml +8 -0
  7. package/skills/afcc-setup-coordinate/assets/gap_report_template.md +35 -0
  8. package/skills/afcc-setup-coordinate/assets/org_profile_template.json +16 -0
  9. package/skills/afcc-setup-coordinate/references/gotchas.md +22 -0
  10. package/skills/afcc-setup-coordinate/scripts/audit_org.sh +159 -0
  11. package/skills/agentforce-bot-upgrade/SKILL.md +117 -66
  12. package/skills/agentforce-bot-upgrade/assets/_vendored/agent-spec-template.md +139 -0
  13. package/skills/agentforce-bot-upgrade/references/_vendored/agent-design-and-spec-creation.md +1211 -0
  14. package/skills/agentforce-bot-upgrade/references/_vendored/agent-script-core-language.md +1390 -0
  15. package/skills/agentforce-bot-upgrade/references/_vendored/agent-subagent-map-diagrams.md +341 -0
  16. package/skills/agentforce-bot-upgrade/references/_vendored/agent-user-setup.md +672 -0
  17. package/skills/agentforce-bot-upgrade/references/_vendored/agent-validation-and-debugging.md +904 -0
  18. package/skills/agentforce-bot-upgrade/references/_vendored/agentscript-toolchain.md +112 -0
  19. package/skills/agentforce-bot-upgrade/references/_vendored/architecture-patterns.md +277 -0
  20. package/skills/agentforce-bot-upgrade/references/_vendored/common-control-flow-pitfalls.md +255 -0
  21. package/skills/agentforce-bot-upgrade/references/_vendored/control-flow-actions-sequencing.md +198 -0
  22. package/skills/agentforce-bot-upgrade/references/_vendored/control-flow-lifecycle-side-effects.md +87 -0
  23. package/skills/agentforce-bot-upgrade/references/_vendored/data-library-reference.md +891 -0
  24. package/skills/agentforce-bot-upgrade/references/_vendored/instruction-resolution.md +658 -0
  25. package/skills/agentforce-bot-upgrade/references/_vendored/org-setup-for-adl.md +551 -0
  26. package/skills/agentforce-bot-upgrade/references/_vendored/patterns-by-requirement.md +88 -0
  27. package/skills/agentforce-bot-upgrade/references/_vendored/posture-and-determinism.md +215 -0
  28. package/skills/agentforce-bot-upgrade/references/extraction-blueprint.md +11 -4
  29. package/skills/agentforce-bot-upgrade/references/generate-agent-spec.md +19 -3
  30. package/skills/agentforce-bot-upgrade/references/handoff-output-format.md +82 -52
  31. package/skills/agentforce-bot-upgrade/references/input-contract.md +8 -8
  32. package/skills/agentforce-bot-upgrade/references/mapping-rules.md +19 -6
  33. package/skills/agentforce-bot-upgrade/references/post-conversion-enhancements-reference.md +65 -6
  34. package/skills/agentforce-bot-upgrade/references/quality-checklist.md +4 -4
  35. package/skills/agentforce-bot-upgrade/references/sf-cli-bot-reference.md +17 -3
  36. package/skills/agentforce-hyperclassifier-configure/README.md +24 -0
  37. package/skills/agentforce-hyperclassifier-configure/SKILL.md +111 -0
  38. package/skills/agentforce-hyperclassifier-configure/assets/customer-org.env.example +4 -0
  39. package/skills/agentforce-hyperclassifier-configure/assets/sample_descriptions.json +8 -0
  40. package/skills/agentforce-hyperclassifier-configure/assets/sample_evals.csv +17 -0
  41. package/skills/agentforce-hyperclassifier-configure/references/api-contract.md +41 -0
  42. package/skills/agentforce-hyperclassifier-configure/references/authentication.md +35 -0
  43. package/skills/agentforce-hyperclassifier-configure/references/evaluation.md +46 -0
  44. package/skills/agentforce-hyperclassifier-configure/references/installation.md +35 -0
  45. package/skills/agentforce-hyperclassifier-configure/references/onboarding.md +93 -0
  46. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/__init__.py +1 -0
  47. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/client.py +219 -0
  48. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/eca.py +178 -0
  49. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/evaluation.py +207 -0
  50. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/onboarding.py +191 -0
  51. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/optimizer.py +187 -0
  52. package/skills/agentforce-hyperclassifier-configure/scripts/hyperclassifier.py +111 -0
  53. package/skills/agentforce-hyperclassifier-configure/scripts/report_hyperclassifier.py +149 -0
  54. package/skills/agentforce-hyperclassifier-configure/scripts/setup_hyperclassifier.py +74 -0
  55. package/skills/agentforce-hyperclassifier-configure/scripts/tests/test_hyperclassifier_skill.py +887 -0
  56. package/skills/agentforce-offline-experimentation-run/SKILL.md +14 -22
  57. package/skills/agentforce-offline-experimentation-run/scripts/bt_compare.py +81 -0
  58. package/skills/agentforce-offline-experimentation-run/scripts/bt_fetch.py +358 -0
  59. package/skills/agentforce-offline-experimentation-run/scripts/bt_patch_agent.py +110 -0
  60. package/skills/agentforce-offline-experimentation-run/scripts/btlib/__init__.py +34 -0
  61. package/skills/agentforce-offline-experimentation-run/scripts/btlib/agentpatch.py +483 -0
  62. package/skills/agentforce-offline-experimentation-run/scripts/btlib/agentsrc.py +565 -0
  63. package/skills/agentforce-offline-experimentation-run/scripts/btlib/cache.py +95 -0
  64. package/skills/agentforce-offline-experimentation-run/scripts/btlib/compare.py +617 -0
  65. package/skills/agentforce-offline-experimentation-run/scripts/btlib/fetch.py +1012 -0
  66. package/skills/agentforce-offline-experimentation-run/scripts/btlib/judge.py +140 -0
  67. package/skills/agentforce-offline-experimentation-run/scripts/btlib/messages.py +93 -0
  68. package/skills/agentforce-offline-experimentation-run/scripts/btlib/patch.py +327 -0
  69. package/skills/agentforce-offline-experimentation-run/scripts/btlib/redact.py +40 -0
  70. package/skills/agentforce-offline-experimentation-run/scripts/btlib/results.py +288 -0
  71. package/skills/agentforce-offline-experimentation-run/scripts/btlib/scoring.py +340 -0
  72. package/skills/agentforce-offline-experimentation-run/scripts/btlib/sfap.py +354 -0
  73. package/skills/agentforce-offline-experimentation-run/scripts/btlib/splits.py +136 -0
  74. package/skills/agentforce-offline-experimentation-run/scripts/btlib/stdm.py +98 -0
  75. package/skills/agentforce-offline-experimentation-run/scripts/btlib/tokens.py +173 -0
  76. package/skills/agentforce-offline-experimentation-run/scripts/btlib/units.py +199 -0
  77. package/skills/agentforce-offline-experimentation-run/scripts/btlib/versions.py +194 -0
  78. package/skills/agentforce-offline-experimentation-run/scripts/build_report.py +367 -379
  79. package/skills/agentforce-offline-experimentation-run/scripts/resolve-token.sh +23 -6
  80. package/skills/agentforce-offline-experimentation-run/scripts/sfap_replay.py +483 -796
  81. package/skills/commerce-react-storefront-create/SKILL.md +54 -21
  82. package/skills/dx-lifecycle-center/SKILL.md +22 -13
  83. package/skills/dx-lifecycle-center/examples/workflows.md +54 -17
  84. package/skills/dx-lifecycle-center/references/connect-api.md +33 -4
  85. package/skills/dx-lifecycle-center/references/connect-org.md +62 -12
  86. package/skills/dx-lifecycle-center/references/deploy.md +3 -3
  87. package/skills/dx-lifecycle-center/references/hub-org.md +19 -3
  88. package/skills/dx-lifecycle-center/references/list-orgs.md +50 -24
  89. package/skills/dx-lifecycle-center/references/troubleshooting.md +22 -1
  90. package/skills/dx-lifecycle-center/scripts/hub-get.sh +41 -0
  91. package/skills/dx-lifecycle-center/scripts/resolve-environment.sh +151 -4
  92. package/skills/dx-org-devhub-configure/SKILL.md +85 -84
  93. package/skills/dx-org-devhub-configure/examples/status-output.md +25 -2
  94. package/skills/dx-org-devhub-configure/scripts/devhub.sh +265 -140
  95. package/skills/dx-org-devhub-configure/scripts/test-devhub.sh +100 -15
  96. package/skills/dx-packaging-convert-1gp-to-2gp-create/SKILL.md +63 -0
  97. package/skills/dx-packaging-convert-1gp-to-2gp-create/references/conversion-operations.md +252 -0
  98. package/skills/dx-packaging-move-to-2gp-migrate/SKILL.md +88 -0
  99. package/skills/dx-packaging-move-to-2gp-migrate/references/api-operations.md +167 -0
  100. package/skills/dx-packaging-push-upgrade-configure/README.md +47 -0
  101. package/skills/dx-packaging-push-upgrade-configure/SKILL.md +355 -0
  102. package/skills/dx-packaging-push-upgrade-configure/references/best-practices.md +61 -0
  103. package/skills/dx-packaging-push-upgrade-configure/references/cli-reference.md +148 -0
  104. package/skills/dx-packaging-push-upgrade-configure/references/objects.md +106 -0
  105. package/skills/dx-packaging-push-upgrade-configure/references/soql-recipes.md +144 -0
  106. package/skills/dx-scratch-def-configure/SKILL.md +163 -0
  107. package/skills/dx-scratch-def-configure/examples/confirm-card.md +53 -0
  108. package/skills/dx-scratch-def-configure/examples/report-recipes.md +100 -0
  109. package/skills/dx-scratch-def-configure/references/features.json +3270 -0
  110. package/skills/dx-scratch-def-configure/references/project-scratch-def.schema.json +1841 -0
  111. package/skills/dx-scratch-def-configure/references/settings-map.json +682 -0
  112. package/skills/dx-scratch-def-configure/scripts/lib_scratch_def.py +1306 -0
  113. package/skills/dx-scratch-def-configure/scripts/requirements.txt +3 -0
  114. package/skills/dx-scratch-def-configure/scripts/scrape_config_values.py +848 -0
  115. package/skills/education-cloud-domain-configure/SKILL.md +1 -1
  116. package/skills/education-cloud-multi-campus-configure/SKILL.md +1 -1
  117. package/skills/education-cloud-student-recruitment-agent-configure/SKILL.md +1 -1
  118. package/skills/experience-afv-analytics-query/SKILL.md +239 -0
  119. package/skills/experience-afv-analytics-query/references/references.md +176 -0
  120. package/skills/experience-app-mcp-delivery-generate/SKILL.md +142 -0
  121. package/skills/experience-app-mcp-delivery-generate/references/eca-consumer-key.md +26 -0
  122. package/skills/experience-app-mcp-delivery-generate/references/mcp-config-delivery.md +38 -0
  123. package/skills/experience-app-mcp-delivery-generate/references/plugin-format-and-publishing.md +80 -0
  124. package/skills/experience-app-mcp-delivery-generate/scripts/developer_name.mjs +9 -0
  125. package/skills/experience-app-mcp-delivery-generate/scripts/discover_mcp_context.mjs +114 -0
  126. package/skills/experience-app-mcp-delivery-generate/scripts/generate_mcp_config.mjs +27 -0
  127. package/skills/experience-app-mcp-delivery-generate/scripts/generate_plugin.mjs +184 -0
  128. package/skills/experience-app-mcp-delivery-generate/scripts/mcp_config.mjs +57 -0
  129. package/skills/experience-app-mcp-delivery-generate/scripts/preflight.mjs +109 -0
  130. package/skills/experience-app-mcp-delivery-generate/scripts/retrieve_eca_consumer_key.mjs +143 -0
  131. package/skills/experience-app-mcp-generate/SKILL.md +174 -0
  132. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.eca-meta.xml +7 -0
  133. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaGlblOauth-meta.xml +15 -0
  134. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaOauth-meta.xml +6 -0
  135. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaOauthPlcy-meta.xml +12 -0
  136. package/skills/experience-app-mcp-generate/assets/__ECA_NAME___defaultPolicy.ecaPlcy-meta.xml +7 -0
  137. package/skills/experience-app-mcp-generate/assets/__MCP_SERVER_NAME__.mcpServerDefinition-meta.xml +5 -0
  138. package/skills/experience-app-mcp-generate/references/eca-fields.md +76 -0
  139. package/skills/experience-app-mcp-generate/references/mcp-objects.md +66 -0
  140. package/skills/experience-app-mcp-generate/references/tool-bindings.md +85 -0
  141. package/skills/experience-app-mcp-generate/references/troubleshooting.md +41 -0
  142. package/skills/experience-app-mcp-generate/references/ui-frameworks.md +19 -0
  143. package/skills/experience-app-mcp-generate/references/widget-resources.md +96 -0
  144. package/skills/experience-app-mcp-generate/scripts/activate_server.mjs +166 -0
  145. package/skills/experience-app-mcp-generate/scripts/check_setup_progress.mjs +212 -0
  146. package/skills/experience-app-mcp-generate/scripts/list_sites.mjs +211 -0
  147. package/skills/experience-app-mcp-generate/scripts/merge_tools.mjs +407 -0
  148. package/skills/experience-app-mcp-generate/scripts/preflight.mjs +127 -0
  149. package/skills/experience-app-mcp-generate/scripts/render_eca.mjs +144 -0
  150. package/skills/experience-app-mcp-generate/scripts/render_mcp_server.mjs +64 -0
  151. package/skills/experience-app-mcp-generate/scripts/retrieve_existing_prompts.mjs +145 -0
  152. package/skills/experience-app-mcp-generate/scripts/retrieve_existing_tools.mjs +72 -0
  153. package/skills/experience-app-mcp-generate/scripts/scan_tool_candidates.mjs +195 -0
  154. package/skills/experience-app-mcp-generate/scripts/utils/callback_url.mjs +36 -0
  155. package/skills/experience-app-mcp-generate/scripts/utils/developer_name.mjs +9 -0
  156. package/skills/experience-app-mcp-generate/scripts/utils/eca_check.mjs +156 -0
  157. package/skills/experience-app-mcp-generate/scripts/utils/metadata_path.mjs +13 -0
  158. package/skills/experience-app-mcp-generate/scripts/verify_server.mjs +118 -0
  159. package/skills/experience-cms-content-type-generate/SKILL.md +1 -1
  160. package/skills/experience-design-validate/SKILL.md +1 -1
  161. package/skills/experience-search-coordinate/SKILL.md +18 -12
  162. package/skills/experience-search-coordinate/references/content-route.md +79 -1
  163. package/skills/field-service-data-capture-migrate/SKILL.md +1 -1
  164. package/skills/nonprofit-fundraising-configure/SKILL.md +1 -1
  165. package/skills/nonprofit-fundraising-configure/references/mcp-invocation.md +52 -4
  166. package/skills/nonprofit-fundraising-configure/references/permission-targeting.md +19 -2
  167. package/skills/platform-apex-generate/SKILL.md +14 -11
  168. package/skills/platform-apex-test-generate/SKILL.md +2 -1
  169. package/skills/platform-custom-field-generate/SKILL.md +24 -16
  170. package/skills/platform-custom-metadata-type-generate/SKILL.md +1 -0
  171. package/skills/platform-custom-setting-generate/SKILL.md +1 -0
  172. package/skills/platform-datamask-run/SKILL.md +52 -71
  173. package/skills/platform-datamask-run/references/api-surface.md +10 -4
  174. package/skills/platform-datamask-run/references/policy-authoring.md +56 -7
  175. package/skills/platform-datamask-run/references/run-and-abort.md +17 -10
  176. package/skills/platform-datamask-run/scripts/poll-job.sh +15 -25
  177. package/skills/platform-dataspace-access-configure/SKILL.md +43 -10
  178. package/skills/platform-flexipage-generate/SKILL.md +7 -10
  179. package/skills/platform-flexipage-generate/references/mcp_action_examples.md +42 -38
  180. package/skills/platform-metadata-discovery-get/SKILL.md +185 -0
  181. package/skills/platform-metadata-discovery-get/references/api-map.md +25 -0
  182. package/skills/platform-metadata-discovery-get/references/h360-routes.md +30 -0
  183. package/skills/platform-metadata-discovery-get/references/scoped-soql.md +52 -0
  184. package/skills/platform-metadata-grounding-get/SKILL.md +170 -0
  185. package/skills/platform-policy-rule-generate/SKILL.md +85 -231
  186. package/skills/platform-policy-rule-generate/references/condition-model.md +47 -0
  187. package/skills/platform-policy-rule-generate/references/condition-templates.md +89 -0
  188. package/skills/platform-policy-rule-generate/references/conjunction-compiler.md +25 -0
  189. package/skills/platform-policy-rule-generate/references/conjunction-expression.md +30 -0
  190. package/skills/platform-policy-rule-generate/references/consumer-all.md +9 -0
  191. package/skills/platform-policy-rule-generate/references/consumer-datacloud-ui.md +99 -0
  192. package/skills/platform-policy-rule-generate/references/deploy-errors.md +24 -36
  193. package/skills/platform-policy-rule-generate/references/examples/ExistsJoinRLS/package.xml +12 -0
  194. package/skills/platform-policy-rule-generate/references/examples/ExistsJoinRLS/policyRuleDefinitionSets/ExistsJoinRLS.policyRuleDefinitionSet +5 -0
  195. package/skills/platform-policy-rule-generate/references/examples/ExistsJoinRLS/policyRuleDefinitions/ExistsJoinRLS_Rule_1.policyRuleDefinition +91 -0
  196. package/skills/platform-policy-rule-generate/references/examples/FieldReadDeny/package.xml +12 -0
  197. package/skills/platform-policy-rule-generate/references/examples/FieldReadDeny/policyRuleDefinitionSets/FieldReadDeny.policyRuleDefinitionSet +5 -0
  198. package/skills/platform-policy-rule-generate/references/examples/FieldReadDeny/policyRuleDefinitions/FieldReadDeny_Rule_1.policyRuleDefinition +72 -0
  199. package/skills/platform-policy-rule-generate/references/examples/LastCharactersFieldMasking/package.xml +12 -0
  200. package/skills/platform-policy-rule-generate/references/examples/LastCharactersFieldMasking/policyRuleDefinitionSets/LastCharactersFieldMasking.policyRuleDefinitionSet +5 -0
  201. package/skills/platform-policy-rule-generate/references/examples/LastCharactersFieldMasking/policyRuleDefinitions/LastCharactersFieldMasking_Rule_1.policyRuleDefinition +77 -0
  202. package/skills/platform-policy-rule-generate/references/examples/PrincipalFieldMatchRLS/package.xml +12 -0
  203. package/skills/platform-policy-rule-generate/references/examples/PrincipalFieldMatchRLS/policyRuleDefinitionSets/PrincipalFieldMatchRLS.policyRuleDefinitionSet +5 -0
  204. package/skills/platform-policy-rule-generate/references/examples/PrincipalFieldMatchRLS/policyRuleDefinitions/PrincipalFieldMatchRLS_Rule_1.policyRuleDefinition +77 -0
  205. package/skills/platform-policy-rule-generate/references/examples/TaggedObjectAccess/package.xml +12 -0
  206. package/skills/platform-policy-rule-generate/references/examples/TaggedObjectAccess/policyRuleDefinitionSets/TaggedObjectAccess.policyRuleDefinitionSet +5 -0
  207. package/skills/platform-policy-rule-generate/references/examples/TaggedObjectAccess/policyRuleDefinitions/TaggedObjectAccess_Rule_1.policyRuleDefinition +65 -0
  208. package/skills/platform-policy-rule-generate/references/headless-transport.md +87 -0
  209. package/skills/platform-policy-rule-generate/references/policy-schema-full.md +18 -11
  210. package/skills/platform-policy-rule-generate/references/policy-shapes.md +107 -0
  211. package/skills/platform-policy-rule-generate/references/principal-expression.md +31 -0
  212. package/skills/platform-policy-rule-generate/references/reference-resolution.md +51 -0
  213. package/skills/platform-policy-rule-generate/references/resource-expression.md +48 -0
  214. package/skills/platform-policy-rule-generate/references/runtime-context.md +9 -0
  215. package/skills/platform-policy-rule-generate/references/templates-access.md +11 -9
  216. package/skills/platform-policy-rule-generate/references/templates-advanced.md +5 -3
  217. package/skills/platform-policy-rule-generate/references/templates-record.md +37 -22
  218. package/skills/platform-policy-rule-generate/references/templates-transform.md +10 -8
  219. package/skills/platform-policy-rule-generate/references/templates.md +2 -2
  220. package/skills/platform-policy-rule-generate/references/ui-compatibility.md +36 -18
  221. package/skills/platform-report-generate/SKILL.md +29 -5
  222. package/skills/platform-report-generate/references/chart-types.md +26 -2
  223. package/skills/platform-report-generate/references/column-names.md +43 -0
  224. package/skills/platform-report-generate/references/errors-and-troubleshooting.md +1 -1
  225. package/skills/platform-report-generate/references/summary-formulas-sorting-limits.md +118 -0
  226. package/skills/platform-report-generate/references/verification-checklist.md +22 -2
  227. package/skills/service-digital-engagement-channel-configure/SKILL.md +49 -110
  228. package/skills/service-digital-engagement-channel-configure/assets/messaging_channel_template.xml +35 -0
  229. package/skills/service-digital-engagement-channel-configure/examples/asa_agent_channel.xml +2 -2
  230. package/skills/service-digital-engagement-channel-configure/examples/auth_queue_channel.xml +58 -0
  231. package/skills/service-digital-engagement-channel-configure/examples/omni_flow_channel.xml +2 -2
  232. package/skills/service-digital-engagement-channel-configure/examples/omni_queue_channel.xml +3 -3
  233. package/skills/service-digital-engagement-channel-configure/references/channel_settings.md +128 -28
  234. package/skills/service-digital-engagement-channel-configure/references/onboarding_contract.md +16 -20
  235. package/skills/service-digital-engagement-channel-configure/references/prechat_params.md +10 -0
  236. package/skills/service-digital-engagement-channel-configure/references/recaptcha_handoff.md +38 -0
  237. package/skills/service-digital-engagement-channel-configure/references/user_verification.md +9 -0
  238. package/skills/service-digital-engagement-channel-configure/scripts/check-api-version.sh +4 -4
  239. package/skills/service-digital-engagement-channel-configure/scripts/normalize-channel-name.sh +12 -7
  240. package/skills/service-e911-configure/SKILL.md +242 -0
  241. package/skills/service-itsm-agentic-setup-agent-runtime-access-assign/SKILL.md +1 -1
  242. package/skills/service-itsm-agentic-setup-agentforce-coordinate/SKILL.md +1 -1
  243. package/skills/service-itsm-agentic-setup-agentforce-studio-configure/SKILL.md +1 -1
  244. package/skills/service-itsm-agentic-setup-agentforce-studio-validate/SKILL.md +1 -1
  245. package/skills/service-itsm-agentic-setup-employee-agent-configure/SKILL.md +1 -1
  246. package/skills/service-itsm-agentic-setup-fulfiller-agent-configure/SKILL.md +1 -1
  247. package/skills/service-itsm-agentic-setup-incident-management/SKILL.md +47 -44
  248. package/skills/service-itsm-agentic-setup-incident-management/examples/output-templates.md +110 -83
  249. package/skills/service-itsm-agentic-setup-incident-management/references/manage-incidents-with-ai.md +7 -3
  250. package/skills/service-itsm-agentic-setup-incident-management/references/priority-matrix.md +7 -5
  251. package/skills/service-itsm-agentic-setup-incident-management/references/sla-milestones.md +2 -2
  252. package/skills/service-itsm-agentic-setup-incident-management/references/status-checks.md +437 -0
  253. package/skills/service-itsm-agentic-setup-itsm-agentforce-permset-assign/SKILL.md +1 -1
  254. package/skills/agentforce-bot-upgrade/references/planner-workflow-reference.md +0 -78
  255. package/skills/experience-content-media-image-generate/SKILL.md +0 -83
  256. package/skills/experience-content-media-image-generate/scripts/download-image.sh +0 -84
  257. package/skills/experience-content-media-stock-image-search/SKILL.md +0 -193
  258. package/skills/experience-content-media-stock-image-search/scripts/download-stock-image.py +0 -102
@@ -0,0 +1,93 @@
1
+ # CLI discovery → ECA onboarding → OrgJWT → evaluations
2
+
3
+ This workflow incorporates the [Salesforce CLI org reference](https://developer.salesforce.com/docs/platform/salesforce-cli-reference/guide/cli_reference_org.html), [Connected App/ECA configuration skill](https://github.com/forcedotcom/sf-skills/tree/main/skills/integration-connectivity-connected-app-configure), and [Models API configuration skill](https://github.com/forcedotcom/sf-skills/tree/main/skills/platform-models-api-configure). Their guidance is incorporated here so those skills do not need to be installed. The generic Models API skill also configures an agent's own model provider; this optimizer uses bundled HTTP clients and does not change Claude Code, Codex or OpenCode provider settings.
4
+
5
+ ## Discover the org and its ECA
6
+
7
+ ```bash
8
+ python3 "$SKILL_DIR/scripts/setup_hyperclassifier.py" inspect --target-org <alias>
9
+ # Omit --target-org to use the CLI's configured default.
10
+ # If there is no default or the desired org is unclear:
11
+ python3 "$SKILL_DIR/scripts/setup_hyperclassifier.py" orgs
12
+ ```
13
+
14
+ The helper captures `sf org display --target-org <alias> --json` and `sf org list auth --json` privately and prints only org identity fields. Both commands can include tokens in their raw JSON, so never paste or log their unfiltered output. For CLI versions that omit or redact the token from `org display`, the supported secret command is `sf org auth show-access-token --target-org <alias> --json`; `read_org_session()` captures it in memory. `inspect --check-session-token` reports availability only and rejects redaction placeholders. Do not use `--verbose` or export an SFDX auth URL for this workflow.
15
+
16
+ With that CLI org session, the helper runs the Tooling API equivalent of:
17
+
18
+ ```sql
19
+ SELECT Id, DeveloperName, MasterLabel
20
+ FROM ExternalClientApplication
21
+ WHERE DeveloperName = 'agentforce_hyperclassifier_optimize'
22
+ OR MasterLabel = 'agentforce-hyperclassifier-optimize'
23
+ ```
24
+
25
+ `sf data query --target-org <alias> --use-tooling-api --query '<query>' --json` uses the CLI session token for the customer's org endpoint. A valid session token does **not** imply a gateway-compatible OrgJWT or `sfap_api` access. Failed queries, missing permissions and expired sessions must be resolved before concluding the ECA is missing.
26
+
27
+ For a new login, use the CLI's browser authorization-code flow:
28
+
29
+ ```bash
30
+ sf org login web --alias <alias> --instance-url https://test.salesforce.com
31
+ # Use https://login.salesforce.com for production, or the customer's My Domain.
32
+ ```
33
+
34
+ The user completes browser login. Never request a password or SFDX auth URL in chat.
35
+
36
+ ## Existing ECA or supplied credentials
37
+
38
+ Ask the user to retrieve the Consumer Key and Consumer Secret in Setup → External Client Apps Manager → the app → Settings → OAuth Settings → Consumer Key and Secret. Save them locally using `assets/customer-org.env.example`, outside the repository, with mode 600. The ECA discovery API does not disclose its Consumer Secret.
39
+
40
+ ```bash
41
+ python3 "$SKILL_DIR/scripts/setup_hyperclassifier.py" configure \
42
+ --target-org <alias> --env-file /private/path/customer-org.env
43
+ ```
44
+
45
+ Alternatively omit `--env-file` in an interactive terminal for hidden Consumer Key and Secret prompts. An unattended agent should ask the user to populate a private file, not attempt to type or echo secrets into an automated terminal. The helper verifies that the credential origin matches the selected org and saves a private copy under `~/.config/agentforce-hyperclassifier-optimize/<org-id>/credentials.env`, alongside a nonsecret `profile.json`. It refuses overwrites; for rotation, back up the private credential file privately and deliberately replace it.
46
+
47
+ If the dedicated ECA is missing, explicitly offer these alternatives: reuse credentials for another appropriately configured customer ECA, or create the dedicated ECA. A supplied ECA needs the scopes/flow described in [authentication.md](authentication.md). A session token alone is not an alternative.
48
+
49
+ ## Create the dedicated ECA
50
+
51
+ Creation requires a customer org admin with ECA/metadata deployment permission and API 65.0+ for the named-user JWT timeout policy. The helper rejects an older selected API version before creating metadata; refresh the CLI's org version before retrying. Establish the exact target org and Run As user. Prefer a dedicated integration user with only the required model/product permissions; use `--run-as` to name it. Omitting or passing an empty `--run-as` uses the current CLI user and emits a warning on stderr and in the successful preparation response's `warnings` array. The warning identifies that user and explains the permission implications; stdout remains valid JSON. An explicit nonempty `--run-as` suppresses this fallback warning and returns an empty `warnings` array. Do not silently use a different principal or assume an administrator is the appropriate runtime identity. Ask for the app contact email if it cannot be inferred from user-provided context.
52
+
53
+ ```bash
54
+ python3 "$SKILL_DIR/scripts/setup_hyperclassifier.py" prepare-eca \
55
+ --target-org <alias> --contact-email admin@example.com --run-as integration@example.com
56
+ ```
57
+
58
+ This creates a separate SFDX project in the private per-org workspace with:
59
+
60
+ - `ExternalClientApplication`, label `agentforce-hyperclassifier-optimize`, API name `agentforce_hyperclassifier_optimize`, Local distribution.
61
+ - Global OAuth settings enabling client credentials and named-user JWTs, with a required consumer secret.
62
+ - OAuth scopes `Api, RefreshToken, SFApiPlatform` (`api`, `refresh_token`, `sfap_api`).
63
+ - A dedicated permission set for app preauthorization only; it grants no new object/system permissions.
64
+ - `plan.json` identifying the org, Run As user, scopes, policy choices and deployment steps.
65
+
66
+ Review the actual XML and plan. App creation is a distinct org mutation; proceed only when the user's request already authorizes it, or obtain authorization for this concrete plan. Preparation is local and does not deploy. It stages a complete project before publishing `eca/`, so a failed write can be retried. If `eca/` already exists, review and reuse its plan. For a legacy partial tree without a plan, back it up and move it aside before preparing again; inspect org deployment status before any new deployment. Preparation never overwrites prior work.
67
+
68
+ ```bash
69
+ python3 "$SKILL_DIR/scripts/setup_hyperclassifier.py" deploy-eca --target-org <alias>
70
+ # Once creation in this org is authorized:
71
+ python3 "$SKILL_DIR/scripts/setup_hyperclassifier.py" deploy-eca --target-org <alias> --apply
72
+ ```
73
+
74
+ Deployment uses `sf project deploy start --source-dir ... --target-org <alias> --wait 10 --json` from the dedicated project. It then retrieves the app's generated default policies before editing them. The OAuth policy specifies the active Run As user, the dedicated preauthorization permission set, a 30-minute JWT, admin-approved users and enforced IP restrictions. The general policy enables OAuth. Finally, `sf org assign permset --target-org <alias> --name <permission-set> --on-behalf-of <run-as> --json` assigns preauthorization to the selected user.
75
+
76
+ The helper records attempted stages and validated deployment IDs/statuses, including failed or still-running CLI results. It never regenerates OAuth security settings from an invented schema. Existing policies are backed up before edits. It refuses duplicate ECAs, cross-org plans and blind retries after partial deployment. If a deployment fails or times out, inspect its recorded ID with `sf project deploy report --job-id <id> --target-org <alias> --json` and inspect the org state before recovery. A process/network failure before the CLI returns an ID cannot be reconstructed locally; inspect the org's Deployment Status and CLI job records instead. If generated policy names differ, list/retrieve the actual policy metadata for that app and adapt the plan; do not deploy guessed policy names or rerun creation. Do not automatically delete a partly created app or relax IP restrictions.
77
+
78
+ Use the permission-set name in the generated policy and verify the retrieved association. Salesforce's field reference describes IDs, but retrieved ECA policies can contain permission-set names; do not replace working references with guessed IDs. The ECA metadata reference also describes API Only for the Run As user, while related connected-app guidance differs. Do not assume a universal runtime requirement or grant broad permissions: verify the chosen user's effective access and token issuance in the target org.
79
+
80
+ Consumer credentials are generated by Salesforce after deployment. Retrieve them privately in Setup and run `configure` as above. The helper cannot bypass Salesforce's protected secret-reveal step. App preauthorization does not grant Models API entitlement; the Run As user must already have the relevant product/model permissions.
81
+
82
+ ## Verify and start the full workflow
83
+
84
+ ```bash
85
+ python3 "$SKILL_DIR/scripts/hyperclassifier.py" preflight \
86
+ --target-org <alias> --evals ./evals.csv --descriptions ./descriptions.json
87
+ ```
88
+
89
+ The client exchanges the saved ECA credentials at the customer's `/services/oauth2/token` endpoint, checks signed JWT shape/expiry, and calls the gateway. It never reuses the CLI session token for this request. Only successful preflight establishes current full-description contract access.
90
+
91
+ For optimization readiness, add `--check-proposer --proposer-model <available-model>` to preflight. The optimizer also checks its proposer before every new baseline, and counts that call in its budget.
92
+
93
+ Continue with the evaluation and optimization commands in `SKILL.md`, using the same input paths. `--workspace <path>` supports a custom private directory; use it consistently in setup and evaluation commands. Explicit `--env-file` remains available for unattended environments without an installed CLI, once ECA onboarding is complete.
@@ -0,0 +1 @@
1
+ """Portable customer-org classification and description optimization."""
@@ -0,0 +1,219 @@
1
+ """Customer ECA authentication and bounded HTTPS requests using the standard library."""
2
+
3
+ import base64
4
+ from datetime import timezone
5
+ from email.utils import parsedate_to_datetime
6
+ import http.client
7
+ import json
8
+ import math
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import time
13
+ import urllib.error
14
+ import urllib.parse
15
+ import urllib.request
16
+
17
+
18
+ API = "https://api.salesforce.com"
19
+ CLASSIFIER_PATH = "/ai/gpt/v1/chat/generations"
20
+ CLASSIFIER_MODEL = "llmgateway__EinsteinHyperClassifier"
21
+ CREDENTIAL_KEYS = ("SF_INSTANCE_URL", "SF_CLIENT_ID", "SF_CLIENT_SECRET")
22
+
23
+
24
+ class ServiceError(RuntimeError):
25
+ """A deliberately sanitized transport, authentication, or contract failure."""
26
+
27
+
28
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
29
+ """Prevent credentials from following a redirect to a different destination."""
30
+
31
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
32
+ return None
33
+
34
+
35
+ def load_credentials(env_file=None):
36
+ """Read credentials as literal data, with an explicit file taking precedence."""
37
+ values = {key: os.environ.get(key, "") for key in CREDENTIAL_KEYS}
38
+ if env_file:
39
+ path = Path(env_file)
40
+ if path.is_symlink() or not path.is_file():
41
+ raise ValueError("Credential file must be a regular, non-symlink file")
42
+ if os.name == "posix" and path.stat().st_mode & 0o077:
43
+ raise ValueError("Credential file must be private: chmod 600 <file>")
44
+ seen = set()
45
+ for line in path.read_text(encoding="utf-8").splitlines():
46
+ line = line.strip()
47
+ if not line or line.startswith("#"):
48
+ continue
49
+ key, separator, value = line.partition("=")
50
+ key, value = key.strip(), value.strip()
51
+ if not separator or key not in CREDENTIAL_KEYS or key in seen:
52
+ raise ValueError("Credential file has an unknown, duplicate, or malformed key")
53
+ seen.add(key)
54
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
55
+ value = value[1:-1]
56
+ values[key] = value
57
+ if any(not values[key] for key in CREDENTIAL_KEYS):
58
+ raise ValueError("Set SF_INSTANCE_URL, SF_CLIENT_ID and SF_CLIENT_SECRET privately")
59
+ instance = values["SF_INSTANCE_URL"].rstrip("/")
60
+ # Restrict the destination before sending the consumer secret.
61
+ values["SF_INSTANCE_URL"] = my_domain_origin(instance)
62
+ return values
63
+
64
+
65
+ def my_domain_origin(value):
66
+ """Allow only verified Salesforce My Domain origins before sending secrets."""
67
+ pattern = (r"https://[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?"
68
+ r"(?:\.(?:sandbox|develop|scratch|demo|trailblaze|patch))?\.my\.salesforce\.com")
69
+ if not isinstance(value, str) or not re.fullmatch(pattern, value):
70
+ raise ValueError("Org URL must be an HTTPS Salesforce My Domain origin")
71
+ return value
72
+
73
+
74
+ def retry_delay(value, attempt):
75
+ """Honor server delay or stop instead of retrying before a long cooldown."""
76
+ fallback = min(2 ** attempt, 8)
77
+ value = value.strip()
78
+ try:
79
+ if value.isascii() and value.isdigit():
80
+ # Avoid unbounded conversion of an untrusted numeric header.
81
+ digits = value.lstrip('0') or '0'
82
+ delay = int(digits) if len(digits) <= 2 else 31
83
+ else:
84
+ date = parsedate_to_datetime(value)
85
+ if date.tzinfo is None:
86
+ date = date.replace(tzinfo=timezone.utc)
87
+ delay = max(0, date.timestamp() - time.time())
88
+ except (ValueError, TypeError, OverflowError):
89
+ return fallback
90
+ if delay > 30:
91
+ raise ServiceError("Server Retry-After exceeds the 30-second retry wait budget; retry later") from None
92
+ return delay
93
+
94
+
95
+ def jwt_expiry(token):
96
+ """Inspect token shape and expiry; the Salesforce API verifies its signature."""
97
+ try:
98
+ if not isinstance(token, str) or len(token) > 20000 or not re.fullmatch(
99
+ r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", token):
100
+ raise ValueError()
101
+ parts = token.split(".")
102
+ if len(parts) != 3 or not parts[2]:
103
+ raise ValueError()
104
+ decode = lambda part: json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)))
105
+ header, claims = decode(parts[0]), decode(parts[1])
106
+ if not isinstance(header, dict) or not isinstance(claims, dict):
107
+ raise ValueError()
108
+ if header.get("alg") not in ("RS256", "RS384", "RS512", "ES256", "ES384", "ES512"):
109
+ raise ValueError()
110
+ expiry = claims.get("exp")
111
+ if (isinstance(expiry, bool) or not isinstance(expiry, (int, float))
112
+ or not math.isfinite(expiry) or expiry <= time.time() + 30):
113
+ raise ValueError()
114
+ return expiry
115
+ except (ValueError, TypeError, AttributeError, UnicodeError, OverflowError):
116
+ raise ServiceError("OAuth must return an unexpired signed JWT; enable JWT tokens for named users") from None
117
+
118
+
119
+ class Client:
120
+ """Keep credentials in memory and send inference only to api.salesforce.com."""
121
+
122
+ def __init__(self, credentials, timeout=60, retries=1, max_calls=10000):
123
+ self.credentials = credentials
124
+ self.timeout = timeout
125
+ self.retries = retries
126
+ self.max_calls = max_calls
127
+ self.calls = 0
128
+ self.http_attempts = 0
129
+ self.token = None
130
+ self.expires = 0
131
+ self.opener = urllib.request.build_opener(NoRedirect())
132
+
133
+ def _request(self, url, payload, headers):
134
+ for attempt in range(self.retries + 1):
135
+ self.http_attempts += 1
136
+ request = urllib.request.Request(url, data=payload, headers=headers, method="POST")
137
+ try:
138
+ with self.opener.open(request, timeout=self.timeout) as response:
139
+ raw = response.read(4_000_001)
140
+ if len(raw) > 4_000_000:
141
+ raise ServiceError("Response exceeded the size limit")
142
+ try:
143
+ data = json.loads(raw)
144
+ except (ValueError, UnicodeError):
145
+ raise ServiceError("Service returned invalid JSON") from None
146
+ if not isinstance(data, dict):
147
+ raise ServiceError("Service returned an unexpected JSON envelope")
148
+ return 200, data
149
+ except urllib.error.HTTPError as error:
150
+ status = error.code
151
+ retry_after = error.headers.get("Retry-After", "") if error.headers else ""
152
+ error.close()
153
+ if status not in (429, 500, 502, 503, 504) or attempt == self.retries:
154
+ return status, {}
155
+ delay = retry_delay(retry_after, attempt)
156
+ except (urllib.error.URLError, TimeoutError, OSError, http.client.HTTPException):
157
+ if attempt == self.retries:
158
+ raise ServiceError("HTTPS connection failed or timed out; check network and TLS") from None
159
+ delay = min(2 ** attempt, 8)
160
+ time.sleep(delay)
161
+ raise ServiceError("Request retry limit reached")
162
+
163
+ def _authenticate(self):
164
+ body = urllib.parse.urlencode({"grant_type": "client_credentials",
165
+ "client_id": self.credentials["SF_CLIENT_ID"],
166
+ "client_secret": self.credentials["SF_CLIENT_SECRET"]}).encode()
167
+ status, data = self._request(self.credentials["SF_INSTANCE_URL"] + "/services/oauth2/token", body,
168
+ {"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"})
169
+ if status != 200:
170
+ raise ServiceError(f"OAuth HTTP {status}; check ECA client credentials, Run As user and policy")
171
+ token = data.get("access_token")
172
+ self.expires = jwt_expiry(token)
173
+ self.token = token
174
+
175
+ def post(self, path, payload):
176
+ """Make one logical inference call with at most one refresh after HTTP 401."""
177
+ if path != CLASSIFIER_PATH and not re.fullmatch(
178
+ r"/einstein/platform/v1/models/[A-Za-z0-9_.-]+/generations", path):
179
+ raise ValueError("Unsupported inference path")
180
+ if self.calls >= self.max_calls:
181
+ raise ServiceError("Inference call budget exhausted")
182
+ self.calls += 1
183
+ for refresh in range(2):
184
+ if not self.token or self.expires <= time.time() + 30:
185
+ self._authenticate()
186
+ headers = {"Authorization": "Bearer " + self.token, "Content-Type": "application/json",
187
+ "Accept": "application/json", "x-sfdc-app-context": "EinsteinGPT",
188
+ "x-client-feature-id": "ai-platform-models-connected-app"}
189
+ status, data = self._request(API + path, json.dumps(payload).encode(), headers)
190
+ if status == 200:
191
+ return data
192
+ if status == 401 and refresh == 0:
193
+ self.token = None
194
+ continue
195
+ raise ServiceError(f"Inference HTTP {status}; check org entitlement, OAuth scopes and API contract")
196
+ raise ServiceError("Authentication refresh failed")
197
+
198
+ def classify(self, utterance, topics):
199
+ """Send the utterance and complete descriptions, never the expected action."""
200
+ return self.post(CLASSIFIER_PATH, {
201
+ "model": CLASSIFIER_MODEL, "messages": [{"role": "user", "content": utterance}],
202
+ "topics_config": {"return_single_topic": False, "topics": topics},
203
+ "generation_settings": {"parameters": {"return_probability": True}},
204
+ })
205
+
206
+ def propose(self, model, prompt):
207
+ """Generate candidate text through the documented Models API."""
208
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+", model):
209
+ raise ValueError("Invalid proposer model identifier")
210
+ data = self.post(f"/einstein/platform/v1/models/{model}/generations", {"prompt": prompt})
211
+ generation = data.get("generation")
212
+ content = generation.get("generatedText") if isinstance(generation, dict) else None
213
+ if not isinstance(content, str) or not content.strip():
214
+ raise ServiceError("Proposer returned no generation.generatedText")
215
+ return content
216
+
217
+ def check_proposer(self, model):
218
+ """Check generation availability without exposing customer evaluation text."""
219
+ self.propose(model, "Reply with the word READY.")
@@ -0,0 +1,178 @@
1
+ """Prepare and deploy a dedicated ECA without embedding consumer credentials."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ import re
6
+ import shutil
7
+ import tempfile
8
+ import xml.etree.ElementTree as ET
9
+
10
+ from .evaluation import write_json
11
+ from .onboarding import APP_LABEL, APP_NAME, CLIError, deployment_details, discover_eca, sf
12
+
13
+
14
+ NS = "http://soap.sforce.com/2006/04/metadata"
15
+ ET.register_namespace("", NS)
16
+
17
+
18
+ def _xml(path, kind, values):
19
+ root = ET.Element("{" + NS + "}" + kind)
20
+ for key, value in values.items():
21
+ ET.SubElement(root, "{" + NS + "}" + key).text = str(value)
22
+ path.parent.mkdir(parents=True, exist_ok=True)
23
+ ET.indent(root)
24
+ ET.ElementTree(root).write(path, encoding="UTF-8", xml_declaration=True)
25
+
26
+
27
+ def require_eca_api(version):
28
+ """Reject incompatible plans before creating any local or remote ECA metadata."""
29
+ if not re.fullmatch(r"[0-9]{2,3}\.0", str(version)) or int(str(version).split('.')[0]) < 65:
30
+ raise ValueError("ECA JWT timeout policies require API 65.0 or later; refresh the CLI org API version before preparation")
31
+
32
+
33
+ def prepare_eca(org, workspace, contact_email, run_as, app_name=APP_NAME):
34
+ """Write a reviewable local ECA project and deployment plan for one org."""
35
+ require_eca_api(org["api_version"])
36
+ project = Path(workspace) / "eca"
37
+ if project.exists():
38
+ detail = "Review and reuse eca/plan.json." if (project / "plan.json").is_file() else (
39
+ "Preparation is incomplete. Back up and move the local eca directory aside, then run prepare-eca again.")
40
+ raise ValueError(f"ECA project already exists at {project}. {detail} Inspect org deployment status before any redeployment.")
41
+ if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,59}", app_name):
42
+ raise ValueError("ECA API name must be an identifier of at most 60 characters")
43
+ if not re.fullmatch(r"[^\s@]+@[^\s@]+\.[^\s@]+", contact_email or ""):
44
+ raise ValueError("A contact email is required")
45
+ if not run_as or any(c in run_as for c in ("'", "\\", "\n", "\r")):
46
+ raise ValueError("Supply the exact active Run As username")
47
+ if discover_eca(org, app_name):
48
+ raise ValueError("The optimizer ECA already exists; reuse its credentials instead of creating a duplicate")
49
+ result = sf(["data", "query", "--target-org", org["alias"], "--query",
50
+ f"SELECT Id, Username, IsActive FROM User WHERE Username = '{run_as}' AND IsActive = true"])
51
+ if not isinstance(result, dict) or len(result.get("records", [])) != 1:
52
+ raise ValueError("Run As must resolve to exactly one active user in the selected org")
53
+ with tempfile.TemporaryDirectory(prefix=".eca-prepare-", dir=workspace) as temporary:
54
+ staged = Path(temporary)
55
+ plan = _prepare_project(org, staged, contact_email, run_as, app_name)
56
+ if project.exists():
57
+ raise ValueError("ECA preparation appeared concurrently; inspect the existing project before retrying")
58
+ staged.rename(project)
59
+ return plan
60
+
61
+
62
+ def _prepare_project(org, project, contact_email, run_as, app_name):
63
+ """Publish only a complete prepared tree; failures leave no abandoned project."""
64
+ write_json(project / "sfdx-project.json", {"packageDirectories": [{"path": "force-app", "default": True}],
65
+ "namespace": "", "sourceApiVersion": org["api_version"]})
66
+ base = project / "force-app/main/default"
67
+ permission = app_name + "_Access"
68
+ _xml(base / f"externalClientApps/{app_name}.eca-meta.xml", "ExternalClientApplication", {
69
+ "contactEmail": contact_email, "description": "Customer-org access for HyperClassifier evaluation and optimization.",
70
+ "distributionState": "Local", "isProtected": "false", "label": APP_LABEL})
71
+ _xml(base / f"extlClntAppGlobalOauthSets/{app_name}_glbloauth.ecaGlblOauth-meta.xml", "ExtlClntAppGlobalOauthSettings", {
72
+ "callbackUrl": "https://login.salesforce.com/services/oauth2/success", "externalClientApplication": app_name,
73
+ "isClientCredentialsFlowEnabled": "true", "isConsumerSecretOptional": "false", "isIntrospectAllTokens": "false",
74
+ "isNamedUserJwtEnabled": "true", "isPkceRequired": "true", "isSecretRequiredForRefreshToken": "true",
75
+ "label": APP_LABEL + " Global OAuth", "shouldRotateConsumerKey": "false", "shouldRotateConsumerSecret": "false"})
76
+ _xml(base / f"extlClntAppOauthSettings/{app_name}_oauth.ecaOauth-meta.xml", "ExtlClntAppOauthSettings", {
77
+ "commaSeparatedOauthScopes": "Api, RefreshToken, SFApiPlatform", "externalClientApplication": app_name,
78
+ "label": APP_LABEL + " OAuth"})
79
+ _xml(base / f"permissionsets/{permission}.permissionset-meta.xml", "PermissionSet", {
80
+ "description": "ECA preauthorization only; grants no additional object or system permissions.",
81
+ "hasActivationRequired": "false", "label": "HyperClassifier Optimizer Access"})
82
+ plan = {"org_id": org["org_id"], "instance_url": org["instance_url"], "alias": org["alias"],
83
+ "app_name": app_name, "app_label": APP_LABEL, "run_as": run_as, "permission_set": permission,
84
+ "api_version": org["api_version"], "scopes": ["api", "refresh_token", "sfap_api"],
85
+ "flow": "client_credentials", "jwt_minutes": 30, "ip_policy": "Enforce",
86
+ "state": "prepared", "steps": []}
87
+ write_json(project / "plan.json", plan)
88
+ return plan
89
+
90
+
91
+ def _deploy(project, org, paths, plan, stage):
92
+ arguments = ["project", "deploy", "start", "--target-org", org["alias"], "--wait", "10"]
93
+ for path in paths:
94
+ arguments.extend(["--source-dir", str(path)])
95
+ record = {"status": "Submitting"}
96
+ plan["steps"].append({stage: record})
97
+ write_json(project / "plan.json", plan)
98
+ try:
99
+ try:
100
+ result = sf(arguments, cwd=project, timeout=720)
101
+ except CLIError as error:
102
+ record.update(error.deployment)
103
+ raise
104
+ record.update(deployment_details(result))
105
+ if record.get("status") != "Succeeded" or not record.get("deployment_id"):
106
+ raise ValueError("Metadata deployment did not complete with a confirmed job ID")
107
+ except ValueError as error:
108
+ job = record.get("deployment_id")
109
+ recovery = (f"Run sf project deploy report --target-org {org['alias']} --job-id {job}."
110
+ if job else "Inspect org deployment status; no job ID was returned.")
111
+ raise ValueError(f"{error}. Recovery: {recovery} Saved in eca/plan.json; do not redeploy blindly.") from None
112
+ finally:
113
+ write_json(project / "plan.json", plan)
114
+
115
+
116
+ def _update_policy(path, values, app_name):
117
+ tree = ET.parse(path)
118
+ root = tree.getroot()
119
+ parent = root.find("{" + NS + "}externalClientApplication")
120
+ if parent is None or parent.text != app_name:
121
+ raise ValueError("Retrieved policy does not belong to the prepared ECA")
122
+ for key, value in values.items():
123
+ element = root.find("{" + NS + "}" + key)
124
+ if element is None:
125
+ element = ET.SubElement(root, "{" + NS + "}" + key)
126
+ element.text = str(value)
127
+ # Metadata serializers use schema ordering; these fields are alphabetic in retrieved policies.
128
+ root[:] = sorted(root, key=lambda element: element.tag)
129
+ ET.indent(root)
130
+ tree.write(path, encoding="UTF-8", xml_declaration=True)
131
+
132
+
133
+ def deploy_eca(org, workspace):
134
+ """Deploy once, retrieve generated policies, configure preauthorization, and assign it."""
135
+ project = Path(workspace) / "eca"
136
+ plan = json.loads((project / "plan.json").read_text(encoding="utf-8"))
137
+ if plan.get("org_id") != org["org_id"] or plan.get("instance_url") != org["instance_url"]:
138
+ raise ValueError("ECA deployment plan belongs to another org")
139
+ if plan["state"] != "prepared":
140
+ raise ValueError("Deployment was already attempted; inspect plan.json and org deployment status before recovery")
141
+ require_eca_api(plan.get("api_version"))
142
+ if discover_eca(org, plan["app_name"]):
143
+ raise ValueError("ECA appeared after preparation; refusing to overwrite it")
144
+ base = project / "force-app/main/default"
145
+ plan["state"] = "deploying"
146
+ write_json(project / "plan.json", plan)
147
+ try:
148
+ _deploy(project, org, [base], plan, "base")
149
+ app = plan["app_name"]
150
+ oauth_name, policy_name = app + "_oauth_defaultPolicy", app + "_defaultPolicy"
151
+ sf(["project", "retrieve", "start", "--target-org", org["alias"], "--wait", "10",
152
+ "--metadata", "ExtlClntAppOauthConfigurablePolicies:" + oauth_name,
153
+ "--metadata", "ExtlClntAppConfigurablePolicies:" + policy_name], cwd=project, timeout=720)
154
+ oauth = base / f"extlClntAppOauthPolicies/{oauth_name}.ecaOauthPlcy-meta.xml"
155
+ policy = base / f"extlClntAppPolicies/{policy_name}.ecaPlcy-meta.xml"
156
+ backup = project / "retrieved-policy-backup"
157
+ backup.mkdir(mode=0o700)
158
+ for path in (oauth, policy):
159
+ if not path.is_file():
160
+ raise ValueError("Generated policy names differ; inspect metadata and retrieve the app's policies before continuing")
161
+ shutil.copy2(path, backup / path.name)
162
+ _update_policy(oauth, {"clientCredentialsFlowUser": plan["run_as"],
163
+ "commaSeparatedPermissionSet": plan["permission_set"],
164
+ "ipRelaxationPolicyType": "Enforce", "isClientCredentialsFlowEnabled": "true",
165
+ "namedUserJwtSessionTimeoutType": "Custom", "namedUserJwtTimeout": "30",
166
+ "permittedUsersPolicyType": "AdminApprovedPreAuthorized"}, app)
167
+ _update_policy(policy, {"isEnabled": "true", "isOauthPluginEnabled": "true"}, app)
168
+ _deploy(project, org, [oauth, policy], plan, "policies")
169
+ assigned = sf(["org", "assign", "permset", "--target-org", org["alias"],
170
+ "--name", plan["permission_set"], "--on-behalf-of", plan["run_as"]])
171
+ if isinstance(assigned, dict) and assigned.get("failures"):
172
+ raise ValueError("Permission-set assignment reported failures")
173
+ plan["state"] = "awaiting_credentials"
174
+ return plan
175
+ finally:
176
+ if plan["state"] == "deploying":
177
+ plan["state"] = "incomplete_check_org_before_retry"
178
+ write_json(project / "plan.json", plan)