Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

feat(model-apps): Dataverse Custom API invocation for /genpage (behind default-OFF custom-api flag) (#403)

Akshay Maloo50457bb426e3
diff --git a/evals/model-apps/genpage/evals.json b/evals/model-apps/genpage/evals.json
index fda24a3a6..d7443022a 100644
--- a/evals/model-apps/genpage/evals.json
+++ b/evals/model-apps/genpage/evals.json
@@ -4,7 +4,7 @@
"common_workflow_assertions": [
"A workflow-log.md file is saved to the working directory documenting all phases attempted",
"Phase 0: A working directory is created with a kebab-case name derived from the user's description",
- "Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version >= 2.7.0 is verified",
+ "Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version > 2.10.0 is verified",
"Phase 1 (Planner): pac auth list is run and the active environment is identified and reported to the user",
"Phase 1 (Planner): Question 1 (new or edit) is asked via AskUserQuestion",
"Phase 1 (Planner): genpage-plan.md ALWAYS contains 'Solution:' and 'Publisher Prefix:' lines in ## Environment; default fallback is 'Solution: Default' + 'Publisher Prefix: new' for code-only flows",
diff --git a/evals/model-apps/genpage/fixtures/1-account-card-gallery/workflow-log.md b/evals/model-apps/genpage/fixtures/1-account-card-gallery/workflow-log.md
index c771abb92..936054fe5 100644
--- a/evals/model-apps/genpage/fixtures/1-account-card-gallery/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/1-account-card-gallery/workflow-log.md
@@ -8,7 +8,7 @@
### Prereq checks
- `node --version` → v20.11.0
-- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
- (Run separately, not chained with &&)
### Auth check
diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/workflow-log.md b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/workflow-log.md
index 6a4a4655e..ca38f8bf1 100644
--- a/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/11-recruitment-multi-page/workflow-log.md
@@ -8,7 +8,7 @@
### Prereq checks
- `node --version` → v20.11.0
-- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
### Auth check
- `pac auth list` → active profile [email protected]
diff --git a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/workflow-log.md b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/workflow-log.md
index 5a17ad18c..689d761b7 100644
--- a/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/11-recruitment-pages-real/workflow-log.md
@@ -8,7 +8,7 @@
v20.18.2
`pac help`
-PAC CLI Version 2.7.4+g06bb2eb (.NET 10.0.8)
+PAC CLI Version 2.11.0+g06bb2eb (.NET 10.0.8)
`pac auth list`
Index Active Kind Name User Cloud Type Environment Environment Url
@@ -76,7 +76,7 @@ User response: approved
### Decisions
- Environment: AuroraBAPEnv610b3 (https://aurorabapenv610b3.crmtest.dynamics.com/)
-- PAC CLI: 2.7.4 (>= 2.7.0 requirement met)
+- PAC CLI: 2.11.0 (> 2.10.0 requirement met)
- Node: v20.18.2
- Languages: English only — no localization code needed
- Both target entities (contact, appointment) confirmed as Standard tables in the environment
diff --git a/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.md b/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.md
index 53e4eefe6..4b9ff4a56 100644
--- a/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/13-contact-localization/workflow-log.md
@@ -8,7 +8,7 @@
### Prereq checks
- `node --version` → v20.11.0
-- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
### Auth check
- `pac auth list` → active profile [email protected]
diff --git a/evals/model-apps/genpage/fixtures/15-support-tickets-real/workflow-log.md b/evals/model-apps/genpage/fixtures/15-support-tickets-real/workflow-log.md
index 145471e01..ded4dc013 100644
--- a/evals/model-apps/genpage/fixtures/15-support-tickets-real/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/15-support-tickets-real/workflow-log.md
@@ -8,7 +8,7 @@
v20.18.2
`pac help`
-PAC CLI Version 2.7.4+g06bb2eb (.NET 10.0.8) — >= 2.7.0 confirmed.
+PAC CLI Version 2.11.0+g06bb2eb (.NET 10.0.8) — > 2.10.0 confirmed.
### Step 2: Authenticate and Select Environment
diff --git a/evals/model-apps/genpage/fixtures/17-weather-connectors-off/workflow-log.md b/evals/model-apps/genpage/fixtures/17-weather-connectors-off/workflow-log.md
index be40da0d9..701a3bdae 100644
--- a/evals/model-apps/genpage/fixtures/17-weather-connectors-off/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/17-weather-connectors-off/workflow-log.md
@@ -8,7 +8,7 @@
### Prereq checks
- `node --version` → v20.11.0
-- `pac help` → PAC CLI Version 2.8.2 (>= 2.7.0 verified)
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
- (Commands run separately, not chained with &&)
### Auth check
diff --git a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md
index 6585e5513..c7282b271 100644
--- a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md
@@ -8,7 +8,7 @@
### Prereq checks
- `node --version` → v20.11.0
-- `pac help` → PAC CLI Version 2.8.2 (>= 2.7.0 verified)
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
- (Commands run separately, not chained with &&)
### Auth check
diff --git a/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/workflow-log.md b/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/workflow-log.md
index d54db4f4e..27a5b9ec2 100644
--- a/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/2-mock-dashboard-real/workflow-log.md
@@ -8,7 +8,7 @@
v20.18.2
`pac help`
-Microsoft PowerPlatform CLI Version: 2.7.4+g06bb2eb (.NET 10.0.8) — PAC CLI Version 2.7.4 (>= 2.7.0 required) — OK.
+Microsoft PowerPlatform CLI Version: 2.11.0+g06bb2eb (.NET 10.0.8) — PAC CLI Version 2.11.0 (> 2.10.0 required) — OK.
### Authentication
diff --git a/evals/model-apps/genpage/fixtures/2-mock-dashboard/workflow-log.md b/evals/model-apps/genpage/fixtures/2-mock-dashboard/workflow-log.md
index 3ccc591cc..94000c9e3 100644
--- a/evals/model-apps/genpage/fixtures/2-mock-dashboard/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/2-mock-dashboard/workflow-log.md
@@ -8,7 +8,7 @@
### Prereq checks
- `node --version` → v20.11.0
-- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
- (Commands run separately, not chained with &&)
### Auth check
diff --git a/evals/model-apps/genpage/fixtures/4-case-wizard/workflow-log.md b/evals/model-apps/genpage/fixtures/4-case-wizard/workflow-log.md
index 8d5d467f8..b34c0ec1e 100644
--- a/evals/model-apps/genpage/fixtures/4-case-wizard/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/4-case-wizard/workflow-log.md
@@ -8,7 +8,7 @@
### Prereq checks
- `node --version` → v20.11.0
-- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
### Auth check
- `pac auth list` → active profile [email protected]
diff --git a/evals/model-apps/genpage/fixtures/5-kanban-task-board/workflow-log.md b/evals/model-apps/genpage/fixtures/5-kanban-task-board/workflow-log.md
index 1e0e059af..8d8abc56d 100644
--- a/evals/model-apps/genpage/fixtures/5-kanban-task-board/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/5-kanban-task-board/workflow-log.md
@@ -8,7 +8,7 @@
v20.18.2
`pac help`
-PAC CLI Version 2.7.4+g06bb2eb (.NET 10.0.8) — version >= 2.7.0 confirmed.
+PAC CLI Version 2.11.0+g06bb2eb (.NET 10.0.8) — version > 2.10.0 confirmed.
`pac auth list`
Index Active Kind Name User Cloud Type Environment Environment Url
diff --git a/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/workflow-log.md b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/workflow-log.md
index a435a4edc..2ed67e2a0 100644
--- a/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/workflow-log.md
+++ b/evals/model-apps/genpage/fixtures/7-job-candidates-new-entities/workflow-log.md
@@ -8,7 +8,7 @@
### Prereq checks
- `node --version` → v20.11.0
-- `pac help` → PAC CLI Version 2.7.3 (>= 2.7.0 verified)
+- `pac help` → PAC CLI Version 2.11.0 (> 2.10.0 verified)
### Auth check
- `pac auth list` → active profile [email protected]
diff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.js
index d09067e8e..70f95efbe 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-1.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js
@@ -340,7 +340,7 @@ WORKFLOW_ASSERTIONS.set(
);
WORKFLOW_ASSERTIONS.set(
- 'Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version >= 2.7.0 is verified',
+ 'Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version > 2.10.0 is verified',
({ fixture }) => {
const log = fixture.workflowLog;
if (!log) return fail('no workflow-log.md');
@@ -349,8 +349,17 @@ WORKFLOW_ASSERTIONS.set(
if (/node\s+--version\s*&&\s*pac\s+help/.test(log)) {
return fail('node --version and pac help are chained with && (forbidden)');
}
- if (!/2\.\s*7|>=\s*2\.7|version\s+\d+\.\d+/i.test(log)) {
- return fail('no PAC CLI version verification recorded');
+ // Parse the recorded PAC CLI version and enforce the contract (> 2.10.0), rather than merely
+ // matching version-shaped text — an older pac (e.g. 2.7.x) must fail. Anchor on the "PAC CLI" /
+ // "PowerPlatform CLI" phrase so the earlier `node --version → v20.x` line can't be mistaken for the
+ // pac version. Accepts the forms pac emits, e.g. "PAC CLI Version 2.11.0", "PAC CLI: 2.11.0",
+ // "Microsoft PowerPlatform CLI Version: 2.11.0+g06bb2eb (.NET 10.0.8)".
+ const m = /(?:PAC|PowerPlatform)\s+CLI(?:\s+Version)?[:\s]+v?(\d+)\.(\d+)(?:\.(\d+))?/i.exec(log);
+ if (!m) return fail('no PAC CLI version recorded (expected e.g. "PAC CLI Version 2.11.0")');
+ const [major, minor, patch] = [Number(m[1]), Number(m[2]), Number(m[3] || 0)];
+ const gtMin = major > 2 || (major === 2 && (minor > 10 || (minor === 10 && patch > 0)));
+ if (!gtMin) {
+ return fail(`recorded PAC CLI version ${major}.${minor}.${patch} does not satisfy > 2.10.0`);
}
return pass();
}
diff --git a/evals/model-apps/genpage/tests/assertions-layer-1.test.js b/evals/model-apps/genpage/tests/assertions-layer-1.test.js
index 1ced54839..bf34eb122 100644
--- a/evals/model-apps/genpage/tests/assertions-layer-1.test.js
+++ b/evals/model-apps/genpage/tests/assertions-layer-1.test.js
@@ -185,17 +185,40 @@ test('workflow-log.md present: pass when content exceeds threshold', () => {
// ---------- Phase 1 prereq checks ----------
test('node --version and pac help: pass when both recorded separately', () => {
- const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version >= 2.7.0 is verified');
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version > 2.10.0 is verified');
const log = `## Phase 1
- node --version → v20
-- pac help → PAC CLI Version 2.7.3
+- pac help → PAC CLI Version 2.11.0
`;
const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });
assert.equal(result.status, 'pass');
});
+test('node --version and pac help: fail when the recorded version is <= 2.10.0', () => {
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version > 2.10.0 is verified');
+ const log = `## Phase 1
+- node --version → v20
+- pac help → PAC CLI Version 2.7.3
+`;
+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });
+ assert.equal(result.status, 'fail');
+ assert.match(result.reason, /2\.10\.0/);
+});
+
+test('node --version and pac help: fail when only the node version is present (must not be mistaken for pac)', () => {
+ // The node line records v20.x; without a "PAC CLI Version" line there is no valid pac version, so
+ // the assertion must NOT pass by grabbing 20.x from `node --version`.
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version > 2.10.0 is verified');
+ const log = `## Phase 1
+- node --version → v20.11.0
+- pac help → (ran, but version not captured)
+`;
+ const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });
+ assert.equal(result.status, 'fail');
+});
+
test('node --version and pac help: fail when chained with &&', () => {
- const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version >= 2.7.0 is verified');
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version > 2.10.0 is verified');
const log = `node --version && pac help → 2.7.3`;
const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });
assert.equal(result.status, 'fail');
@@ -203,7 +226,7 @@ test('node --version and pac help: fail when chained with &&', () => {
});
test('node --version and pac help: fail when version not verified', () => {
- const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version >= 2.7.0 is verified');
+ const check = WORKFLOW_ASSERTIONS.get('Phase 1 (Planner): node --version and pac help are run separately (not chained with &&) and PAC CLI version > 2.10.0 is verified');
const log = `- node --version\n- pac help`;
const result = check({ fixture: fix({ workflowLog: log }), eval: evalStub() });
assert.equal(result.status, 'fail');
diff --git a/evals/model-apps/genpage/tests/run-layer-1.test.js b/evals/model-apps/genpage/tests/run-layer-1.test.js
index 32334289c..ddcf3d366 100644
--- a/evals/model-apps/genpage/tests/run-layer-1.test.js
+++ b/evals/model-apps/genpage/tests/run-layer-1.test.js
@@ -34,7 +34,7 @@ function mockEval2Artifacts() {
- working directory created
## Phase 1
- node --version
-- pac help → PAC CLI Version 2.7.3 (>= 2.7.0 verified)
+- pac help → PAC CLI Version 2.11.0 (> 2.10.0 verified)
- pac auth list — active profile, environment https://x.crm.dynamics.com
- AskUserQuestion: new or edit → create new
- Solution selection question SKIPPED (code-only flow)
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index 899bb56eb..841160428 100644
--- a/plugins/model-apps/.claude-plugin/plugin.json
+++ b/plugins/model-apps/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "model-apps",
"version": "2.4.3",
- "description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI >= 2.7.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
+ "description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
"url": "https://www.microsoft.com"
diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.json
index 899bb56eb..841160428 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "model-apps",
"version": "2.4.3",
- "description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI >= 2.7.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
+ "description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
"url": "https://www.microsoft.com"
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index b8f98f76e..672ac23b9 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -28,7 +28,8 @@ Plus **`/report-issue`** to file bugs against this repo. All Dataverse mutation
shared, vendored SDK (`scripts/vendor/cds-maker-sdk.cjs`) — see `## Building & Testing`.
**Requirements:**
-- **PAC CLI ≥ 2.7.0** — for app and generative-page deploy operations
+**Requirements:**
+- **PAC CLI > 2.10.0** — for app and generative-page deploy operations (incl. the genpage `upload` connector/Custom API flags)
- **Azure CLI (`az`)** — Dataverse Web API auth (SDK + entity builder); must be logged in with the
same identity as the active `pac` profile
@@ -369,8 +370,10 @@ agents/ ← Agent definitions (invoked by skills via Task
genpage-entity-builder.md ← DV entity creation via plugin's Web API scripts (create flow)
genpage-page-builder.md ← Writes one .tsx file; runs in parallel for multi-page (create flow)
genpage-edit-planner.md ← Reads download artifacts, plans edits, writes edit plan (edit flow)
+ genpage-customapi-builder.md ← Single owner of the custom-api gate; discovers bound Custom APIs, writes ## Custom API Bindings + actions.json (create & edit flows)
references/ ← Shared reference docs
rules.md ← Full code-gen rules, DataAPI types, layout patterns, common errors
+ custom-api.md ← Dataverse Custom API (Action/Function) invocation contract (loaded when the plan has ## Custom API Bindings)
connectors.md ← GenPage connector binding contract and runtime patterns
plan-schema.md ← Schema contract for genpage-plan.md
data-caching.md ← Rule 15 on-mount fetch: de-dupe + cache (loaded conditionally)
@@ -378,7 +381,7 @@ references/ ← Shared reference docs
supported-dependencies.md ← Versioned package list for generated pages
troubleshooting.md ← Deployment/runtime/env issues
verified-icons.txt ← ~5000 Fluent UI icon names; Grep-validated by page-builder
-samples/ ← Example .tsx files (12 samples) plus app-builder spec samples
+samples/ ← Example .tsx files (13 samples) plus app-builder spec samples
scripts/
launch-playwright-mcp.js ← Playwright MCP server launcher (fullscreen; uses lib/detect-browser.js)
playwright-mcp-fullscreen.config.json ← Fullscreen browser config for the launcher
@@ -387,6 +390,7 @@ scripts/
dataverse-request.js ← General Dataverse Web API wrapper (escape hatch)
list-connections.js ← Connector discovery: PAC connections + Dataverse connection references
create-connection-reference.js ← Creates Dataverse connectionreference rows for connector bindings
+ list-custom-apis.js ← Discovers bindable Custom APIs (Global + entity-bound) + parameter kinds (custom-api gated)
add-page-to-solution.js ← Adds GenPages and optional connection references to a solution
provision-entities.js ← CLI wrapper for entity provisioning (solution + data-model + sample-data)
provision-solution.js ← Creates a Dataverse solution via the SDK
@@ -486,6 +490,7 @@ Agents are invoked by skills via the `Task` tool — they are not user-invocable
| `genpage-page-builder` | `genpage` (create flow) **and** `app-builder` (Phase 1.5) | Generates one complete `.tsx` page from a plan document and schema; runs in parallel with other builders for multi-page requests. `/app-builder` projects its App Spec into that plan format via `scripts/write-page-plan.js` and dispatches this same agent |
| `genpage-edit-planner` | `genpage` (edit flow) | Reads the downloaded page artifacts (page.tsx, config.json, prompt.txt), gathers change requirements, presents edit plan, writes `genpage-edit-plan.md`. The orchestrator applies the edit inline. |
| `genpage-connector-builder` | `genpage` orchestrator (create **and** edit flows) | **Single owner of the connectors feature gate.** Performs connector discovery (connections, connection references, datasets, tables, operations, schema), creates Dataverse connection references, and writes the `## Connector Bindings` contract + `connectors.json`. The orchestrator forwards its output into the planner or edit-planner prompt. |
+| `genpage-customapi-builder` | `genpage` orchestrator (create **and** edit flows) | **Single owner of the custom-api feature gate.** Discovers the Dataverse Custom APIs a page can bind to (Global + entity-bound Actions/Functions) plus their parameter kinds via `list-custom-apis.js`, and writes the `## Custom API Bindings` contract + `actions.json`. The orchestrator forwards its output into the planner or edit-planner prompt. |
## Key Concepts
@@ -526,7 +531,8 @@ values in `feature-flags.json` at the plugin root.
- **Script backstop:** connector entrypoints call the shared
`exitIfConnectorsDisabled()` helper (DRY — no inlined gate) and fail closed with
exit 3 when OFF: `list-connections.js`, `create-connection-reference.js`, and the
- `--connection-refs` branch of `add-page-to-solution.js`.
+ `--connection-refs` branch of `add-page-to-solution.js`. Custom API entrypoints call
+ the parallel `exitIfCustomApiDisabled()` helper the same way: `list-custom-apis.js`.
- **Validation:** `KNOWN_FLAGS` + `validateFlags()` warn on unknown keys / non-boolean
values in the committed file (so a typo can't silently do nothing, or — after a flip
to `true` — accidentally enable the wrong thing).
@@ -580,6 +586,30 @@ The **`connectors`** flag currently ships OFF: GenPage connector support needs t
pac CLI connector verbs (PowerPlatform-Scale-AdminTools), the GenUX authoring control
(power-platform-ux), and the maker/admin ECS setting to all be released first.
+**Custom API gate — the single owner is `genpage-customapi-builder`.** Every Custom API
+entry point must go through it or the helper; the checklist of places that gate:
+
+1. Discovery — `genpage-customapi-builder` runs the probe first (planner + edit-planner
+ delegate to it; they do not gate inline).
+2. Scripts — `list-custom-apis.js` (`exitIfCustomApiDisabled`).
+3. Deploy — SKILL Phase 4.6 **re-probes** the flag and treats absent/malformed
+ `## Custom API Bindings` as no bindings (a plan authored while ON must not deploy
+ Custom API bindings after OFF).
+4. ALM — none needed: `config.json`'s `actionBindings` travels inside the page's
+ `uxagentprojectfile` rows automatically (the Custom APIs themselves are a separate
+ deployment prerequisite, bound by name).
+5. Codegen — `genpage-page-builder` emits `executeAction` / `executeFunction` /
+ `listBoundActions` code only when the plan has an actual binding table (never on an
+ absent/sentinel section).
+
+The **`custom-api`** flag currently ships OFF: GenPage Custom API invocation needs the
+AIBuilder CoderAgent action prompt, the shared `pai-gen-ux-action-runtime` plus the UCI and
+Controls host runtimes, a pac CLI `model genpage upload --actions` verb
+(PowerPlatform-Scale-AdminTools) to persist `actionBindings` into `config.json`, and the
+`GenUxPluginActionAllowList` ECS setting to all be released first. Note the maker-facing name
+is "Custom API" while the shipped wire contract stays `actionBindings` / `executeAction`
+(see `references/custom-api.md`).
+
## Hooks & Validators
Hooks are registered centrally in `hooks/hooks.json` (auto-loaded by the plugin
diff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.md
index 1c69905c3..b2d016bfd 100644
--- a/plugins/model-apps/README.md
+++ b/plugins/model-apps/README.md
@@ -22,7 +22,7 @@ claude --plugin-dir /path/to/power-platform-skills/plugins/model-apps
| Prerequisite | Required for | Install |
|---|---|---|
| [Node.js](https://nodejs.org/) (LTS) | All skills | `winget install OpenJS.NodeJS.LTS` |
-| [PAC CLI](https://learn.microsoft.com/en-us/power-platform/developer/cli/introduction) >= 2.7.0 | Schema generation, app creation, table listing, deployment | `dotnet tool install -g Microsoft.PowerApps.CLI.Tool` |
+| [PAC CLI](https://learn.microsoft.com/en-us/power-platform/developer/cli/introduction) > 2.10.0 | Schema generation, app creation, table listing, deployment | `dotnet tool install -g Microsoft.PowerApps.CLI.Tool` |
| [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) (`az`) | Dataverse Web API auth for entity creation | `winget install Microsoft.AzureCLI` |
After installing `az`, run `az login` with the same identity as your active `pac auth list` profile. Without `az`, the `/genpage` skill still works for pages over existing entities or mock data — it only fails when entity creation is needed.
diff --git a/plugins/model-apps/agents/genpage-customapi-builder.md b/plugins/model-apps/agents/genpage-customapi-builder.md
new file mode 100644
index 000000000..b3b76c59d
--- /dev/null
+++ b/plugins/model-apps/agents/genpage-customapi-builder.md
@@ -0,0 +1,173 @@
+---
+name: genpage-customapi-builder
+description: >-
+ Owns ALL GenPage Dataverse Custom API (plug-in) work: it is the single owner of the
+ custom-api feature-flag gate, discovers the Custom APIs a page can bind to (Global and
+ entity-bound Actions/Functions) plus their declared request-parameter kinds, and produces
+ the ## Custom API Bindings contract. Invoked by the genpage skill from BOTH the create flow
+ (planner) and the edit flow (edit-planner) — never invoked directly by users.
+color: green
+tools:
+ - Read
+ - Write
+ - Bash
+ - AskUserQuestion
+ - TaskCreate
+ - TaskUpdate
+ - TaskList
+---
+
+# Genpage Custom API Builder
+
+You are the Dataverse **Custom API** specialist for generative pages. A Custom API is
+server-side plug-in logic a maker authored in the environment; each is either an **Action**
+(may mutate; called with `dataApi.executeAction`) or a **Function** (read-only; called with
+`dataApi.executeFunction`). You are the **single owner** of Custom API discovery and the
+feature gate. Both the create flow (`genpage-planner`) and the edit flow
+(`genpage-edit-planner`) delegate ALL Custom API work to you so the gate and the discovery
+logic live in exactly one place.
+
+You do **not** create Custom APIs — they are pre-existing artifacts. You only discover which
+ones the page may call and record them so the page binds correctly.
+
+You will be invoked via `Task` with a prompt that includes:
+
+- **Mode:** `create` or `edit`.
+- **Working directory** — where to write outputs and read/write logs.
+- **Plugin root** (`${PLUGIN_ROOT}`) — where the JS scripts live.
+- **Environment URL** — e.g. `https://aurorabapenv4ab3f.crmtest.dynamics.com`.
+- **Page tables** — the Dataverse table logical name(s) the page is bound to (from the plan's
+ `## Existing Entities` / `pageInput`), or "none" for a mock/global-only page.
+- **Intent** — the server-side operation(s) the request implies (e.g. "approve the order",
+ "escalate the case", "compute an order summary") and, for `edit`, whether the maker wants to
+ **add**, **replace**, or **remove** a Custom API call.
+- **Existing bindings** (`edit` only) — the current `config.json.actionBindings` array read
+ from the deployed page.
+
+## Outputs (the contract with your callers)
+
+Write both of these into the working directory, then return a one-line summary:
+
+1. **`custom-api-bindings.md`** — a markdown fragment whose entire body is the value of the
+ plan's `## Custom API Bindings` section. It is **either** the exact literal
+ `No custom API bindings.` **or** the binding table described in Step 5. The caller splices
+ this verbatim into `genpage-plan.md`.
+2. **`actions.json`** — the working-dir binding file for `pac model genpage upload --actions`.
+ It is a **bare JSON array** of bindings (see `${PLUGIN_ROOT}/references/custom-api.md`), or
+ `[]` when there are none. Never the `{ "actionBindings": [...] }` object wrapper — that is
+ the deployed page `config.json` shape, which `pac` writes. The file is named `actions.json`
+ because it matches the runtime wire contract (`actionBindings`) and the pac `--actions`
+ verb; see the "Vocabulary" note in `custom-api.md`.
+
+Log every command you run (with its purpose) into the working directory's `workflow-log.md`.
+
+## Step 1 — Feature gate (you own it; run it FIRST, always)
+
+Probe the flag before ANY discovery, for both create and edit:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" custom-api
+```
+
+Record the result in `workflow-log.md` (e.g. `feature-flags.js custom-api → disabled`).
+
+**If it prints `disabled` (exit 1)** — Custom API support is not live in PROD:
+
+- Do **not** run `list-custom-apis.js` or any other discovery.
+- **create:** write `custom-api-bindings.md` containing exactly `No custom API bindings.` and
+ `actions.json` containing `[]`. Return `custom-api disabled — no bindings`.
+- **edit:** the feature is OFF, so you must **not add or discover** new bindings. **Preserve**
+ the existing bindings passed to you: write them unchanged to `actions.json` (bare array) and
+ reproduce them in `custom-api-bindings.md`. Return
+ `custom-api disabled — existing bindings preserved, none added`.
+
+Only when it prints `enabled` (exit 0) do you continue to Step 2. The flag lives in
+`plugins/model-apps/feature-flags.json`; it is flipped to `true` (or
+`GENPAGE_ENABLE_CUSTOM_API=1` for a single run) once the AIBuilder action prompt, the shared
+action runtime + UCI/Controls hosts, the pac `upload --actions` verb, and the
+`GenUxPluginActionAllowList` setting are all released.
+
+## Step 2 — Discovery (enabled only)
+
+Enumerate the Custom APIs the page can bind to — every Global API plus those bound to the
+page's table(s). Custom API metadata lives in ordinary Dataverse tables, so this is a plain
+Web API query (no pac verb needed):
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/list-custom-apis.js" "<ENV_URL>" --entities "<page table logical names, comma-separated>"
+```
+
+Omit `--entities` for a mock/global-only page to get every Global API. The script returns
+`{ ok, customApis: [{ name, displayName, isFunction, bindingType, boundEntityLogicalName?,
+parameterKinds }] }`, already projected into the binding shape.
+
+Match the maker's **intent** to the discovered APIs by `displayName` / `name`. When more than
+one plausibly matches, present the choices via `AskUserQuestion` (show `name`, Action vs
+Function, and Global vs the bound table). **Never invent** a Custom API `name`, a parameter
+name, or a parameter kind that the script did not return — a name the runtime does not find in
+the manifest fails closed with `not_bound`, and a wrong parameter kind corrupts the wire type.
+
+If `list-custom-apis.js` returns no API matching the intent, do **not** fabricate one: leave it
+out and tell the caller the operation was not found (the page then simply omits that call).
+
+## Step 3 — Kind and binding fidelity (every selected API)
+
+For each API the page will call, carry these through EXACTLY as discovered — they are the
+governance the runtime enforces before dispatch (see `custom-api.md`):
+
+- **Kind** (`isFunction`): an Action is called with `executeAction`; a Function with
+ `executeFunction`. A mismatch is rejected with `wrong_operation_kind`. Never "offer both".
+- **Binding**: `bindingType: 'Global'` ⇒ omit `boundEntityLogicalName`; the page must NOT pass
+ `boundTo`. `bindingType: 'Entity'` ⇒ record `boundEntityLogicalName`; the page MUST pass a
+ `boundTo` whose `entityName` equals it. `bindingType: 'EntityCollection'` ⇒ **skip it — do not add
+ it as a binding.** The runtime's `boundTo` is a single record (`{ entityName, id }`); there is no
+ collection-bound invocation shape, so a page cannot call a collection-bound Custom API. If the maker
+ explicitly needs one, tell them it is not supported by the generated-page runtime rather than
+ emitting a binding that will fail. (`list-custom-apis.js` already filters these out; this is the
+ rule if you ever see one.)
+- **`parameterKinds`**: keep every discovered request parameter and its kind. The runtime has
+ no other source for parameter types; a missing or wrong kind causes `invalid_parameter`.
+
+## Step 4 — Edit mode reconciliation (`edit` only)
+
+Start from the **existing bindings** you were given and apply the edit intent:
+
+- **Preserve unchanged:** keep bindings the edit does not touch, verbatim.
+- **Add:** run Steps 2–3 for the new operation and append the binding.
+- **Replace:** discover the replacement (Steps 2–3) and swap it in by `name`.
+- **Remove:** drop the named binding(s).
+- Use ONLY names, kinds, bound entities, and parameter kinds you discovered this run or that
+ were in the existing bindings. Never fabricate.
+
+## Step 5 — Write outputs
+
+Write the final binding set to both output files (see "Outputs"):
+
+- **When there are bindings:** `custom-api-bindings.md` contains the table below;
+ `actions.json` contains the equivalent bare JSON array.
+
+ ```markdown
+ | Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |
+ |------|------|--------------|--------------|-------------------------|
+ | new_ApproveOrder | Action | salesorder | Approve Order | Comment: String, Amount: Decimal |
+ | new_GetOrderSummary | Function | (Global) | Get Order Summary | OrderId: Guid |
+ ```
+
+ The matching `actions.json`:
+
+ ```json
+ [
+ { "name": "new_ApproveOrder", "isFunction": false, "boundEntityLogicalName": "salesorder", "displayName": "Approve Order", "parameterKinds": { "Comment": "String", "Amount": "Decimal" } },
+ { "name": "new_GetOrderSummary", "isFunction": true, "displayName": "Get Order Summary", "parameterKinds": { "OrderId": "Guid" } }
+ ]
+ ```
+
+ Use `(Global)` in the `Bound Entity` cell for an unbound API, and omit
+ `boundEntityLogicalName` from its `actions.json` entry. A Function has `"isFunction": true`;
+ an Action has `"isFunction": false`.
+
+- **When there are none:** `custom-api-bindings.md` contains exactly `No custom API bindings.`
+ and `actions.json` contains `[]`.
+
+Return a concise summary: mode, gate result, and the `name`s of the bindings written (or
+"none").
diff --git a/plugins/model-apps/agents/genpage-edit-planner.md b/plugins/model-apps/agents/genpage-edit-planner.md
index 7247aa15b..c6c72302d 100644
--- a/plugins/model-apps/agents/genpage-edit-planner.md
+++ b/plugins/model-apps/agents/genpage-edit-planner.md
@@ -142,6 +142,12 @@ Ask questions via `AskUserQuestion`, one at a time:
> deployed binding**. The orchestrator will run discovery and re-invoke you with a
> real connector contract and upload-file status.
+> **Custom API changes** (Dataverse Action/Function / plug-in logic): if the edit adds,
+> replaces, or removes a server-side Custom API call, capture it in the plan's `### Custom
+> API Changes` below. Do **not** run Custom API discovery here — the orchestrator delegates
+> that to the `genpage-customapi-builder` agent (which owns the `custom-api` feature gate).
+> Preserving or clearing existing Custom API bindings needs no discovery.
+
Mark "Analyze existing page" task complete.
## Step 3 — Present Edit Plan for Approval
@@ -166,6 +172,10 @@ Enter plan mode (`EnterPlanMode`) with:
- [none | add <source> | replace <logicalName> with <source> | remove <logicalName>]
(the orchestrator delegates any add/replace/remove to genpage-connector-builder)
+### Custom API Changes
+- [none | add <operation> | replace <name> with <operation> | remove <name>]
+ (the orchestrator delegates any add/replace/remove to genpage-customapi-builder)
+
### Preservation Constraints
- [What must remain unchanged — feature preservation, specific behaviors]
diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.md
index dd0cace39..1024318a3 100644
--- a/plugins/model-apps/agents/genpage-page-builder.md
+++ b/plugins/model-apps/agents/genpage-page-builder.md
@@ -54,6 +54,12 @@ table, the page uses `props.dataApi` connector methods (`queryConnectorTable` /
inline data. Never fabricate connector rows/fields; use only the discovered
`Fields`/`Parameters`/`Response` from the plan.
+**Custom APIs are likewise decided separately from Data mode** by the plan's `## Custom API
+Bindings` (see the Custom-API step below): when it has an actual binding table, the page may
+call `props.dataApi.executeAction` / `executeFunction` **even in `mock` data mode** (e.g. a
+Global Function that computes a value). Never fabricate a Custom API name, parameter, or
+parameter kind; use only the plan's `## Custom API Bindings` values.
+
## Step 1 — Read the Plan Document
Read `genpage-plan.md` at the path provided in your invocation prompt.
@@ -136,6 +142,19 @@ over the plan: the orchestrator re-probes the connectors feature flag right befo
code generation, so a plan authored while the flag was ON must not produce connector
calls that this run will never bind.
+Only when the plan's `## Custom API Bindings` section contains an actual binding table
+(a `| Name | Kind | …` header with at least one data row) do you treat the page as
+Custom-API-backed and also read:
+
+```
+${PLUGIN_ROOT}/references/custom-api.md
+```
+
+If the `## Custom API Bindings` section is the literal `No custom API bindings.`, is
+empty, is missing entirely, or contains no binding row, the page has **no Custom APIs** —
+do not read custom-api.md and do not emit any `executeAction` / `executeFunction` /
+`listBoundActions` code.
+
Read the relevant sample file identified in the plan:
```
@@ -402,6 +421,35 @@ if (!response.ok) { return; }
const weather = response.body as WeatherResponse;
```
+### Custom API invocation (Dataverse Actions & Functions)
+
+When the plan has `## Custom API Bindings`, the page may invoke Dataverse Custom APIs on the
+signed-in user's own token. Use only the `Name`, `Kind`, `Bound Entity`, and `Parameters`
+values from that section — never guess a Custom API name, parameter name, or parameter kind.
+Read `${PLUGIN_ROOT}/references/custom-api.md` and emit calls with the verified patterns
+there. The methods are optional at runtime, so every call must be presence-checked; guard
+each **Action** against double-submit, read results from `res.outputs` (never `res.value`),
+surface only the sanitized `res.error?.message`, and **never auto-retry** an `indeterminate`
+result (only `error.code === 'network'` is safely retryable, via a manual "Try again").
+
+Match the call to the row's `Kind`: an **Action** row uses `executeAction`; a **Function** row
+uses `executeFunction`. Calling the wrong one is rejected with `wrong_operation_kind`. For an
+entity-bound row (a `Bound Entity` table, not `(Global)`), pass
+`boundTo: { entityName: pageInput.entityName, id: pageInput.recordId }` whose `entityName`
+equals that table; for a `(Global)` row, omit `boundTo` entirely.
+
+```typescript
+const actionApi = dataApi as unknown as { executeAction?: (request: { name: string; parameters?: Record<string, unknown>; boundTo?: { entityName: string; id: string } }) => Promise<{ ok: boolean; indeterminate?: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string } }>; };
+if (typeof actionApi.executeAction !== 'function' || isSubmitting) { return; } // presence-check + double-submit guard
+setIsSubmitting(true);
+try {
+ const res = await actionApi.executeAction({ name: 'new_ApproveOrder', parameters: { Comment: comment, Amount: amount }, boundTo: { entityName: pageInput.entityName, id: pageInput.recordId } });
+ if (res.indeterminate) { setError("We couldn't confirm this completed — refresh before retrying."); return; }
+ if (!res.ok) { setError(res.error?.message ?? 'The action failed.'); return; }
+ const { NewStatus } = res.outputs as { NewStatus: string };
+} finally { setIsSubmitting(false); }
+```
+
## Step 6 — Write the .tsx File
Write the complete `.tsx` file to the working directory at the target file path.
diff --git a/plugins/model-apps/agents/genpage-planner.md b/plugins/model-apps/agents/genpage-planner.md
index a1323844c..af3658733 100644
--- a/plugins/model-apps/agents/genpage-planner.md
+++ b/plugins/model-apps/agents/genpage-planner.md
@@ -49,7 +49,7 @@ outcomes — because the eval harness greps the log for these tokens. Concretely
- The plan-presentation call is recorded as `EnterPlanMode called` followed
by the user's response (`approved` / `revised`).
- The PAC CLI version output is recorded explicitly (the assertion checks
- for `>= 2.7.0`-shaped text — `PAC CLI Version 2.7.x` is the canonical
+ for `> 2.10.0`-shaped text — `PAC CLI Version 2.10.x` is the canonical
form).
Decisions and outcomes can be summarized at the end of the section, but they
@@ -70,9 +70,10 @@ node --version
pac help
```
-`pac help` output includes the version number. Verify the version is **>= 2.7.0**
-(required for `pac model create` support). If the version is older, instruct the
-user to update: `dotnet tool update --global Microsoft.PowerApps.CLI.Tool`.
+`pac help` output includes the version number. Verify the version is **> 2.10.0**
+(required for `pac model create` support and the genpage `upload` connector/Custom API
+flags). If the version is older, instruct the user to update:
+`dotnet tool update --global Microsoft.PowerApps.CLI.Tool`.
If either command fails, inform the user and provide installation instructions.
Do NOT proceed until prerequisites are met.
@@ -250,6 +251,37 @@ Read `connector-bindings.md` and splice its contents verbatim into the
If the request implies **only** Dataverse and/or mock data (no connector source),
write `## Connector Bindings` as exactly `No connector bindings.`.
+### Custom API Detection (delegated to genpage-customapi-builder)
+
+If the request implies **server-side Dataverse logic** — approving/escalating a record,
+running a calculation or validation, or any operation that maps to a Dataverse **Custom API**
+(Action or Function) rather than a plain row read/write — delegate ALL Custom API work to the
+`genpage-customapi-builder` agent via the `Task` tool. Do **not** run the feature-gate probe
+or any Custom API discovery inline — that agent is the single owner of the `custom-api`
+feature gate, Custom API discovery, and the binding contract.
+
+Invoke `genpage-customapi-builder` with a prompt containing:
+
+- **Mode:** `create`
+- **Working directory**, **Plugin root** (`${PLUGIN_ROOT}`), **Environment URL**
+- **Page tables:** the table logical name(s) the page is bound to (from `## Existing
+ Entities` / `pageInput`), or "none"
+- **Intent:** the server-side operation(s) the request implies (e.g. "approve the order",
+ "escalate the case", "compute an order summary")
+
+It writes two files into the working directory:
+
+- `custom-api-bindings.md` — the exact body for the plan's `## Custom API Bindings` section
+ (either `No custom API bindings.` or the binding table).
+- `actions.json` — the bare-array binding file for deployment (`--actions`).
+
+Read `custom-api-bindings.md` and splice its contents verbatim into the
+`## Custom API Bindings` section of `genpage-plan.md`.
+
+If the request implies **no** server-side Custom API operation (plain Dataverse CRUD and/or
+mock data only), skip the agent entirely and write `## Custom API Bindings` as exactly
+`No custom API bindings.`.
+
### App Detection
Run:
@@ -378,6 +410,7 @@ Enter plan mode (`EnterPlanMode`) and present:
- Entities that exist: [list]
- Entities to create: [list — with columns, types, relationships, choices]
- Connector bindings: [ready-to-bind connectionreference logical names, or "none"]
+- Custom API bindings: [bound Custom API names (Action/Function), or "none"]
- Sample data: will ask after entity creation
### App
diff --git a/plugins/model-apps/feature-flags.json b/plugins/model-apps/feature-flags.json
index 6ebf4e8b2..e2bb19699 100644
--- a/plugins/model-apps/feature-flags.json
+++ b/plugins/model-apps/feature-flags.json
@@ -1,4 +1,5 @@
{
"_comment": "Feature flags for the /genpage skill. Unreleased features ship OFF so the skill behaves identically to production until the full cross-repo stack is live in PROD.",
- "connectors": false
-}
+ "connectors": false,
+ "custom-api": false
+}
\ No newline at end of file
diff --git a/plugins/model-apps/references/custom-api.md b/plugins/model-apps/references/custom-api.md
new file mode 100644
index 000000000..85bbba446
--- /dev/null
+++ b/plugins/model-apps/references/custom-api.md
@@ -0,0 +1,180 @@
+# Action Bindings (Dataverse Custom API invocation)
+
+Action-backed GenPages call Dataverse **Custom API Actions and Functions** — server-side
+plug-in business logic the page could not otherwise reach — on the **signed-in user's own
+token** (no broker, no impersonation). The `name` string a page passes to
+`dataApi.executeAction` / `executeFunction` **MUST** equal an `actionBindings[].name` value
+in the page `config.json`, and that Custom API must exist in the target environment.
+
+> **Gated behind the `custom-api` feature flag (default OFF).** This reference is only used
+> when Custom API support is enabled — see the Feature Flags section in the plugin `AGENTS.md`
+> and `feature-flags.json`. When OFF, pages are Dataverse / mock-data (and, when their own
+> flag is on, connector) only; **no Custom API code is emitted and no `actionBindings` are
+> written**. The `genpage-customapi-builder` agent is the single owner of this gate.
+
+> **Vocabulary.** Makers author **Custom APIs** (the Dataverse `customapi` artifact); each is
+> either an **Action** (may mutate; call with `executeAction`) or a **Function** (read-only;
+> call with `executeFunction`). The shipped runtime contract uses the technical term
+> *action*: bindings persist into `config.json.actionBindings` and the pac verb is
+> `--actions`. So the maker-facing skill says "Custom API" while the wire format stays
+> `actionBindings` — the two describe the same thing at different layers.
+
+## Binding shape: `actions.json` (array) vs page `config.json` (object)
+
+The skill writes a **bare JSON array** of bindings to working-dir `actions.json`.
+`pac model genpage upload --actions <actions.json>` then persists that array into the
+deployed page's `config.json` under an `actionBindings` property. The two files therefore
+have **different shapes** — do not write the object wrapper to `actions.json`.
+
+**`actions.json`** — what the skill writes (a JSON array; no wrapper object):
+
+```json
+[
+ {
+ "name": "new_ApproveOrder",
+ "isFunction": false,
+ "boundEntityLogicalName": "salesorder",
+ "displayName": "Approve Order",
+ "parameterKinds": { "Comment": "String", "Amount": "Decimal" }
+ },
+ {
+ "name": "new_GetOrderSummary",
+ "isFunction": true,
+ "displayName": "Get Order Summary",
+ "parameterKinds": { "OrderId": "Guid" }
+ }
+]
+```
+
+**page `config.json`** — what `pac` writes into the deployed page (the same array wrapped
+under `actionBindings`; the skill never writes this file directly):
+
+```json
+{
+ "actionBindings": [ /* ...the identical array from actions.json... */ ]
+}
+```
+
+- `name`: the Custom API **unique name** (e.g. `new_ApproveOrder`); this is the exact string
+ the TSX passes as `executeAction({ name })` / `executeFunction({ name })`. **This is the
+ revision-bound gate — a name not in `actionBindings` is rejected client-side with
+ `not_bound` and is never dispatched.**
+- `isFunction`: `true` ⇒ a read-only **Function** (call with `executeFunction`; GET
+ semantics); `false`/absent ⇒ an **Action** (call with `executeAction`; may mutate; POST).
+ Calling the wrong method is rejected with `wrong_operation_kind` before dispatch.
+- `boundEntityLogicalName`: present ⇒ the operation is **entity-bound** and its calls
+ **REQUIRE** a `boundTo` whose `entityName` equals this value; absent ⇒ the operation is
+ **Global** and calls must **NOT** pass `boundTo`.
+- `displayName`: friendly name surfaced by `listBoundActions()`; discovery/affordance only.
+- `parameterKinds`: the Custom API's DECLARED request-parameter kinds, keyed by parameter
+ unique name (e.g. `{ "Amount": "Decimal" }`). The runtime has no other source for these,
+ so record every request parameter's Dataverse type. Values are `DataverseParameterKind`
+ strings: `String`, `Integer`, `Decimal`, `Float`, `Money`, `Boolean`, `DateTime`, `Guid`,
+ `StringArray`, `EntityReference`, `Entity`, `EntityCollection`, `Picklist`.
+ See <https://learn.microsoft.com/power-apps/developer/data-platform/custom-api>.
+
+## Runtime requirements
+
+- Always cast `dataApi` to the optional action-method shape and **presence-check** the method
+ before calling it — the methods are absent on older runtimes.
+- **Actions may mutate: guard against double-submit.** Keep an `isSubmitting` flag per
+ action-triggering control; disable it while a call is in flight; never fire a second
+ `executeAction` for the same trigger before the first resolves.
+- **Functions are read-only** — safe to call on mount / on a filter change; no double-submit
+ guard needed (still avoid pointless overlapping fetches; ignore stale responses).
+- **`boundTo` rules** (checked against the manifest BEFORE dispatch; every mismatch is
+ `invalid_bound_to`): an entity-bound operation (`boundEntityLogicalName` present) REQUIRES
+ `boundTo`; `boundTo.entityName` must equal that table; a Global operation must NOT receive
+ `boundTo`; both `entityName` and `id` must be non-empty. Build it from a record the page
+ already has — `{ entityName: pageInput.entityName, id: pageInput.recordId }` when embedded
+ on a form — never a hard-coded/invented GUID.
+- **Read outputs from `res.outputs`, never `res.value`.**
+- **Never surface raw fault text.** On `res.ok === false`, show only the SANITIZED
+ `res.error?.message` in a message bar. Never render stack traces or plug-in fault detail.
+- **Never auto-retry.** `res.indeterminate` (timeout after dispatch — the server may have
+ committed) must never be retried automatically; ask the user to refresh. Only
+ `res.error?.code === 'network'` is safely retryable (the request never left the client), and
+ even then only via a manual "Try again". Do not confuse the two.
+- **Never guess** a name, parameter name, or output field. Use only the plan's
+ `## Custom API Bindings` values and the declared parameter/output names.
+- Keep non-action pages unchanged; only emit action code when the plan has action bindings.
+
+## DataAPI method shapes
+
+These are OPTIONAL methods on `props.dataApi`; presence-check each before use.
+
+```typescript
+interface ActionBoundTo { entityName: string; id: string; }
+interface ExecuteActionRequest { name: string; parameters?: Record<string, unknown>; boundTo?: ActionBoundTo; }
+interface ExecuteFunctionRequest { name: string; parameters?: Record<string, unknown>; boundTo?: ActionBoundTo; }
+interface ActionError { message: string; code?: string; correlationId?: string; }
+interface ActionResult { ok: boolean; indeterminate?: boolean; outputs?: Record<string, unknown>; error?: ActionError; }
+interface BoundActionInfo { name: string; displayName: string; isFunction: boolean; bindingType: 'Global' | 'Entity'; boundEntityLogicalName?: string; }
+
+type ActionDataApi = {
+ executeAction?(request: ExecuteActionRequest): Promise<ActionResult>;
+ executeFunction?(request: ExecuteFunctionRequest): Promise<ActionResult>;
+ listBoundActions?(): Promise<BoundActionInfo[]>;
+};
+```
+
+### `error.code` values the runtime can return
+
+Teach every one; a page that mishandles a code degrades badly.
+
+- `wrong_operation_kind` — an Action was called with `executeFunction` (or the reverse). Fix
+ the call site; do NOT retry with the other method.
+- `invalid_parameter` — a value did not match its declared Dataverse type (from
+ `parameterKinds`). Pass a `number` for numeric, `boolean` for boolean, ISO/`Date` for
+ date-time, a GUID-formatted string for a GUID, `string[]` for an array.
+- `invalid_bound_to` — `boundTo` did not satisfy the binding (missing on an entity-bound op,
+ wrong table, present on a Global op, or incomplete).
+- `not_bound` — the name is not in this page's `actionBindings`. Never guess names.
+- `not_permitted` / `not_enabled` — blocked by environment governance (allow-list / kill
+ switch or per-user privilege).
+- `indeterminate` — the call timed out AFTER being sent; the server may have committed it.
+ Never auto-retry; ask the user to refresh and confirm.
+- `network` — the request never left the client (offline / synchronous failure before
+ dispatch); nothing was committed, so a **manual** "Try again" is appropriate. Still never
+ auto-retry.
+
+## Verified Action pattern (may mutate; double-submit guarded)
+
+```typescript
+const actionApi = dataApi as unknown as { executeAction?: (request: { name: string; parameters?: Record<string, unknown>; boundTo?: { entityName: string; id: string } }) => Promise<{ ok: boolean; indeterminate?: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string } }>; };
+if (typeof actionApi.executeAction !== 'function') { return; } // presence-check; hide/disable the trigger
+if (isSubmitting) { return; } // double-submit guard
+setIsSubmitting(true);
+try {
+ const res = await actionApi.executeAction({
+ name: 'new_ApproveOrder',
+ parameters: { Comment: comment, Amount: amount }, // types match parameterKinds
+ boundTo: { entityName: pageInput.entityName, id: pageInput.recordId }, // REQUIRED: entity-bound
+ });
+ if (res.indeterminate) { setError("We couldn't confirm this completed — refresh before retrying."); return; }
+ if (!res.ok) { setError(res.error?.message ?? 'The action failed.'); return; } // sanitized only
+ const { NewStatus } = res.outputs as { NewStatus: string }; // read from outputs, never value
+} finally {
+ setIsSubmitting(false);
+}
+```
+
+For a **Global** action, omit `boundTo` entirely.
+
+## Verified Function pattern (read-only; safe on mount)
+
+```typescript
+const actionApi = dataApi as unknown as { executeFunction?: (request: { name: string; parameters?: Record<string, unknown> }) => Promise<{ ok: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string } }>; };
+if (typeof actionApi.executeFunction !== 'function') { return; }
+const res = await actionApi.executeFunction({ name: 'new_GetOrderSummary', parameters: { OrderId: orderId } });
+if (!res.ok) { setError(res.error?.message ?? 'Could not load the summary.'); return; }
+const { Total, Status } = res.outputs as { Total: number; Status: string };
+```
+
+## Optional discovery: `listBoundActions`
+
+`dataApi.listBoundActions?.()` returns the operations THIS PAGE is bound to (`name`,
+`displayName`, `isFunction`, `bindingType`). Use it only to render affordances for what is
+available; it reflects the page's `actionBindings`, **not** the signed-in user's privileges,
+so a listed operation can still fail with `not_permitted`. Never use it to discover names —
+always code against the plan's `## Custom API Bindings`.
diff --git a/plugins/model-apps/references/plan-schema.md b/plugins/model-apps/references/plan-schema.md
index 7662435cd..15d1c125e 100644
--- a/plugins/model-apps/references/plan-schema.md
+++ b/plugins/model-apps/references/plan-schema.md
@@ -138,6 +138,21 @@ at runtime.]
| new_uxtest_sharepoint | /providers/Microsoft.PowerApps/apis/shared_sharepointonline | https://.../sites/foo | 5709dd6f-... | Pet | | PetName (string), OwnerName (string), PetType ({Value:string}), Created (datetime) | | |
| new_uxtest_msnweather | /providers/Microsoft.PowerApps/apis/shared_msnweather | | | | CurrentWeather | | Location (required), units (optional) | temperature (number), conditions (string), humidity (number) |
+## Custom API Bindings
+[If NO Custom APIs are used, the value is exactly:]
+No custom API bindings.
+
+[Else, one row per bound Custom API. `Kind` is Action (may mutate; called with
+executeAction) or Function (read-only; called with executeFunction). `Bound Entity` is the
+table logical name for an entity-bound API, or `(Global)` for an unbound one. `Parameters`
+lists each request parameter as `name: Kind` using the declared Dataverse parameter kind.
+All values are discovered by genpage-customapi-builder via list-custom-apis.js — never
+fabricated. Persisted (via `pac ... upload --actions`) into config.json's `actionBindings`.]
+| Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |
+|------|------|--------------|--------------|-------------------------|
+| new_ApproveOrder | Action | salesorder | Approve Order | Comment: String, Amount: Decimal |
+| new_GetOrderSummary | Function | (Global) | Get Order Summary | OrderId: Guid |
+
## Solution Packaging
[OPTIONAL section — include ONLY when packaging into a solution. Omit it entirely
to skip packaging; when absent, the orchestrator skips Phase 6.7. This section is
@@ -194,6 +209,7 @@ connector bindings." sentinel).]
| `## Entity Creation Required` | Entity-builder | Exact literal "No entity creation required..." when empty, else per-entity subsections |
| `## Existing Entities` | Orchestrator (for `pac model genpage generate-types --data-sources`) | Comma-separated logical names |
| `## Connector Bindings` | Planner, page-builder, orchestrator deploy | Exact literal "No connector bindings." when empty; logical names must match Dataverse connectionreferences; tabular bindings must include discovered optional `Fields`; REST/action bindings must include discovered `Parameters` and `Response` |
+| `## Custom API Bindings` | Planner, page-builder, orchestrator deploy | Exact literal "No custom API bindings." when empty; names must match existing Dataverse Custom APIs (`customapi.uniquename`); entity-bound rows carry the bound table (else `(Global)`); every row carries its discovered `Parameters` kinds |
| `## Solution Packaging` | Orchestrator (Phase 6.7) | Opt-in; absent = skip |
| `## Design Preferences` | Page-builder | Prose, free-form |
| `## Relevant Samples` | Page-builder (for Read path resolution) | Sample filename must match a file in `${PLUGIN_ROOT}/samples/` |
@@ -209,6 +225,7 @@ Before the orchestrator fans out to builders in Phase 5, it should verify:
- [ ] Every page in `## Pages` has a matching `### [Page Name]` subsection in `## Per-Page Specifications`
- [ ] If `## Pages` contains Dataverse entities, `## Existing Entities` is non-empty OR `## Entity Creation Required` is non-empty
- [ ] Every non-empty `## Connector Bindings` logical name matches an existing `connectionreference` in the selected environment
+- [ ] Every non-empty `## Custom API Bindings` name matches an existing `customapi` (uniquename) in the selected environment; entity-bound rows carry the bound table and every row its parameter kinds
- [ ] Every tabular connector binding records discovered `Fields`; generated connector row interfaces must mark every field optional
- [ ] Every REST/action connector binding records discovered `Parameters` and `Response`; generated request/response interfaces must be built from those schemas only
diff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.md
index 37f351dc9..28448da41 100644
--- a/plugins/model-apps/references/rules.md
+++ b/plugins/model-apps/references/rules.md
@@ -602,6 +602,19 @@ Platform connectors via `queryConnectorTable` (tabular) and
presence-check before calling. See [connectors.md](./connectors.md) for the
required patterns and the binding contract.
+### Custom API DataAPI (optional — only when the plan has Custom API Bindings)
+
+When the plan's `## Custom API Bindings` is non-empty, the page may invoke Dataverse
+**Custom APIs** (server-side plug-in logic) on the signed-in user's own token. A Custom
+API of kind **Action** (may mutate) is called with `dataApi.executeAction`; a **Function**
+(read-only) with `dataApi.executeFunction`; `dataApi.listBoundActions` enumerates the
+page's bound operations. These are optional runtime methods — always presence-check before
+calling, guard Actions against double-submit, read results from `res.outputs` (never
+`res.value`), surface only the sanitized `res.error?.message`, and never auto-retry an
+`indeterminate` result. Call only the `name`s in the plan's `## Custom API Bindings`; a name
+not bound to the page fails with `not_bound`. See [custom-api.md](./custom-api.md) for the
+required patterns, the `boundTo` rules, and the full `error.code` contract.
+
---
## DataAPI Usage Examples
diff --git a/plugins/model-apps/references/troubleshooting.md b/plugins/model-apps/references/troubleshooting.md
index c7e42a8ce..e9df3c1b6 100644
--- a/plugins/model-apps/references/troubleshooting.md
+++ b/plugins/model-apps/references/troubleshooting.md
@@ -20,7 +20,7 @@ This plugin creates **pages within existing** model-driven apps — it cannot cr
- Install: `dotnet tool install --global Microsoft.PowerApps.CLI.Tool`
- Update: `dotnet tool update --global Microsoft.PowerApps.CLI.Tool`
- Or download from the [Microsoft Power Platform CLI](https://learn.microsoft.com/en-us/power-platform/developer/cli/introduction) page
-- Verify: `pac help` (version must be >= 2.7.0)
+- Verify: `pac help` (version must be > 2.10.0)
---
diff --git a/plugins/model-apps/samples/13-custom-api-invocation.tsx b/plugins/model-apps/samples/13-custom-api-invocation.tsx
new file mode 100644
index 000000000..81793da77
--- /dev/null
+++ b/plugins/model-apps/samples/13-custom-api-invocation.tsx
@@ -0,0 +1,235 @@
+import { useEffect, useState } from 'react';
+import type { GeneratedComponentProps } from './RuntimeTypes';
+import {
+ makeStyles,
+ tokens,
+ Text,
+ Spinner,
+ Button,
+ Card,
+ Field,
+ Textarea,
+ MessageBar,
+ MessageBarBody,
+} from '@fluentui/react-components';
+
+// Sample: Dataverse Custom API (plug-in) invocation from a form-embedded page.
+// Demonstrates (see references/custom-api.md — gated behind the `custom-api` feature flag):
+// - Presence-checking optional dataApi methods before wiring a trigger (cast to an
+// optional action-method shape; the methods are absent on older runtimes)
+// - A read-only FUNCTION on mount (executeFunction) — no double-submit guard needed
+// - An entity-bound ACTION (executeAction) with boundTo derived from pageInput, and a
+// double-submit guard so a mutating call can't fire twice
+// - Result handling per the contract: read res.outputs (never res.value), surface only the
+// sanitized res.error.message, and NEVER auto-retry an indeterminate result
+// - Only `network` is safely retryable (the request never left the client)
+// Custom API names, parameters, and output fields come from the plan's `## Custom API
+// Bindings` — never guessed. Here: new_GetOrderSummary (Function) + new_ApproveOrder (Action,
+// bound to salesorder).
+
+// Optional runtime methods — not part of the generated dataApi type, so declare the shape and
+// presence-check before every call.
+type ActionResult = {
+ ok: boolean;
+ indeterminate?: boolean;
+ outputs?: Record<string, unknown>;
+ error?: { message: string; code?: string };
+};
+type CustomApiDataApi = {
+ executeAction?: (request: {
+ name: string;
+ parameters?: Record<string, unknown>;
+ boundTo?: { entityName: string; id: string };
+ }) => Promise<ActionResult>;
+ executeFunction?: (request: {
+ name: string;
+ parameters?: Record<string, unknown>;
+ }) => Promise<ActionResult>;
+};
+
+type OrderSummary = { Total: number; Status: string };
+
+const useStyles = makeStyles({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalL,
+ padding: tokens.spacingHorizontalXL,
+ width: '100%',
+ boxSizing: 'border-box',
+ },
+ card: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalM,
+ padding: tokens.spacingHorizontalL,
+ },
+ summaryGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'minmax(120px, max-content) 1fr',
+ rowGap: tokens.spacingVerticalS,
+ columnGap: tokens.spacingHorizontalL,
+ },
+ label: {
+ color: tokens.colorNeutralForeground2,
+ fontWeight: tokens.fontWeightSemibold,
+ },
+ actions: {
+ display: 'flex',
+ gap: tokens.spacingHorizontalM,
+ alignItems: 'center',
+ },
+ spinnerWrap: {
+ display: 'flex',
+ justifyContent: 'center',
+ padding: tokens.spacingVerticalXXL,
+ },
+});
+
+const GeneratedComponent = (props: GeneratedComponentProps) => {
+ const { dataApi, pageInput } = props;
+ const styles = useStyles();
+
+ // The page is embedded on a Dataverse form, so pageInput carries the record the bound
+ // Action must target. Derive synchronously from props (no useState — state init re-renders).
+ const entityName = pageInput?.entityName;
+ const recordId = pageInput?.recordId;
+
+ // Cast once to the optional action-method shape and presence-check each method before use.
+ const actionApi = dataApi as unknown as CustomApiDataApi;
+ const canReadSummary = typeof actionApi.executeFunction === 'function';
+ const canApprove = typeof actionApi.executeAction === 'function';
+
+ const [summary, setSummary] = useState<OrderSummary | null>(null);
+ const [loadingSummary, setLoadingSummary] = useState<boolean>(canReadSummary);
+ const [summaryError, setSummaryError] = useState<string | null>(null);
+
+ const [reason, setReason] = useState<string>('');
+ const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
+ const [approveMessage, setApproveMessage] = useState<{ intent: 'success' | 'warning' | 'error'; text: string } | null>(null);
+ const [canRetry, setCanRetry] = useState<boolean>(false);
+
+ // FUNCTION: read-only, safe to run on mount and whenever the record changes. No double-submit
+ // guard — a function never mutates. Ignore a stale response instead of blocking concurrent reads.
+ useEffect(() => {
+ if (!canReadSummary || !recordId) {
+ setSummary(null);
+ setLoadingSummary(false);
+ return;
+ }
+ let cancelled = false;
+ setLoadingSummary(true);
+ setSummaryError(null);
+ (async () => {
+ const res = await actionApi.executeFunction!({
+ name: 'new_GetOrderSummary',
+ parameters: { OrderId: recordId }, // GUID-formatted string, matching the declared kind
+ });
+ if (cancelled) return;
+ if (!res.ok) {
+ setSummaryError(res.error?.message ?? 'Could not load the order summary.'); // sanitized only
+ setLoadingSummary(false);
+ return;
+ }
+ const { Total, Status } = res.outputs as OrderSummary; // read from outputs, never `value`
+ setSummary({ Total, Status });
+ setLoadingSummary(false);
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [actionApi, canReadSummary, recordId]);
+
+ // ACTION: may mutate, so guard against double-submit and require boundTo (this operation is
+ // bound to `salesorder`; its entityName must match the record the page is on).
+ const approve = async () => {
+ if (!canApprove || isSubmitting || !entityName || !recordId) return;
+ setIsSubmitting(true);
+ setApproveMessage(null);
+ setCanRetry(false);
+ try {
+ const res = await actionApi.executeAction!({
+ name: 'new_ApproveOrder',
+ parameters: { Comment: reason },
+ boundTo: { entityName, id: recordId },
+ });
+ if (res.indeterminate) {
+ // Never auto-retry — the server may have committed it. Ask the user to refresh.
+ setApproveMessage({ intent: 'warning', text: "We couldn't confirm the approval completed — refresh before retrying." });
+ return;
+ }
+ if (!res.ok) {
+ setApproveMessage({ intent: 'error', text: res.error?.message ?? 'The approval failed.' });
+ // Only a `network` failure is safely retryable: the request never left the client.
+ setCanRetry(res.error?.code === 'network');
+ return;
+ }
+ const { NewStatus } = res.outputs as { NewStatus: string };
+ setApproveMessage({ intent: 'success', text: `Order approved. New status: ${NewStatus}.` });
+ } finally {
+ setIsSubmitting(false); // never leave the button stuck disabled
+ }
+ };
+
+ if (entityName !== 'salesorder' || !recordId) {
+ return (
+ <div className={styles.root}>
+ <Text>Open this page from a sales order form to manage its approval.</Text>
+ </div>
+ );
+ }
+
+ return (
+ <div className={styles.root}>
+ <Card className={styles.card}>
+ <Text as="h2" size={600} weight="semibold">Order summary</Text>
+ {loadingSummary ? (
+ <div className={styles.spinnerWrap}>
+ <Spinner labelPosition="below" label="Loading summary…" />
+ </div>
+ ) : summaryError ? (
+ <MessageBar intent="error"><MessageBarBody>{summaryError}</MessageBarBody></MessageBar>
+ ) : summary ? (
+ <div className={styles.summaryGrid}>
+ <Text className={styles.label}>Total</Text>
+ <Text>{summary.Total}</Text>
+ <Text className={styles.label}>Status</Text>
+ <Text>{summary.Status}</Text>
+ </div>
+ ) : (
+ <Text>Order summary is unavailable on this runtime.</Text>
+ )}
+ </Card>
+
+ <Card className={styles.card}>
+ <Text as="h2" size={600} weight="semibold">Approve order</Text>
+ {approveMessage && (
+ <MessageBar intent={approveMessage.intent}>
+ <MessageBarBody>{approveMessage.text}</MessageBarBody>
+ </MessageBar>
+ )}
+ <Field label="Approval note">
+ <Textarea
+ value={reason}
+ onChange={(_e, d) => setReason(d.value)}
+ disabled={!canApprove || isSubmitting}
+ placeholder="Optional note recorded with the approval"
+ />
+ </Field>
+ <div className={styles.actions}>
+ <Button appearance="primary" onClick={approve} disabled={!canApprove || isSubmitting}>
+ {isSubmitting ? 'Approving…' : 'Approve order'}
+ </Button>
+ {canRetry && (
+ <Button appearance="secondary" onClick={approve} disabled={isSubmitting}>
+ Try again
+ </Button>
+ )}
+ {!canApprove && <Text>Approval isn't available on this runtime.</Text>}
+ </div>
+ </Card>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
diff --git a/plugins/model-apps/scripts/lib/feature-flags.js b/plugins/model-apps/scripts/lib/feature-flags.js
index 5ae02cd9e..7d183a21d 100644
--- a/plugins/model-apps/scripts/lib/feature-flags.js
+++ b/plugins/model-apps/scripts/lib/feature-flags.js
@@ -83,6 +83,10 @@ function isConnectorsEnabled(opts) {
return isEnabled('connectors', opts);
}
+function isCustomApiEnabled(opts) {
+ return isEnabled('custom-api', opts);
+}
+
// Catalog of every flag the skill knows about, with lifecycle status so makers
// and devs can see what is experimental / in-progress vs GA. `status` is one of
// 'experimental' | 'in-progress' | 'ga'. Keep this the single source of truth —
@@ -99,6 +103,19 @@ const FLAGS = {
'control (power-platform-ux), and the maker/admin ECS setting — all live in PROD.',
enableEnv: 'GENPAGE_ENABLE_CONNECTORS=1',
},
+ 'custom-api': {
+ status: 'in-progress',
+ summary:
+ 'GenPage Dataverse Custom API (plug-in) invocation — calling a Custom API Action or Function ' +
+ 'from a generated page via dataApi.executeAction / executeFunction / listBoundActions, gated by ' +
+ "the page's revision-bound actionBindings manifest.",
+ dependencies:
+ 'the AIBuilder CoderAgent action prompt, the shared pai-gen-ux-action-runtime plus the UCI ' +
+ 'and Controls host runtimes, a pac CLI `model genpage upload --actions` verb ' +
+ '(PowerPlatform-Scale-AdminTools) to persist actionBindings into config.json, and the ' +
+ 'GenUxPluginActionAllowList ECS setting — all live in PROD.',
+ enableEnv: 'GENPAGE_ENABLE_CUSTOM_API=1',
+ },
};
// Flag names the skill knows about, derived from the catalog. Used to validate the
@@ -121,6 +138,19 @@ function exitIfConnectorsDisabled(opts = {}) {
return undefined;
}
+// Fail-closed gate shared by every Custom API (Dataverse Action/Function) script entry
+// point. Mirrors exitIfConnectorsDisabled so both features gate the same way: exit 3 =
+// "feature off" (distinct from 1 = runtime/usage error). `exit`/`write` are injectable for tests.
+function exitIfCustomApiDisabled(opts = {}) {
+ const exit = opts.exit || process.exit;
+ const write = opts.write || ((s) => process.stderr.write(s));
+ if (!isCustomApiEnabled(opts)) {
+ write(customApiDisabledMessage() + '\n');
+ return exit(3);
+ }
+ return undefined;
+}
+
// Returns the effective state of every known flag plus where the value came from
// (env override / committed file / default). Powers the `--list` command and any
// observability that wants to record the gate decision in a workflow log.
@@ -167,11 +197,28 @@ function connectorsDisabledMessage() {
);
}
+// Standard operator-facing message printed when a Custom API entrypoint is invoked while
+// the flag is OFF. Centralized (mirrors connectorsDisabledMessage) so every Custom API
+// script speaks with one voice about why it stopped and how to turn the feature on.
+function customApiDisabledMessage() {
+ return (
+ 'Dataverse Custom API support is disabled (feature flag "custom-api" is OFF). ' +
+ 'GenPage Custom API invocation requires the AIBuilder action prompt, the shared action ' +
+ 'runtime, the UCI and Controls host runtimes, a pac CLI `model genpage upload --actions` ' +
+ 'verb, and the GenUxPluginActionAllowList setting to all be live in PROD. To enable for a ' +
+ 'single run set GENPAGE_ENABLE_CUSTOM_API=1, or flip "custom-api" to true in ' +
+ 'plugins/model-apps/feature-flags.json once the dependencies are released.'
+ );
+}
+
module.exports = {
isEnabled,
isConnectorsEnabled,
+ isCustomApiEnabled,
connectorsDisabledMessage,
+ customApiDisabledMessage,
exitIfConnectorsDisabled,
+ exitIfCustomApiDisabled,
describe,
validateFlags,
envVarName,
diff --git a/plugins/model-apps/scripts/list-custom-apis.js b/plugins/model-apps/scripts/list-custom-apis.js
new file mode 100644
index 000000000..03aec480b
--- /dev/null
+++ b/plugins/model-apps/scripts/list-custom-apis.js
@@ -0,0 +1,189 @@
+#!/usr/bin/env node
+
+// Lists the Dataverse Custom APIs a GenPage can bind to — Global ones plus those bound to the
+// page's table(s) — with each API's declared request-parameter kinds. The genpage-customapi-builder
+// agent turns this into actions.json entries ({ name, isFunction, boundEntityLogicalName?,
+// displayName, parameterKinds }) that pac persists into the page config.json under `actionBindings`.
+//
+// Unlike connectors (whose metadata lives outside Dataverse and needs pac verbs), Custom API metadata
+// IS in ordinary Dataverse tables, so discovery is a plain Web API query — no new pac verb needed.
+// customapi — the API definitions (uniquename, isfunction, bindingtype, bound entity)
+// customapirequestparameter — each API's request parameters and their declared `type` (pulled inline
+// via $expand so discovery stays a single request — see main())
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/custom-api
+//
+// Usage:
+// node list-custom-apis.js <envUrl> [--entities <logicalName1,logicalName2>]
+// --entities Restrict entity-bound results to these table logical names (the page's tables).
+// When omitted, ONLY Global APIs are returned (a page that needs entity-bound
+// operations knows its own table(s) and passes them here); this keeps the result set
+// and the follow-up parameter query bounded.
+//
+// Output:
+// { "ok": true, "customApis": [ { name, displayName, isFunction, bindingType,
+// boundEntityLogicalName?, parameterKinds } ] }
+
+const {
+ dataverseRequest,
+ ensureOk,
+ parseArgs,
+ emitResult,
+} = require('./lib/dataverse-auth');
+const { exitIfCustomApiDisabled } = require('./lib/feature-flags');
+
+// customapi.bindingtype is a Dataverse option set. Only the value→meaning mapping matters here;
+// a page invokes a record-bound API via boundTo, so we surface Entity as bound and Global as unbound.
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/customapi
+const BINDING_TYPE = { 0: 'Global', 1: 'Entity', 2: 'EntityCollection' };
+
+// customapirequestparameter.type is a Dataverse option set whose integer values map to the runtime's
+// DataverseParameterKind strings. The runtime reads these from the page manifest (`parameterKinds`)
+// and has no other source, so record them exactly — an Integer mis-recorded as Decimal (or a Guid as
+// String) changes how the value is serialized on the wire.
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/customapirequestparameter
+const PARAMETER_KIND_BY_TYPE = {
+ 0: 'Boolean',
+ 1: 'DateTime',
+ 2: 'Decimal',
+ 3: 'Entity',
+ 4: 'EntityCollection',
+ 5: 'EntityReference',
+ 6: 'Float',
+ 7: 'Integer',
+ 8: 'Money',
+ 9: 'Picklist',
+ 10: 'String',
+ 11: 'StringArray',
+ 12: 'Guid',
+};
+
+function bindingTypeLabel(bindingtype) {
+ return BINDING_TYPE[bindingtype] || 'Global';
+}
+
+function mapParameterKind(typeValue) {
+ // Unknown/absent type values are dropped rather than guessed: recording a wrong kind is worse than
+ // recording none (the runtime then infers the OData type from the JS value at call time).
+ return PARAMETER_KIND_BY_TYPE[typeValue];
+}
+
+function escapeODataString(value) {
+ // OData string literals escape a single quote by doubling it, e.g. O'Brien -> 'O''Brien'.
+ return String(value).replace(/'/g, "''");
+}
+
+// Builds the $filter for the customapi query: every Global API (bindingtype 0), plus the entity-bound
+// APIs for the page's tables when `entities` is non-empty. When NO tables are supplied, return ONLY
+// Global APIs — returning every entity-bound API in the environment can explode the result set (and
+// make the follow-up request-parameter query URL, an OR of per-API ids, too long). A page that wants
+// entity-bound operations always knows its own table(s) and passes them via --entities.
+function buildCustomApiFilter(entities) {
+ const list = (entities || []).map((e) => String(e).trim()).filter(Boolean);
+ if (list.length === 0) {
+ // No page tables supplied: Global only (see above). This matches the genpage-customapi-builder
+ // contract — omit --entities for a mock/global-only page.
+ return 'bindingtype eq 0';
+ }
+ const bound = list
+ .map((e) => `boundentitylogicalname eq '${escapeODataString(e)}'`)
+ .join(' or ');
+ return `bindingtype eq 0 or (${bound})`;
+}
+
+// Maps one API's request-parameter rows (returned inline via $expand of CustomAPIRequestParameters)
+// into { [paramName]: DataverseParameterKind }, dropping any whose declared type is unknown (see
+// mapParameterKind). Because the rows arrive nested under their parent API there is no parent id to
+// group on — unlike the flat cross-API query this replaced.
+function parameterKindsFromRows(rows) {
+ const kinds = {};
+ for (const row of rows || []) {
+ const name = row.uniquename;
+ const kind = mapParameterKind(row.type);
+ if (!name || !kind) continue;
+ kinds[name] = kind;
+ }
+ return kinds;
+}
+
+// Projects one customapi row (+ its parameter kinds) into the discovery shape the builder writes to
+// actions.json. `boundEntityLogicalName` is included only for a truly entity-bound API with a table.
+function toCustomApiEntry(api, parameterKinds) {
+ const bindingType = bindingTypeLabel(api.bindingtype);
+ const entry = {
+ name: api.uniquename,
+ displayName: api.displayname || api.name || api.uniquename,
+ isFunction: Boolean(api.isfunction),
+ bindingType,
+ parameterKinds: parameterKinds || {},
+ };
+ if (bindingType !== 'Global' && api.boundentitylogicalname) {
+ entry.boundEntityLogicalName = api.boundentitylogicalname;
+ }
+ return entry;
+}
+
+async function main() {
+ // Feature gate first (fail closed) — see lib/feature-flags.js. Exit 3 = "feature off", distinct
+ // from 1 = runtime/usage error, so a caller can tell "not released" from "it broke".
+ exitIfCustomApiDisabled();
+
+ const { positional, flags } = parseArgs(process.argv.slice(2));
+ if (positional.length < 1) {
+ process.stderr.write('Usage: node list-custom-apis.js <envUrl> [--entities <logicalName1,logicalName2>]\n');
+ process.exit(1);
+ }
+ const [envUrl] = positional;
+ const entities = (flags.entities || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+
+ try {
+ const filter = encodeURIComponent(buildCustomApiFilter(entities));
+ // Pull each API's request parameters INLINE via $expand rather than issuing a second query that ORs
+ // every matched API id into one $filter. A real environment has hundreds of Global Custom APIs
+ // (system + custom — 800+ is normal), and an OR-of-ids filter over that many rows overruns the
+ // server's URL-length limit (HTTP 414). $expand keeps discovery to a single request whose URL
+ // length is independent of how many APIs match; request parameters per API are few, so the nested
+ // collection is never truncated.
+ const expand = encodeURIComponent('CustomAPIRequestParameters($select=uniquename,type,isoptional)');
+ const apisRes = await dataverseRequest(
+ envUrl,
+ 'GET',
+ 'customapis?$select=customapiid,uniquename,name,displayname,isfunction,bindingtype,boundentitylogicalname' +
+ `&$filter=${filter}&$expand=${expand}`
+ );
+ ensureOk(apisRes, 'List custom APIs');
+ const apis = (apisRes.data?.value || [])
+ .filter((a) => a.uniquename)
+ // Exclude EntityCollection-bound APIs (bindingtype 2). The generated-page runtime's boundTo is a
+ // single record ({ entityName, id }); there is no collection-bound invocation shape, so surfacing
+ // one would only let the builder emit a binding that fails. See genpage-customapi-builder.md.
+ .filter((a) => Number(a.bindingtype) !== 2);
+
+ const customApis = apis
+ .map((api) => toCustomApiEntry(api, parameterKindsFromRows(api.CustomAPIRequestParameters)))
+ .sort((a, b) => String(a.name).localeCompare(String(b.name)));
+
+ emitResult(true, { ok: true, customApis });
+ } catch (e) {
+ emitResult(false, e);
+ }
+}
+
+// Only run when invoked directly as a CLI; when required by tests, export the pure helpers so their
+// logic can be unit-tested without a live environment or side effects.
+if (require.main === module) {
+ main();
+}
+
+module.exports = {
+ BINDING_TYPE,
+ PARAMETER_KIND_BY_TYPE,
+ bindingTypeLabel,
+ mapParameterKind,
+ buildCustomApiFilter,
+ parameterKindsFromRows,
+ toCustomApiEntry,
+ escapeODataString,
+};
diff --git a/plugins/model-apps/scripts/tests/feature-flags.test.js b/plugins/model-apps/scripts/tests/feature-flags.test.js
index 07a1e52d1..fa7216db9 100644
--- a/plugins/model-apps/scripts/tests/feature-flags.test.js
+++ b/plugins/model-apps/scripts/tests/feature-flags.test.js
@@ -9,10 +9,13 @@ const libPath = path.join(__dirname, '..', 'lib', 'feature-flags.js');
const {
isEnabled,
isConnectorsEnabled,
+ isCustomApiEnabled,
connectorsDisabledMessage,
+ customApiDisabledMessage,
envVarName,
parseBool,
exitIfConnectorsDisabled,
+ exitIfCustomApiDisabled,
describe,
validateFlags,
KNOWN_FLAGS,
@@ -26,6 +29,12 @@ test('connectors flag is OFF by default (no env override)', () => {
assert.equal(isConnectorsEnabled({ env: {} }), false);
});
+test('custom-api flag is OFF by default (no env override)', () => {
+ // Same fail-closed contract as connectors: empty env falls through to the committed
+ // feature-flags.json, which ships custom-api:false until the runtime stack is GA in PROD.
+ assert.equal(isCustomApiEnabled({ env: {} }), false);
+});
+
test('unknown flags are OFF (fail-closed)', () => {
assert.equal(isEnabled('does-not-exist', { env: {} }), false);
});
@@ -83,6 +92,12 @@ test('connectorsDisabledMessage explains how to enable', () => {
assert.match(m, /feature-flags\.json/);
});
+test('customApiDisabledMessage explains how to enable', () => {
+ const m = customApiDisabledMessage();
+ assert.match(m, /GENPAGE_ENABLE_CUSTOM_API/);
+ assert.match(m, /feature-flags\.json/);
+});
+
// --- Committed config actually ships OFF ------------------------------------
test('committed feature-flags.json ships connectors: false', () => {
@@ -92,6 +107,13 @@ test('committed feature-flags.json ships connectors: false', () => {
assert.equal(json.connectors, false);
});
+test('committed feature-flags.json ships custom-api: false', () => {
+ const json = JSON.parse(
+ fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8')
+ );
+ assert.equal(json['custom-api'], false);
+});
+
// --- CLI probe (deterministic gate for the skill markdown) ------------------
test('CLI prints "disabled" and exits 1 when OFF', () => {
@@ -142,12 +164,38 @@ test('exitIfConnectorsDisabled is a no-op when ON', () => {
assert.equal(exitCalled, false);
});
+test('exitIfCustomApiDisabled exits 3 and writes the message when OFF', () => {
+ let exitCode = null;
+ let written = '';
+ exitIfCustomApiDisabled({
+ env: {},
+ exit: (c) => { exitCode = c; },
+ write: (s) => { written += s; },
+ });
+ assert.equal(exitCode, 3);
+ assert.match(written, /disabled/i);
+});
+
+test('exitIfCustomApiDisabled is a no-op when ON', () => {
+ let exitCalled = false;
+ exitIfCustomApiDisabled({
+ env: { GENPAGE_ENABLE_CUSTOM_API: '1' },
+ exit: () => { exitCalled = true; },
+ write: () => {},
+ });
+ assert.equal(exitCalled, false);
+});
+
// --- known-flag registry + describe() + validation --------------------------
test('KNOWN_FLAGS includes connectors', () => {
assert.ok(KNOWN_FLAGS.includes('connectors'));
});
+test('KNOWN_FLAGS includes custom-api', () => {
+ assert.ok(KNOWN_FLAGS.includes('custom-api'));
+});
+
test('describe reports effective state and source per known flag', () => {
const envOn = describe({ env: { GENPAGE_ENABLE_CONNECTORS: '1' }, flags: { connectors: false } });
const c1 = envOn.find((f) => f.flag === 'connectors');
@@ -180,6 +228,14 @@ test('FLAGS catalog documents connectors with a status and summary', () => {
assert.ok(FLAGS.connectors.dependencies, 'should document what it depends on');
});
+test('FLAGS catalog documents custom-api with a status and summary', () => {
+ assert.ok(FLAGS['custom-api'], 'custom-api flag should be in the catalog');
+ assert.ok(['experimental', 'in-progress', 'ga'].includes(FLAGS['custom-api'].status));
+ assert.match(FLAGS['custom-api'].summary, /custom api|action|function|plug-?in/i);
+ assert.ok(FLAGS['custom-api'].dependencies, 'should document what it depends on');
+ assert.match(FLAGS['custom-api'].enableEnv, /GENPAGE_ENABLE_CUSTOM_API/);
+});
+
test('KNOWN_FLAGS is derived from the FLAGS catalog', () => {
assert.deepEqual(KNOWN_FLAGS, Object.keys(FLAGS));
});
diff --git a/plugins/model-apps/scripts/tests/list-custom-apis.test.js b/plugins/model-apps/scripts/tests/list-custom-apis.test.js
new file mode 100644
index 000000000..be28a9b78
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/list-custom-apis.test.js
@@ -0,0 +1,132 @@
+'use strict';
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const fs = require('node:fs');
+const { spawnSync } = require('node:child_process');
+
+const scriptPath = path.join(__dirname, '..', 'list-custom-apis.js');
+const scriptSrc = fs.readFileSync(scriptPath, 'utf8');
+
+// --- Source-shape guards (cheap contract checks) ---------------------------
+
+test('queries customapi with request parameters expanded inline (no OR-of-ids param query)', () => {
+ assert.match(scriptSrc, /customapis\?\$select=customapiid,uniquename,name,displayname,isfunction,bindingtype,boundentitylogicalname/);
+ // Parameters are pulled inline via $expand of the CustomAPIRequestParameters navigation property...
+ assert.match(scriptSrc, /CustomAPIRequestParameters\(\$select=uniquename,type,isoptional\)/);
+ // ...NOT via a second query that ORs every matched API id into one $filter. That pattern overran the
+ // server's URL-length limit (HTTP 414) in real environments with hundreds of Global Custom APIs.
+ assert.doesNotMatch(scriptSrc, /_customapiid_value eq/);
+});
+
+test('gates fail-closed via exitIfCustomApiDisabled before any query', () => {
+ assert.match(scriptSrc, /exitIfCustomApiDisabled\(\)/);
+});
+
+// --- Feature gate + arg validation (spawned CLI) ---------------------------
+
+test('exits 3 with a disabled message when the custom-api flag is OFF', () => {
+ // The gate runs before any Dataverse call, so a valid-looking env URL still bails.
+ const res = spawnSync(process.execPath, [scriptPath, 'https://example.crm.dynamics.com'], {
+ encoding: 'utf8',
+ env: { ...process.env, GENPAGE_ENABLE_CUSTOM_API: '0' },
+ });
+ assert.equal(res.status, 3);
+ assert.match(res.stderr, /disabled/i);
+});
+
+test('missing args exits 1 with usage (when the flag is ON)', () => {
+ // Enable the flag so the run reaches arg validation instead of the feature gate.
+ const res = spawnSync(process.execPath, [scriptPath], {
+ encoding: 'utf8',
+ env: { ...process.env, GENPAGE_ENABLE_CUSTOM_API: '1' },
+ });
+ assert.equal(res.status, 1);
+ assert.match(res.stderr, /Usage:/);
+});
+
+// --- Unit tests for the pure helpers (require.main guard keeps main() from running) ---
+const {
+ bindingTypeLabel,
+ mapParameterKind,
+ buildCustomApiFilter,
+ parameterKindsFromRows,
+ toCustomApiEntry,
+} = require(scriptPath);
+
+test('mapParameterKind maps the customapirequestparameter Type option set to DataverseParameterKind', () => {
+ assert.equal(mapParameterKind(10), 'String');
+ assert.equal(mapParameterKind(7), 'Integer');
+ assert.equal(mapParameterKind(2), 'Decimal');
+ assert.equal(mapParameterKind(12), 'Guid');
+ assert.equal(mapParameterKind(11), 'StringArray');
+ assert.equal(mapParameterKind(5), 'EntityReference');
+ // Unknown/absent types are dropped (undefined), never guessed.
+ assert.equal(mapParameterKind(999), undefined);
+ assert.equal(mapParameterKind(undefined), undefined);
+});
+
+test('bindingTypeLabel maps the option set and defaults to Global', () => {
+ assert.equal(bindingTypeLabel(0), 'Global');
+ assert.equal(bindingTypeLabel(1), 'Entity');
+ assert.equal(bindingTypeLabel(2), 'EntityCollection');
+ assert.equal(bindingTypeLabel(undefined), 'Global');
+});
+
+test('buildCustomApiFilter includes Global plus the page tables, escaping quotes', () => {
+ // No tables → Global only (bindingtype 0), NOT every entity-bound API.
+ const none = buildCustomApiFilter([]);
+ assert.match(none, /bindingtype eq 0/);
+ assert.doesNotMatch(none, /bindingtype ne 0/);
+ assert.doesNotMatch(none, /boundentitylogicalname/);
+
+ const scoped = buildCustomApiFilter(['account', 'contact']);
+ assert.match(scoped, /bindingtype eq 0/);
+ assert.match(scoped, /boundentitylogicalname eq 'account'/);
+ assert.match(scoped, /boundentitylogicalname eq 'contact'/);
+
+ // A single quote in a table name is doubled per OData string-literal escaping.
+ const escaped = buildCustomApiFilter(["o'brien"]);
+ assert.match(escaped, /boundentitylogicalname eq 'o''brien'/);
+});
+
+test('parameterKindsFromRows maps one API\'s expanded params and drops unknown types', () => {
+ // Rows arrive inline via $expand — each element has uniquename + type, but no parent id.
+ const kinds = parameterKindsFromRows([
+ { uniquename: 'Comment', type: 10 },
+ { uniquename: 'Amount', type: 2 },
+ { uniquename: 'Mystery', type: 999 }, // unknown → dropped
+ { uniquename: null, type: 10 }, // no name → dropped
+ ]);
+ assert.deepEqual(kinds, { Comment: 'String', Amount: 'Decimal' });
+});
+
+test('parameterKindsFromRows tolerates missing/empty input', () => {
+ assert.deepEqual(parameterKindsFromRows(undefined), {});
+ assert.deepEqual(parameterKindsFromRows([]), {});
+});
+
+test('toCustomApiEntry omits boundEntityLogicalName for a Global API', () => {
+ const entry = toCustomApiEntry(
+ { uniquename: 'new_NoOp', isfunction: false, bindingtype: 0 },
+ {}
+ );
+ assert.equal(entry.name, 'new_NoOp');
+ assert.equal(entry.displayName, 'new_NoOp'); // falls back to uniquename
+ assert.equal(entry.isFunction, false);
+ assert.equal(entry.bindingType, 'Global');
+ assert.deepEqual(entry.parameterKinds, {});
+ assert.equal('boundEntityLogicalName' in entry, false);
+});
+
+test('toCustomApiEntry sets boundEntityLogicalName for an entity-bound Function and coerces isFunction', () => {
+ const entry = toCustomApiEntry(
+ { uniquename: 'new_GetOrderSummary', displayname: 'Get Order Summary', isfunction: true, bindingtype: 1, boundentitylogicalname: 'salesorder' },
+ { OrderId: 'Guid' }
+ );
+ assert.equal(entry.isFunction, true);
+ assert.equal(entry.bindingType, 'Entity');
+ assert.equal(entry.boundEntityLogicalName, 'salesorder');
+ assert.equal(entry.displayName, 'Get Order Summary');
+ assert.deepEqual(entry.parameterKinds, { OrderId: 'Guid' });
+});
diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.md
index 5eafc3f11..10119c917 100644
--- a/plugins/model-apps/skills/genpage/SKILL.md
+++ b/plugins/model-apps/skills/genpage/SKILL.md
@@ -105,7 +105,7 @@ node "${PLUGIN_ROOT}/scripts/generate-page-manifest.js" <working-dir> <kebab-slu
> NOT inline the planner's questions yourself with `AskUserQuestion`.**
>
> The planner is not optional or skippable. It runs:
-> 1. Prerequisite validation (`node --version`, `pac help` version >= 2.7.0)
+> 1. Prerequisite validation (`node --version`, `pac help` version > 2.10.0)
> 2. Auth verification (`pac auth list`, environment selection)
> 3. The structured "Create new / Edit existing" question (via `AskUserQuestion`
> inside the planner subagent, not here)
@@ -372,6 +372,34 @@ deployed page `config.json` shape that `pac` writes):
Do **not** write connection IDs into `connectors.json` — the importing maker/admin
fills env-specific `ConnectionId` values through solution deployment settings.
+
+### Phase 4.6: Custom API Bindings (Conditional)
+
+**Re-probe the feature gate here — do not rely on the plan content alone.** A plan
+authored while the flag was ON must not deploy Custom API bindings after it is turned OFF:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" custom-api
+```
+
+**If it prints `disabled`:** Custom API support is OFF. Skip this phase entirely — do not
+create or pass `actions.json`, and never add `--actions` on upload — **regardless of what the
+plan's `## Custom API Bindings` section says**. (Backstop: `list-custom-apis.js` also fails
+closed with exit 3 if invoked while OFF.)
+
+**If it prints `enabled`:** read the plan's `## Custom API Bindings` section and treat it as
+bindings **only when it contains an actual binding table** (a `| Name | Kind | …` header with
+at least one data row). If the section is `No custom API bindings.`, empty, missing, or
+malformed, treat the page as having no Custom APIs and skip this phase.
+
+When there are real bindings, the `genpage-customapi-builder` agent already wrote
+`<working-dir>/actions.json` during planning — verify it exists and matches the plan table. If
+it is missing, derive it as a **bare JSON array** of
+`{ name, isFunction, boundEntityLogicalName?, displayName, parameterKinds }` entries (Action row
+`isFunction:false`, Function `true`; `boundEntityLogicalName` only for an entity-bound, non-
+`(Global)`, row) — see `${PLUGIN_ROOT}/references/custom-api.md`. Never the
+`{ "actionBindings": [...] }` object wrapper (the deployed `config.json` shape `pac` writes).
+
### Phase 5: Build Pages (Parallel)
Read `genpage-plan.md` and extract the pages table.
@@ -400,6 +428,11 @@ subagent. Inline the page-builder workflow directly in the orchestrator:
`${PLUGIN_ROOT}/references/connectors.md`. Treat a `No connector bindings.`
sentinel, an empty/missing/malformed section, **or a `disabled` probe** as
having no connectors (same contract as Phase 4.5 and genpage-page-builder).
+3b. Only when the plan's `## Custom API Bindings` section contains an **actual
+ binding table** (a `| Name | Kind | …` header with at least one data row),
+ also read `${PLUGIN_ROOT}/references/custom-api.md`. Treat a
+ `No custom API bindings.` sentinel, or an empty/missing/malformed section, as
+ having no Custom APIs (same contract as Phase 4.6 and genpage-page-builder).
4. If the plan's Per-Page Specification has `Needs caching: true`, also read
`${PLUGIN_ROOT}/references/data-caching.md`
5. If the plan's `## Environment` indicates non-English languages, also read
@@ -490,6 +523,15 @@ Connector deployment matrix:
- **Delete all connectors:** write `[]` to `connectors.json` and pass
`--connectors` so pac clears the page's `connectorBindings`.
+If Phase 4.6 wrote `<working-dir>/actions.json`, pre-flight the same way — the upload `--help`
+must contain `--actions`; if not, stop and surface "Custom API deploy requires a pac build with
+`pac model genpage upload --actions` (PowerPlatform-Scale-AdminTools)." Don't silently drop bindings.
+
+Custom API deployment follows the **identical matrix** as connectors, substituting
+`--actions "<working-dir>/actions.json"` for `--connectors`: pass it on create; on an edit only
+when bindings changed/added/removed (full replace); omit it on an unrelated edit (pac preserves
+existing); write `[]` and pass it to clear all `actionBindings`.
+
**Copy the upload commands below exactly — `--app-id`, `--code-file`, `--prompt`, `--agent-message` are all required and must use these exact flag names.**
**Log the full command verbatim into `workflow-log.md` under a `## Phase 6 — Deploy` section before invoking it.** Including `--prompt` and all other flags. The eval harness greps the log for these tokens — a terse summary like `Command: pac model genpage upload --add-to-sitemap` will fail the `--prompt scoping` assertion. Format:
@@ -500,8 +542,8 @@ Connector deployment matrix:
- Result: page-id = <returned-id>, status = success
```
-When connector bindings are present, the logged command must also include
-`--connectors "<working-dir>/connectors.json"`.
+When present, the logged command must also include `--connectors "<working-dir>/connectors.json"`
+and/or `--actions "<working-dir>/actions.json"`.
#### `--prompt` semantics
@@ -523,13 +565,15 @@ pac model genpage upload `
--name "Page Display Name" `
--data-sources "entity1,entity2" `
--connectors "<working-dir>/connectors.json" `
+ --actions "<working-dir>/actions.json" `
--prompt "<Full page description from plan's ## User Requirements>" `
--model "<current-model-id>" `
--agent-message "Description of what was built and any relevant details" `
--add-to-sitemap
```
-Omit the `--connectors` line when Phase 4.5 did not write `connectors.json`.
+Omit the `--connectors` line when Phase 4.5 did not write `connectors.json`, and the
+`--actions` line when Phase 4.6 did not write `actions.json`.
**For mock data pages:** Same but omit `--data-sources`.
@@ -544,6 +588,7 @@ pac model genpage upload `
--code-file <working-dir>/<file>.tsx `
--data-sources "entity1,entity2" `
--connectors "<working-dir>/connectors.json" `
+ --actions "<working-dir>/actions.json" `
--prompt "<Only the changes in this upload, e.g. 'Add a search box and sort by company name'>" `
--model "<current-model-id>" `
--agent-message "Description of what was changed in this upload"
@@ -551,7 +596,8 @@ pac model genpage upload `
For updates, include the `--connectors` line only when this upload intentionally
replaces or clears connector bindings; otherwise omit it to preserve the
-deployed page's current bindings.
+deployed page's current bindings. The same rule applies to `--actions` for Custom
+API bindings: include it only when this upload intentionally replaces or clears them.
### Phase 6.5: Navigation Fix-Up (Multi-Page Only)
@@ -612,6 +658,10 @@ each `connectionreference` (10158) is added so bindings resolve. At import the
deployer supplies env-specific `ConnectionId` per connection reference via
`pac solution create-settings` + `pac solution import --settings-file`.
+Custom API bindings need **no** extra ALM step: `config.json`'s `actionBindings` travels
+automatically in the `uxagentprojectfile` (10373) rows already pulled with the GenPage. The
+referenced Custom APIs are a separate deployment prerequisite (bound by `name`), not added here.
+
### Phase 7: Verify in Browser (Optional)
After successful deployment, ask the user via `AskUserQuestion`: