@salesforce/afv-skills 1.71.0 → 1.72.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 (116) hide show
  1. package/package.json +1 -1
  2. package/skills/agentforce-generate/SKILL.md +8 -0
  3. package/skills/agentforce-generate/assets/agents/README.md +1 -1
  4. package/skills/agentforce-generate/references/actions-reference.md +4 -0
  5. package/skills/agentforce-generate/references/mcp-actions-in-agent-script.md +233 -0
  6. package/skills/agentforce-generate/references/reference-map.md +1 -0
  7. package/skills/dx-packaging-convert-1gp-to-2gp-create/SKILL.md +9 -7
  8. package/skills/dx-packaging-convert-1gp-to-2gp-create/references/conversion-operations.md +78 -4
  9. package/skills/dx-packaging-move-to-2gp-migrate/SKILL.md +17 -13
  10. package/skills/dx-packaging-move-to-2gp-migrate/references/api-operations.md +110 -9
  11. package/skills/experience-app-mcp-generate/references/troubleshooting.md +1 -1
  12. package/skills/experience-app-mcp-generate/scripts/merge_tools.mjs +49 -18
  13. package/skills/experience-app-mcp-generate/scripts/render_eca.mjs +1 -1
  14. package/skills/experience-app-mcp-generate/scripts/render_mcp_server.mjs +1 -1
  15. package/skills/experience-app-mcp-generate/scripts/scan_tool_candidates.mjs +3 -1
  16. package/skills/experience-ui-bundle-custom-app-generate/SKILL.md +32 -26
  17. package/skills/experience-ui-bundle-custom-app-generate/references/configure-metadata-custom-application.md +6 -24
  18. package/skills/nonprofit-fundraising-configure/references/mcp-invocation.md +4 -6
  19. package/skills/platform-apex-generate/SKILL.md +2 -1
  20. package/skills/platform-apex-generate/assets/abstract.cls +0 -4
  21. package/skills/platform-apex-generate/assets/invocable-action-extension.invocableactionextension-meta.xml +28 -0
  22. package/skills/platform-apex-generate/assets/invocable.cls +2 -0
  23. package/skills/platform-apex-generate/references/dml-declarations.md +69 -0
  24. package/skills/platform-metadata-discovery-get/SKILL.md +15 -10
  25. package/skills/platform-metadata-grounding-get/SKILL.md +5 -3
  26. package/skills/service-add-agents-to-contact-center-create/SKILL.md +138 -0
  27. package/skills/service-agentforce-contact-center-coordinate/SKILL.md +5 -5
  28. package/skills/service-agentforce-contact-center-coordinate/references/omni-flow-routing.md +3 -3
  29. package/skills/service-agentforce-contact-center-coordinate/scripts/create-routing-flows.sh +8 -3
  30. package/skills/service-agentforce-contact-center-coordinate/scripts/create-voice-agent.sh +5 -5
  31. package/skills/service-agentforce-contact-center-coordinate/scripts/resolve-acc-queue.sh +10 -1
  32. package/skills/service-agentforce-contact-center-coordinate/scripts/resolve-channel-line.sh +4 -0
  33. package/skills/service-agentforce-contact-center-coordinate/scripts/resolve-flow-definition.sh +5 -0
  34. package/skills/service-agentforce-contact-center-coordinate/scripts/verify-number-live.sh +6 -1
  35. package/skills/service-concierge-portal-generate/SKILL.md +1 -1
  36. package/skills/service-concierge-portal-generate/references/portal-deploy-runbook.md +21 -8
  37. package/skills/service-digital-engagement-channel-configure/SKILL.md +45 -32
  38. package/skills/service-digital-engagement-channel-configure/assets/public_key_certificate_set_jwks_template.xml +20 -0
  39. package/skills/service-digital-engagement-channel-configure/assets/public_key_certificate_set_jwks_url_template.xml +23 -0
  40. package/skills/service-digital-engagement-channel-configure/assets/public_key_certificate_template.xml +15 -0
  41. package/skills/service-digital-engagement-channel-configure/examples/asa_agent_channel.xml +1 -1
  42. package/skills/service-digital-engagement-channel-configure/examples/auth_queue_channel.xml +3 -3
  43. package/skills/service-digital-engagement-channel-configure/examples/jwks_upload_key.xml +11 -0
  44. package/skills/service-digital-engagement-channel-configure/examples/jwks_upload_keyset.xml +13 -0
  45. package/skills/service-digital-engagement-channel-configure/examples/jwks_url_keyset.xml +17 -0
  46. package/skills/service-digital-engagement-channel-configure/examples/omni_flow_channel.xml +3 -3
  47. package/skills/service-digital-engagement-channel-configure/examples/omni_queue_channel.xml +3 -3
  48. package/skills/service-digital-engagement-channel-configure/examples/user_channel.xml +1 -1
  49. package/skills/service-digital-engagement-channel-configure/references/_vendored/service-onboarding-delegation-guidelines.md +43 -0
  50. package/skills/service-digital-engagement-channel-configure/references/channel_settings.md +1 -1
  51. package/skills/service-digital-engagement-channel-configure/references/keyset_settings.md +46 -0
  52. package/skills/service-digital-engagement-channel-configure/references/keyset_setup.md +42 -0
  53. package/skills/service-digital-engagement-channel-configure/references/onboarding_contract.md +28 -27
  54. package/skills/service-digital-engagement-channel-configure/references/recaptcha_handoff.md +2 -5
  55. package/skills/service-digital-engagement-channel-configure/references/routing_transitions.md +2 -2
  56. package/skills/service-digital-engagement-channel-configure/references/user_verification.md +3 -4
  57. package/skills/service-digital-engagement-channel-configure/references/user_verification_client.md +51 -0
  58. package/skills/service-digital-engagement-channel-configure/scripts/check-api-version.sh +7 -0
  59. package/skills/service-digital-engagement-deployment-configure/SKILL.md +28 -10
  60. package/skills/service-digital-engagement-deployment-configure/references/_vendored/service-onboarding-delegation-guidelines.md +43 -0
  61. package/skills/service-digital-engagement-deployment-configure/references/branding_and_tooling.md +2 -2
  62. package/skills/service-digital-engagement-deployment-configure/references/code_snippet.md +2 -2
  63. package/skills/service-digital-engagement-deployment-configure/references/connect_api_creation.md +13 -7
  64. package/skills/service-digital-engagement-deployment-configure/references/custom_labels.md +127 -0
  65. package/skills/service-digital-engagement-deployment-configure/references/deployment_settings.md +2 -1
  66. package/skills/service-digital-engagement-deployment-configure/references/onboarding_contract.md +24 -25
  67. package/skills/service-digital-engagement-deployment-configure/references/prechat_forms.md +1 -1
  68. package/skills/service-digital-engagement-deployment-configure/scripts/check-api-version.sh +7 -0
  69. package/skills/service-email-to-case-configure/SKILL.md +89 -80
  70. package/skills/service-email-to-case-configure/assets/CaseSettings.settings-meta.xml +1 -1
  71. package/skills/service-email-to-case-configure/examples/CaseSettings-two-addresses.settings-meta.xml +6 -3
  72. package/skills/service-email-to-case-configure/references/_vendored/service-onboarding-delegation-guidelines.md +43 -0
  73. package/skills/service-email-to-case-configure/references/agent-delegation.md +22 -0
  74. package/skills/service-email-to-case-configure/references/apply-mechanics.md +15 -12
  75. package/skills/service-email-to-case-configure/references/end-to-end-proof.md +14 -0
  76. package/skills/service-email-to-case-configure/references/onboarding-delegated-run.md +66 -0
  77. package/skills/service-email-to-case-configure/references/routing_address_reference.md +6 -2
  78. package/skills/service-email-to-case-configure/references/troubleshooting.md +17 -9
  79. package/skills/service-email-to-case-configure/scripts/apply-casesettings.py +863 -925
  80. package/skills/service-email-to-case-configure/scripts/tests/_agent.py +162 -0
  81. package/skills/service-email-to-case-configure/scripts/tests/_fakeorg.py +119 -155
  82. package/skills/service-email-to-case-configure/scripts/tests/_run.py +10 -17
  83. package/skills/service-email-to-case-configure/scripts/tests/test_apply_org_scenarios.py +14 -14
  84. package/skills/service-email-to-case-configure/scripts/tests/test_dispatch_contract.py +316 -0
  85. package/skills/service-email-to-case-configure/scripts/tests/test_new_capabilities.py +12 -43
  86. package/skills/service-email-to-case-configure/scripts/tests/test_validate_casesettings.py +13 -0
  87. package/skills/service-email-to-case-configure/scripts/validate-casesettings.py +17 -5
  88. package/skills/service-itsm-agentic-setup-incident-management/references/status-checks.md +11 -11
  89. package/skills/service-remove-agents-from-contact-center-assign/SKILL.md +145 -0
  90. package/skills/service-voice-configuration-manage/SKILL.md +206 -0
  91. package/skills/service-voice-configuration-manage/assets/regions.json +23 -0
  92. package/skills/service-voice-configuration-manage/references/lookups.md +91 -0
  93. package/skills/service-voice-configuration-manage/references/voice_config_api.md +169 -0
  94. package/skills/service-voice-configuration-manage/scripts/create-configuration.sh +20 -0
  95. package/skills/service-voice-configuration-manage/scripts/delete-configuration.sh +31 -0
  96. package/skills/service-voice-configuration-manage/scripts/get-configuration.sh +18 -0
  97. package/skills/service-voice-configuration-manage/scripts/lib.sh +22 -0
  98. package/skills/service-voice-configuration-manage/scripts/list-configurations.sh +18 -0
  99. package/skills/service-voice-configuration-manage/scripts/lookup-caller-lines.sh +30 -0
  100. package/skills/service-voice-configuration-manage/scripts/lookup-flows.sh +29 -0
  101. package/skills/service-voice-configuration-manage/scripts/lookup-profiles.sh +29 -0
  102. package/skills/service-voice-configuration-manage/scripts/lookup-users.sh +29 -0
  103. package/skills/service-voice-configuration-manage/scripts/update-configuration.sh +20 -0
  104. package/skills/tableau-next-asset-create/SKILL.md +10 -4
  105. package/skills/tableau-next-asset-create/references/dashboard-design-principles.md +133 -0
  106. package/skills/tableau-next-asset-create/references/data-transform-gotchas.md +284 -128
  107. package/skills/tableau-next-asset-create/references/deep-reference-index.md +3 -3
  108. package/skills/tableau-next-asset-create/references/edit-dashboard.md +1 -1
  109. package/skills/tableau-next-asset-create/references/edit-visualization.md +678 -468
  110. package/skills/tableau-next-asset-create/references/shared-gates.md +1 -1
  111. package/skills/tableau-next-asset-create/references/tasks/create-data-transform.md +120 -42
  112. package/skills/tableau-next-asset-create/references/tasks/create-viz.md +8 -0
  113. package/skills/tableau-next-asset-create/references/tasks/edit-viz.md +7 -4
  114. package/skills/tableau-next-asset-create/references/tasks/promote-or-reuse.md +9 -4
  115. package/skills/tableau-next-asset-create/references/viz-authoring.md +1 -1
  116. package/skills/service-email-to-case-configure/scripts/tests/test_get_session.py +0 -134
@@ -0,0 +1,162 @@
1
+ """Plays the agent's part of the SKILL.md flow against a ``FakeOrg``.
2
+
3
+ The script only prints requests and validates responses; the agent does the
4
+ dispatching. ``run_flow`` performs that loop in-process - for each request the
5
+ script prints it hands the request to ``FakeOrg.dispatch``, saves the envelope to
6
+ a file, and feeds the file to the next subcommand - then folds the subcommand
7
+ outputs into one summary so scenario tests can assert on the end state.
8
+
9
+ Order matches SKILL.md: gate, initial read, lookups, Phase A write,
10
+ fresh read, Phase B write, final read, verify. Any subcommand failure surfaces as
11
+ SystemExit exactly as it would stop the agent.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import io
17
+ import json
18
+ import tempfile
19
+ from contextlib import redirect_stdout
20
+ from pathlib import Path
21
+
22
+ ACTIVE = None
23
+
24
+
25
+ class Active:
26
+ """Context manager that makes ``run_main`` use a FakeOrg."""
27
+
28
+ def __init__(self, org):
29
+ self.org = org
30
+
31
+ def __enter__(self):
32
+ global ACTIVE
33
+ ACTIVE = self.org
34
+ return self
35
+
36
+ def __exit__(self, *exc):
37
+ global ACTIVE
38
+ ACTIVE = None
39
+ return False
40
+
41
+
42
+ def _flow_parser():
43
+ ap = argparse.ArgumentParser()
44
+ ap.add_argument("--input")
45
+ ap.add_argument("--routing-email", action="append", default=[])
46
+ ap.add_argument("--owner-type")
47
+ ap.add_argument("--owner-value")
48
+ ap.add_argument("--automated-type")
49
+ ap.add_argument("--automated-value")
50
+ ap.add_argument("--system-user-email")
51
+ ap.add_argument("--overwrite-support-settings", action="store_true")
52
+ ap.add_argument("--verify-only", action="store_true")
53
+ ap.add_argument("--verify-cases", action="store_true")
54
+ ap.add_argument("--supplied-email")
55
+ ap.add_argument("--confirm-production", action="store_true")
56
+ return ap
57
+
58
+
59
+ class Flow:
60
+ def __init__(self, org, mod, tmp):
61
+ self.org, self.mod, self.tmp = org, mod, Path(tmp)
62
+ self.n = 0
63
+
64
+ def script(self, argv):
65
+ """Run one subcommand; return its parsed JSON stdout."""
66
+ buf = io.StringIO()
67
+ with redirect_stdout(buf):
68
+ self.mod.main(argv)
69
+ out = buf.getvalue().strip()
70
+ return json.loads(out) if out else {}
71
+
72
+ def save(self, name, data):
73
+ self.n += 1
74
+ path = self.tmp / f"{self.n:02d}-{name}.json"
75
+ path.write_text(json.dumps(data), encoding="utf-8")
76
+ return str(path)
77
+
78
+ def dispatch_all(self, requests, name):
79
+ return [self.save(name, self.org.dispatch(r)) for r in requests]
80
+
81
+ def fetch(self, argv, name):
82
+ """Run `requests ...` and dispatch what it prints; return saved paths."""
83
+ reqs = self.script(["requests", *argv])["requests"]
84
+ return self.dispatch_all(reqs, name)
85
+
86
+ def write(self, request):
87
+ path = self.save("write", self.org.dispatch(request))
88
+ self.script(["check-write", "--response", path])
89
+
90
+
91
+ def run_flow(org, mod, argv):
92
+ a = _flow_parser().parse_args(argv)
93
+ with tempfile.TemporaryDirectory() as tmp:
94
+ f = Flow(org, mod, tmp)
95
+ if a.verify_cases:
96
+ return _verify_cases(f, a)
97
+ if not a.input:
98
+ raise SystemExit(1)
99
+ ver = []
100
+ if a.verify_only:
101
+ current = f.fetch(["settings", *ver], "current")[0]
102
+ return f.script(["read", "--response", current])
103
+
104
+ summary = {"phaseA": {}, "phaseB": []}
105
+ gate_file = f.fetch(["org", *ver], "org")[0]
106
+ gate = ["gate", "--org", gate_file]
107
+ if a.confirm_production:
108
+ gate.append("--confirm-production")
109
+ summary["orgInfo"] = f.script(gate)["orgInfo"]
110
+
111
+ emails = [x for e in a.routing_email for x in ("--routing-email", e)]
112
+ support = []
113
+ for flag, val in (("--owner-type", a.owner_type),
114
+ ("--owner-value", a.owner_value),
115
+ ("--automated-type", a.automated_type),
116
+ ("--automated-value", a.automated_value),
117
+ ("--system-user-email", a.system_user_email)):
118
+ if val:
119
+ support += [flag, val]
120
+ if a.overwrite_support_settings:
121
+ support.append("--overwrite-support-settings")
122
+ base = ["--input", a.input, *ver, *emails]
123
+
124
+ initial = f.fetch(["settings", *ver], "initial")[0]
125
+ lookups = f.script(["requests", "lookups", "--current", initial,
126
+ *base, *support])["requests"]
127
+ lookup_flags = []
128
+ for req, path in zip(lookups, f.dispatch_all(lookups, "lookup")):
129
+ flag = "--users" if "FROM User" in req["query_params"]["q"] \
130
+ else "--queues"
131
+ lookup_flags += [flag, path]
132
+
133
+ out = f.script(["phase-a", "--current", initial, *base, *support,
134
+ *lookup_flags])
135
+ summary["phaseA"] = out["summary"]["phaseA"]
136
+ summary["supportSettings"] = out["summary"]["supportSettings"]
137
+ f.write(out["request"])
138
+
139
+ current = f.fetch(["settings", *ver], "after-a")[0]
140
+ out = f.script(["phase-b", "--current", current, *base, *support,
141
+ *lookup_flags])
142
+ if "request" in out:
143
+ f.write(out["request"])
144
+
145
+ after = f.fetch(["settings", *ver], "after")[0]
146
+ verified = f.script(["verify", "--initial", initial, "--after", after,
147
+ *base, *support, *lookup_flags])
148
+ summary["verified"] = verified["verified"]
149
+ summary["phaseB"] = verified["phaseB"]
150
+ return summary
151
+
152
+
153
+ def _verify_cases(f, a):
154
+ cases = f.fetch(["cases", *(["--supplied-email", a.supplied_email]
155
+ if a.supplied_email else [])], "cases")[0]
156
+ msgs = f.fetch(["messages", "--cases-response", cases], "messages")
157
+ argv = ["cases", "--cases", cases]
158
+ if msgs:
159
+ argv += ["--messages", msgs[0]]
160
+ if a.supplied_email:
161
+ argv += ["--supplied-email", a.supplied_email]
162
+ return f.script(argv)
@@ -1,19 +1,17 @@
1
1
  """In-memory fake Salesforce org for driving apply-casesettings.py end to end
2
2
  without a live org.
3
3
 
4
- The skill script funnels ALL network I/O through three seams:
5
- * ``post_soap(url, envelope, soap_action)`` — readMetadata / updateMetadata
6
- * ``query_active_user(session_id, instance_url, username)``
7
- * ``query_queue(session_id, instance_url, name)``
8
- plus ``get_session`` for the CLI handshake. Patching those four lets the whole
9
- ``main()`` flow run against this fake.
10
-
11
- ``FakeOrg`` holds a CaseSettings state as a nested dict and applies
12
- ``updateMetadata`` with the SAME merge semantics as the platform:
4
+ The script itself does no I/O: the agent dispatches the requests it prints. This
5
+ fake plays the platform side of those `dispatch` / `dispatch_readonly` calls
6
+ (``FakeOrg.dispatch``), answering with the same `{status_code, body}` envelopes
7
+ the MCP tools return, so the whole agent flow (see ``_agent.py``) runs against it.
8
+
9
+ ``FakeOrg`` holds a CaseSettings state as a nested dict and applies the PUT with
10
+ the SAME merge semantics as the platform:
13
11
  * top-level scalar fields merge at the field level (an omitted field keeps its
14
12
  current value);
15
13
  * inside ``emailToCase``, scalar children merge at the field level;
16
- * the ``routingAddresses`` collection is REPLACED wholesale — but ONLY when the
14
+ * the ``routingAddresses`` collection is REPLACED wholesale - but ONLY when the
17
15
  payload's ``emailToCase`` actually contains routingAddresses. A payload whose
18
16
  ``emailToCase`` omits routingAddresses (e.g. Phase A) leaves existing
19
17
  addresses untouched.
@@ -21,24 +19,21 @@ plus ``get_session`` for the CLI handshake. Patching those four lets the whole
21
19
  in the org (matched by routingName/emailAddress) is DROPPED from the replaced
22
20
  collection if any brand-new address appears AFTER it in document order; new
23
21
  addresses always survive. Placing new addresses BEFORE existing ones (what
24
- the skill's Phase B does) preserves everything. This was proven live: the
25
- platform-managed read-only fields (emailServicesAddress/isVerified) are NOT
26
- the cause — existing addresses dropped with those fields stripped and
27
- survived with them kept; only order mattered. Surviving existing addresses
22
+ the skill's Phase B does) preserves everything. Surviving existing addresses
28
23
  keep their minted read-only fields (so a verified address stays verified).
29
24
 
30
25
  The ``drop_one_existing_on_write`` flag injects a fault: the org drops one
31
26
  existing address on any multi-address write regardless of order, to exercise the
32
- skill's preservation guard (its runtime safety net) independent of the ordering
33
- model above.
27
+ skill's preservation guard independent of the ordering model above.
34
28
 
35
29
  Reads reflect current state. Active users / queues are configured per test.
36
30
  """
37
31
  from __future__ import annotations
38
32
 
39
33
  import copy
34
+ import json
35
+ import re
40
36
  import xml.etree.ElementTree as ET
41
- from unittest import mock
42
37
 
43
38
  META_NS = "http://soap.sforce.com/2006/04/metadata"
44
39
 
@@ -51,6 +46,12 @@ def _local(tag: str) -> str:
51
46
  return tag.split("}", 1)[-1] if "}" in tag else tag
52
47
 
53
48
 
49
+ def _in_list(soql: str, field: str):
50
+ """Values of ``<field> IN ('a', 'b')`` in a SOQL string."""
51
+ m = re.search(rf"{field} IN \(([^)]*)\)", soql)
52
+ return re.findall(r"'((?:[^'\\]|\\.)*)'", m.group(1)) if m else []
53
+
54
+
54
55
  class FakeOrg:
55
56
  """Models a single org's CaseSettings for apply-casesettings.py tests."""
56
57
 
@@ -60,104 +61,115 @@ class FakeOrg:
60
61
  drop_one_existing_on_write=False):
61
62
  # Current CaseSettings state (nested dict; scalars are python str/bool).
62
63
  self.state = copy.deepcopy(case_settings) if case_settings else {}
63
- # Active usernames (exact match, case-insensitive handled below).
64
- self.active_users = {u.lower() for u in (active_users or [])}
64
+ self.active_users = list(active_users or [])
65
65
  # Queue DeveloperNames (and Names) that resolve.
66
66
  self.queues = set(queues or [])
67
- # Record of every updateMetadata payload sent, as nested dicts, for
68
- # asserting exactly what was written (e.g. stripped/kept fields).
67
+ # Every PUT payload sent, as nested dicts, for asserting exactly what was
68
+ # written (e.g. stripped/kept fields).
69
69
  self.writes: list[dict] = []
70
- self.instance_url = "https://fake.my.salesforce.com"
71
- self.auth_username = "authuser@fake.example.com"
72
- # Organization row for the production-gate. is_sandbox=None models an
73
- # unreadable Organization row (gate treats it as production).
70
+ # Every request the agent dispatched, as (tool, method, path).
71
+ self.calls: list[tuple] = []
72
+ # Organization row for the production gate. is_sandbox=None models an
73
+ # unreadable Organization row (no record comes back).
74
74
  self.is_sandbox = is_sandbox
75
75
  self.org_type = org_type
76
76
  self.is_trial = is_trial
77
- # apiVersion the fake `sf org display` reports (for version derivation).
77
+ # Newest version the fake `GET /services/data` lists.
78
78
  self.org_api_version = org_api_version
79
79
  # Rows returned by the Act-3 verify-cases queries.
80
80
  self.cases = list(cases or [])
81
81
  self.email_messages = list(email_messages or [])
82
- # Fault injection: when True, any multi-address write drops one existing
83
- # address regardless of ordering, to exercise the skill's preservation
84
- # guard independently of the (correctly-ordered) happy path.
85
82
  self.drop_one_existing_on_write = drop_one_existing_on_write
86
83
 
87
- # -- session / lookups -------------------------------------------------
88
-
89
- def fake_get_session(self, target_org):
90
- # Mirror the real get_session's version derivation (floor 67.0) so the
91
- # metadata URL matches what a live run would produce. get_session is
92
- # patched wholesale in tests, so resolve_api_version is unit-tested
93
- # directly; this keeps the fake's URL faithful.
94
- version = self.org_api_version
95
- try:
96
- major = int(str(version).split(".")[0])
97
- if major < 67:
98
- version = "67.0"
99
- except (ValueError, IndexError):
100
- version = "67.0"
101
- return ("SESSIONID", f"{self.instance_url}/services/Soap/m/{version}",
102
- self.instance_url, self.auth_username)
103
-
104
- def fake_query_active_user(self, session_id, instance_url, username):
105
- if username and username.lower() in self.active_users:
106
- return username
107
- return None
84
+ # -- dispatch ---------------------------------------------------------
85
+
86
+ def dispatch(self, req: dict) -> dict:
87
+ """Answer one request the script printed, as the MCP tool would."""
88
+ tool, method, path = req["tool"], req["method"], req["path"]
89
+ self.calls.append((tool, method, path))
90
+ # dispatch_readonly is GET-only; anything state-changing must use dispatch.
91
+ assert (tool == "dispatch_readonly") == (method == "GET"), req
92
+ assert re.fullmatch(r"/services/data/(v\d+\.\d+/)?(headless/metadata|query)",
93
+ path), path
94
+ if path.endswith("/headless/metadata"):
95
+ if method == "GET":
96
+ assert req["query_params"] == {"type": "CaseSettings",
97
+ "fullName": "Case"}
98
+ return self._ok({"type": "CaseSettings", "fullName": "Case",
99
+ "xmlRep": self._state_xml()})
100
+ assert method == "PUT" and req["body"]["type"] == "CaseSettings"
101
+ return self._apply_update(req["body"]["xmlRep"])
102
+ return self._query(req["query_params"]["q"])
108
103
 
109
- def fake_query_queue(self, session_id, instance_url, name):
110
- return name if name in self.queues else None
111
-
112
- def fake_query_org_info(self, session_id, instance_url):
113
- return self.is_sandbox, self.org_type, self.is_trial
114
-
115
- def fake_query_email_cases(self, session_id, instance_url,
116
- supplied_email=None):
117
- rows = self.cases
118
- if supplied_email is not None:
119
- rows = [c for c in rows if c.get("SuppliedEmail") == supplied_email]
120
- return list(rows)
121
-
122
- def fake_query_incoming_email_messages(self, session_id, instance_url,
123
- case_ids):
124
- ids = set(case_ids)
125
- return [m for m in self.email_messages
126
- if m.get("Incoming") and m.get("ParentId") in ids]
127
-
128
- # -- SOAP -------------------------------------------------------------
129
-
130
- def fake_post_soap(self, url, envelope, soap_action):
131
- if soap_action == "readMetadata":
132
- return self._read_response()
133
- if soap_action == "updateMetadata":
134
- return self._apply_update(envelope)
135
- raise AssertionError(f"unexpected SOAPAction {soap_action!r}")
136
-
137
- def _read_response(self):
138
- """Build a SOAP-ish response whose .//records mirrors current state."""
139
- env = ET.Element(_q("Envelope"))
140
- body = ET.SubElement(env, _q("Body"))
141
- resp = ET.SubElement(body, _q("readMetadataResponse"))
142
- result = ET.SubElement(resp, _q("result"))
143
- records = ET.SubElement(result, _q("records"))
144
- self._dict_to_xml(records, self.state)
145
- return env
146
-
147
- def _apply_update(self, envelope):
104
+ @staticmethod
105
+ def _ok(body):
106
+ return {"status_code": 200, "body": body}
107
+
108
+ def _query(self, soql: str) -> dict:
109
+ if "FROM Organization" in soql:
110
+ if self.is_sandbox is None:
111
+ return self._ok({"totalSize": 0, "done": True, "records": []})
112
+ return self._ok({"totalSize": 1, "done": True, "records": [{
113
+ "IsSandbox": self.is_sandbox,
114
+ "OrganizationType": self.org_type,
115
+ "TrialExpirationDate":
116
+ "2030-01-01T00:00:00.000+0000" if self.is_trial else None}]})
117
+ if "FROM User" in soql:
118
+ wanted = {n.lower() for n in _in_list(soql, "Username")}
119
+ recs = [{"Username": u} for u in self.active_users
120
+ if u.lower() in wanted]
121
+ return self._ok({"totalSize": len(recs), "records": recs})
122
+ if "FROM Group" in soql:
123
+ wanted = set(_in_list(soql, "DeveloperName")) | set(
124
+ _in_list(soql, "Name"))
125
+ recs = [{"DeveloperName": q, "Name": q} for q in sorted(self.queues)
126
+ if q in wanted]
127
+ return self._ok({"totalSize": len(recs), "records": recs})
128
+ if "FROM Case" in soql:
129
+ rows = self.cases
130
+ m = re.search(r"SuppliedEmail = '([^']*)'", soql)
131
+ if m:
132
+ rows = [c for c in rows if c.get("SuppliedEmail") == m.group(1)]
133
+ return self._ok({"totalSize": len(rows), "records": list(rows)})
134
+ if "FROM EmailMessage" in soql:
135
+ ids = set(_in_list(soql, "ParentId"))
136
+ recs = [m for m in self.email_messages
137
+ if m.get("Incoming") and m.get("ParentId") in ids]
138
+ return self._ok({"totalSize": len(recs), "records": recs})
139
+ raise AssertionError(f"unexpected query: {soql}")
140
+
141
+ def _state_xml(self) -> str:
142
+ root = ET.Element(_q("CaseSettings"))
143
+ self._dict_to_xml(root, self.state)
144
+ ET.register_namespace("", META_NS)
145
+ return ('<?xml version="1.0" encoding="UTF-8"?>\n'
146
+ + ET.tostring(root, encoding="unicode") + "\n")
147
+
148
+ def _apply_update(self, xml_rep: str) -> dict:
148
149
  """Parse the payload, record it, merge it into state, return success."""
149
- root = ET.fromstring(envelope)
150
- # find the <metadata> element under updateMetadata
151
- metadata = None
152
- for el in root.iter():
153
- if _local(el.tag) == "metadata":
154
- metadata = el
155
- break
156
- assert metadata is not None, "updateMetadata payload missing <metadata>"
157
- payload = self._xml_to_dict(metadata)
150
+ payload = self._xml_to_dict(ET.fromstring(xml_rep))
151
+ rejected = self._reject_outlook(payload)
152
+ if rejected:
153
+ return {"status_code": 400, "body": {"results": [{
154
+ "success": False, "fullName": "Case", "errors": [
155
+ {"statusCode": "INVALID_FIELD", "message": rejected}]}]}}
158
156
  self.writes.append(copy.deepcopy(payload))
159
157
  self._merge(payload)
160
- return self._success_response()
158
+ return self._ok({"results": [{"success": True, "fullName": "Case",
159
+ "errors": []}]})
160
+
161
+ @staticmethod
162
+ def _reject_outlook(payload):
163
+ addrs = (payload.get("emailToCase") or {}).get("routingAddresses") or []
164
+ for a in [addrs] if isinstance(addrs, dict) else addrs:
165
+ if a.get("addressType") != "Outlook":
166
+ continue
167
+ label = f"EmailToCaseRoutingAddress[{a.get('routingName')}]"
168
+ if a.get("emailAddress"):
169
+ return f"{label}: emailAddress is not available for an Outlook routing address"
170
+ if not a.get("caseOwner"):
171
+ return f"{label}: Missing caseOwner"
172
+ return None
161
173
 
162
174
  def _merge(self, payload):
163
175
  for key, val in payload.items():
@@ -248,16 +260,6 @@ class FakeOrg:
248
260
  return []
249
261
  return [addrs] if isinstance(addrs, dict) else list(addrs)
250
262
 
251
- @staticmethod
252
- def _success_response():
253
- env = ET.Element(_q("Envelope"))
254
- body = ET.SubElement(env, _q("Body"))
255
- resp = ET.SubElement(body, _q("updateMetadataResponse"))
256
- result = ET.SubElement(resp, _q("result"))
257
- ET.SubElement(result, _q("success")).text = "true"
258
- ET.SubElement(result, _q("fullName")).text = "Case"
259
- return env
260
-
261
263
  # -- dict <-> xml -----------------------------------------------------
262
264
 
263
265
  def _dict_to_xml(self, parent, value):
@@ -304,54 +306,16 @@ class FakeOrg:
304
306
 
305
307
  # -- patching ---------------------------------------------------------
306
308
 
307
- def patch(self, apply_mod):
308
- """Return a context manager patching the four seams on apply_mod."""
309
- return _Patches(self, apply_mod)
310
-
311
-
312
- class _Patches:
313
- def __init__(self, org: FakeOrg, apply_mod):
314
- self.org = org
315
- self.mod = apply_mod
316
- self._patchers = []
317
-
318
- def __enter__(self):
319
- # get_session has a documented side-effect: unless --api-version was
320
- # given, it sets the module's API_VERSION global to the org-derived,
321
- # floored version. The real function is mocked here, so mirror that
322
- # side-effect on the patched module using its own resolve_api_version.
323
- mod = self.mod
324
- org = self.org
325
-
326
- def fake_get_session(target_org):
327
- if not getattr(mod, "_API_VERSION_EXPLICIT", False):
328
- mod.API_VERSION = mod.resolve_api_version(org.org_api_version)
329
- return org.fake_get_session(target_org)
330
-
331
- seams = {
332
- "get_session": fake_get_session,
333
- "post_soap": self.org.fake_post_soap,
334
- "query_active_user": self.org.fake_query_active_user,
335
- "query_queue": self.org.fake_query_queue,
336
- "query_org_info": self.org.fake_query_org_info,
337
- "query_email_cases": self.org.fake_query_email_cases,
338
- "query_incoming_email_messages":
339
- self.org.fake_query_incoming_email_messages,
340
- }
341
- for name, fn in seams.items():
342
- p = mock.patch.object(self.mod, name, side_effect=fn)
343
- p.start()
344
- self._patchers.append(p)
345
- return self
346
-
347
- def __exit__(self, *exc):
348
- for p in self._patchers:
349
- p.stop()
350
- return False
309
+ def patch(self, apply_mod=None):
310
+ """Context manager making ``run_main`` drive the agent flow against this
311
+ org. ``apply_mod`` is accepted for call-site symmetry with the old seam
312
+ patching; the script itself has no seams left to patch."""
313
+ from . import _agent
314
+ return _agent.Active(self)
351
315
 
352
316
 
353
317
  def last_e2c_write(org: FakeOrg) -> dict:
354
- """The emailToCase block of the most recent updateMetadata payload."""
318
+ """The emailToCase block of the most recent PUT payload."""
355
319
  for w in reversed(org.writes):
356
320
  if "emailToCase" in w:
357
321
  return w["emailToCase"]
@@ -359,7 +323,7 @@ def last_e2c_write(org: FakeOrg) -> dict:
359
323
 
360
324
 
361
325
  def top_level_keys_written(org: FakeOrg) -> set:
362
- """Union of all top-level keys across every updateMetadata payload."""
326
+ """Union of all top-level keys across every PUT payload."""
363
327
  keys: set = set()
364
328
  for w in org.writes:
365
329
  keys |= set(w.keys())
@@ -1,16 +1,11 @@
1
- """Helpers to drive apply-casesettings.py main() in tests: write a temp
2
- CaseSettings input file and invoke main() with an argv, capturing the JSON
3
- summary it prints. main() calls fail()->sys.exit(1) on error, and argparse may
4
- sys.exit(2); both surface as SystemExit for the test to assert on.
1
+ """Helpers to drive the apply-casesettings.py flow in tests: write a temp
2
+ CaseSettings input file and run the agent flow against a FakeOrg. The script's
3
+ fail() calls sys.exit(1) and argparse may sys.exit(2); both surface as SystemExit
4
+ for the test to assert on.
5
5
  """
6
6
  from __future__ import annotations
7
7
 
8
- import io
9
- import json
10
- import tempfile
11
- from contextlib import redirect_stdout
12
8
  from pathlib import Path
13
- from unittest import mock
14
9
 
15
10
 
16
11
  def write_input(tmpdir: str, xml: str) -> str:
@@ -20,14 +15,12 @@ def write_input(tmpdir: str, xml: str) -> str:
20
15
 
21
16
 
22
17
  def run_main(apply_mod, argv):
23
- """Run main() with the given argv (excluding program name). Returns the
24
- parsed JSON summary dict printed to stdout. Raises SystemExit as-is."""
25
- buf = io.StringIO()
26
- with mock.patch("sys.argv", ["apply-casesettings.py", *argv]):
27
- with redirect_stdout(buf):
28
- apply_mod.main()
29
- out = buf.getvalue().strip()
30
- return json.loads(out) if out else {}
18
+ """Run the agent flow for ``argv`` (the old single-command flag set) against
19
+ the active FakeOrg and return the combined JSON summary. Failures surface as
20
+ SystemExit, as they would stop the agent."""
21
+ from . import _agent
22
+ assert _agent.ACTIVE is not None, "wrap the call in org.patch(apply_mod)"
23
+ return _agent.run_flow(_agent.ACTIVE, apply_mod, list(argv))
31
24
 
32
25
 
33
26
  class Input: