@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.
- package/README.md +55 -5
- package/package.json +1 -1
- package/skills/afcc-setup-coordinate/SKILL.md +348 -0
- package/skills/afcc-setup-coordinate/assets/console-app/AFCC_Service_Console.app-meta.xml +19 -0
- package/skills/afcc-setup-coordinate/assets/console-app/Admin.profile-meta.xml +8 -0
- package/skills/afcc-setup-coordinate/assets/console-app/Standard.profile-meta.xml +8 -0
- package/skills/afcc-setup-coordinate/assets/gap_report_template.md +35 -0
- package/skills/afcc-setup-coordinate/assets/org_profile_template.json +16 -0
- package/skills/afcc-setup-coordinate/references/gotchas.md +22 -0
- package/skills/afcc-setup-coordinate/scripts/audit_org.sh +159 -0
- package/skills/agentforce-bot-upgrade/SKILL.md +117 -66
- package/skills/agentforce-bot-upgrade/assets/_vendored/agent-spec-template.md +139 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/agent-design-and-spec-creation.md +1211 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/agent-script-core-language.md +1390 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/agent-subagent-map-diagrams.md +341 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/agent-user-setup.md +672 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/agent-validation-and-debugging.md +904 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/agentscript-toolchain.md +112 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/architecture-patterns.md +277 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/common-control-flow-pitfalls.md +255 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/control-flow-actions-sequencing.md +198 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/control-flow-lifecycle-side-effects.md +87 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/data-library-reference.md +891 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/instruction-resolution.md +658 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/org-setup-for-adl.md +551 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/patterns-by-requirement.md +88 -0
- package/skills/agentforce-bot-upgrade/references/_vendored/posture-and-determinism.md +215 -0
- package/skills/agentforce-bot-upgrade/references/extraction-blueprint.md +11 -4
- package/skills/agentforce-bot-upgrade/references/generate-agent-spec.md +19 -3
- package/skills/agentforce-bot-upgrade/references/handoff-output-format.md +82 -52
- package/skills/agentforce-bot-upgrade/references/input-contract.md +8 -8
- package/skills/agentforce-bot-upgrade/references/mapping-rules.md +19 -6
- package/skills/agentforce-bot-upgrade/references/post-conversion-enhancements-reference.md +65 -6
- package/skills/agentforce-bot-upgrade/references/quality-checklist.md +4 -4
- package/skills/agentforce-bot-upgrade/references/sf-cli-bot-reference.md +17 -3
- package/skills/agentforce-hyperclassifier-configure/README.md +24 -0
- package/skills/agentforce-hyperclassifier-configure/SKILL.md +111 -0
- package/skills/agentforce-hyperclassifier-configure/assets/customer-org.env.example +4 -0
- package/skills/agentforce-hyperclassifier-configure/assets/sample_descriptions.json +8 -0
- package/skills/agentforce-hyperclassifier-configure/assets/sample_evals.csv +17 -0
- package/skills/agentforce-hyperclassifier-configure/references/api-contract.md +41 -0
- package/skills/agentforce-hyperclassifier-configure/references/authentication.md +35 -0
- package/skills/agentforce-hyperclassifier-configure/references/evaluation.md +46 -0
- package/skills/agentforce-hyperclassifier-configure/references/installation.md +35 -0
- package/skills/agentforce-hyperclassifier-configure/references/onboarding.md +93 -0
- package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/__init__.py +1 -0
- package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/client.py +219 -0
- package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/eca.py +178 -0
- package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/evaluation.py +207 -0
- package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/onboarding.py +191 -0
- package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/optimizer.py +187 -0
- package/skills/agentforce-hyperclassifier-configure/scripts/hyperclassifier.py +111 -0
- package/skills/agentforce-hyperclassifier-configure/scripts/report_hyperclassifier.py +149 -0
- package/skills/agentforce-hyperclassifier-configure/scripts/setup_hyperclassifier.py +74 -0
- package/skills/agentforce-hyperclassifier-configure/scripts/tests/test_hyperclassifier_skill.py +887 -0
- package/skills/agentforce-offline-experimentation-run/SKILL.md +14 -22
- package/skills/agentforce-offline-experimentation-run/scripts/bt_compare.py +81 -0
- package/skills/agentforce-offline-experimentation-run/scripts/bt_fetch.py +358 -0
- package/skills/agentforce-offline-experimentation-run/scripts/bt_patch_agent.py +110 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/__init__.py +34 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/agentpatch.py +483 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/agentsrc.py +565 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/cache.py +95 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/compare.py +617 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/fetch.py +1012 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/judge.py +140 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/messages.py +93 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/patch.py +327 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/redact.py +40 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/results.py +288 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/scoring.py +340 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/sfap.py +354 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/splits.py +136 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/stdm.py +98 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/tokens.py +173 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/units.py +199 -0
- package/skills/agentforce-offline-experimentation-run/scripts/btlib/versions.py +194 -0
- package/skills/agentforce-offline-experimentation-run/scripts/build_report.py +367 -379
- package/skills/agentforce-offline-experimentation-run/scripts/resolve-token.sh +23 -6
- package/skills/agentforce-offline-experimentation-run/scripts/sfap_replay.py +483 -796
- package/skills/commerce-react-storefront-create/SKILL.md +54 -21
- package/skills/dx-lifecycle-center/SKILL.md +22 -13
- package/skills/dx-lifecycle-center/examples/workflows.md +54 -17
- package/skills/dx-lifecycle-center/references/connect-api.md +33 -4
- package/skills/dx-lifecycle-center/references/connect-org.md +62 -12
- package/skills/dx-lifecycle-center/references/deploy.md +3 -3
- package/skills/dx-lifecycle-center/references/hub-org.md +19 -3
- package/skills/dx-lifecycle-center/references/list-orgs.md +50 -24
- package/skills/dx-lifecycle-center/references/troubleshooting.md +22 -1
- package/skills/dx-lifecycle-center/scripts/hub-get.sh +41 -0
- package/skills/dx-lifecycle-center/scripts/resolve-environment.sh +151 -4
- package/skills/dx-org-devhub-configure/SKILL.md +85 -84
- package/skills/dx-org-devhub-configure/examples/status-output.md +25 -2
- package/skills/dx-org-devhub-configure/scripts/devhub.sh +265 -140
- package/skills/dx-org-devhub-configure/scripts/test-devhub.sh +100 -15
- package/skills/dx-packaging-convert-1gp-to-2gp-create/SKILL.md +63 -0
- package/skills/dx-packaging-convert-1gp-to-2gp-create/references/conversion-operations.md +252 -0
- package/skills/dx-packaging-move-to-2gp-migrate/SKILL.md +88 -0
- package/skills/dx-packaging-move-to-2gp-migrate/references/api-operations.md +167 -0
- package/skills/dx-packaging-push-upgrade-configure/README.md +47 -0
- package/skills/dx-packaging-push-upgrade-configure/SKILL.md +355 -0
- package/skills/dx-packaging-push-upgrade-configure/references/best-practices.md +61 -0
- package/skills/dx-packaging-push-upgrade-configure/references/cli-reference.md +148 -0
- package/skills/dx-packaging-push-upgrade-configure/references/objects.md +106 -0
- package/skills/dx-packaging-push-upgrade-configure/references/soql-recipes.md +144 -0
- package/skills/dx-scratch-def-configure/SKILL.md +163 -0
- package/skills/dx-scratch-def-configure/examples/confirm-card.md +53 -0
- package/skills/dx-scratch-def-configure/examples/report-recipes.md +100 -0
- package/skills/dx-scratch-def-configure/references/features.json +3270 -0
- package/skills/dx-scratch-def-configure/references/project-scratch-def.schema.json +1841 -0
- package/skills/dx-scratch-def-configure/references/settings-map.json +682 -0
- package/skills/dx-scratch-def-configure/scripts/lib_scratch_def.py +1306 -0
- package/skills/dx-scratch-def-configure/scripts/requirements.txt +3 -0
- package/skills/dx-scratch-def-configure/scripts/scrape_config_values.py +848 -0
- package/skills/education-cloud-domain-configure/SKILL.md +1 -1
- package/skills/education-cloud-multi-campus-configure/SKILL.md +1 -1
- package/skills/education-cloud-student-recruitment-agent-configure/SKILL.md +1 -1
- package/skills/experience-afv-analytics-query/SKILL.md +239 -0
- package/skills/experience-afv-analytics-query/references/references.md +176 -0
- package/skills/experience-app-mcp-delivery-generate/SKILL.md +142 -0
- package/skills/experience-app-mcp-delivery-generate/references/eca-consumer-key.md +26 -0
- package/skills/experience-app-mcp-delivery-generate/references/mcp-config-delivery.md +38 -0
- package/skills/experience-app-mcp-delivery-generate/references/plugin-format-and-publishing.md +80 -0
- package/skills/experience-app-mcp-delivery-generate/scripts/developer_name.mjs +9 -0
- package/skills/experience-app-mcp-delivery-generate/scripts/discover_mcp_context.mjs +114 -0
- package/skills/experience-app-mcp-delivery-generate/scripts/generate_mcp_config.mjs +27 -0
- package/skills/experience-app-mcp-delivery-generate/scripts/generate_plugin.mjs +184 -0
- package/skills/experience-app-mcp-delivery-generate/scripts/mcp_config.mjs +57 -0
- package/skills/experience-app-mcp-delivery-generate/scripts/preflight.mjs +109 -0
- package/skills/experience-app-mcp-delivery-generate/scripts/retrieve_eca_consumer_key.mjs +143 -0
- package/skills/experience-app-mcp-generate/SKILL.md +174 -0
- package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.eca-meta.xml +7 -0
- package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaGlblOauth-meta.xml +15 -0
- package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaOauth-meta.xml +6 -0
- package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaOauthPlcy-meta.xml +12 -0
- package/skills/experience-app-mcp-generate/assets/__ECA_NAME___defaultPolicy.ecaPlcy-meta.xml +7 -0
- package/skills/experience-app-mcp-generate/assets/__MCP_SERVER_NAME__.mcpServerDefinition-meta.xml +5 -0
- package/skills/experience-app-mcp-generate/references/eca-fields.md +76 -0
- package/skills/experience-app-mcp-generate/references/mcp-objects.md +66 -0
- package/skills/experience-app-mcp-generate/references/tool-bindings.md +85 -0
- package/skills/experience-app-mcp-generate/references/troubleshooting.md +41 -0
- package/skills/experience-app-mcp-generate/references/ui-frameworks.md +19 -0
- package/skills/experience-app-mcp-generate/references/widget-resources.md +96 -0
- package/skills/experience-app-mcp-generate/scripts/activate_server.mjs +166 -0
- package/skills/experience-app-mcp-generate/scripts/check_setup_progress.mjs +212 -0
- package/skills/experience-app-mcp-generate/scripts/list_sites.mjs +211 -0
- package/skills/experience-app-mcp-generate/scripts/merge_tools.mjs +407 -0
- package/skills/experience-app-mcp-generate/scripts/preflight.mjs +127 -0
- package/skills/experience-app-mcp-generate/scripts/render_eca.mjs +144 -0
- package/skills/experience-app-mcp-generate/scripts/render_mcp_server.mjs +64 -0
- package/skills/experience-app-mcp-generate/scripts/retrieve_existing_prompts.mjs +145 -0
- package/skills/experience-app-mcp-generate/scripts/retrieve_existing_tools.mjs +72 -0
- package/skills/experience-app-mcp-generate/scripts/scan_tool_candidates.mjs +195 -0
- package/skills/experience-app-mcp-generate/scripts/utils/callback_url.mjs +36 -0
- package/skills/experience-app-mcp-generate/scripts/utils/developer_name.mjs +9 -0
- package/skills/experience-app-mcp-generate/scripts/utils/eca_check.mjs +156 -0
- package/skills/experience-app-mcp-generate/scripts/utils/metadata_path.mjs +13 -0
- package/skills/experience-app-mcp-generate/scripts/verify_server.mjs +118 -0
- package/skills/experience-cms-content-type-generate/SKILL.md +1 -1
- package/skills/experience-design-validate/SKILL.md +1 -1
- package/skills/experience-search-coordinate/SKILL.md +18 -12
- package/skills/experience-search-coordinate/references/content-route.md +79 -1
- package/skills/field-service-data-capture-migrate/SKILL.md +1 -1
- package/skills/nonprofit-fundraising-configure/SKILL.md +1 -1
- package/skills/nonprofit-fundraising-configure/references/mcp-invocation.md +52 -4
- package/skills/nonprofit-fundraising-configure/references/permission-targeting.md +19 -2
- package/skills/platform-apex-generate/SKILL.md +14 -11
- package/skills/platform-apex-test-generate/SKILL.md +2 -1
- package/skills/platform-custom-field-generate/SKILL.md +24 -16
- package/skills/platform-custom-metadata-type-generate/SKILL.md +1 -0
- package/skills/platform-custom-setting-generate/SKILL.md +1 -0
- package/skills/platform-datamask-run/SKILL.md +52 -71
- package/skills/platform-datamask-run/references/api-surface.md +10 -4
- package/skills/platform-datamask-run/references/policy-authoring.md +56 -7
- package/skills/platform-datamask-run/references/run-and-abort.md +17 -10
- package/skills/platform-datamask-run/scripts/poll-job.sh +15 -25
- package/skills/platform-dataspace-access-configure/SKILL.md +43 -10
- package/skills/platform-flexipage-generate/SKILL.md +7 -10
- package/skills/platform-flexipage-generate/references/mcp_action_examples.md +42 -38
- package/skills/platform-metadata-discovery-get/SKILL.md +185 -0
- package/skills/platform-metadata-discovery-get/references/api-map.md +25 -0
- package/skills/platform-metadata-discovery-get/references/h360-routes.md +30 -0
- package/skills/platform-metadata-discovery-get/references/scoped-soql.md +52 -0
- package/skills/platform-metadata-grounding-get/SKILL.md +170 -0
- package/skills/platform-policy-rule-generate/SKILL.md +85 -231
- package/skills/platform-policy-rule-generate/references/condition-model.md +47 -0
- package/skills/platform-policy-rule-generate/references/condition-templates.md +89 -0
- package/skills/platform-policy-rule-generate/references/conjunction-compiler.md +25 -0
- package/skills/platform-policy-rule-generate/references/conjunction-expression.md +30 -0
- package/skills/platform-policy-rule-generate/references/consumer-all.md +9 -0
- package/skills/platform-policy-rule-generate/references/consumer-datacloud-ui.md +99 -0
- package/skills/platform-policy-rule-generate/references/deploy-errors.md +24 -36
- package/skills/platform-policy-rule-generate/references/examples/ExistsJoinRLS/package.xml +12 -0
- package/skills/platform-policy-rule-generate/references/examples/ExistsJoinRLS/policyRuleDefinitionSets/ExistsJoinRLS.policyRuleDefinitionSet +5 -0
- package/skills/platform-policy-rule-generate/references/examples/ExistsJoinRLS/policyRuleDefinitions/ExistsJoinRLS_Rule_1.policyRuleDefinition +91 -0
- package/skills/platform-policy-rule-generate/references/examples/FieldReadDeny/package.xml +12 -0
- package/skills/platform-policy-rule-generate/references/examples/FieldReadDeny/policyRuleDefinitionSets/FieldReadDeny.policyRuleDefinitionSet +5 -0
- package/skills/platform-policy-rule-generate/references/examples/FieldReadDeny/policyRuleDefinitions/FieldReadDeny_Rule_1.policyRuleDefinition +72 -0
- package/skills/platform-policy-rule-generate/references/examples/LastCharactersFieldMasking/package.xml +12 -0
- package/skills/platform-policy-rule-generate/references/examples/LastCharactersFieldMasking/policyRuleDefinitionSets/LastCharactersFieldMasking.policyRuleDefinitionSet +5 -0
- package/skills/platform-policy-rule-generate/references/examples/LastCharactersFieldMasking/policyRuleDefinitions/LastCharactersFieldMasking_Rule_1.policyRuleDefinition +77 -0
- package/skills/platform-policy-rule-generate/references/examples/PrincipalFieldMatchRLS/package.xml +12 -0
- package/skills/platform-policy-rule-generate/references/examples/PrincipalFieldMatchRLS/policyRuleDefinitionSets/PrincipalFieldMatchRLS.policyRuleDefinitionSet +5 -0
- package/skills/platform-policy-rule-generate/references/examples/PrincipalFieldMatchRLS/policyRuleDefinitions/PrincipalFieldMatchRLS_Rule_1.policyRuleDefinition +77 -0
- package/skills/platform-policy-rule-generate/references/examples/TaggedObjectAccess/package.xml +12 -0
- package/skills/platform-policy-rule-generate/references/examples/TaggedObjectAccess/policyRuleDefinitionSets/TaggedObjectAccess.policyRuleDefinitionSet +5 -0
- package/skills/platform-policy-rule-generate/references/examples/TaggedObjectAccess/policyRuleDefinitions/TaggedObjectAccess_Rule_1.policyRuleDefinition +65 -0
- package/skills/platform-policy-rule-generate/references/headless-transport.md +87 -0
- package/skills/platform-policy-rule-generate/references/policy-schema-full.md +18 -11
- package/skills/platform-policy-rule-generate/references/policy-shapes.md +107 -0
- package/skills/platform-policy-rule-generate/references/principal-expression.md +31 -0
- package/skills/platform-policy-rule-generate/references/reference-resolution.md +51 -0
- package/skills/platform-policy-rule-generate/references/resource-expression.md +48 -0
- package/skills/platform-policy-rule-generate/references/runtime-context.md +9 -0
- package/skills/platform-policy-rule-generate/references/templates-access.md +11 -9
- package/skills/platform-policy-rule-generate/references/templates-advanced.md +5 -3
- package/skills/platform-policy-rule-generate/references/templates-record.md +37 -22
- package/skills/platform-policy-rule-generate/references/templates-transform.md +10 -8
- package/skills/platform-policy-rule-generate/references/templates.md +2 -2
- package/skills/platform-policy-rule-generate/references/ui-compatibility.md +36 -18
- package/skills/platform-report-generate/SKILL.md +29 -5
- package/skills/platform-report-generate/references/chart-types.md +26 -2
- package/skills/platform-report-generate/references/column-names.md +43 -0
- package/skills/platform-report-generate/references/errors-and-troubleshooting.md +1 -1
- package/skills/platform-report-generate/references/summary-formulas-sorting-limits.md +118 -0
- package/skills/platform-report-generate/references/verification-checklist.md +22 -2
- package/skills/service-digital-engagement-channel-configure/SKILL.md +49 -110
- package/skills/service-digital-engagement-channel-configure/assets/messaging_channel_template.xml +35 -0
- package/skills/service-digital-engagement-channel-configure/examples/asa_agent_channel.xml +2 -2
- package/skills/service-digital-engagement-channel-configure/examples/auth_queue_channel.xml +58 -0
- package/skills/service-digital-engagement-channel-configure/examples/omni_flow_channel.xml +2 -2
- package/skills/service-digital-engagement-channel-configure/examples/omni_queue_channel.xml +3 -3
- package/skills/service-digital-engagement-channel-configure/references/channel_settings.md +128 -28
- package/skills/service-digital-engagement-channel-configure/references/onboarding_contract.md +16 -20
- package/skills/service-digital-engagement-channel-configure/references/prechat_params.md +10 -0
- package/skills/service-digital-engagement-channel-configure/references/recaptcha_handoff.md +38 -0
- package/skills/service-digital-engagement-channel-configure/references/user_verification.md +9 -0
- package/skills/service-digital-engagement-channel-configure/scripts/check-api-version.sh +4 -4
- package/skills/service-digital-engagement-channel-configure/scripts/normalize-channel-name.sh +12 -7
- package/skills/service-e911-configure/SKILL.md +242 -0
- package/skills/service-itsm-agentic-setup-agent-runtime-access-assign/SKILL.md +1 -1
- package/skills/service-itsm-agentic-setup-agentforce-coordinate/SKILL.md +1 -1
- package/skills/service-itsm-agentic-setup-agentforce-studio-configure/SKILL.md +1 -1
- package/skills/service-itsm-agentic-setup-agentforce-studio-validate/SKILL.md +1 -1
- package/skills/service-itsm-agentic-setup-employee-agent-configure/SKILL.md +1 -1
- package/skills/service-itsm-agentic-setup-fulfiller-agent-configure/SKILL.md +1 -1
- package/skills/service-itsm-agentic-setup-incident-management/SKILL.md +47 -44
- package/skills/service-itsm-agentic-setup-incident-management/examples/output-templates.md +110 -83
- package/skills/service-itsm-agentic-setup-incident-management/references/manage-incidents-with-ai.md +7 -3
- package/skills/service-itsm-agentic-setup-incident-management/references/priority-matrix.md +7 -5
- package/skills/service-itsm-agentic-setup-incident-management/references/sla-milestones.md +2 -2
- package/skills/service-itsm-agentic-setup-incident-management/references/status-checks.md +437 -0
- package/skills/service-itsm-agentic-setup-itsm-agentforce-permset-assign/SKILL.md +1 -1
- package/skills/agentforce-bot-upgrade/references/planner-workflow-reference.md +0 -78
- package/skills/experience-content-media-image-generate/SKILL.md +0 -83
- package/skills/experience-content-media-image-generate/scripts/download-image.sh +0 -84
- package/skills/experience-content-media-stock-image-search/SKILL.md +0 -193
- package/skills/experience-content-media-stock-image-search/scripts/download-stock-image.py +0 -102
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""SFAP /chat/generations client and the production request shape.
|
|
2
|
+
|
|
3
|
+
The token is read from its 0600 file on every call: it never enters argv, the environment
|
|
4
|
+
of child processes, or any artifact, and a token refreshed in place is picked up without a
|
|
5
|
+
restart. On a 401, on_unauthorized(token_used) may refresh it (tokens.TokenRefresher); a True
|
|
6
|
+
return sends the request once more. Failures come back as status 'infra_error' after
|
|
7
|
+
retries, never as an answer.
|
|
8
|
+
|
|
9
|
+
A timeout is retried once only: each one costs the whole timeout, and a model that runs away on a
|
|
10
|
+
request runs away again. The provider has its own limit (EinsteinBYOM: ~180 s, then a 502 whose
|
|
11
|
+
body says "Timeout"), recorded as provider_timeout; the default --timeout is above it, so that the
|
|
12
|
+
provider, not the client, cuts a slow answer off.
|
|
13
|
+
|
|
14
|
+
Production request fields (from captured gateway payloads) reproduced here:
|
|
15
|
+
tools [{"function": {name, description, parameters}}] (no "type")
|
|
16
|
+
tool_config {"mode": "auto", "allowed_tools": [all tools], "parallel_calls": true}
|
|
17
|
+
generation_settings {"num_generations": 1, penalties 0, "stop_sequences": [],
|
|
18
|
+
"parameters": {"seed": n}} — no max_tokens, no temperature
|
|
19
|
+
system_prompt_strategy "use_model_parameter"; enable_pii_masking false
|
|
20
|
+
Not reproduced: safety/bias scoring flags, trust settings, localization, turn ids, tags.
|
|
21
|
+
|
|
22
|
+
STDM records a step's request before production's LLM client changes it. These of its
|
|
23
|
+
last-mile transform steps are ported as written, so the model sees what production's model saw:
|
|
24
|
+
tools every top-level property gets title = its name; ":" in a property name becomes
|
|
25
|
+
"_" (in properties, required and that title), unless the new name is taken
|
|
26
|
+
messages an assistant message with no text and no tool calls is dropped; earlier calls to
|
|
27
|
+
a renamed tool get the same renaming of their argument keys
|
|
28
|
+
answer the renamed argument keys are mapped back (restore_param_names), as production
|
|
29
|
+
records them, so they score against the golden as production's did
|
|
30
|
+
Not ported, since no recorded request needs them: tool names cut to 64 characters (a longer
|
|
31
|
+
name fails loudly, HTTP 400), the repair of unpaired tool calls, URL placeholders. The seed is
|
|
32
|
+
--seed + repeat, not production's constant 75197747: it only picks the draw, and a constant
|
|
33
|
+
would make the k repeats one cached answer.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
import copy
|
|
37
|
+
import hashlib
|
|
38
|
+
import json
|
|
39
|
+
import socket
|
|
40
|
+
import time
|
|
41
|
+
import urllib.error
|
|
42
|
+
import urllib.parse
|
|
43
|
+
import urllib.request
|
|
44
|
+
|
|
45
|
+
from .redact import redact, register_secret
|
|
46
|
+
from .units import parse_arguments
|
|
47
|
+
|
|
48
|
+
RETRY_STATUS = {408, 425, 429, 500, 502, 503, 504}
|
|
49
|
+
# No answer in time: the client's timeout, or the provider's (a 502/504 whose body says so).
|
|
50
|
+
TIMEOUT_KINDS = ("timeout", "provider_timeout")
|
|
51
|
+
DEFAULT_TIMEOUT = 200
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def sanitize_tools_for_sfap(tools):
|
|
55
|
+
"""Drop additionalProperties and empty `required` (SFAP has rejected both with a 400)."""
|
|
56
|
+
sanitized = []
|
|
57
|
+
for tool in tools:
|
|
58
|
+
tool = copy.deepcopy(tool)
|
|
59
|
+
params = (tool.get("function") or {}).get("parameters") or {}
|
|
60
|
+
params.pop("additionalProperties", None)
|
|
61
|
+
if "required" in params and not params["required"]:
|
|
62
|
+
del params["required"]
|
|
63
|
+
sanitized.append(tool)
|
|
64
|
+
return sanitized
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _param_renames(properties):
|
|
68
|
+
"""[(name, name with ":" -> "_")], skipping a rename onto another property's name."""
|
|
69
|
+
return [(k, k.replace(":", "_")) for k in properties
|
|
70
|
+
if ":" in k and k.replace(":", "_") not in properties]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def param_name_lookup(tools):
|
|
74
|
+
"""{tool name: {sent parameter name: recorded name}} for the tools whose names production renames."""
|
|
75
|
+
lookup = {}
|
|
76
|
+
for t in tools or []:
|
|
77
|
+
fn = t.get("function") or {}
|
|
78
|
+
props = (fn.get("parameters") or {}).get("properties")
|
|
79
|
+
renames = _param_renames(props) if isinstance(props, dict) else []
|
|
80
|
+
if renames:
|
|
81
|
+
lookup[fn.get("name")] = {new: old for old, new in renames}
|
|
82
|
+
return lookup
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _production_parameters(parameters):
|
|
86
|
+
"""In place: titles added, ":" renamed, as production sends a tool's parameters."""
|
|
87
|
+
props = parameters.get("properties")
|
|
88
|
+
if not isinstance(props, dict):
|
|
89
|
+
return
|
|
90
|
+
for key, value in props.items():
|
|
91
|
+
if isinstance(value, dict):
|
|
92
|
+
value.setdefault("title", key)
|
|
93
|
+
renames = _param_renames(props)
|
|
94
|
+
for old, new in renames:
|
|
95
|
+
props[new] = props.pop(old)
|
|
96
|
+
if isinstance(props[new], dict) and props[new].get("title") == old:
|
|
97
|
+
props[new]["title"] = new
|
|
98
|
+
if isinstance(parameters.get("required"), list):
|
|
99
|
+
rename = dict(renames)
|
|
100
|
+
parameters["required"] = [rename.get(r, r) for r in parameters["required"]]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _remap_arguments(arguments, mapping):
|
|
104
|
+
"""Top-level keys of a JSON arguments string renamed; anything else returned as is."""
|
|
105
|
+
if not arguments or not mapping:
|
|
106
|
+
return arguments
|
|
107
|
+
try:
|
|
108
|
+
parsed = json.loads(arguments)
|
|
109
|
+
except (json.JSONDecodeError, TypeError):
|
|
110
|
+
return arguments
|
|
111
|
+
if not isinstance(parsed, dict):
|
|
112
|
+
return arguments
|
|
113
|
+
return json.dumps({mapping.get(k, k): v for k, v in parsed.items()})
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _empty_assistant(m):
|
|
117
|
+
content = m.get("content")
|
|
118
|
+
return (m.get("role") == "assistant" and not m.get("tool_invocations")
|
|
119
|
+
and not (content.strip() if isinstance(content, str) else content))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def production_messages(messages, lookup):
|
|
123
|
+
"""The messages as production sends them: empty assistant messages dropped, and earlier
|
|
124
|
+
calls to a tool in `lookup` with their argument keys renamed as its parameters are. A new
|
|
125
|
+
list; a message that changes is copied, the others are shared."""
|
|
126
|
+
out = []
|
|
127
|
+
for m in messages:
|
|
128
|
+
if _empty_assistant(m):
|
|
129
|
+
continue
|
|
130
|
+
calls = m.get("tool_invocations") or []
|
|
131
|
+
if any((c.get("function") or {}).get("name") in lookup for c in calls):
|
|
132
|
+
renamed = []
|
|
133
|
+
for c in calls:
|
|
134
|
+
fn = c.get("function") or {}
|
|
135
|
+
if fn.get("name") in lookup:
|
|
136
|
+
forward = {old: new for new, old in lookup[fn["name"]].items()}
|
|
137
|
+
c = dict(c, function=dict(fn, arguments=_remap_arguments(fn.get("arguments"), forward)))
|
|
138
|
+
renamed.append(c)
|
|
139
|
+
m = dict(m, tool_invocations=renamed)
|
|
140
|
+
out.append(m)
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def restore_param_names(response, tools):
|
|
145
|
+
"""A parsed answer with the renamed argument keys mapped back, as production records it."""
|
|
146
|
+
lookup = param_name_lookup(tools)
|
|
147
|
+
if not response or not any(c.get("name") in lookup for c in response.get("tool_calls") or []):
|
|
148
|
+
return response
|
|
149
|
+
calls = []
|
|
150
|
+
for c in response["tool_calls"]:
|
|
151
|
+
mapping = lookup.get(c.get("name"))
|
|
152
|
+
if mapping and "args_raw" not in c:
|
|
153
|
+
c = dict(c, args={mapping.get(k, k): v for k, v in c["args"].items()})
|
|
154
|
+
calls.append(c)
|
|
155
|
+
return dict(response, tool_calls=calls)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def to_sfap_tools(tools):
|
|
159
|
+
"""Step tool definitions (gen_ai.request.tools) in the production request shape."""
|
|
160
|
+
out = []
|
|
161
|
+
for t in sanitize_tools_for_sfap(tools):
|
|
162
|
+
fn = t.get("function") or {}
|
|
163
|
+
if isinstance(fn.get("parameters"), dict):
|
|
164
|
+
_production_parameters(fn["parameters"])
|
|
165
|
+
out.append({"function": fn})
|
|
166
|
+
return out
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def build_payload(model, messages, tools=None, seed=None, parameters=None):
|
|
170
|
+
payload = {"model": model, "messages": production_messages(messages, param_name_lookup(tools))}
|
|
171
|
+
if tools:
|
|
172
|
+
payload["tools"] = to_sfap_tools(tools)
|
|
173
|
+
payload["tool_config"] = {
|
|
174
|
+
"mode": "auto",
|
|
175
|
+
"allowed_tools": [{"name": (t.get("function") or {}).get("name"), "type": "function"}
|
|
176
|
+
for t in tools],
|
|
177
|
+
"parallel_calls": True,
|
|
178
|
+
}
|
|
179
|
+
gen_params = {}
|
|
180
|
+
if seed is not None:
|
|
181
|
+
gen_params["seed"] = seed
|
|
182
|
+
gen_params.update(parameters or {})
|
|
183
|
+
payload["generation_settings"] = {
|
|
184
|
+
"num_generations": 1, "frequency_penalty": 0.0, "presence_penalty": 0.0,
|
|
185
|
+
"stop_sequences": [], "parameters": gen_params,
|
|
186
|
+
}
|
|
187
|
+
payload["system_prompt_strategy"] = "use_model_parameter"
|
|
188
|
+
payload["enable_pii_masking"] = False
|
|
189
|
+
return payload
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def request_sha(messages, tools):
|
|
193
|
+
"""Identity of a request's content (messages + tools), independent of model and seed."""
|
|
194
|
+
blob = json.dumps({"messages": messages, "tools": tools}, sort_keys=True,
|
|
195
|
+
separators=(",", ":"), ensure_ascii=False)
|
|
196
|
+
return hashlib.sha256(blob.encode("utf-8")).hexdigest()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _usage(body):
|
|
200
|
+
gd = body.get("generation_details") or {}
|
|
201
|
+
for holder in (gd.get("parameters"), body.get("parameters"), body):
|
|
202
|
+
if isinstance(holder, dict) and isinstance(holder.get("usage"), dict):
|
|
203
|
+
return holder["usage"]
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def parse_generation(body):
|
|
208
|
+
"""{text, tool_calls, finish_reason, usage} from a 200 body, or None if it has no generation."""
|
|
209
|
+
gens = ((body or {}).get("generation_details") or {}).get("generations") or []
|
|
210
|
+
if not gens:
|
|
211
|
+
return None
|
|
212
|
+
g = gens[0]
|
|
213
|
+
calls = []
|
|
214
|
+
for inv in g.get("tool_invocations") or []:
|
|
215
|
+
fn = inv.get("function") or {}
|
|
216
|
+
args, raw = parse_arguments(fn.get("arguments"))
|
|
217
|
+
call = {"name": fn.get("name"), "args": args}
|
|
218
|
+
if raw is not None:
|
|
219
|
+
call["args_raw"] = raw
|
|
220
|
+
calls.append(call)
|
|
221
|
+
params = g.get("parameters") if isinstance(g.get("parameters"), dict) else {}
|
|
222
|
+
return {"text": g.get("content") or "", "tool_calls": calls,
|
|
223
|
+
"finish_reason": params.get("finish_reason") or g.get("finish_reason"),
|
|
224
|
+
"usage": _usage(body)}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
class SfapClient:
|
|
228
|
+
def __init__(self, base_url, token_file, core_tenant_id, timeout=DEFAULT_TIMEOUT, max_retries=3,
|
|
229
|
+
backoff=2.0, rate_limit_backoff=10.0, timeout_retries=1, feature_id="AgentBacktesting",
|
|
230
|
+
app_context="EinsteinGPT", opener=None, sleep=time.sleep, on_unauthorized=None):
|
|
231
|
+
missing = [n for n, v in (("base_url", base_url), ("token_file", token_file),
|
|
232
|
+
("core_tenant_id", core_tenant_id)) if not v]
|
|
233
|
+
if missing:
|
|
234
|
+
raise ValueError("SFAP config missing: " + ", ".join(missing)
|
|
235
|
+
+ " (run scripts/resolve-token.sh and pass --token-info)")
|
|
236
|
+
parsed = urllib.parse.urlparse(base_url)
|
|
237
|
+
if parsed.scheme != "https":
|
|
238
|
+
raise ValueError(f"base_url must use https (got {parsed.scheme!r})")
|
|
239
|
+
if not parsed.hostname or not parsed.hostname.endswith(".salesforce.com"):
|
|
240
|
+
raise ValueError(f"base_url hostname must be *.salesforce.com (got {parsed.hostname!r})")
|
|
241
|
+
self.url = base_url.rstrip("/") + "/chat/generations"
|
|
242
|
+
self.token_file = token_file
|
|
243
|
+
self.core_tenant_id = core_tenant_id
|
|
244
|
+
self.timeout = timeout
|
|
245
|
+
self.max_retries = max_retries
|
|
246
|
+
self.backoff = backoff
|
|
247
|
+
self.rate_limit_backoff = rate_limit_backoff
|
|
248
|
+
self.timeout_retries = timeout_retries
|
|
249
|
+
self.feature_id = feature_id
|
|
250
|
+
self.app_context = app_context
|
|
251
|
+
self._open = (opener.open if opener else urllib.request.urlopen)
|
|
252
|
+
self._sleep = sleep
|
|
253
|
+
self._on_unauthorized = on_unauthorized
|
|
254
|
+
|
|
255
|
+
def _token(self):
|
|
256
|
+
with open(self.token_file) as f:
|
|
257
|
+
token = f.read().strip()
|
|
258
|
+
if not token:
|
|
259
|
+
raise RuntimeError("SFAP token file is empty")
|
|
260
|
+
register_secret(token)
|
|
261
|
+
return token
|
|
262
|
+
|
|
263
|
+
def _delay(self, attempt, retry_after=None, http_status=None):
|
|
264
|
+
if retry_after:
|
|
265
|
+
try:
|
|
266
|
+
return min(60.0, float(retry_after))
|
|
267
|
+
except ValueError:
|
|
268
|
+
pass
|
|
269
|
+
if http_status == 429: # a quota, usually per minute: a few seconds' wait meets it again
|
|
270
|
+
return min(60.0, self.rate_limit_backoff * (2 ** (attempt - 1)))
|
|
271
|
+
return min(30.0, self.backoff * (2 ** (attempt - 1)))
|
|
272
|
+
|
|
273
|
+
def post(self, payload):
|
|
274
|
+
"""POST once per attempt. Returns {status, http_status, body, error, error_kind, attempts, latency_ms}."""
|
|
275
|
+
data = json.dumps(payload).encode("utf-8")
|
|
276
|
+
attempts, timeouts, refreshed, t0 = 0, 0, False, time.monotonic()
|
|
277
|
+
while True:
|
|
278
|
+
attempts += 1
|
|
279
|
+
err_kind, err, http_status, retry_after = None, None, None, None
|
|
280
|
+
try:
|
|
281
|
+
token = self._token()
|
|
282
|
+
except (OSError, RuntimeError) as e:
|
|
283
|
+
return self._fail("token", f"cannot read the SFAP token file: {type(e).__name__}",
|
|
284
|
+
None, attempts, t0)
|
|
285
|
+
try:
|
|
286
|
+
req = urllib.request.Request(self.url, data=data, method="POST", headers={
|
|
287
|
+
"Authorization": f"Bearer {token}",
|
|
288
|
+
"Content-Type": "application/json",
|
|
289
|
+
"x-sfdc-app-context": self.app_context,
|
|
290
|
+
"x-client-feature-id": self.feature_id,
|
|
291
|
+
"x-sfdc-core-tenant-id": self.core_tenant_id,
|
|
292
|
+
})
|
|
293
|
+
with self._open(req, timeout=self.timeout) as resp:
|
|
294
|
+
raw = resp.read().decode("utf-8", "replace")
|
|
295
|
+
http_status = resp.status
|
|
296
|
+
try:
|
|
297
|
+
body = json.loads(raw)
|
|
298
|
+
except json.JSONDecodeError:
|
|
299
|
+
return self._fail("bad_json", f"HTTP {http_status}: response is not JSON: {redact(raw)[:200]}",
|
|
300
|
+
http_status, attempts, t0)
|
|
301
|
+
return {"status": "ok", "http_status": http_status, "body": body, "error": None,
|
|
302
|
+
"error_kind": None, "attempts": attempts,
|
|
303
|
+
"latency_ms": int((time.monotonic() - t0) * 1000)}
|
|
304
|
+
except urllib.error.HTTPError as e:
|
|
305
|
+
http_status = e.code
|
|
306
|
+
retry_after = e.headers.get("Retry-After") if e.headers else None
|
|
307
|
+
try:
|
|
308
|
+
body = e.read().decode("utf-8", "replace")
|
|
309
|
+
except Exception:
|
|
310
|
+
body = ""
|
|
311
|
+
finally:
|
|
312
|
+
e.close()
|
|
313
|
+
err_kind, err = f"http_{e.code}", f"HTTP {e.code}: {redact(body)[:300]}" # redact before cutting
|
|
314
|
+
if e.code in (502, 504) and "timeout" in body.lower():
|
|
315
|
+
err_kind = "provider_timeout"
|
|
316
|
+
if e.code == 401 and self._on_unauthorized and not refreshed:
|
|
317
|
+
refreshed = True
|
|
318
|
+
if self._on_unauthorized(token):
|
|
319
|
+
continue
|
|
320
|
+
if e.code not in RETRY_STATUS:
|
|
321
|
+
return self._fail(err_kind, err, http_status, attempts, t0)
|
|
322
|
+
except (socket.timeout, TimeoutError):
|
|
323
|
+
err_kind, err = "timeout", f"timeout after {self.timeout}s"
|
|
324
|
+
except urllib.error.URLError as e:
|
|
325
|
+
if isinstance(e.reason, (socket.timeout, TimeoutError)):
|
|
326
|
+
err_kind, err = "timeout", f"timeout after {self.timeout}s"
|
|
327
|
+
else:
|
|
328
|
+
err_kind, err = "network", f"network error: {e.reason}"
|
|
329
|
+
except (ConnectionError, OSError) as e:
|
|
330
|
+
err_kind, err = "network", f"network error: {e}"
|
|
331
|
+
if err_kind in TIMEOUT_KINDS:
|
|
332
|
+
timeouts += 1
|
|
333
|
+
if attempts > self.max_retries or timeouts > self.timeout_retries:
|
|
334
|
+
return self._fail(err_kind, err, http_status, attempts, t0)
|
|
335
|
+
self._sleep(self._delay(attempts, retry_after, http_status))
|
|
336
|
+
|
|
337
|
+
@staticmethod
|
|
338
|
+
def _fail(kind, err, http_status, attempts, t0):
|
|
339
|
+
return {"status": "infra_error", "http_status": http_status, "body": None,
|
|
340
|
+
"error": redact(err), "error_kind": kind, "attempts": attempts,
|
|
341
|
+
"latency_ms": int((time.monotonic() - t0) * 1000)}
|
|
342
|
+
|
|
343
|
+
def generate(self, payload):
|
|
344
|
+
"""post() plus parsing; a 200 without a generation is an infra error too."""
|
|
345
|
+
res = self.post(payload)
|
|
346
|
+
if res["status"] != "ok":
|
|
347
|
+
res["response"] = None
|
|
348
|
+
return res
|
|
349
|
+
parsed = parse_generation(res["body"])
|
|
350
|
+
if parsed is None:
|
|
351
|
+
res.update(status="infra_error", error_kind="empty_response",
|
|
352
|
+
error="HTTP 200 without generation_details.generations")
|
|
353
|
+
res["response"] = parsed
|
|
354
|
+
return res
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Session splits (--val-fraction, --split) and excluded sessions (--exclude-sessions).
|
|
2
|
+
|
|
3
|
+
A unit's split depends on its session alone: sha256 of the salt and the session ID, read as a
|
|
4
|
+
number in [0, 1), gives "val" below the val fraction and "test" otherwise. So every step of a
|
|
5
|
+
session lands in one split, a session keeps its split when other sessions are added or
|
|
6
|
+
removed, and another salt gives an independent split.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import csv
|
|
10
|
+
import hashlib
|
|
11
|
+
import io
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
from collections import Counter
|
|
15
|
+
|
|
16
|
+
from . import stdm
|
|
17
|
+
|
|
18
|
+
DEFAULT_SALT = "bt-split/1"
|
|
19
|
+
SPLITS = ("test", "val")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SplitError(ValueError):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def session_split(session_id, val_fraction, salt=DEFAULT_SALT):
|
|
27
|
+
h = hashlib.sha256(f"{salt}\0{session_id}".encode("utf-8")).hexdigest()
|
|
28
|
+
return "val" if int(h[:13], 16) / 16 ** 13 < val_fraction else "test"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def label(units, val_fraction, salt=DEFAULT_SALT):
|
|
32
|
+
"""Set each unit's split; returns {split: [sessions, units]}. Units that already carry
|
|
33
|
+
another split (an earlier run's labels) are refused: relabelling would mix the sets."""
|
|
34
|
+
new = [session_split(u["session_id"], val_fraction, salt) for u in units]
|
|
35
|
+
clash = sum(1 for u, s in zip(units, new) if u.get("split") not in (None, s))
|
|
36
|
+
if clash:
|
|
37
|
+
raise SplitError(f"{clash} units already carry another split (labelled with another salt or "
|
|
38
|
+
"fraction); use those, or split anew from --details")
|
|
39
|
+
for u, s in zip(units, new):
|
|
40
|
+
u["split"] = s
|
|
41
|
+
sessions = {u["session_id"]: u["split"] for u in units}
|
|
42
|
+
counts = Counter(sessions.values())
|
|
43
|
+
return {s: [counts[s], new.count(s)] for s in SPLITS}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def read_session_ids(path):
|
|
47
|
+
"""Session IDs from a file that names sessions:
|
|
48
|
+
- one ID per line (blank lines and '#' comments skipped);
|
|
49
|
+
- JSONL with a session_id on each line: units.jsonl, results.jsonl;
|
|
50
|
+
- JSON: a list of objects with a session_id (bt_fetch's sessions.json or details.json, the
|
|
51
|
+
Apex class's output, also as an `sf apex run --json` file), or the old replay's
|
|
52
|
+
replay_results.json. Not a list of strings: step and generation IDs look like session IDs;
|
|
53
|
+
- CSV with a session_id column: replay_results_sfap.csv, the old replay's too.
|
|
54
|
+
Any other file is refused, so that it never passes as a list of IDs that excludes nothing. So is
|
|
55
|
+
an ID that is not letters, digits, '_', '.' and '-': matched exactly, " s1" would exclude nothing.
|
|
56
|
+
"""
|
|
57
|
+
with open(path, encoding="utf-8-sig") as f: # -sig: a CSV saved by Excel starts with a BOM
|
|
58
|
+
text = f.read()
|
|
59
|
+
lines = [(n, s.strip()) for n, s in enumerate(text.split("\n"), 1)]
|
|
60
|
+
lines = [(n, s) for n, s in lines if s and not s.startswith("#")]
|
|
61
|
+
if not lines:
|
|
62
|
+
return set()
|
|
63
|
+
first = lines[0][1]
|
|
64
|
+
if first[0] in "[{":
|
|
65
|
+
try:
|
|
66
|
+
doc = json.loads(text)
|
|
67
|
+
except ValueError as e:
|
|
68
|
+
if first[0] == "[":
|
|
69
|
+
raise SplitError(f"not valid JSON ({e})") from None
|
|
70
|
+
return _jsonl_ids(lines)
|
|
71
|
+
return _document_ids(doc)
|
|
72
|
+
if "," in first or first == "session_id":
|
|
73
|
+
return _csv_ids(text)
|
|
74
|
+
for n, s in lines:
|
|
75
|
+
if not _SESSION_ID.match(s):
|
|
76
|
+
raise SplitError(f"line {n} is not a session ID, and the file is not JSON, JSONL or CSV")
|
|
77
|
+
return {s for _, s in lines}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
_SESSION_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*\Z")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _jsonl_ids(lines):
|
|
84
|
+
ids = set()
|
|
85
|
+
for n, s in lines:
|
|
86
|
+
try:
|
|
87
|
+
row = json.loads(s)
|
|
88
|
+
except ValueError:
|
|
89
|
+
raise SplitError(f"line {n}: not JSON") from None
|
|
90
|
+
ids.add(_session_id(row.get("session_id") if isinstance(row, dict) else None, f"line {n}"))
|
|
91
|
+
return ids
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _document_ids(doc):
|
|
95
|
+
if isinstance(doc, list):
|
|
96
|
+
items = doc
|
|
97
|
+
elif not isinstance(doc, dict):
|
|
98
|
+
raise SplitError("JSON that is neither a list nor an object")
|
|
99
|
+
else:
|
|
100
|
+
try:
|
|
101
|
+
found = stdm.parse_sf_output(doc, "sf apex run output")
|
|
102
|
+
except stdm.StdmError as e:
|
|
103
|
+
raise SplitError(str(e)) from None
|
|
104
|
+
if found is not None: # an `sf apex run --json` file
|
|
105
|
+
if not found:
|
|
106
|
+
raise SplitError("an sf apex run output without an STDM_RESULT line")
|
|
107
|
+
items = [x for payload in found.values() for x in (payload if isinstance(payload, list) else [payload])]
|
|
108
|
+
elif isinstance(doc.get("rows"), list): # the old replay's replay_results.json
|
|
109
|
+
items = [{"session_id": r.get("AiAgentSessionId")} if isinstance(r, dict) else r for r in doc["rows"]]
|
|
110
|
+
else:
|
|
111
|
+
items = [doc]
|
|
112
|
+
ids = set()
|
|
113
|
+
for i, item in enumerate(items, 1):
|
|
114
|
+
if isinstance(item, str):
|
|
115
|
+
raise SplitError(f"item {i} is a string, not an object with a session_id (step IDs look the "
|
|
116
|
+
"same); write a list of session IDs one per line")
|
|
117
|
+
ids.add(_session_id(item.get("session_id") if isinstance(item, dict) else None, f"item {i}"))
|
|
118
|
+
return ids
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _csv_ids(text):
|
|
122
|
+
rows = csv.DictReader(io.StringIO(text))
|
|
123
|
+
if "session_id" not in (rows.fieldnames or ()):
|
|
124
|
+
raise SplitError("a CSV without a session_id column")
|
|
125
|
+
ids = set()
|
|
126
|
+
for i, row in enumerate(rows, 1):
|
|
127
|
+
ids.add(_session_id((row.get("session_id") or "").strip(), f"CSV row {i}"))
|
|
128
|
+
return ids
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _session_id(value, where):
|
|
132
|
+
if not isinstance(value, str) or not value:
|
|
133
|
+
raise SplitError(f"{where}: no session_id")
|
|
134
|
+
if not _SESSION_ID.match(value):
|
|
135
|
+
raise SplitError(f"{where}: its session_id is not a session ID")
|
|
136
|
+
return value
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Read STDM query results.
|
|
2
|
+
|
|
3
|
+
The skill's fetch phases run Apex with `sf apex run --json` and print each result as one
|
|
4
|
+
debug line, `...|DEBUG|STDM_RESULT:<json>` (or `STDM_RESULT_<suffix>:` when one script
|
|
5
|
+
prints several). The source echo of the script also contains `STDM_RESULT:`, which is why
|
|
6
|
+
only the `|DEBUG|` form is matched. Inside a debug message the log writes '|' as '|';
|
|
7
|
+
that is undone before parsing (the old skill parser kept the entity, e.g. in prompts).
|
|
8
|
+
bt_fetch.py's scripts print several pages per query, `STDM_RESULT_<query>_<page>:`.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
from .redact import redact
|
|
15
|
+
|
|
16
|
+
_MARKER = re.compile(r"\|DEBUG\|(STDM_RESULT(?:_[A-Za-z0-9_]+)?):")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class StdmError(Exception):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_apex_logs(logs):
|
|
24
|
+
"""{marker: parsed JSON} for every STDM_RESULT debug line in an Apex log."""
|
|
25
|
+
found = {}
|
|
26
|
+
for m in _MARKER.finditer(logs):
|
|
27
|
+
line_end = logs.find("\n", m.end())
|
|
28
|
+
raw = logs[m.end():] if line_end < 0 else logs[m.end():line_end]
|
|
29
|
+
# The debug log escapes its own field separator inside messages: '|' -> '|'.
|
|
30
|
+
raw = raw.strip().replace("|", "|")
|
|
31
|
+
try:
|
|
32
|
+
found[m.group(1)] = json.loads(raw)
|
|
33
|
+
except json.JSONDecodeError as e:
|
|
34
|
+
raise StdmError(
|
|
35
|
+
f"{m.group(1)}: debug line is not valid JSON ({e.msg} at char {e.pos} of {len(raw)}). "
|
|
36
|
+
"The debug log was probably truncated (Apex caps a log at 20 MB); "
|
|
37
|
+
"fetch fewer sessions or steps per batch.") from None
|
|
38
|
+
return found
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def parse_sf_output(data, where):
|
|
42
|
+
"""{marker: payload} from the parsed output of `sf apex run --json`: {} when its log has no
|
|
43
|
+
STDM_RESULT line, None when data is not that output. A run that failed to compile or threw,
|
|
44
|
+
and an error of the sf CLI itself (no org, expired session), raise StdmError."""
|
|
45
|
+
if not isinstance(data, dict):
|
|
46
|
+
return None
|
|
47
|
+
res = data.get("result")
|
|
48
|
+
if isinstance(res, dict) and "logs" in res:
|
|
49
|
+
if res.get("success") is False or res.get("compiled") is False:
|
|
50
|
+
msg = str(res.get("compileProblem") or res.get("exceptionMessage") or "unknown error")
|
|
51
|
+
if res.get("compiled") is False and isinstance(res.get("line"), int) and res["line"] > 0:
|
|
52
|
+
msg += f" (line {res['line']}, column {res.get('column')})"
|
|
53
|
+
raise StdmError(f"{where}: Apex run failed: {redact(msg)[:300]}")
|
|
54
|
+
return parse_apex_logs(res.get("logs") or "")
|
|
55
|
+
if data.get("status") not in (None, 0) and isinstance(data.get("message"), str):
|
|
56
|
+
name = data.get("name")
|
|
57
|
+
raise StdmError(f"{where}: sf failed" + (f" ({name})" if isinstance(name, str) else "")
|
|
58
|
+
+ f": {redact(data['message'])[:300]}")
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def load_result_file(path):
|
|
63
|
+
"""{marker: payload} from an `sf apex run --json` output file.
|
|
64
|
+
|
|
65
|
+
A file holding plain JSON (a list or an object without the sf CLI envelope) is
|
|
66
|
+
returned as {None: payload}, so already-extracted files work too.
|
|
67
|
+
"""
|
|
68
|
+
with open(path, encoding="utf-8") as f:
|
|
69
|
+
data = json.load(f)
|
|
70
|
+
found = parse_sf_output(data, path)
|
|
71
|
+
if found is None:
|
|
72
|
+
return {None: data}
|
|
73
|
+
if not found:
|
|
74
|
+
raise StdmError(f"{path}: no |DEBUG|STDM_RESULT line in the Apex log")
|
|
75
|
+
return found
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def load_conversations(paths):
|
|
79
|
+
"""Merge ConversationData lists from one or more details files.
|
|
80
|
+
|
|
81
|
+
Accepts getMultipleConversationDetails output (a list), getConversationDetails output
|
|
82
|
+
(one object), or several markers per file. The first copy of a session wins.
|
|
83
|
+
Returns (conversations, duplicate_count).
|
|
84
|
+
"""
|
|
85
|
+
convos, seen, dupes = [], set(), 0
|
|
86
|
+
for path in paths:
|
|
87
|
+
for payload in load_result_file(path).values():
|
|
88
|
+
items = payload if isinstance(payload, list) else [payload]
|
|
89
|
+
for c in items:
|
|
90
|
+
if not isinstance(c, dict) or "turns" not in c or not isinstance(c.get("session_id"), str) \
|
|
91
|
+
or not c["session_id"].strip():
|
|
92
|
+
raise StdmError(f"{path}: expected ConversationData objects (a session_id, turns)")
|
|
93
|
+
if c["session_id"] in seen:
|
|
94
|
+
dupes += 1
|
|
95
|
+
continue
|
|
96
|
+
seen.add(c["session_id"])
|
|
97
|
+
convos.append(c)
|
|
98
|
+
return convos, dupes
|