@salesforce/afv-skills 1.68.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 (188) hide show
  1. package/package.json +1 -1
  2. package/skills/afcc-setup-coordinate/SKILL.md +348 -0
  3. package/skills/afcc-setup-coordinate/assets/console-app/AFCC_Service_Console.app-meta.xml +19 -0
  4. package/skills/afcc-setup-coordinate/assets/console-app/Admin.profile-meta.xml +8 -0
  5. package/skills/afcc-setup-coordinate/assets/console-app/Standard.profile-meta.xml +8 -0
  6. package/skills/afcc-setup-coordinate/assets/gap_report_template.md +35 -0
  7. package/skills/afcc-setup-coordinate/assets/org_profile_template.json +16 -0
  8. package/skills/afcc-setup-coordinate/references/gotchas.md +22 -0
  9. package/skills/afcc-setup-coordinate/scripts/audit_org.sh +159 -0
  10. package/skills/agentforce-bot-upgrade/SKILL.md +117 -66
  11. package/skills/agentforce-bot-upgrade/assets/_vendored/agent-spec-template.md +139 -0
  12. package/skills/agentforce-bot-upgrade/references/_vendored/agent-design-and-spec-creation.md +1211 -0
  13. package/skills/agentforce-bot-upgrade/references/_vendored/agent-script-core-language.md +1390 -0
  14. package/skills/agentforce-bot-upgrade/references/_vendored/agent-subagent-map-diagrams.md +341 -0
  15. package/skills/agentforce-bot-upgrade/references/_vendored/agent-user-setup.md +672 -0
  16. package/skills/agentforce-bot-upgrade/references/_vendored/agent-validation-and-debugging.md +904 -0
  17. package/skills/agentforce-bot-upgrade/references/_vendored/agentscript-toolchain.md +112 -0
  18. package/skills/agentforce-bot-upgrade/references/_vendored/architecture-patterns.md +277 -0
  19. package/skills/agentforce-bot-upgrade/references/_vendored/common-control-flow-pitfalls.md +255 -0
  20. package/skills/agentforce-bot-upgrade/references/_vendored/control-flow-actions-sequencing.md +198 -0
  21. package/skills/agentforce-bot-upgrade/references/_vendored/control-flow-lifecycle-side-effects.md +87 -0
  22. package/skills/agentforce-bot-upgrade/references/_vendored/data-library-reference.md +891 -0
  23. package/skills/agentforce-bot-upgrade/references/_vendored/instruction-resolution.md +658 -0
  24. package/skills/agentforce-bot-upgrade/references/_vendored/org-setup-for-adl.md +551 -0
  25. package/skills/agentforce-bot-upgrade/references/_vendored/patterns-by-requirement.md +88 -0
  26. package/skills/agentforce-bot-upgrade/references/_vendored/posture-and-determinism.md +215 -0
  27. package/skills/agentforce-bot-upgrade/references/extraction-blueprint.md +11 -4
  28. package/skills/agentforce-bot-upgrade/references/generate-agent-spec.md +19 -3
  29. package/skills/agentforce-bot-upgrade/references/handoff-output-format.md +82 -52
  30. package/skills/agentforce-bot-upgrade/references/input-contract.md +8 -8
  31. package/skills/agentforce-bot-upgrade/references/mapping-rules.md +19 -6
  32. package/skills/agentforce-bot-upgrade/references/post-conversion-enhancements-reference.md +65 -6
  33. package/skills/agentforce-bot-upgrade/references/quality-checklist.md +4 -4
  34. package/skills/agentforce-bot-upgrade/references/sf-cli-bot-reference.md +17 -3
  35. package/skills/agentforce-hyperclassifier-configure/README.md +24 -0
  36. package/skills/agentforce-hyperclassifier-configure/SKILL.md +111 -0
  37. package/skills/agentforce-hyperclassifier-configure/assets/customer-org.env.example +4 -0
  38. package/skills/agentforce-hyperclassifier-configure/assets/sample_descriptions.json +8 -0
  39. package/skills/agentforce-hyperclassifier-configure/assets/sample_evals.csv +17 -0
  40. package/skills/agentforce-hyperclassifier-configure/references/api-contract.md +41 -0
  41. package/skills/agentforce-hyperclassifier-configure/references/authentication.md +35 -0
  42. package/skills/agentforce-hyperclassifier-configure/references/evaluation.md +46 -0
  43. package/skills/agentforce-hyperclassifier-configure/references/installation.md +35 -0
  44. package/skills/agentforce-hyperclassifier-configure/references/onboarding.md +93 -0
  45. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/__init__.py +1 -0
  46. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/client.py +219 -0
  47. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/eca.py +178 -0
  48. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/evaluation.py +207 -0
  49. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/onboarding.py +191 -0
  50. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/optimizer.py +187 -0
  51. package/skills/agentforce-hyperclassifier-configure/scripts/hyperclassifier.py +111 -0
  52. package/skills/agentforce-hyperclassifier-configure/scripts/report_hyperclassifier.py +149 -0
  53. package/skills/agentforce-hyperclassifier-configure/scripts/setup_hyperclassifier.py +74 -0
  54. package/skills/agentforce-hyperclassifier-configure/scripts/tests/test_hyperclassifier_skill.py +887 -0
  55. package/skills/agentforce-offline-experimentation-run/scripts/btlib/judge.py +23 -31
  56. package/skills/agentforce-offline-experimentation-run/scripts/btlib/messages.py +2 -1
  57. package/skills/agentforce-offline-experimentation-run/scripts/btlib/sfap.py +118 -2
  58. package/skills/agentforce-offline-experimentation-run/scripts/build_report.py +2 -2
  59. package/skills/agentforce-offline-experimentation-run/scripts/resolve-token.sh +9 -2
  60. package/skills/agentforce-offline-experimentation-run/scripts/sfap_replay.py +12 -1
  61. package/skills/commerce-react-storefront-create/SKILL.md +54 -21
  62. package/skills/dx-lifecycle-center/SKILL.md +24 -18
  63. package/skills/dx-lifecycle-center/examples/workflows.md +57 -34
  64. package/skills/dx-lifecycle-center/references/connect-api.md +33 -4
  65. package/skills/dx-lifecycle-center/references/connect-org.md +59 -28
  66. package/skills/dx-lifecycle-center/references/deploy.md +3 -3
  67. package/skills/dx-lifecycle-center/references/hub-org.md +19 -3
  68. package/skills/dx-lifecycle-center/references/list-orgs.md +50 -24
  69. package/skills/dx-lifecycle-center/references/troubleshooting.md +22 -1
  70. package/skills/dx-lifecycle-center/scripts/hub-get.sh +41 -0
  71. package/skills/dx-lifecycle-center/scripts/resolve-environment.sh +151 -4
  72. package/skills/dx-packaging-convert-1gp-to-2gp-create/SKILL.md +63 -0
  73. package/skills/dx-packaging-convert-1gp-to-2gp-create/references/conversion-operations.md +252 -0
  74. package/skills/dx-packaging-move-to-2gp-migrate/SKILL.md +2 -3
  75. package/skills/dx-packaging-move-to-2gp-migrate/references/api-operations.md +10 -7
  76. package/skills/dx-packaging-push-upgrade-configure/README.md +47 -0
  77. package/skills/dx-packaging-push-upgrade-configure/SKILL.md +355 -0
  78. package/skills/dx-packaging-push-upgrade-configure/references/best-practices.md +61 -0
  79. package/skills/dx-packaging-push-upgrade-configure/references/cli-reference.md +148 -0
  80. package/skills/dx-packaging-push-upgrade-configure/references/objects.md +106 -0
  81. package/skills/dx-packaging-push-upgrade-configure/references/soql-recipes.md +144 -0
  82. package/skills/experience-afv-analytics-query/SKILL.md +239 -0
  83. package/skills/experience-afv-analytics-query/references/references.md +176 -0
  84. package/skills/experience-app-mcp-delivery-generate/SKILL.md +142 -0
  85. package/skills/experience-app-mcp-delivery-generate/references/eca-consumer-key.md +26 -0
  86. package/skills/experience-app-mcp-delivery-generate/references/mcp-config-delivery.md +38 -0
  87. package/skills/experience-app-mcp-delivery-generate/references/plugin-format-and-publishing.md +80 -0
  88. package/skills/experience-app-mcp-delivery-generate/scripts/developer_name.mjs +9 -0
  89. package/skills/experience-app-mcp-delivery-generate/scripts/discover_mcp_context.mjs +114 -0
  90. package/skills/experience-app-mcp-delivery-generate/scripts/generate_mcp_config.mjs +27 -0
  91. package/skills/experience-app-mcp-delivery-generate/scripts/generate_plugin.mjs +184 -0
  92. package/skills/experience-app-mcp-delivery-generate/scripts/mcp_config.mjs +57 -0
  93. package/skills/experience-app-mcp-delivery-generate/scripts/preflight.mjs +109 -0
  94. package/skills/experience-app-mcp-delivery-generate/scripts/retrieve_eca_consumer_key.mjs +143 -0
  95. package/skills/experience-app-mcp-generate/SKILL.md +174 -0
  96. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.eca-meta.xml +7 -0
  97. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaGlblOauth-meta.xml +15 -0
  98. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaOauth-meta.xml +6 -0
  99. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaOauthPlcy-meta.xml +12 -0
  100. package/skills/experience-app-mcp-generate/assets/__ECA_NAME___defaultPolicy.ecaPlcy-meta.xml +7 -0
  101. package/skills/experience-app-mcp-generate/assets/__MCP_SERVER_NAME__.mcpServerDefinition-meta.xml +5 -0
  102. package/skills/experience-app-mcp-generate/references/eca-fields.md +76 -0
  103. package/skills/experience-app-mcp-generate/references/mcp-objects.md +66 -0
  104. package/skills/experience-app-mcp-generate/references/tool-bindings.md +85 -0
  105. package/skills/experience-app-mcp-generate/references/troubleshooting.md +41 -0
  106. package/skills/experience-app-mcp-generate/references/ui-frameworks.md +19 -0
  107. package/skills/experience-app-mcp-generate/references/widget-resources.md +96 -0
  108. package/skills/experience-app-mcp-generate/scripts/activate_server.mjs +166 -0
  109. package/skills/experience-app-mcp-generate/scripts/check_setup_progress.mjs +212 -0
  110. package/skills/experience-app-mcp-generate/scripts/list_sites.mjs +211 -0
  111. package/skills/experience-app-mcp-generate/scripts/merge_tools.mjs +407 -0
  112. package/skills/experience-app-mcp-generate/scripts/preflight.mjs +127 -0
  113. package/skills/experience-app-mcp-generate/scripts/render_eca.mjs +144 -0
  114. package/skills/experience-app-mcp-generate/scripts/render_mcp_server.mjs +64 -0
  115. package/skills/experience-app-mcp-generate/scripts/retrieve_existing_prompts.mjs +145 -0
  116. package/skills/experience-app-mcp-generate/scripts/retrieve_existing_tools.mjs +72 -0
  117. package/skills/experience-app-mcp-generate/scripts/scan_tool_candidates.mjs +195 -0
  118. package/skills/experience-app-mcp-generate/scripts/utils/callback_url.mjs +36 -0
  119. package/skills/experience-app-mcp-generate/scripts/utils/developer_name.mjs +9 -0
  120. package/skills/experience-app-mcp-generate/scripts/utils/eca_check.mjs +156 -0
  121. package/skills/experience-app-mcp-generate/scripts/utils/metadata_path.mjs +13 -0
  122. package/skills/experience-app-mcp-generate/scripts/verify_server.mjs +118 -0
  123. package/skills/experience-cms-content-type-generate/SKILL.md +1 -1
  124. package/skills/nonprofit-fundraising-configure/SKILL.md +1 -1
  125. package/skills/nonprofit-fundraising-configure/references/mcp-invocation.md +52 -4
  126. package/skills/nonprofit-fundraising-configure/references/permission-targeting.md +19 -2
  127. package/skills/platform-custom-field-generate/SKILL.md +24 -16
  128. package/skills/platform-custom-metadata-type-generate/SKILL.md +1 -0
  129. package/skills/platform-custom-setting-generate/SKILL.md +1 -0
  130. package/skills/platform-dataspace-access-configure/SKILL.md +25 -10
  131. package/skills/platform-flexipage-generate/SKILL.md +7 -10
  132. package/skills/platform-flexipage-generate/references/mcp_action_examples.md +42 -38
  133. package/skills/platform-policy-rule-generate/SKILL.md +9 -7
  134. package/skills/platform-policy-rule-generate/references/condition-model.md +3 -3
  135. package/skills/platform-policy-rule-generate/references/conjunction-expression.md +9 -1
  136. package/skills/platform-policy-rule-generate/references/consumer-datacloud-ui.md +9 -1
  137. package/skills/platform-policy-rule-generate/references/examples/ExistsJoinRLS/policyRuleDefinitionSets/ExistsJoinRLS.policyRuleDefinitionSet +1 -2
  138. package/skills/platform-policy-rule-generate/references/examples/FieldReadDeny/policyRuleDefinitionSets/FieldReadDeny.policyRuleDefinitionSet +1 -2
  139. package/skills/platform-policy-rule-generate/references/examples/LastCharactersFieldMasking/policyRuleDefinitionSets/LastCharactersFieldMasking.policyRuleDefinitionSet +1 -2
  140. package/skills/platform-policy-rule-generate/references/examples/PrincipalFieldMatchRLS/policyRuleDefinitionSets/PrincipalFieldMatchRLS.policyRuleDefinitionSet +1 -2
  141. package/skills/platform-policy-rule-generate/references/examples/TaggedObjectAccess/policyRuleDefinitionSets/TaggedObjectAccess.policyRuleDefinitionSet +1 -0
  142. package/skills/platform-policy-rule-generate/references/headless-transport.md +2 -2
  143. package/skills/platform-policy-rule-generate/references/policy-schema-full.md +1 -1
  144. package/skills/platform-policy-rule-generate/references/policy-shapes.md +33 -0
  145. package/skills/platform-policy-rule-generate/references/templates-advanced.md +1 -1
  146. package/skills/platform-policy-rule-generate/references/ui-compatibility.md +5 -5
  147. package/skills/platform-report-generate/SKILL.md +20 -1
  148. package/skills/platform-report-generate/references/summary-formulas-sorting-limits.md +118 -0
  149. package/skills/platform-report-generate/references/verification-checklist.md +12 -0
  150. package/skills/service-digital-engagement-channel-configure/SKILL.md +44 -107
  151. package/skills/service-digital-engagement-channel-configure/assets/messaging_channel_template.xml +2 -0
  152. package/skills/service-digital-engagement-channel-configure/examples/asa_agent_channel.xml +2 -2
  153. package/skills/service-digital-engagement-channel-configure/examples/auth_queue_channel.xml +58 -0
  154. package/skills/service-digital-engagement-channel-configure/examples/omni_flow_channel.xml +2 -2
  155. package/skills/service-digital-engagement-channel-configure/examples/omni_queue_channel.xml +3 -3
  156. package/skills/service-digital-engagement-channel-configure/references/channel_settings.md +18 -14
  157. package/skills/service-digital-engagement-channel-configure/references/onboarding_contract.md +16 -20
  158. package/skills/service-digital-engagement-channel-configure/references/prechat_params.md +10 -0
  159. package/skills/service-digital-engagement-channel-configure/references/recaptcha_handoff.md +38 -0
  160. package/skills/service-digital-engagement-channel-configure/references/user_verification.md +9 -0
  161. package/skills/service-digital-engagement-channel-configure/scripts/check-api-version.sh +4 -4
  162. package/skills/service-digital-engagement-channel-configure/scripts/normalize-channel-name.sh +12 -7
  163. package/skills/service-e911-configure/SKILL.md +242 -0
  164. package/skills/service-itsm-agentic-setup-agent-runtime-access-assign/SKILL.md +1 -1
  165. package/skills/service-itsm-agentic-setup-agentforce-coordinate/SKILL.md +1 -1
  166. package/skills/service-itsm-agentic-setup-agentforce-studio-configure/SKILL.md +1 -1
  167. package/skills/service-itsm-agentic-setup-agentforce-studio-validate/SKILL.md +1 -1
  168. package/skills/service-itsm-agentic-setup-employee-agent-configure/SKILL.md +1 -1
  169. package/skills/service-itsm-agentic-setup-fulfiller-agent-configure/SKILL.md +1 -1
  170. package/skills/service-itsm-agentic-setup-incident-management/SKILL.md +47 -44
  171. package/skills/service-itsm-agentic-setup-incident-management/examples/output-templates.md +110 -83
  172. package/skills/service-itsm-agentic-setup-incident-management/references/manage-incidents-with-ai.md +7 -3
  173. package/skills/service-itsm-agentic-setup-incident-management/references/priority-matrix.md +7 -5
  174. package/skills/service-itsm-agentic-setup-incident-management/references/sla-milestones.md +2 -2
  175. package/skills/service-itsm-agentic-setup-incident-management/references/status-checks.md +437 -0
  176. package/skills/service-itsm-agentic-setup-itsm-agentforce-permset-assign/SKILL.md +1 -1
  177. package/skills/agentforce-bot-upgrade/references/planner-workflow-reference.md +0 -78
  178. package/skills/dx-lifecycle-center/assets/widgets/connect-connected/connect-connected.json +0 -65
  179. package/skills/dx-lifecycle-center/assets/widgets/connect-connected/schema.json +0 -32
  180. package/skills/dx-lifecycle-center/assets/widgets/connect-sign-in/connect-sign-in.json +0 -57
  181. package/skills/dx-lifecycle-center/assets/widgets/connect-sign-in/schema.json +0 -21
  182. package/skills/dx-lifecycle-center/scripts/card-policy.jq +0 -71
  183. package/skills/dx-lifecycle-center/scripts/fill-widget.jq +0 -29
  184. package/skills/dx-lifecycle-center/scripts/widget.sh +0 -28
  185. package/skills/experience-content-media-image-generate/SKILL.md +0 -83
  186. package/skills/experience-content-media-image-generate/scripts/download-image.sh +0 -84
  187. package/skills/experience-content-media-stock-image-search/SKILL.md +0 -193
  188. package/skills/experience-content-media-stock-image-search/scripts/download-stock-image.py +0 -102
@@ -0,0 +1,1211 @@
1
+ # Agent Design and Spec Creation
2
+
3
+ ## Table of Contents
4
+
5
+ 1. Agent Spec: Purpose and Lifecycle
6
+ 2. Discovery Questions (Outcome First)
7
+ 3. Environment Prerequisites
8
+ 4. Subagent Architecture
9
+ 5. Mapping Action Implementations
10
+ 6. Transition Patterns
11
+ 7. Deterministic vs. Subjective Flow Control
12
+ 8. Gating Patterns
13
+ 9. Action Loop Prevention
14
+
15
+ ---
16
+
17
+ ## 1. Agent Spec: Purpose and Lifecycle
18
+
19
+ An **Agent Spec** is a structured design document describing business outcomes,
20
+ use cases, actions, subagents, and control flow. It documents mutable state only
21
+ when the runtime needs it. Build the spec before writing Agent Script. For
22
+ existing agents, reverse-engineer the spec from the `.agent` file so intent is
23
+ explicit before changes.
24
+
25
+ If the user supplies a sufficiently detailed design or Agent Spec and explicitly
26
+ says it is already approved, use it as the current build contract. Do not
27
+ recreate or reapprove it unless requirements are missing or materially change.
28
+
29
+ ### What an Agent Spec Contains
30
+
31
+ - **Purpose & Scope** — what business outcome the agent should drive
32
+ - **Behavioral Intent** — what the agent is supposed to achieve (requirements and constraints), not just what code exists
33
+ - **Subagent Map** — a Mermaid flowchart showing all subagents, transitions (with type labels: handoff or delegation), and when transitions occur
34
+ - **Actions & Implementations** — each action's name, implementation type (Apex class, Flow, Prompt Template), inputs/outputs, and whether implementation exists or needs creation
35
+ - **Variables (when needed)** — declarations, trusted writers, named
36
+ deterministic consumers, causes, and lifecycle behavior
37
+ - **Deterministic Controls (when needed)** — only include gating/invariants that are required by trust, policy, regulation, or observed failures
38
+ - **Interaction Style** — brand voice, personality, escalation tone, and response style constraints
39
+ - **Subagent Posture** — scripted, mixed, or agentic posture per subagent with a short justification
40
+
41
+ ### Planned vs. Existing Entries
42
+
43
+ Agent Spec entries can be planned or existing — both are valid:
44
+
45
+ - **Planned (placeholder):** "The `confirm_booking` action needs an Apex class `BookingConfirmer` that accepts reservation_id (string), guest_name (string), and returns confirmation_number (string), booking_date (date)." This is a not-yet-implemented requirement.
46
+
47
+ - **Existing (implemented):** "The `fetch_weather` action uses Apex class `WeatherService`, invoked via `apex://WeatherService`. Accepts dateToCheck (date), returns maxTemp/minTemp (number)." This documents current implementation.
48
+
49
+ Both go in the same Agent Spec section.
50
+
51
+ ### Lifecycle Stages
52
+
53
+ The Agent Spec evolves across the agent's lifecycle:
54
+
55
+ **Creation (sparse).** Purpose, outcomes, use cases, and planned notes about action implementations ("this action needs an Apex class that accepts X, returns Y"). No full flowchart yet.
56
+
57
+ **Build (filled).** Flowchart added with transition types labeled. Action implementations mapped (existing implementations identified with filenames, missing implementations stubbed with protocols and I/O specs). Add variables and deterministic controls only where required and justified.
58
+
59
+ **Comprehension (reverse-engineered).** Starting from an existing `.agent` file, produce a complete Agent Spec by parsing subagents, tracing transitions, analyzing actions, and documenting state. This is the "what does this agent do?" output.
60
+
61
+ **Diagnosis (reference).** Compare actual runtime behavior against the Agent Spec to find where intent and implementation diverge.
62
+
63
+ ### Agent Spec Template
64
+
65
+ Use the starter spec template at `assets/agent-spec-template.md` for new agents.
66
+
67
+ ---
68
+
69
+ ## 2. Discovery Questions (Outcome First)
70
+
71
+ These discovery categories drive the Agent Spec. Start from outcomes and business
72
+ process first, then map to actions/subagents. When comprehending an existing
73
+ agent, extract the same answers from `.agent` and project files.
74
+
75
+ **Resolve as many questions as possible from available context before asking the human.** Scan existing code, project metadata, prior conversation, and any provided requirements. Only surface questions the human must answer — never forward this list verbatim.
76
+
77
+ Default new actions to placeholders (`NEEDS STUB`) during planning. Reuse/generate
78
+ implementation work is an explicit user choice. Follow the execution policy in
79
+ `SKILL.md` for when to scan existing implementations or generate new ones.
80
+
81
+ ### Agent Identity & Purpose *(feeds Purpose & Scope)*
82
+
83
+ - What is the agent's name? (no spaces, letters/numbers/underscores only)
84
+ - What is the agent's primary purpose in one sentence?
85
+ - What should the welcome message say?
86
+ - What personality should the agent have? (professional, friendly, formal, casual)
87
+ - What error message should the agent show if something breaks?
88
+
89
+ ### Outcomes, Process, and Requirements *(feeds Behavioral Intent and Deterministic Controls)*
90
+
91
+ - What outcome should the agent produce for the business and user?
92
+ - What process or policy should the agent follow (for example, verification, time-window checks, escalation rules)?
93
+ - Which steps are strict invariants versus flexible conversational guidance?
94
+ - Which requirements are regulated, audited, trust-sensitive, or otherwise must be deterministic?
95
+
96
+ ### Subagents & Conversation Flow *(feeds Subagent Map)*
97
+
98
+ - What distinct conversation areas (subagents) does the agent need?
99
+ - Default to one execution block: put the focused domain directly in
100
+ `start_agent <domain>:` and create zero `subagent` blocks. Add another block
101
+ only when objective, instructions, actions, authority, or escalation
102
+ behavior changes and cannot remain coherent in the current scope.
103
+ - Treat greetings, cancellation acknowledgments, completion messages,
104
+ ambiguity questions, and ordinary dialogue steps as branches unless they
105
+ genuinely require a separate scope.
106
+ - If multiple genuine domains need current-intent classification, use
107
+ `start_agent agent_router`.
108
+ - What are the possible transitions between subagents?
109
+ - Are there subagents that delegate to others and need to return?
110
+ - Are there guardrail subagents (off-topic redirection, ambiguity handling, security gates)?
111
+ - Are there any workflow-local linear steps within a subagent (instead of treating the whole agent as linear)?
112
+
113
+ ### Reasoning & Instructions *(feeds Behavioral Intent)*
114
+
115
+ - What should the agent do in each subagent?
116
+ - What trusted output or invariant changes the instructions, if any?
117
+ - Should the agent do anything before or after reasoning in a given subagent? (e.g., security checks, data fetches, automatic transitions)
118
+ - What data transformations (if any) does the LLM need to do?
119
+
120
+ ### Subagent Posture *(feeds posture-and-determinism.md)*
121
+
122
+ - For each subagent, should posture be scripted, mixed, or agentic?
123
+ - If deterministic controls are added, what is the explicit cause (regulation/trust/observed failure)?
124
+ - Which controls are true invariants (`available when`) vs guidance?
125
+
126
+ ### Actions & External Systems *(feeds Actions & Implementations)*
127
+
128
+ - What external systems does the agent call?
129
+ - Salesforce Flows (autolaunched only)
130
+ - Apex classes (invocable only)
131
+ - Prompt Templates
132
+ - External APIs (not directly; must be wrapped in Apex or Flow)
133
+ - For each action: what inputs, outputs, and availability conditions are required?
134
+ - Should any action be a placeholder stub first so the team can iterate on behavior before full implementation?
135
+ - What custom objects exist in the project? Scan `objects/` for `.object-meta.xml` files. Check relationships (lookup, master-detail) between objects — related objects often contain data the agent should expose even when not explicitly mentioned in the prompt.
136
+
137
+ ### Runtime State *(optional; feeds Variables and Deterministic Controls)*
138
+
139
+ Surviving conversation history already carries ordinary conversational facts.
140
+ Do not mirror names, preferences, questions asked, or dialogue stages into
141
+ variables.
142
+
143
+ For each proposed variable:
144
+
145
+ - Which named `if`, `available when`, transition, action input, or later-turn
146
+ exact output consumes it?
147
+ - Does that consumer need the exact external identifier, or only a trusted
148
+ complete/incomplete outcome? Keep a display-only final identifier in the
149
+ action result and surviving history when a boolean is sufficient for control.
150
+ - Does it record trusted action output, prove authorization/eligibility/
151
+ confirmation, preserve exact action data flow, enforce external ordering, or
152
+ outlive the configured history window?
153
+ - Who writes it, and what are its reset, expiry, correction, and cancellation
154
+ semantics?
155
+
156
+ If these questions have no concrete answer, omit the variable.
157
+
158
+ ---
159
+
160
+ ## 3. Environment Prerequisites
161
+
162
+ **⚠️ MANDATORY: Run these checks immediately after determining the agent type during discovery.** Do not proceed to subagent architecture or code generation until the environment is validated.
163
+
164
+ Posture guidance is separate from architecture. Read [Posture and Determinism](posture-and-determinism.md) to choose subagent posture (scripted, mixed, agentic) based on requirements and observed failures.
165
+
166
+ ### `AgentforceEmployeeAgent`
167
+
168
+ 1. Confirm the file normally omits `access.default_agent_user`. If the generated boilerplate includes an `access` block, remove it along with any MessagingSession linked variables and escalation subagent.
169
+
170
+ **⚠️ Setting `default_agent_user` on an employee agent causes publish and preview to fail with an unhelpful "unknown error."**
171
+
172
+ ### `AgentforceServiceAgent`
173
+
174
+ REQUIRES `access.default_agent_user`. Query the org to find an active Einstein Agent User:
175
+
176
+ ```bash
177
+ sf data query --json -q "SELECT Username FROM User WHERE Profile.UserLicense.Name = 'Einstein Agent' AND IsActive = true LIMIT 5"
178
+ ```
179
+
180
+ **If results are returned:** Ask which username to use. Record choice in the Agent Spec Configuration section. Verify permissions per [Agent User Setup & Permissions](agent-user-setup.md).
181
+
182
+ **If no results are returned:** STOP. Do NOT invent a username. Ask if you should create a new user, then read [Agent User Setup & Permissions](agent-user-setup.md) for user creation instructions.
183
+
184
+ **WRONG:** Fabricating a username when query returns nothing
185
+ ```text
186
+ default_agent_user: "myagent@example.com" # made up, will fail at publish
187
+ ```
188
+
189
+ **RIGHT:** Stopping and asking to create a new user
190
+ ```text
191
+ "No Einstein Agent User found in this org. Would you like me to create one for you?"
192
+ ```
193
+
194
+ ### Recording Prerequisites in the Agent Spec
195
+
196
+ Add a "Configuration" section to the Agent Spec:
197
+
198
+ - **Agent type**: `AgentforceServiceAgent` or `AgentforceEmployeeAgent`
199
+ - **Default agent user**: confirmed username (service agents), or "N/A — employee agent"
200
+ - **Permissions verified**: yes/no — see [Agent User Setup & Permissions](agent-user-setup.md)
201
+
202
+ ---
203
+
204
+ ## 4. Subagent Architecture
205
+
206
+ Subagents are responsibility and capability scopes, not conversation-state
207
+ markers. Create a subagent only when the boundary changes its objective,
208
+ instructions, available actions, authority, or escalation behavior and the
209
+ result cannot remain coherent in one scope. When designing a new agent, plan
210
+ those boundaries before writing code. When comprehending an existing agent,
211
+ identify what behavior each boundary changes.
212
+
213
+ ### Subagent Strategies
214
+
215
+ Every subagent in an agent serves one of three roles: domain, guardrail, or escalation.
216
+
217
+ **Domain Subagents.** The core conversation areas where the agent does its work.
218
+ Each domain subagent handles a specific area (orders, billing, weather, events)
219
+ with distinct instructions, actions, authority, or escalation behavior. Most
220
+ focused agents need only the `start_agent`; add domain subagents only for
221
+ genuine additional domains.
222
+
223
+ **Guardrail Subagents.** Specialized scopes for boundaries that need their own
224
+ instructions, actions, authority, or escalation behavior. Off-topic redirection
225
+ and ambiguity clarification are ordinary branches by default. Create
226
+ `off_topic` or `ambiguous_question` subagents only when their distinct policy
227
+ cannot remain coherent in the current scope. When modifying an existing agent,
228
+ do not delete such scopes without testing their behavior, but do not copy them
229
+ into every new design.
230
+
231
+ ```agentscript
232
+ subagent off_topic:
233
+ description: "Handle off-topic requests"
234
+ reasoning:
235
+ instructions: ->
236
+ | Explain that the request is outside scope, state the supported
237
+ capabilities, and ask which supported task the user wants help
238
+ with.
239
+
240
+ subagent ambiguous_question:
241
+ description: "Ask for clarification"
242
+ reasoning:
243
+ instructions: ->
244
+ | Explain briefly that the request is unclear and ask one focused
245
+ question for the missing detail needed to proceed.
246
+ ```
247
+
248
+ **Escalation Subagents.** Hand off via `@utils.escalate`. It ends the current
249
+ agent turn and transfers control to the configured escalation path; the source
250
+ subagent does not resume automatically. Do not assume the broader messaging
251
+ session ends unless that channel's escalation contract says so.
252
+
253
+ ```agentscript
254
+ subagent escalation:
255
+ reasoning:
256
+ actions:
257
+ escalate: @utils.escalate
258
+ description: "Connect with a human agent"
259
+ ```
260
+
261
+ ### Single-Subagent vs. Multi-Subagent
262
+
263
+ Decide this before choosing an architecture pattern.
264
+
265
+ Use **single-subagent** if:
266
+ - The agent handles one domain only (FAQ, weather checker, status lookup)
267
+ - All interactions naturally stay in the same context
268
+ - No boundary needs a different action set, authority, or escalation behavior
269
+
270
+ Use **multi-subagent** if:
271
+ - The agent handles multiple distinct domains (customer service: orders + billing + account)
272
+ - Different subagents have different instructions or action sets
273
+ - Users may need to switch contexts mid-conversation
274
+ - You need security gates or clearly distinct action sets
275
+
276
+ ### Architecture Patterns
277
+
278
+ Default to the smallest architecture: one `start_agent <domain>:` execution
279
+ block and zero `subagent` blocks. Do not create an `agent_router` that merely
280
+ transitions to one domain. Add a boundary only when objective, instructions,
281
+ actions, authority, or escalation behavior changes and cannot remain coherent
282
+ in the current scope. Use
283
+ router-first (`start_agent agent_router`) when multiple genuine domains require
284
+ current-intent classification. Treat linear flow as workflow-local external
285
+ ordering, not as the default shape for a conversation.
286
+
287
+ Use [Patterns by Requirement](patterns-by-requirement.md) to choose the right
288
+ pattern for the scenario. Use [Architecture Patterns](architecture-patterns.md)
289
+ for detailed mechanics and migration guidance.
290
+
291
+ **Router-First Architecture.** One central router (`start_agent agent_router`) transitions to specialized domain subagents. Subagents may transition directly to other subagents when the workflow calls for it, or return to router when reclassification is needed. Use when the agent handles multiple distinct domains that don't naturally flow together.
292
+
293
+ Example: The Local Info Agent. The `agent_router` router transitions to domain and guardrail subagents.
294
+
295
+ ```agentscript
296
+ start_agent agent_router:
297
+ reasoning:
298
+ actions:
299
+ go_to_weather: @utils.transition to @subagent.local_weather
300
+ go_to_events: @utils.transition to @subagent.local_events
301
+ go_to_hours: @utils.transition to @subagent.resort_hours
302
+ go_to_off_topic: @utils.transition to @subagent.off_topic
303
+ go_to_ambiguous_question: @utils.transition to @subagent.ambiguous_question
304
+
305
+ # Domain subagents — each has its own instructions and actions
306
+ subagent local_weather:
307
+ reasoning:
308
+ instructions: | Handle weather questions.
309
+
310
+ subagent local_events:
311
+ reasoning:
312
+ instructions: | Handle event questions.
313
+
314
+ # resort_hours, off_topic, ambiguous_question defined further down the file
315
+ ```
316
+
317
+ **Staged Flow.** Subagents may form a pipeline when the benefit of strict
318
+ ordering outweighs the loss of conversational flexibility—for example, when
319
+ an external protocol requires successful verification before a protected
320
+ commit. A staged flow improves repeatability and auditability, but adds state,
321
+ maintenance, and friction around corrections or changed intent. A prompt-led
322
+ multi-question conversation is usually more flexible but cannot guarantee the
323
+ same order.
324
+
325
+ Choose deliberately. For stages that persist across turns, define the
326
+ correction, cancellation, retry, or intent-change behavior that the actual use
327
+ cases need. A short-lived deterministic guard does not need ceremonial state
328
+ or every possible exit path.
329
+
330
+ ```agentscript
331
+ start_agent intake:
332
+ reasoning:
333
+ actions:
334
+ go_next: @utils.transition to @subagent.verification
335
+
336
+ subagent verification:
337
+ reasoning:
338
+ actions:
339
+ go_next: @utils.transition to @subagent.details_gathering
340
+
341
+ subagent details_gathering:
342
+ reasoning:
343
+ actions:
344
+ go_next: @utils.transition to @subagent.confirmation
345
+ ```
346
+
347
+ **Escalation Chain.** Tiered support where each level has increasing capabilities. First-level resolves common issues with basic actions; second-level has access to more powerful actions or broader authority; final level escalates to a human. Use when support difficulty varies and you want to resolve simple issues quickly without involving higher tiers.
348
+
349
+ ```agentscript
350
+ subagent level_1_support:
351
+ reasoning:
352
+ instructions: | Try to resolve the issue using the FAQ and basic troubleshooting.
353
+ actions:
354
+ check_faq: @actions.search_faq
355
+ escalate: @utils.transition to @subagent.level_2_support
356
+
357
+ subagent level_2_support:
358
+ reasoning:
359
+ instructions: | You have access to account tools. Try to resolve before escalating.
360
+ actions:
361
+ lookup_account: @actions.get_account_details
362
+ modify_account: @actions.update_account
363
+ escalate_to_human: @utils.escalate
364
+ ```
365
+
366
+ **Verification Gate.** A security or permission check before allowing access to protected subagents. The gate validates the user, then transitions to the protected subagent or denies access.
367
+
368
+ In this example, `user_role` must be trusted output from an authorization
369
+ action. The two transitions are its named consumers; the cause is authorization.
370
+
371
+ ```agentscript
372
+ start_agent security_gate:
373
+ reasoning:
374
+ actions:
375
+ go_admin: @utils.transition to @subagent.admin_panel
376
+ available when @variables.user_role == "admin"
377
+ go_denied: @utils.transition to @subagent.access_denied
378
+ available when @variables.user_role != "admin"
379
+
380
+ subagent access_denied:
381
+ reasoning:
382
+ instructions: | You don't have permission to access this.
383
+ ```
384
+
385
+ **Single-Subagent.** The entire agent is one subagent — no transitions. Use for focused QA agents where all interactions stay in the same domain.
386
+
387
+ ```agentscript
388
+ start_agent faq:
389
+ description: "Answer questions about pricing"
390
+ reasoning:
391
+ instructions: | Answer questions about our pricing plans.
392
+ actions:
393
+ lookup_plan: @actions.get_plan_details
394
+ ```
395
+
396
+ ### Composing Patterns
397
+
398
+ Real agents often combine patterns. A router-first agent may use a verification gate before protected subagents. A linear flow may include escalation exits at each stage. When composing, each subagent still serves exactly one role (domain, guardrail, or escalation) — the architecture pattern determines how they connect.
399
+
400
+ ---
401
+
402
+ ## 5. Mapping Action Implementations
403
+
404
+ Every action in Agent Script needs an implementation in Salesforce. When creating
405
+ an agent, identify existing implementations and stub what's missing. When
406
+ comprehending an existing agent, trace each action to its implementation.
407
+
408
+ ### Valid Action Implementation Types
409
+
410
+ The most common implementation types are Apex, Flows, and Prompt Templates.
411
+
412
+ **Apex**: Only **invocable Apex classes** work. A regular Apex class, even if it has public methods, will not work. Invocable classes use two key annotations:
413
+
414
+ `@InvocableMethod` marks the entry point. Its attributes: `label` (human-readable name), `description` (what the method does). Read these when comprehending existing action implementations.
415
+
416
+ > ⚠️ **An Apex class can only have ONE `@InvocableMethod`.** If you need multiple actions, create separate classes — one per action.
417
+
418
+ `@InvocableVariable` marks each input and output field on the inner Request/Result classes. Its attributes: `label` (human-readable field name), `description` (what the field represents), `required` (whether the field must be provided). Use these to build action input/output definitions.
419
+
420
+ ```apex
421
+ // WRONG — regular class, not invocable
422
+ public class WeatherFetcher {
423
+ public static String getWeather(String date) { ... }
424
+ }
425
+
426
+ // RIGHT — invocable class with annotated I/O (multiline annotations)
427
+ public class WeatherFetcher {
428
+ public class Request {
429
+ @InvocableVariable(
430
+ label='Date'
431
+ description='Date to check weather for'
432
+ required=true
433
+ )
434
+ public Date dateToCheck;
435
+ }
436
+ public class Result {
437
+ @InvocableVariable(
438
+ label='Max Temp'
439
+ description='Maximum temperature in Fahrenheit'
440
+ )
441
+ public Decimal maxTemp;
442
+ @InvocableVariable(
443
+ label='Min Temp'
444
+ description='Minimum temperature in Fahrenheit'
445
+ )
446
+ public Decimal minTemp;
447
+ }
448
+ @InvocableMethod(
449
+ label='Fetch Weather'
450
+ description='Gets weather forecast for a given date'
451
+ )
452
+ public static List<Result> getWeather(List<Request> requests) { ... }
453
+ }
454
+ ```
455
+
456
+ Wire with the exact registered target identifier, commonly
457
+ `target: "apex://ClassName"`.
458
+
459
+ > **One `@InvocableMethod` per Apex class.** This verified Apex constraint
460
+ > governs implementation structure; it does not justify rewriting an action
461
+ > target supplied by the user, project, org metadata, or an approved contract.
462
+ > Preserve the exact target. If its implementation mapping is uncertain, flag
463
+ > that uncertainty and verify it from the implementation or target org before
464
+ > proposing a contract change. Do not infer from a dotted target that several
465
+ > `@InvocableMethod`s share one class.
466
+
467
+ **Flows**: Only **autolaunched Flows** work. Screen Flows, record-triggered Flows, and schedule-triggered Flows will not work. The Flow must start only when explicitly invoked.
468
+
469
+ Wire with: `target: "flow://FlowApiName"`
470
+
471
+ **Prompt Templates**: Salesforce Prompt Templates (custom or industry-specific).
472
+
473
+ Wire with: `target: "prompt://TemplateName"` (short form). The long form `generatePromptResponse://TemplateName` also works but prefer the short form.
474
+
475
+ ### How to Identify Existing Actions
476
+
477
+ Read `sfdx-project.json` and look at the `packageDirectories` array — each entry's `path` field tells you where source files live (typically `force-app/main/default/`).
478
+
479
+ Then scan for each type within those directories:
480
+
481
+ **Finding invocable Apex:** Search `classes/` for files containing `@InvocableMethod`. For each match, read the class to extract the `@InvocableVariable` annotations on its inner `Request` and `Result` classes — these define the action's input and output contract. Pay attention to the `@InvocableVariable` types: they map to Agent Script types (`String` → `string`, `Boolean` → `boolean`, `Decimal` → `number`, `Integer` → `integer`, `Date` → `date`, `Datetime` → `datetime`). See the full type mapping table in "Connecting Existing Actions to Action Definitions" below.
482
+
483
+ **Finding autolaunched Flows:** Search `flows/` for `.flow-meta.xml` files. Read each file and check the `<processType>` element. Only `AutoLaunchedFlow` is valid for actions. Examine the `<variables>` elements to identify inputs (`isInput=true`) and outputs (`isOutput=true`) with their data types.
484
+
485
+ **Finding Prompt Templates:** Search `promptTemplates/` for template metadata files. Review the template's input variables and output format.
486
+
487
+ **Finding External Services:** Search `externalServiceRegistrations/` for `.externalServiceRegistration-meta.xml` files. These represent registered external APIs (REST endpoints). Check the schema for available operations, inputs, and outputs. Wire with `target: "externalService://ServiceName"`.
488
+
489
+ **Finding Standard Invocable Actions:** These are platform-provided actions (e.g., `sendEmail`, `chatterPost`). Query the org: `sf api request rest --json "/services/data/v63.0/actions/standard" -o <org-alias>` to list all available standard actions. Wire with `target: "standardInvocableAction://actionName"`.
490
+
491
+ ### How to Map Existing Actions
492
+
493
+ For each candidate action, verify it matches what the agent needs:
494
+
495
+ - **Input contract** — does the action accept the parameters the agent will send?
496
+ - **Output contract** — does the action return data the agent needs?
497
+ - **Target format** — use the correct protocol (`apex://`, `flow://`, `prompt://`)
498
+
499
+ Example — existing Apex class `OrderLookup`:
500
+
501
+ ```apex
502
+ public class OrderLookup {
503
+ public class Request {
504
+ @InvocableVariable(required=true)
505
+ public String orderId;
506
+ }
507
+ public class Result {
508
+ @InvocableVariable public String status;
509
+ @InvocableVariable public Decimal amount;
510
+ @InvocableVariable public Date orderDate;
511
+ }
512
+ @InvocableMethod(label='Fetch Order')
513
+ public static List<Result> getOrderStatus(List<Request> requests) { ... }
514
+ }
515
+ ```
516
+
517
+ In the Agent Spec, record:
518
+ ```text
519
+ check_order action:
520
+ Existing Action: Apex class OrderLookup (invocable)
521
+ Target: apex://OrderLookup
522
+ Inputs: orderId (string, required)
523
+ Outputs: status (string), amount (number), orderDate (date)
524
+ Status: IMPLEMENTED
525
+ ```
526
+
527
+ ### Connecting Existing Actions to Action Definitions
528
+
529
+ Each `@InvocableVariable` on the request class becomes an action input; each on the result class becomes an output. The `target` field points to the existing action.
530
+
531
+ **Critical: Input and output names must exactly match the Apex `@InvocableVariable` field names, character-for-character.** If the Apex field is `dateToCheck`, the Agent Script input must be `dateToCheck` — not `date_to_check`, not `DateToCheck`. The platform validates these names at publish time; mismatches cause publish failures.
532
+
533
+ ```agentscript
534
+ # WRONG — snake_case doesn't match the Apex field names
535
+ subagent orders:
536
+ actions:
537
+ check_order: @actions.check_order
538
+ target: "apex://OrderLookup"
539
+ inputs:
540
+ order_id: string # Apex field is orderId, NOT order_id
541
+ outputs:
542
+ order_date: date # Apex field is orderDate, NOT order_date
543
+
544
+ # RIGHT — names match Apex @InvocableVariable field names exactly
545
+ subagent orders:
546
+ actions:
547
+ check_order: @actions.check_order
548
+ target: "apex://OrderLookup"
549
+ description: "Look up order status"
550
+ inputs:
551
+ orderId: string # matches Request.orderId
552
+ outputs:
553
+ status: string # matches Result.status
554
+ filter_from_agent: False
555
+ amount: number # matches Result.amount (Decimal → number)
556
+ filter_from_agent: False
557
+ orderDate: date # matches Result.orderDate (Date → date)
558
+ filter_from_agent: False
559
+ ```
560
+
561
+ #### Primitive Agent Script Type Mapping
562
+
563
+ Primitive types (individual and arrays) require only an Agent Script type.
564
+
565
+ | Agent Script Type | Apex | Flow | Prompt Template |
566
+ |---|---|---|---|
567
+ | `string` | String | Text | UNGROUNDED |
568
+ | `boolean` | Boolean | Boolean | UNGROUNDED |
569
+ | `number` | Decimal | UNGROUNDED | UNGROUNDED |
570
+ | `integer` | Integer | UNGROUNDED | UNGROUNDED |
571
+ | `long` | Long | UNGROUNDED | UNGROUNDED |
572
+ | `date` | Date | Date | UNGROUNDED |
573
+ | `datetime` | Datetime | UNGROUNDED | UNGROUNDED |
574
+ | `list[T]` | `List<T>` | UNGROUNDED | UNGROUNDED |
575
+
576
+ `integer`, `long`, and `datetime` are valid in action I/O only — not valid for agent variables.
577
+
578
+ #### Complex Agent Script Type Mapping
579
+
580
+ Complex types (Apex classes, SObject records) require both `object` or `list[object]` AND `complex_data_type_name`. **Correct value depends on action `target`, not data shape.**
581
+
582
+ | Target | Action Type | Agent Script Type | `complex_data_type_name` Format | Example |
583
+ |---|---|---|---|---|
584
+ | `apex://` | `List<InnerClass>` | `list[object]` | `@apexClassType/c__Class$InnerClass` | `@apexClassType/c__StationSupplyChecker$SupplyInfo` |
585
+ | `apex://` | `InnerClass` (single) | `object` | `@apexClassType/c__Class$InnerClass` | `@apexClassType/c__StationSupplyChecker$SupplyInfo` |
586
+ | `flow://` | SObject collection | `list[object]` | `lightning__recordInfoType` | `lightning__recordInfoType` |
587
+ | `flow://` | Single SObject | `object` | `lightning__recordInfoType` | `lightning__recordInfoType` |
588
+ | `prompt://` | UNGROUNDED | UNGROUNDED | UNGROUNDED | UNGROUNDED |
589
+
590
+ Format: `@apexClassType/c__<OuterClass>$<InnerClass>`. The `c__` prefix is the default namespace. The `$` separates outer from inner class.
591
+
592
+ NEVER use `lightning__recordInfoType` for `apex://` targets. ONLY use for Flow SObject returns.
593
+
594
+ ```agentscript
595
+ # WRONG — lightning__recordInfoType with apex:// target
596
+ get_properties:
597
+ target: "apex://PropertyQueryService"
598
+ outputs:
599
+ properties: list[object]
600
+ complex_data_type_name: "lightning__recordInfoType"
601
+
602
+ # WRONG — outer class name only, missing $InnerClass
603
+ get_properties:
604
+ target: "apex://PropertyQueryService"
605
+ outputs:
606
+ properties: list[object]
607
+ complex_data_type_name: "@apexClassType/c__PropertyQueryService"
608
+
609
+ # RIGHT — full inner class path, matches apex:// target
610
+ get_properties:
611
+ target: "apex://PropertyQueryService"
612
+ outputs:
613
+ properties: list[object]
614
+ complex_data_type_name: "@apexClassType/c__PropertyQueryService$PropertyInfo"
615
+ ```
616
+
617
+ Example — `flow://` target returning records:
618
+ ```agentscript
619
+ get_customer:
620
+ target: "flow://GetCustomerInfo"
621
+ outputs:
622
+ customer_info: object
623
+ complex_data_type_name: "lightning__recordInfoType"
624
+ ```
625
+
626
+ Example — `apex://` target returning structured data:
627
+ ```agentscript
628
+ check_supplies:
629
+ target: "apex://StationSupplyChecker"
630
+ outputs:
631
+ supplies: list[object]
632
+ complex_data_type_name: "@apexClassType/c__StationSupplyChecker$SupplyInfo"
633
+ ```
634
+
635
+ #### Output Visibility (`filter_from_agent`)
636
+
637
+ Each output requires a visibility decision: Should the agent display this value to the user, or keep it internal for routing and logic?
638
+
639
+ The `filter_from_agent` property controls this. The name is inverted — `True` means the output is **filtered out** (hidden from the user), `False` means it is **visible**.
640
+
641
+ Capture this decision during spec creation using the **Visible to User?** column in the Agent Spec template. Wrong choice causes agent to retrieve data but never display it.
642
+
643
+ | `filter_from_agent` | User sees the value? |
644
+ |---|---|
645
+ | `False` | Yes — displayed in the agent's response |
646
+ | `True` | No — available to the LLM for reasoning but not shown |
647
+
648
+ **Show** outputs the user asked for: records, summaries, computed results, status messages.
649
+
650
+ **Hide** outputs that are internal plumbing: success flags (`isSuccess`, `hasData`), IDs consumed by downstream actions, routing signals used in `available when` gates.
651
+
652
+ ```agentscript
653
+ get_properties:
654
+ target: "apex://PropertyQueryService"
655
+ outputs:
656
+ properties: list[object]
657
+ filter_from_agent: False # Desired info. Show to user
658
+ complex_data_type_name: "@apexClassType/c__PropertyQueryService$PropertyInfo"
659
+ hasData: boolean
660
+ filter_from_agent: True # Internal flag. Hide from user
661
+ ```
662
+
663
+ **⚠️ Invalid action implementations (non-autolaunched Flow, non-invocable Apex) may pass validation and simulation-mode preview. The failure surfaces at deploy or as cryptic runtime errors in live mode.** Always verify implementation type before wiring.
664
+
665
+ ### How to Stub Missing Logic
666
+
667
+ When no implementation exists for an action, stub it as an invocable Apex class. Always use Apex for stubs — do not attempt to hand-craft Flow XML or Prompt Template metadata.
668
+
669
+ First, record the stub in the Agent Spec:
670
+ ```text
671
+ fetch_invoice action:
672
+ Existing Action: (none — needs creation)
673
+ Target: apex://InvoiceFetcher (proposed)
674
+ Inputs: invoiceId (string, required)
675
+ Outputs: invoiceAmount (number), dueDate (date), status (string)
676
+ Requirements: Invocable Apex class that accepts invoiceId,
677
+ queries Invoice records, returns amount/dueDate/status
678
+ ```
679
+
680
+ Second, find the default package directory by reading `sfdx-project.json` at the project root and locating the `packageDirectories` entry where `"default": true`. The `path` value in that entry is the package root (commonly `force-app`, but not guaranteed).
681
+
682
+ Third, generate an empty Apex class using the following command:
683
+
684
+ ```bash
685
+ sf template generate apex class --json --name InvoiceFetcher --output-dir <PACKAGE_DIR>/main/default/classes
686
+ ```
687
+
688
+ This creates both the `.cls` and `.cls-meta.xml` files. Do not create test classes for stubs.
689
+
690
+ **Stub vs. functional implementation.** If the prompt implies data access ("grounded in X data," "query Y records," "look up Z"), write functional Apex with bulkified SOQL per `assets/invocable-apex-template.cls`. Prefer static SOQL. If dynamic SOQL is required, NEVER append `WITH USER_MODE` to the query string — use `Database.query(q, AccessLevel.USER_MODE)` instead. See *Dynamic SOQL* in the template.
691
+
692
+ If the prompt does not imply data access, or if the action's data requirements are unclear, write a minimal stub — hardcoded return values only. Do not add SOQL, conditional logic, or complex inner class structures to minimal stubs.
693
+
694
+ Fourth, replace the generated class body with a stub. Use multiline `@InvocableVariable` annotations per `assets/invocable-apex-template.cls`:
695
+
696
+ ```apex
697
+ public class InvoiceFetcher {
698
+ public class Request {
699
+ @InvocableVariable(
700
+ label='Invoice ID'
701
+ description='ID of the invoice to fetch'
702
+ required=true
703
+ )
704
+ public String invoiceId;
705
+ }
706
+ public class Result {
707
+ @InvocableVariable(
708
+ label='Invoice Amount'
709
+ description='Total amount of the invoice'
710
+ )
711
+ public Decimal invoiceAmount;
712
+ @InvocableVariable(
713
+ label='Due Date'
714
+ description='Payment due date'
715
+ )
716
+ public Date dueDate;
717
+ @InvocableVariable(
718
+ label='Status'
719
+ description='Current invoice status'
720
+ )
721
+ public String status;
722
+ }
723
+ @InvocableMethod(
724
+ label='Fetch Invoice'
725
+ description='Retrieves invoice details by ID'
726
+ )
727
+ public static List<Result> fetch(List<Request> requests) {
728
+ // Stub — return minimal hardcoded values to unblock deployment
729
+ Result r = new Result();
730
+ r.status = 'stub';
731
+ return new List<Result>{ r };
732
+ }
733
+ }
734
+ ```
735
+
736
+ ALWAYS deploy one class at a time to isolate compile errors:
737
+
738
+ `sf project deploy start --json --metadata ApexClass:<ClassName>`
739
+
740
+ ALWAYS fix deploy errors BEFORE generating and deploying the next stub.
741
+
742
+ ---
743
+
744
+ ## 6. Transition Patterns
745
+
746
+ When creating a new agent, label every transition in your Agent Spec's Subagent Map as either **handoff** or **delegation**. When analyzing an existing agent, classify each transition to determine whether context flow matches the design intent.
747
+
748
+ ### Handoff: Non-Returning Transition
749
+
750
+ A handoff is a one-way transition. The user moves to a new subagent and control never returns to the original subagent. Handoffs use `@utils.transition to` in `reasoning.actions`.
751
+
752
+ Use handoff when:
753
+ - Switching modes (preview → confirm → complete)
754
+ - Entry point routing (agent_router → domain subagents)
755
+ - One-way workflows (checkout → order_confirmation → end)
756
+
757
+ ```agentscript
758
+ subagent agent_router:
759
+ reasoning:
760
+ actions:
761
+ go_to_checkout: @utils.transition to @subagent.checkout
762
+ description: "Start checkout"
763
+
764
+ subagent checkout:
765
+ reasoning:
766
+ actions:
767
+ go_to_confirm: @utils.transition to @subagent.order_confirmation
768
+ description: "Proceed to confirmation"
769
+ ```
770
+
771
+ After `go_to_confirm` executes, the active execution target is
772
+ `order_confirmation`. If the user later says "go back," the agent routes them
773
+ through `agent_router` (the entry point), not automatically to `checkout`.
774
+ Handoffs do not maintain a return stack. This does not mean surviving user and
775
+ assistant messages disappear from model-visible conversation history.
776
+
777
+ ### Delegation: Handoff with Explicit Return
778
+
779
+ Delegation hands control to another subagent using `@subagent.X` in `reasoning.actions`. It signals *intent* to return, but the return does not happen automatically — the delegated subagent must explicitly transition back to the caller.
780
+
781
+ Use delegation when:
782
+ - One subagent needs advice from a specialist and should continue after
783
+ - Reusable sub-workflows (e.g., identity verification called from multiple subagents)
784
+ - A subagent needs to temporarily visit another subagent, then resume
785
+
786
+ **Critical Rule:** `@subagent.X` delegates control. It does NOT implement call-return semantics. If you want the user to return to the calling subagent, code an explicit `transition to @subagent.<caller>` in the delegated subagent. Without it, the next user utterance falls through to `agent_router`.
787
+
788
+ WRONG: Assuming `@subagent.specialist` returns automatically
789
+ ```agentscript
790
+ subagent main:
791
+ reasoning:
792
+ actions:
793
+ consult_specialist: @subagent.specialist # WRONG — assumes return
794
+
795
+ # After specialist runs, control does NOT return to main.
796
+ # The next user utterance routes through agent_router.
797
+ ```
798
+
799
+ RIGHT: Delegated subagent defines explicit return transition
800
+ ```agentscript
801
+ subagent main:
802
+ reasoning:
803
+ actions:
804
+ consult_specialist: @subagent.specialist
805
+ description: "Consult specialist"
806
+
807
+ subagent specialist:
808
+ reasoning:
809
+ actions:
810
+ go_to_main: @utils.transition to @subagent.main
811
+ description: "Return to main"
812
+ ```
813
+
814
+ ---
815
+
816
+ ## 7. Deterministic vs. Subjective Flow Control
817
+
818
+ Instructions are suggestions the LLM *may* follow. Gates and guards are enforced by the runtime and *cannot* be bypassed. For every requirement, choose the right flow control type.
819
+
820
+ ### Classifying Flow Control Requirements
821
+
822
+ **Deterministic flow control** — the runtime enforces it. Use when the requirement is non-negotiable:
823
+ - Security: "only admin users can access this"
824
+ - Financial: "never approve transactions above $10,000 without human review"
825
+ - Confirmed consequence: "do not submit until the exact target and explicit confirmation are recorded"
826
+ - External ordering: "step 2 is unavailable until step 1 returns success"
827
+ - Observed failure: a reproduced trace proves model reasoning cannot reliably enforce the requirement
828
+
829
+ **Subjective flow control** — the LLM decides. Use when flexibility is acceptable:
830
+ - Conversational tone: "respond professionally but warmly"
831
+ - Natural language generation: "summarize the results in your own words"
832
+ - User preferences: "if the user is impatient, give short answers; if curious, explain more"
833
+
834
+ **The test:** name the regulation, authorization boundary, irreversible
835
+ consequence, external ordering constraint, or reproduced trace failure. If none
836
+ exists, leave the decision to model reasoning. Awkward phrasing or the mere
837
+ presence of multiple conversational questions is not a deterministic cause.
838
+
839
+ WRONG: Security rule as an instruction (LLM can ignore it)
840
+ ```agentscript
841
+ subagent admin_panel:
842
+ reasoning:
843
+ instructions: ->
844
+ | Only respond if the user is an admin.
845
+ If they are not an admin, tell them access is denied.
846
+ ```
847
+
848
+ Model instructions influence behavior but do not provide the same enforcement
849
+ as a runtime gate over a trusted authorization value. For this protected
850
+ boundary, use a `before_reasoning` guard that resolves before the planner. See
851
+ Section 8 for the available gating mechanisms.
852
+
853
+ ### Writing Effective Instructions
854
+
855
+ Three useful factors for subjective control effectiveness are clear response
856
+ duties, instruction ordering, and grounding.
857
+
858
+ **Describe the duty, not a draft reply.** By default, tell the model what the
859
+ response must accomplish: the facts to use, claims to avoid, action to take,
860
+ and next conversational objective. Do not write ordinary prompt fragments as
861
+ finished user-facing copy. Copy-first instructions can hide the intended
862
+ behavior, adapt poorly to conversation context, and make conflicting duties
863
+ harder to notice.
864
+
865
+ Use exact response copy only when the wording itself is a requirement, such as
866
+ an approved legal or compliance notice. State that contract explicitly with
867
+ language such as `Respond with exactly this text, with no additions:`. Label
868
+ optional wording as an example and state which tone or content properties the
869
+ model should preserve.
870
+
871
+ **Instruction Ordering.** The runtime resolves instructions top-to-bottom —
872
+ evaluating conditions and expanding template expressions — before the LLM sees
873
+ the assembled result. Ordering controls the order of prompt fragments, not
874
+ whether the model can respond before a later deterministic condition resolves.
875
+ Put the current objective and highest-consequence guidance where it is easy to
876
+ notice, and use exclusive predicates or a transition when two duties must not
877
+ coexist.
878
+
879
+ The checkout examples assume `cart_validation_failed`, `cart_total`,
880
+ `free_shipping_eligible`, and `shipping_cost` are exact outputs from cart and
881
+ entitlement actions. Each is consumed by the shown prompt branch or output
882
+ reference; none mirrors a conversational fact.
883
+
884
+ RIGHT: Completed and first-entry duties are mutually exclusive
885
+ ```agentscript
886
+ subagent checkout:
887
+ reasoning:
888
+ instructions: ->
889
+ if @variables.cart_validation_failed:
890
+ | Explain that one or more cart items are unavailable. Do not
891
+ offer payment. Ask the user to review or remove those items.
892
+
893
+ if @variables.cart_validation_failed == False:
894
+ | Tell the user the current cart total is
895
+ {!@variables.cart_total}. Ask whether they want to proceed to
896
+ payment or cancel.
897
+
898
+ if @variables.cart_validation_failed == False and @variables.free_shipping_eligible:
899
+ | Tell the user shipping is free.
900
+
901
+ if @variables.cart_validation_failed == False and @variables.free_shipping_eligible == False:
902
+ | Tell the user standard shipping costs
903
+ {!@variables.shipping_cost}.
904
+ ```
905
+
906
+ WRONG: Conflicting fragments can be assembled together
907
+ ```agentscript
908
+ subagent checkout:
909
+ reasoning:
910
+ instructions: ->
911
+ | Tell the user the current cart total is
912
+ {!@variables.cart_total}. Ask whether they want to proceed to
913
+ payment or cancel.
914
+
915
+ if @variables.cart_validation_failed:
916
+ | Explain that one or more cart items are unavailable and ask
917
+ the user to review or remove them.
918
+ ```
919
+
920
+ The problem is not that the model responds before the bottom condition is
921
+ evaluated; deterministic resolution finishes first. The problem is that both
922
+ the payment duty and failure duty can reach the same assembled prompt.
923
+
924
+ **Grounding.** The platform's grounding service validates that the agent's response matches action output data. Paraphrasing or embellishing may cause grounding failures. In the example below, `event_date` is exact action output consumed by the response.
925
+
926
+ - Use specific values: `"The event is on {!@variables.event_date}"` grounds reliably; `"The event is next week"` may not.
927
+ - Avoid transforming values: return `"Tuesday"` as-is, not `"day after Monday"`.
928
+ - Avoid embellishment instructions: `"Respond like a pirate"` increases grounding risk — embellished content has no output to ground against.
929
+
930
+ Grounding validation requires **live mode preview** (`sf agent preview --use-live-actions --json`). Simulated mode preview generates fake outputs, so grounding has nothing real to validate against.
931
+
932
+ **Naming output fields in post-action instructions.** Name the fields needed in
933
+ the response when generic result-presentation guidance produces the wrong
934
+ format or tool choice in the target runtime. Observed configurations may expose
935
+ platform presentation tools such as `show_command`; if traces show the model
936
+ selecting one when direct text is required, add a scoped instruction to compose
937
+ text and test it with that configuration. Do not add a universal
938
+ `show_command` prohibition to agents where the tool is absent or desired.
939
+
940
+ ### Post-Action Behavior
941
+
942
+ When a model-selected action batch completes without a handoff, pause,
943
+ cancellation, or limit, the runtime begins another reasoning iteration with
944
+ updated state. The LLM may call the same still-available action again. To
945
+ prevent unwanted loops, see Section 9 (Action Loop Prevention).
946
+
947
+ ---
948
+
949
+ ## 8. Gating Patterns
950
+
951
+ ### `available when` — Action Visibility Gate
952
+
953
+ An action marked `available when <condition>` is hidden from the LLM when the condition is false. The LLM cannot call an unavailable action.
954
+
955
+ The examples below assume `refund_confirmed` is written only by the explicit
956
+ confirmation path. Its named consumer is the consequential refund-action gate.
957
+
958
+ **WRONG: Relying on instructions to prevent action calls**
959
+ ```agentscript
960
+ subagent refunds:
961
+ reasoning:
962
+ instructions: ->
963
+ | If the refund is not confirmed, do not call
964
+ {!@actions.issue_refund}.
965
+
966
+ actions:
967
+ issue: @actions.issue_refund # Always visible
968
+ ```
969
+
970
+ The action is visible; instructions tell the LLM not to call it. The LLM may ignore instructions.
971
+
972
+ **RIGHT: Using `available when` to hide the action**
973
+ ```agentscript
974
+ subagent refunds:
975
+ reasoning:
976
+ actions:
977
+ issue: @actions.issue_refund
978
+ available when @variables.refund_confirmed == True
979
+ ```
980
+
981
+ If `refund_confirmed` is False, the LLM sees no `issue` action. Reset the value
982
+ when the user cancels or changes any material refund parameter.
983
+
984
+ ### Conditional Instructions — Prompt Text Gate
985
+
986
+ Use `if/else` in instructions only when a named controlled value changes the
987
+ text the model must receive. This does not hide actions; it changes what the LLM
988
+ is told to do. Do not add a variable merely to create a conditional prompt.
989
+
990
+ ```agentscript
991
+ subagent refunds:
992
+ reasoning:
993
+ instructions: ->
994
+ | Explain the refund review result.
995
+
996
+ if @variables.refund_authorized:
997
+ | The refund is authorized. Explain the approved amount.
998
+ else:
999
+ | The refund is not authorized. Explain the available review
1000
+ or escalation options.
1001
+ ```
1002
+
1003
+ Use conditional instructions when the branch has a named cause and the variable
1004
+ has a trusted writer. Let surviving history and model judgment handle ordinary
1005
+ preferences and current intent.
1006
+
1007
+ In this example, `refund_authorized` must be trusted output from the refund
1008
+ review action. The prompt branch consumes that authorization result.
1009
+
1010
+ ### `before_reasoning` Guards — Early Exit
1011
+
1012
+ The `before_reasoning` block runs before the LLM is invoked. Code here executes every time the subagent is entered. The LLM never sees it, cannot override it, and cannot skip it.
1013
+
1014
+ Here `user_role` is trusted authorization output, the guard is its named
1015
+ consumer, and the cause is restricted admin authority.
1016
+
1017
+ ```agentscript
1018
+ subagent admin_panel:
1019
+ before_reasoning:
1020
+ if @variables.user_role != "admin":
1021
+ transition to @subagent.access_denied
1022
+
1023
+ reasoning:
1024
+ instructions: | You are in the admin panel.
1025
+ ```
1026
+
1027
+ If the user is not an admin, they transition out before the LLM is invoked. The admin subagent's reasoning instructions never execute.
1028
+
1029
+ ### Multi-Condition Gating
1030
+
1031
+ Combine `available when`, conditional instructions, and guards to enforce complex rules.
1032
+
1033
+ Example: "Show the payment action only if the user is authenticated AND the cart is not empty AND we're not in a preview/demo mode"
1034
+
1035
+ Assume `is_demo_mode` comes from deployment configuration,
1036
+ `authenticated` from verification output, and `items_in_cart` from the cart
1037
+ service. The consumers enforce environment safety, authorization, and the
1038
+ preconditions of a consequential payment.
1039
+
1040
+ ```agentscript
1041
+ subagent checkout:
1042
+ before_reasoning:
1043
+ if @variables.is_demo_mode:
1044
+ transition to @subagent.demo_complete
1045
+
1046
+ reasoning:
1047
+ instructions: ->
1048
+ if @variables.items_in_cart == 0:
1049
+ | Explain that the cart is empty and ask the user to select an
1050
+ item before checkout.
1051
+
1052
+ if @variables.items_in_cart > 0:
1053
+ | Summarize the current order and help the user review it before
1054
+ payment.
1055
+
1056
+ actions:
1057
+ pay: @actions.process_payment
1058
+ available when @variables.authenticated == True
1059
+ and @variables.items_in_cart > 0
1060
+ ```
1061
+
1062
+ ### External-Outcome Sequential Gate
1063
+
1064
+ Use state for ordered stages only when each value records a successful external
1065
+ outcome consumed by the next runtime gate. Do not also store a `current_step`
1066
+ counter.
1067
+
1068
+ ```agentscript
1069
+ variables:
1070
+ step1_verified: mutable boolean = False
1071
+ step2_verified: mutable boolean = False
1072
+ step3_verified: mutable boolean = False
1073
+
1074
+ subagent verification:
1075
+ reasoning:
1076
+ actions:
1077
+ verify_step1: @actions.run_check_1
1078
+ set @variables.step1_verified = @outputs.success
1079
+ verify_step2: @actions.run_check_2
1080
+ available when @variables.step1_verified == True
1081
+ set @variables.step2_verified = @outputs.success
1082
+ verify_step3: @actions.run_check_3
1083
+ available when @variables.step2_verified == True
1084
+ set @variables.step3_verified = @outputs.success
1085
+ proceed: @utils.transition to @subagent.confirmed
1086
+ available when @variables.step3_verified == True
1087
+ ```
1088
+
1089
+ Each flag has one trusted writer and a named next-step consumer. Failed actions
1090
+ must leave the next action unavailable. Define only the correction,
1091
+ cancellation, reset, and expiry semantics relevant to the real workflow and
1092
+ the lifetime of that state.
1093
+
1094
+ ### Same-Turn Behavior After Gate Transitions
1095
+
1096
+ When a gate subagent (e.g., username collection) uses `after_reasoning` to transition into a routing subagent, both subagents process in the **same user turn**. The router receives the user's original message — the one that satisfied the gate — not a fresh utterance.
1097
+
1098
+ This means if the user said "My username is alex" and the gate transitions to a subagent router, the router's reasoning fires against "My username is alex." Since that message doesn't match any domain subagent, the router may misclassify it (e.g., routing to `off_topic`).
1099
+
1100
+ **Mitigation:** Avoid a same-turn gate-to-router transition when the triggering
1101
+ utterance is not itself routable. Transition directly to the known destination,
1102
+ or let the gate produce its outcome and route the next user turn normally.
1103
+ Do not introduce an “arrived from gate” latch unless a reproduced trace requires
1104
+ it and the latch has reset, cancellation, and intent-change behavior.
1105
+
1106
+ ---
1107
+
1108
+ ## 9. Action Loop Prevention
1109
+
1110
+ An action loop occurs when the LLM calls the same action repeatedly without new user input. Three things combine to cause loops:
1111
+
1112
+ - **No `available when` gate.** An action without an `available when` condition appears in the LLM's context every reasoning cycle. There is no mechanism that automatically hides an action after it executes — if you don't gate it, it stays visible indefinitely.
1113
+ - **Variable-bound input.** When you bind an input to a variable (`with param = @variables.x`), the action is "ready to go" every cycle — the LLM doesn't need to extract values from the conversation. It can invoke the action with zero friction.
1114
+ - **No post-action instructions.** The instructions don't tell the LLM what to do after the action completes, so it may call the action again.
1115
+
1116
+ **WRONG: All three loop conditions present**
1117
+ ```agentscript
1118
+ subagent events:
1119
+ reasoning:
1120
+ instructions: ->
1121
+ | Use the {!@actions.check_events} action to find events.
1122
+
1123
+ actions:
1124
+ check_events: @actions.check_events
1125
+ with interest = @variables.guest_interest # Variable-bound input
1126
+ ```
1127
+
1128
+ No gate, variable-bound input, no post-action guidance. The LLM can call `check_events` every cycle.
1129
+
1130
+ ### Three Mitigations
1131
+
1132
+ **1. Explicit Post-Action Instructions (most common).**
1133
+
1134
+ Tell the LLM to stop calling the action after receiving results. Name the specific output fields the LLM should include in its text response — vague instructions like "present the results" let platform tools hijack the response (see Section 7, Grounding).
1135
+
1136
+ ```agentscript
1137
+ subagent events:
1138
+ reasoning:
1139
+ instructions: ->
1140
+ | Use {!@actions.check_events} to find events matching the guest's interest.
1141
+ After you receive the results, write the data directly in your text response.
1142
+ For each event, include the eventName, eventDate, and location values from
1143
+ the action output. Use the exact values returned — do NOT paraphrase or round.
1144
+ Do NOT call the action again — you already have the information you need.
1145
+ Do NOT use the show_command tool. Always compose your response as direct text.
1146
+
1147
+ actions:
1148
+ check_events: @actions.check_events
1149
+ with interest = ...
1150
+ ```
1151
+
1152
+ **2. Slot-Filling Instead of Conversational State.**
1153
+
1154
+ Use `...` so the model extracts the latest value from the current turn and
1155
+ surviving history. Do not copy the query into a variable merely to reuse it.
1156
+
1157
+ ```agentscript
1158
+ subagent search:
1159
+ reasoning:
1160
+ instructions: ->
1161
+ | Help the user search for products. Ask what they want, then use
1162
+ {!@actions.search}.
1163
+
1164
+ actions:
1165
+ search: @actions.search
1166
+ with query = ...
1167
+ ```
1168
+
1169
+ The model must decide whether the latest conversation contains a new search
1170
+ request instead of receiving a permanently ready variable-bound action.
1171
+
1172
+ **3. Machine Guard for Consequential Repeats.**
1173
+
1174
+ When repeat execution could change external state twice, use an explicit
1175
+ confirmation value and successful action identifier as machine-checkable
1176
+ consumers. This is safety state, not conversation-flow state.
1177
+
1178
+ ```agentscript
1179
+ variables:
1180
+ operation_confirmed: mutable boolean = False
1181
+ operation_id: mutable string = ""
1182
+
1183
+ subagent commit:
1184
+ reasoning:
1185
+ actions:
1186
+ execute: @actions.commit_operation
1187
+ with target = ...
1188
+ available when @variables.operation_confirmed == True
1189
+ and @variables.operation_id == ""
1190
+ set @variables.operation_id = @outputs.id
1191
+ ```
1192
+
1193
+ Write `operation_confirmed` only from the explicit confirmation path; reset it
1194
+ on cancel or any material correction. Preserve `operation_id` as the successful
1195
+ external result and idempotency evidence.
1196
+
1197
+ **Combine mitigations for reinforcement:**
1198
+
1199
+ ```agentscript
1200
+ subagent lookup:
1201
+ reasoning:
1202
+ instructions: ->
1203
+ | Once you have the result, present it. Do NOT call the action again.
1204
+
1205
+ actions:
1206
+ lookup: @actions.find_data
1207
+ with key = ... # Requires extraction each time
1208
+ ```
1209
+
1210
+ Use state in the combined design only if the action is consequential enough to
1211
+ require the machine guard above.