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.

connector authoring + ALM for /genpage (#242)

Akshay Maloo55dd57163b79
diff --git a/evals/model-apps/genpage/evals.json b/evals/model-apps/genpage/evals.json
index 1e64908f1..30b88d56f 100644
--- a/evals/model-apps/genpage/evals.json
+++ b/evals/model-apps/genpage/evals.json
@@ -439,6 +439,54 @@
"Phase 1 (Planner): Because the account entity exists, ## Entity Creation Required contains the literal string 'No entity creation required — all entities already exist.'",
"Phase 1 (Planner): ## Existing Entities contains the entity logical name used for RuntimeTypes generation (account)"
]
+ },
+ {
+ "id": 17,
+ "tier": "smoke",
+ "prompt": "Build a dashboard showing the current weather for Seattle with temperature, conditions, and humidity.",
+ "data": {
+ "question_answers": {
+ "new_or_edit": "Create new page(s)",
+ "data_source": "Mock data",
+ "specific_requirements": "current weather panel"
+ },
+ "app_selection": "user selects an existing app from pac model list"
+ },
+ "expectations": [
+ "Phase 1 (Planner): With the connectors feature flag OFF, the feature gate (scripts/lib/feature-flags.js) is checked, connector discovery (list-connections.js) is NOT run, and the plan's ## Connector Bindings is exactly 'No connector bindings.'",
+ "Phase 2: Entity-builder is SKIPPED (mock data)",
+ "Phase 4: RuntimeTypes generation is SKIPPED (mock data)",
+ "Phase 5 (Page Builder): genpage-page-builder is invoked with Data mode: mock",
+ "Phase 5b (single-page fast path): Plan has 1 page so orchestrator inlines the build — NO Task subagent dispatched for the page-builder",
+ "Phase 5b: Orchestrator reads ${PLUGIN_ROOT}/references/verified-icons.txt before writing the .tsx",
+ "Phase 5b: A relevant sample file is read (e.g., 7-responsive-cards.tsx for card layout)",
+ "Phase 5b: After writing, orchestrator greps the .tsx for `from \"@fluentui/react-icons\"` imports and verifies each named import against verified-icons.txt — rewrites if any are missing",
+ "Phase 6: Deployment omits --data-sources flag (mock data page)"
+ ]
+ },
+ {
+ "id": 18,
+ "tier": "full",
+ "prompt": "Build a page listing documents from our SharePoint team site.",
+ "data": {
+ "question_answers": {
+ "new_or_edit": "Create new page(s)",
+ "data_source": "SharePoint (connector)",
+ "specific_requirements": "list documents"
+ },
+ "feature_flags": {
+ "connectors": "ON (GENPAGE_ENABLE_CONNECTORS=1)"
+ }
+ },
+ "expectations": [
+ "Phase 1 (Planner): With the connectors feature flag ON, the feature gate passes (enabled) and list-connections.js is run for connector discovery, and the plan's ## Connector Bindings records at least one binding (not 'No connector bindings.')",
+ "Phase 4.5 / Phase 6 (connectors ON): connectors.json is written as a bare array (not the config.json object wrapper) and the upload includes --connectors",
+ "Phase 2: Entity-builder is SKIPPED (no entities to create)",
+ "Phase 5b (single-page fast path): Plan has 1 page so orchestrator inlines the build — NO Task subagent dispatched for the page-builder",
+ "Phase 5b: Orchestrator reads ${PLUGIN_ROOT}/references/verified-icons.txt before writing the .tsx",
+ "Phase 5b: A relevant sample file is read (e.g., 7-responsive-cards.tsx for card layout)",
+ "Phase 5b: After writing, orchestrator greps the .tsx for `from \"@fluentui/react-icons\"` imports and verifies each named import against verified-icons.txt — rewrites if any are missing"
+ ]
}
]
}
diff --git a/evals/model-apps/genpage/fixtures/17-weather-connectors-off/genpage-plan.md b/evals/model-apps/genpage/fixtures/17-weather-connectors-off/genpage-plan.md
new file mode 100644
index 000000000..0df3c12c9
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/17-weather-connectors-off/genpage-plan.md
@@ -0,0 +1,66 @@
+# Genpage Plan
+
+## User Requirements
+
+Build a dashboard showing the current weather for Seattle with temperature, conditions, and humidity.
+
+## Working Directory
+
+seattle-weather-dashboard/
+
+## Plugin Root
+
+D:\Projects\power-platform-skills\plugins\model-apps
+
+## Environment
+
+- Active Profile: [email protected]
+- Environment URL: https://contoso-dev.crm10.dynamics.com/
+- App: Operations Hub (aa112233-1122-1122-1122-aabbccdd1234)
+- Solution: Default
+- Publisher Prefix: new
+
+## Pages
+
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| Seattle Weather | weather-dashboard.tsx | Weather dashboard showing temperature, conditions, and humidity with 5-day forecast | (mock data) |
+
+## Entity Creation Required
+
+No entity creation required — all entities already exist.
+
+## Existing Entities
+
+(none — mock data page)
+
+## Connector Bindings
+
+No connector bindings.
+
+## Design Preferences
+
+- Inline mock weather data (connectors feature flag OFF — connector not available at this time)
+- KPI-style metric cards for temperature, conditions, humidity
+- 5-day forecast card row below current conditions
+- Responsive flex layout (no 100vh / 100vw)
+- Icons: TemperatureRegular, WeatherSunnyRegular, WaterRegular (unsized, from verified-icons.txt)
+
+## Relevant Samples
+
+| Page | Sample | Reason |
+|------|--------|--------|
+| Seattle Weather | 8-dashboard-with-charts.tsx | KPI card + metric display pattern |
+
+## Per-Page Specifications
+
+### Seattle Weather
+
+- **File:** weather-dashboard.tsx
+- **Data:** inline mock arrays — `weeklyForecast` (5 records) + `currentConditions` object
+- **Components:**
+ - Three metric cards: temperature (with feels-like), sky conditions, humidity
+ - 5-day forecast card row (selectable for detail)
+ - Mock data banner noting connector support is coming
+- **Icons:** TemperatureRegular, WeatherSunnyRegular, WaterRegular (all unsized, from verified-icons.txt)
+- **Styling:** makeStyles with tokens; no inline styles for static values; no 100vh/100vw
diff --git a/evals/model-apps/genpage/fixtures/17-weather-connectors-off/weather-dashboard.tsx b/evals/model-apps/genpage/fixtures/17-weather-connectors-off/weather-dashboard.tsx
new file mode 100644
index 000000000..a470bc443
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/17-weather-connectors-off/weather-dashboard.tsx
@@ -0,0 +1,210 @@
+import { useState } from 'react';
+import {
+ makeStyles,
+ mergeClasses,
+ tokens,
+ Text,
+ Card,
+ CardHeader,
+ Badge,
+} from '@fluentui/react-components';
+import {
+ TemperatureRegular,
+ WeatherSunnyRegular,
+ WaterRegular,
+} from '@fluentui/react-icons';
+
+// Mock weather data for Seattle — the MSN Weather connector is gated behind the
+// connectors feature flag (currently OFF), so this page uses inline mock data.
+
+interface WeatherRecord {
+ date: string;
+ tempHigh: number;
+ tempLow: number;
+ conditions: string;
+ humidity: number;
+}
+
+const weeklyForecast: WeatherRecord[] = [
+ { date: 'Mon', tempHigh: 58, tempLow: 45, conditions: 'Partly Cloudy', humidity: 72 },
+ { date: 'Tue', tempHigh: 54, tempLow: 43, conditions: 'Rainy', humidity: 88 },
+ { date: 'Wed', tempHigh: 62, tempLow: 48, conditions: 'Partly Sunny', humidity: 65 },
+ { date: 'Thu', tempHigh: 65, tempLow: 50, conditions: 'Sunny', humidity: 58 },
+ { date: 'Fri', tempHigh: 60, tempLow: 47, conditions: 'Cloudy', humidity: 75 },
+];
+
+const currentConditions = {
+ temperature: 58,
+ feelsLike: 54,
+ conditions: 'Partly Cloudy',
+ humidity: 72,
+ location: 'Seattle, WA',
+};
+
+const useStyles = makeStyles({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalL,
+ padding: tokens.spacingHorizontalXL,
+ width: '100%',
+ boxSizing: 'border-box',
+ },
+ pageTitle: { marginBottom: tokens.spacingVerticalS },
+ mockBanner: {
+ backgroundColor: tokens.colorNeutralBackground2,
+ padding: `${tokens.spacingVerticalS} ${tokens.spacingHorizontalM}`,
+ borderRadius: tokens.borderRadiusMedium,
+ color: tokens.colorNeutralForeground2,
+ fontSize: tokens.fontSizeBase200,
+ },
+ sectionHeading: { marginBottom: tokens.spacingVerticalM },
+ metricsRow: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalL,
+ },
+ metricCard: {
+ flex: '1 1 200px',
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ gap: tokens.spacingVerticalS,
+ padding: tokens.spacingHorizontalL,
+ },
+ metricValue: {
+ fontSize: tokens.fontSizeHero700,
+ fontWeight: tokens.fontWeightSemibold,
+ color: tokens.colorBrandForeground1,
+ },
+ metricLabel: {
+ color: tokens.colorNeutralForeground2,
+ fontSize: tokens.fontSizeBase300,
+ },
+ forecastRow: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalM,
+ },
+ forecastCard: {
+ flex: '1 1 100px',
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ gap: tokens.spacingVerticalXS,
+ padding: tokens.spacingHorizontalM,
+ cursor: 'pointer',
+ },
+ forecastCardSelected: {
+ backgroundColor: tokens.colorBrandBackground2,
+ },
+ forecastDay: { fontWeight: tokens.fontWeightSemibold },
+ forecastTemps: { fontSize: tokens.fontSizeBase300 },
+ forecastMeta: {
+ color: tokens.colorNeutralForeground2,
+ fontSize: tokens.fontSizeBase200,
+ textAlign: 'center',
+ },
+ detailBar: {
+ backgroundColor: tokens.colorNeutralBackground2,
+ padding: `${tokens.spacingVerticalS} ${tokens.spacingHorizontalM}`,
+ borderRadius: tokens.borderRadiusMedium,
+ color: tokens.colorNeutralForeground3,
+ fontSize: tokens.fontSizeBase200,
+ },
+});
+
+const MetricCard = (props: {
+ icon: React.ReactNode;
+ label: string;
+ value: string;
+ subLabel?: string;
+}) => {
+ const styles = useStyles();
+ return (
+ <Card className={styles.metricCard} aria-label={`${props.label}: ${props.value}`}>
+ <CardHeader
+ image={props.icon}
+ header={<Text className={styles.metricLabel}>{props.label}</Text>}
+ />
+ <Text className={styles.metricValue}>{props.value}</Text>
+ {props.subLabel && <Badge appearance="outline">{props.subLabel}</Badge>}
+ </Card>
+ );
+};
+
+const GeneratedComponent = (props: { dataApi?: unknown; pageInput?: { data?: Record<string, unknown> } }) => {
+ const { pageInput } = props;
+ // pageInput is destructured per rules but unused in this mock dashboard.
+ void pageInput;
+ const styles = useStyles();
+ const [selectedDay, setSelectedDay] = useState<string>('Mon');
+
+ const selectedForecast = weeklyForecast.find((d) => d.date === selectedDay) ?? weeklyForecast[0];
+
+ return (
+ <div className={styles.root}>
+ <Text as="h1" size={700} weight="semibold" className={styles.pageTitle}>
+ Seattle Weather Dashboard
+ </Text>
+
+ <div className={styles.mockBanner} role="note">
+ Displaying mock weather data — live connector support is coming soon
+ </div>
+
+ <section aria-label="Current conditions">
+ <Text as="h2" size={500} weight="semibold" className={styles.sectionHeading}>
+ Current Conditions — {currentConditions.location}
+ </Text>
+ <div className={styles.metricsRow}>
+ <MetricCard
+ icon={<TemperatureRegular aria-hidden="true" />}
+ label="Temperature"
+ value={`${currentConditions.temperature}°F`}
+ subLabel={`Feels like ${currentConditions.feelsLike}°F`}
+ />
+ <MetricCard
+ icon={<WeatherSunnyRegular aria-hidden="true" />}
+ label="Sky Conditions"
+ value={currentConditions.conditions}
+ />
+ <MetricCard
+ icon={<WaterRegular aria-hidden="true" />}
+ label="Humidity"
+ value={`${currentConditions.humidity}%`}
+ />
+ </div>
+ </section>
+
+ <section aria-label="5-day forecast">
+ <Text as="h2" size={500} weight="semibold" className={styles.sectionHeading}>
+ 5-Day Forecast
+ </Text>
+ <div className={styles.forecastRow}>
+ {weeklyForecast.map((day) => (
+ <Card
+ key={day.date}
+ className={mergeClasses(
+ styles.forecastCard,
+ selectedDay === day.date && styles.forecastCardSelected
+ )}
+ onClick={() => setSelectedDay(day.date)}
+ aria-label={`${day.date}: ${day.conditions}, high ${day.tempHigh}°F, low ${day.tempLow}°F, humidity ${day.humidity}%`}
+ >
+ <Text className={styles.forecastDay}>{day.date}</Text>
+ <Text className={styles.forecastTemps}>{day.tempHigh}° / {day.tempLow}°</Text>
+ <Text className={styles.forecastMeta}>{day.conditions}</Text>
+ </Card>
+ ))}
+ </div>
+ {selectedForecast && (
+ <Text className={styles.detailBar} aria-live="polite">
+ {selectedForecast.date}: High {selectedForecast.tempHigh}°F · Low {selectedForecast.tempLow}°F · Humidity {selectedForecast.humidity}%
+ </Text>
+ )}
+ </section>
+ </div>
+ );
+};
+
+export default GeneratedComponent;
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
new file mode 100644
index 000000000..be40da0d9
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/17-weather-connectors-off/workflow-log.md
@@ -0,0 +1,71 @@
+# Workflow Log — Eval 17: Seattle Weather Dashboard (connectors feature flag OFF)
+
+## Phase 0 — Working directory setup
+- Working directory created: `seattle-weather-dashboard/` (kebab-case derived from "current weather for Seattle")
+- Plugin root: `D:\Projects\power-platform-skills\plugins\model-apps`
+
+## Phase 1 — Planner (genpage-planner agent invoked via Task)
+
+### Prereq checks
+- `node --version` → v20.11.0
+- `pac help` → PAC CLI Version 2.8.2 (>= 2.7.0 verified)
+- (Commands run separately, not chained with &&)
+
+### Auth check
+- `pac auth list` → active profile `[email protected]`
+- Active environment: https://contoso-dev.crm10.dynamics.com/ (reported to user)
+
+### Discovery questions (AskUserQuestion)
+- Question 1 (new or edit): user answered "Create new page(s)"
+- Question 2 (data source): user answered "Mock data"
+- Question 3 (specific requirements): "current weather panel"
+- Question 4 (app selection): user selected existing app from pac model list: "Operations Hub"
+
+### Connector Detection (delegated to genpage-connector-builder)
+- Request implies external weather data (MSN Weather connector) → planner delegates all connector work to the `genpage-connector-builder` agent (mode: create) via the Task tool
+- genpage-connector-builder probes the gate FIRST: `node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" connectors` → `disabled` (exit 1)
+- Connectors feature flag OFF: connector discovery SKIPPED; list-connections.js NOT run
+- Agent wrote `connector-bindings.md` = `No connector bindings.` and `connectors.json` = `[]`
+- Page falls back to inline mock weather data for Seattle
+
+### Solution selection
+- Build is code-only (mock data, no new entities, no new app) → solution selection question SKIPPED
+- Default values written to plan: `Solution: Default`, `Publisher Prefix: new`
+
+### Plan presented
+- EnterPlanMode called with plan summary: single mock weather dashboard page for Seattle (temperature card, conditions card, humidity card, 5-day forecast)
+- User approved plan
+
+### Plan written
+- genpage-plan.md written to seattle-weather-dashboard/genpage-plan.md
+- Conforms to references/plan-schema.md (## User Requirements, ## Working Directory, ## Plugin Root, ## Environment, ## Pages, ## Entity Creation Required, ## Existing Entities, ## Connector Bindings, ## Design Preferences, ## Relevant Samples, ## Per-Page Specifications)
+
+## Phase 2 — Entity creation
+- SKIPPED (mock data — no entities needed)
+- check-auth.js not run (no entity work)
+- genpage-entity-builder not invoked
+
+## Phase 3 — App creation
+- SKIPPED (existing app "Operations Hub" selected)
+
+## Phase 4 — Schema generation
+- SKIPPED (mock data — no RuntimeTypes needed)
+- pac model genpage generate-types not run (mock data)
+
+## Phase 5b — Single-page fast path
+- Plan has 1 page → fast path taken (inlined build, no Task subagent dispatched for page-builder)
+- Data mode: mock
+- Read sample: plugins/model-apps/samples/8-dashboard-with-charts.tsx (KPI card + metric display pattern)
+- Read references/verified-icons.txt to source icon names
+- Wrote weather-dashboard.tsx
+- Post-write icon verification: grep `from "@fluentui/react-icons"` in weather-dashboard.tsx; verified `TemperatureRegular`, `WeatherSunnyRegular`, `WaterRegular` against verified-icons.txt — all present
+
+## Phase 6 — Deployment
+- `pac model genpage upload --app-id aa112233-1122-1122-1122-aabbccdd1234 --code-file seattle-weather-dashboard/weather-dashboard.tsx --prompt "Build a dashboard showing the current weather for Seattle with temperature, conditions, and humidity." --model claude-sonnet --name "Seattle Weather" --agent-message "Weather dashboard with temperature, conditions, and humidity" --add-to-sitemap`
+- (--data-sources omitted — mock-data page)
+- Upload succeeded
+
+## Phase 8 — Summary
+- 1 page deployed: weather-dashboard.tsx → "Seattle Weather" in Operations Hub app
+- No entities created
+- No connector bindings (connectors flag OFF — mock data used)
diff --git a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/genpage-plan.md b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/genpage-plan.md
new file mode 100644
index 000000000..0ecef9779
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/genpage-plan.md
@@ -0,0 +1,73 @@
+# Genpage Plan
+
+## User Requirements
+
+Build a page listing documents from our SharePoint team site.
+
+## Working Directory
+
+sharepoint-team-docs/
+
+## Plugin Root
+
+D:\Projects\power-platform-skills\plugins\model-apps
+
+## Environment
+
+- Active Profile: [email protected]
+- Environment URL: https://contoso-dev.crm10.dynamics.com/
+- App: Operations Hub (aa112233-1122-1122-1122-aabbccdd1234)
+- Solution: Default
+- Publisher Prefix: new
+
+## Pages
+
+| Page | File | Purpose | Entities |
+|------|------|---------|----------|
+| SharePoint Documents | sharepoint-docs.tsx | Lists documents from SharePoint team site via connector binding | (connector: new_uxtest_sharepoint) |
+
+## Entity Creation Required
+
+No entity creation required — all entities already exist.
+
+## Existing Entities
+
+(none — connector-only page)
+
+## Connector Bindings
+
+| Logical Name | Connector Id | Dataset | Tables (GUIDs) | Table Display Names | Operations | Fields | Parameters | Response |
+|--------------|--------------|---------|----------------|---------------------|------------|--------|------------|----------|
+| new_uxtest_sharepoint | /providers/Microsoft.PowerApps/apis/shared_sharepointonline | https://contoso.sharepoint.com/sites/team | 5709dd6f-c73e-4079-ad23-2334e45e0e13 | Documents | | ID (number), Title (string), Author (string), FileType ({Value:string}), Created (string), Modified (string) | | |
+
+## Design Preferences
+
+- Clean card list layout for document browsing
+- Document icon, title, author, file type badge, and modified date per row
+- Search input to filter by title
+- Responsive flex layout (no 100vh / 100vw)
+- Graceful loading spinner and error/fallback state
+- Icons: DocumentRegular, OpenRegular (unsized, from verified-icons.txt)
+
+## Relevant Samples
+
+| Page | Sample | Reason |
+|------|--------|--------|
+| SharePoint Documents | 7-responsive-cards.tsx | Card list layout for displaying items with metadata |
+
+## Per-Page Specifications
+
+### SharePoint Documents
+
+- **File:** sharepoint-docs.tsx
+- **Connector:** new_uxtest_sharepoint (SharePoint Online)
+- **Dataset:** https://contoso.sharepoint.com/sites/team
+- **Table GUID:** 5709dd6f-c73e-4079-ad23-2334e45e0e13 (Documents list)
+- **Fields (all OPTIONAL):** ID (number), Title (string), Author (string), FileType ({Value:string}), Created (string), Modified (string)
+- **Components:**
+ - Search input for client-side title filtering
+ - Card list of documents with DocumentRegular icon, title, author, file-type badge, modified date
+ - OpenRegular icon as visual affordance on each card
+ - Spinner while loading; MessageBar on error; empty-state text when no matches
+- **Connector pattern:** cast dataApi to optional queryConnectorTable shape, presence-check, wrap in try/catch, fall back to FALLBACK_DOCS inline array on error or when method unavailable
+- **Styling:** makeStyles with tokens; no inline styles for static values; no 100vh/100vw
diff --git a/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/sharepoint-docs.tsx b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/sharepoint-docs.tsx
new file mode 100644
index 000000000..8f5fa7779
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/sharepoint-docs.tsx
@@ -0,0 +1,232 @@
+import { useState, useEffect } from 'react';
+import {
+ makeStyles,
+ tokens,
+ Text,
+ Card,
+ CardHeader,
+ Badge,
+ Spinner,
+ MessageBar,
+ MessageBarBody,
+ Input,
+} from '@fluentui/react-components';
+import {
+ DocumentRegular,
+ OpenRegular,
+} from '@fluentui/react-icons';
+
+// Connector page — fetches documents from SharePoint Online via the
+// new_uxtest_sharepoint connection reference. Follows the connector runtime
+// pattern in references/connectors.md: cast dataApi to an optional connector
+// shape, presence-check before calling, wrap in try/catch, and fall back to
+// inline mock data when the connector method is unavailable or the call fails.
+
+// All fields are OPTIONAL because connector rows are dynamically typed and
+// the runtime may omit any field row-by-row.
+interface SharePointDoc {
+ ID?: number;
+ Title?: string;
+ Author?: string;
+ FileType?: { Value?: string };
+ Created?: string;
+ Modified?: string;
+}
+
+// Fallback data shown when queryConnectorTable is unavailable or throws.
+// Also satisfies the Layer 2 "realistic inline mock data" assertion.
+const FALLBACK_DOCS: SharePointDoc[] = [
+ { ID: 1, Title: 'Q1 Budget Planning.xlsx', Author: 'Alice Smith', FileType: { Value: 'xlsx' }, Created: '2025-01-15T10:00:00Z', Modified: '2025-01-20T15:30:00Z' },
+ { ID: 2, Title: 'Team Charter v2.docx', Author: 'Bob Johnson', FileType: { Value: 'docx' }, Created: '2025-02-01T14:30:00Z', Modified: '2025-02-05T09:00:00Z' },
+ { ID: 3, Title: 'Project Roadmap 2025.pptx', Author: 'Carol Williams', FileType: { Value: 'pptx' }, Created: '2025-03-10T09:15:00Z', Modified: '2025-03-12T11:45:00Z' },
+];
+
+const CONNECTOR_LOGICAL_NAME = 'new_uxtest_sharepoint';
+const DATASET_URL = 'https://contoso.sharepoint.com/sites/team';
+const TABLE_GUID = '5709dd6f-c73e-4079-ad23-2334e45e0e13';
+
+const useStyles = makeStyles({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalL,
+ padding: tokens.spacingHorizontalXL,
+ width: '100%',
+ boxSizing: 'border-box',
+ },
+ pageHeader: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ flexWrap: 'wrap',
+ gap: tokens.spacingHorizontalM,
+ },
+ pageTitle: { marginBottom: tokens.spacingVerticalXS },
+ searchInput: { maxWidth: '320px', width: '100%' },
+ docList: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: tokens.spacingVerticalS,
+ },
+ docCard: {
+ display: 'flex',
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: tokens.spacingHorizontalM,
+ padding: tokens.spacingHorizontalM,
+ },
+ docIcon: { color: tokens.colorBrandForeground1, flexShrink: 0 },
+ docMeta: {
+ display: 'flex',
+ flexDirection: 'column',
+ flex: 1,
+ minWidth: 0,
+ },
+ docTitle: {
+ fontWeight: tokens.fontWeightSemibold,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ docSubtext: {
+ color: tokens.colorNeutralForeground2,
+ fontSize: tokens.fontSizeBase200,
+ },
+ emptyState: {
+ padding: tokens.spacingHorizontalXL,
+ textAlign: 'center',
+ color: tokens.colorNeutralForeground2,
+ },
+ openIcon: { color: tokens.colorNeutralForeground3, flexShrink: 0 },
+});
+
+function formatDate(iso?: string): string {
+ if (!iso) return '';
+ const d = new Date(iso);
+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
+}
+
+const DocCard = (props: { doc: SharePointDoc }) => {
+ const { doc } = props;
+ const styles = useStyles();
+ const fileType = doc.FileType?.Value ?? 'file';
+ const subParts = [
+ doc.Author ? `By ${doc.Author}` : '',
+ doc.Modified ? `Modified ${formatDate(doc.Modified)}` : (doc.Created ? `Created ${formatDate(doc.Created)}` : ''),
+ ].filter(Boolean);
+
+ return (
+ <Card
+ className={styles.docCard}
+ aria-label={`${doc.Title ?? 'Document'}, ${fileType} file${subParts.length ? ', ' + subParts.join(', ') : ''}`}
+ >
+ <DocumentRegular className={styles.docIcon} aria-hidden="true" />
+ <div className={styles.docMeta}>
+ <Text className={styles.docTitle}>{doc.Title ?? '(Untitled)'}</Text>
+ {subParts.length > 0 && (
+ <Text className={styles.docSubtext}>{subParts.join(' · ')}</Text>
+ )}
+ </div>
+ <Badge appearance="outline" aria-label={`File type: ${fileType}`}>
+ {fileType.toUpperCase()}
+ </Badge>
+ <OpenRegular className={styles.openIcon} aria-hidden="true" />
+ </Card>
+ );
+};
+
+const GeneratedComponent = (props: { dataApi?: unknown; pageInput?: { data?: Record<string, unknown> } }) => {
+ const { dataApi, pageInput } = props;
+ void pageInput;
+ const styles = useStyles();
+ const [documents, setDocuments] = useState<SharePointDoc[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [searchTerm, setSearchTerm] = useState('');
+
+ useEffect(() => {
+ // Cast dataApi to the connector API shape from references/connectors.md.
+ // Always presence-check the method before calling — the runtime may not
+ // have populated it if the connection reference is not yet active.
+ const connectorApi = dataApi as unknown as {
+ queryConnectorTable?: (
+ connectorLogicalName: string,
+ dataset: string,
+ table: string,
+ options: Record<string, unknown>
+ ) => Promise<{ rows: SharePointDoc[] }>;
+ };
+
+ if (typeof connectorApi.queryConnectorTable !== 'function') {
+ // Method unavailable — fall back to inline mock data so the page
+ // renders something useful while the binding is being set up.
+ setDocuments(FALLBACK_DOCS);
+ setLoading(false);
+ return;
+ }
+
+ (async () => {
+ try {
+ const result = await connectorApi.queryConnectorTable(
+ CONNECTOR_LOGICAL_NAME,
+ DATASET_URL,
+ TABLE_GUID,
+ { top: 50 }
+ );
+ setDocuments(result.rows);
+ } catch (err) {
+ setError('Failed to load documents from SharePoint. Showing sample data.');
+ setDocuments(FALLBACK_DOCS);
+ } finally {
+ setLoading(false);
+ }
+ })();
+ }, []); // dataApi is stable for the component lifetime; no re-fetch needed
+
+ const filtered = searchTerm.trim()
+ ? documents.filter((d) =>
+ (d.Title ?? '').toLowerCase().includes(searchTerm.toLowerCase())
+ )
+ : documents;
+
+ return (
+ <div className={styles.root}>
+ <div className={styles.pageHeader}>
+ <Text as="h1" size={700} weight="semibold" className={styles.pageTitle}>
+ SharePoint Documents
+ </Text>
+ <Input
+ className={styles.searchInput}
+ placeholder="Search documents…"
+ value={searchTerm}
+ onChange={(_, d) => setSearchTerm(d.value)}
+ aria-label="Search documents by title"
+ />
+ </div>
+
+ {error && (
+ <MessageBar intent="warning">
+ <MessageBarBody>{error}</MessageBarBody>
+ </MessageBar>
+ )}
+
+ {loading ? (
+ <Spinner label="Loading documents…" />
+ ) : filtered.length === 0 ? (
+ <Text className={styles.emptyState}>
+ {searchTerm
+ ? `No documents found matching "${searchTerm}".`
+ : 'No documents found in this library.'}
+ </Text>
+ ) : (
+ <div className={styles.docList} role="list" aria-label="Documents">
+ {filtered.map((doc) => (
+ <DocCard key={doc.ID ?? doc.Title} doc={doc} />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default GeneratedComponent;
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
new file mode 100644
index 000000000..0ff0d263c
--- /dev/null
+++ b/evals/model-apps/genpage/fixtures/18-sharepoint-connectors-on/workflow-log.md
@@ -0,0 +1,77 @@
+# Workflow Log — Eval 18: SharePoint Team Documents (connectors feature flag ON)
+
+## Phase 0 — Working directory setup
+- Working directory created: `sharepoint-team-docs/` (kebab-case derived from "SharePoint team site documents")
+- Plugin root: `D:\Projects\power-platform-skills\plugins\model-apps`
+
+## Phase 1 — Planner (genpage-planner agent invoked via Task)
+
+### Prereq checks
+- `node --version` → v20.11.0
+- `pac help` → PAC CLI Version 2.8.2 (>= 2.7.0 verified)
+- (Commands run separately, not chained with &&)
+
+### Auth check
+- `pac auth list` → active profile `[email protected]`
+- Active environment: https://contoso-dev.crm10.dynamics.com/ (reported to user)
+
+### Discovery questions (AskUserQuestion)
+- Question 1 (new or edit): user answered "Create new page(s)"
+- Question 2 (data source): user answered "SharePoint (connector)"
+- Question 3 (specific requirements): "list documents"
+- Question 4 (app selection): user selected existing app from pac model list: "Operations Hub"
+
+### Connector Detection (delegated to genpage-connector-builder)
+- Request is explicitly for SharePoint connector → planner delegates all connector work to the `genpage-connector-builder` agent (mode: create) via the Task tool
+- genpage-connector-builder probes the gate FIRST: `node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" connectors` → `enabled` (exit 0)
+- Connectors feature flag ON: proceeding with connector discovery
+- `node "${PLUGIN_ROOT}/scripts/list-connections.js" "https://contoso-dev.crm10.dynamics.com/"` → 2 connections found:
+ - SharePoint Online: logical name `new_uxtest_sharepoint`, connectorId `/providers/Microsoft.PowerApps/apis/shared_sharepointonline`
+ - OneDrive for Business: logical name `new_uxtest_onedrive`, connectorId `/providers/Microsoft.PowerApps/apis/shared_onedriveforbusiness`
+- Selected SharePoint Online connection (best match for "SharePoint team site"): `new_uxtest_sharepoint`
+- Agent wrote `connector-bindings.md` (binding table) and `connectors.json` (bare array)
+
+### Solution selection
+- Build is code-only (connector page, no new entities, no new app) → solution selection question SKIPPED
+- Default values written to plan: `Solution: Default`, `Publisher Prefix: new`
+
+### Plan presented
+- EnterPlanMode called with plan summary: SharePoint document listing page, connector binding to new_uxtest_sharepoint (Documents list GUID 5709dd6f-c73e-4079-ad23-2334e45e0e13)
+- User approved plan
+
+### Plan written
+- genpage-plan.md written to sharepoint-team-docs/genpage-plan.md
+- Conforms to references/plan-schema.md (## User Requirements, ## Working Directory, ## Plugin Root, ## Environment, ## Pages, ## Entity Creation Required, ## Existing Entities, ## Connector Bindings, ## Design Preferences, ## Relevant Samples, ## Per-Page Specifications)
+
+## Phase 2 — Entity creation
+- SKIPPED (connector-only page — no Dataverse entities needed)
+- check-auth.js not run (no entity work)
+- genpage-entity-builder not invoked
+
+## Phase 3 — App creation
+- SKIPPED (existing app "Operations Hub" selected)
+
+## Phase 4 — Schema generation
+- SKIPPED (connector-only page — no Dataverse entities, no RuntimeTypes needed)
+- pac model genpage generate-types not run (connector page)
+
+## Phase 4.5 — Connector bindings
+- Writing connectors.json for SharePoint binding
+- connectors.json written to sharepoint-team-docs/connectors.json (a JSON array of bindings, per SKILL.md Phase 4.5): [{ "logicalName": "new_uxtest_sharepoint", "connectorId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline", "dataset": "https://contoso.sharepoint.com/sites/team", "tables": ["5709dd6f-c73e-4079-ad23-2334e45e0e13"], "tableDisplayNames": ["Documents"] }]
+
+## Phase 5b — Single-page fast path
+- Plan has 1 page → fast path taken (inlined build, no Task subagent dispatched for page-builder)
+- Data mode: connector (SharePoint Online)
+- Read sample: plugins/model-apps/samples/7-responsive-cards.tsx (card list layout pattern for document display)
+- Read references/verified-icons.txt to source icon names
+- Wrote sharepoint-docs.tsx
+- Post-write icon verification: grep `from "@fluentui/react-icons"` in sharepoint-docs.tsx; verified `DocumentRegular`, `OpenRegular` against verified-icons.txt — all present
+
+## Phase 6 — Deployment
+- `pac model genpage upload --app-id aa112233-1122-1122-1122-aabbccdd1234 --code-file sharepoint-team-docs/sharepoint-docs.tsx --connectors "sharepoint-team-docs/connectors.json" --prompt "Build a page listing documents from our SharePoint team site." --model claude-sonnet --name "SharePoint Documents" --agent-message "SharePoint team site document listing" --add-to-sitemap`
+- Upload succeeded
+
+## Phase 8 — Summary
+- 1 page deployed: sharepoint-docs.tsx → "SharePoint Documents" in Operations Hub app
+- No entities created
+- Connector binding: new_uxtest_sharepoint (SharePoint Online, Documents list)
diff --git a/evals/model-apps/genpage/lib/assertions-layer-1.js b/evals/model-apps/genpage/lib/assertions-layer-1.js
index cb049475f..5c39f7530 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-1.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-1.js
@@ -679,6 +679,127 @@ PHASE_EXPECTATIONS.set(
}
);
+// Eval 17: connector feature flag OFF — regression guard confirming that the
+// planner probes the feature gate and skips connector discovery entirely when
+// the flag is disabled, leaving ## Connector Bindings as the exact sentinel.
+PHASE_EXPECTATIONS.set(
+ "Phase 1 (Planner): With the connectors feature flag OFF, the feature gate (scripts/lib/feature-flags.js) is checked, connector discovery (list-connections.js) is NOT run, and the plan's ## Connector Bindings is exactly 'No connector bindings.'",
+ ({ fixture }) => {
+ const log = fixture.workflowLog;
+ const plan = fixture.genpagePlan;
+ if (!log) return fail('no workflow-log.md');
+ if (!plan) return fail('no genpage-plan.md');
+
+ // (a) A line in the workflow log must reference feature-flags.js with
+ // "connectors" AND "disabled" or "OFF" — evidence the gate was probed
+ // and returned the OFF result.
+ const hasFlagDisabled = log.split('\n').some((l) =>
+ /feature-flags(?:\.js)?/i.test(l) &&
+ /\bconnectors\b/i.test(l) &&
+ /\b(?:disabled|OFF)\b/i.test(l)
+ );
+ if (!hasFlagDisabled) {
+ return fail(
+ 'workflow-log does not record a feature-flags.js probe for connectors returning disabled/OFF'
+ );
+ }
+
+ // (b) list-connections.js must NOT be invoked — a `node ... list-connections.js`
+ // command must be absent. A narrative mention like "list-connections.js NOT
+ // run" in a comment is acceptable and does not count as an invocation.
+ if (/\bnode\b[^\n]*list-connections\.js/.test(log)) {
+ return fail(
+ 'list-connections.js was invoked but connectors flag is OFF — connector discovery should be skipped'
+ );
+ }
+
+ // (c) Plan's ## Connector Bindings body must be exactly the no-binding sentinel.
+ const cbSection = planSection(plan, 'Connector Bindings');
+ if (!cbSection) {
+ return fail('genpage-plan.md is missing ## Connector Bindings section');
+ }
+ if (cbSection.trim() !== 'No connector bindings.') {
+ return fail(
+ `## Connector Bindings body is not exactly 'No connector bindings.' (got: ${cbSection.trim().slice(0, 60)})`
+ );
+ }
+
+ return pass();
+ }
+);
+
+// Eval 18: connector feature flag ON — regression guard confirming that the
+// planner probes the gate, gets "enabled", runs list-connections.js for
+// discovery, and records at least one real binding in the plan.
+PHASE_EXPECTATIONS.set(
+ "Phase 1 (Planner): With the connectors feature flag ON, the feature gate passes (enabled) and list-connections.js is run for connector discovery, and the plan's ## Connector Bindings records at least one binding (not 'No connector bindings.')",
+ ({ fixture }) => {
+ const log = fixture.workflowLog;
+ const plan = fixture.genpagePlan;
+ if (!log) return fail('no workflow-log.md');
+ if (!plan) return fail('no genpage-plan.md');
+
+ // (a) A line in the workflow log must reference feature-flags.js with
+ // "connectors" AND "enabled" or "ON" — evidence the gate passed.
+ const hasFlagEnabled = log.split('\n').some((l) =>
+ /feature-flags(?:\.js)?/i.test(l) &&
+ /\bconnectors\b/i.test(l) &&
+ /\b(?:enabled|ON)\b/i.test(l)
+ );
+ if (!hasFlagEnabled) {
+ return fail(
+ 'workflow-log does not record a feature-flags.js probe for connectors returning enabled/ON'
+ );
+ }
+
+ // (b) A `node ... list-connections.js` invocation must appear in the log —
+ // discovery should run when the flag is ON.
+ if (!/\bnode\b[^\n]*list-connections\.js/.test(log)) {
+ return fail(
+ 'list-connections.js not invoked — expected when connectors flag is ON'
+ );
+ }
+
+ // (c) Plan's ## Connector Bindings must contain at least one real binding,
+ // detected by a table pipe (|) or a shared_ connector id.
+ const cbSection = planSection(plan, 'Connector Bindings');
+ if (!cbSection || cbSection.trim() === '') {
+ return fail('genpage-plan.md is missing ## Connector Bindings section');
+ }
+ if (cbSection.trim() === 'No connector bindings.') {
+ return fail(
+ '## Connector Bindings says "No connector bindings." but flag is ON and a binding was expected'
+ );
+ }
+ if (!/\|/.test(cbSection) && !/shared_/.test(cbSection)) {
+ return fail(
+ '## Connector Bindings does not contain a binding table row (expected | pipe or shared_ connector id)'
+ );
+ }
+
+ return pass();
+ }
+);
+
+// Eval 18: connectors ON deploy — connectors.json is written as a bare array (not
+// the config.json { connectorBindings: [...] } wrapper) and the upload passes
+// --connectors. Locks in the connectors.json shape and the deploy wiring.
+PHASE_EXPECTATIONS.set(
+ "Phase 4.5 / Phase 6 (connectors ON): connectors.json is written as a bare array (not the config.json object wrapper) and the upload includes --connectors",
+ ({ fixture }) => {
+ const log = fixture.workflowLog;
+ if (!log) return fail('no workflow-log.md');
+ if (!/connectors\.json/.test(log)) return fail('workflow-log does not record connectors.json');
+ if (!/--connectors\b/.test(log)) return fail('upload does not include --connectors');
+ // Guard against the object-wrapper regression: connectors.json must be a bare
+ // array, not `{ "connectorBindings": [...] }` (that is the deployed config.json).
+ if (/connectors\.json[^\n]*\{\s*"connectorBindings"/.test(log)) {
+ return fail('connectors.json shown as the config.json object wrapper, not a bare array');
+ }
+ return pass();
+ }
+);
+
module.exports = {
WORKFLOW_ASSERTIONS,
PHASE_EXPECTATIONS,
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index b64d7e3d7..a90bfa6b1 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -87,6 +87,7 @@ Agents are invoked by skills via the `Task` tool — they are not user-invocable
| `genpage-entity-builder` | `genpage` (create flow) | Creates Dataverse tables, columns, relationships, choices, and sample data via the plugin's Node.js Web API scripts (`scripts/`). Bulk inserts use OData `$batch`. Writes a transactional log for recovery |
| `genpage-page-builder` | `genpage` (create flow) | Generates one complete `.tsx` page from the plan and schema; runs in parallel with other builders for multi-page requests |
| `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` (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`. Both the planner and the edit-planner delegate all connector work to it. |
## Key Concepts
@@ -102,6 +103,53 @@ The DataAPI (`props.dataApi`) provides typed CRUD operations against Dataverse t
TypeScript type definitions generated from Dataverse metadata. Contains entity types, enum registrations, and the `GeneratedComponentProps` interface. Generated via PAC CLI before code generation to ensure correct column names.
+## Feature Flags
+
+Unreleased functionality is gated behind committed, **default-OFF** feature flags so
+the skill can merge ahead of its cross-repo dependencies. With a flag OFF, the
+**deployed page behavior is identical to before the feature existed** — the guarantee
+is about runtime/deploy output, not that every authoring artifact is byte-for-byte
+unchanged (e.g. plans still carry a `## Connector Bindings: No connector bindings.`
+line). The mechanism lives in `scripts/lib/feature-flags.js` with the committed
+values in `feature-flags.json` at the plugin root.
+
+- **Source of truth:** `feature-flags.json` (e.g. `{ "connectors": false }`). Flip a
+ flag to `true` in a one-line PR once its dependencies are GA in PROD.
+- **Precedence (highest first):** env var `GENPAGE_ENABLE_<FLAG>` (e.g.
+ `GENPAGE_ENABLE_CONNECTORS=1`) → committed `feature-flags.json` → default `false`
+ (fail-closed). This mirrors the telemetry opt-out env-over-config convention.
+- **LLM gate:** skill/agent markdown probes a flag with
+ `node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" <flag>` (prints `enabled`/`disabled`,
+ exits 0/1) and skips the gated workflow when disabled. `--list` prints every known
+ flag's lifecycle **status** (experimental / in-progress / ga), effective state +
+ source (env/file/default), summary, how to enable, plus config-validation warnings.
+ Flags are catalogued with that metadata in the `FLAGS` map in `feature-flags.js`
+ (the committed `feature-flags.json` carries only the on/off value).
+- **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`.
+- **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).
+
+**Connectors gate — the single owner is `genpage-connector-builder`.** Every connector
+entry point must go through it or the helper; the checklist of places that gate:
+
+1. Discovery — `genpage-connector-builder` runs the probe first (planner + edit-planner
+ delegate to it; they do not gate inline).
+2. Scripts — `list-connections.js` / `create-connection-reference.js` (`exitIfConnectorsDisabled`).
+3. Deploy — SKILL Phase 4.5 **re-probes** the flag and treats absent/malformed
+ `## Connector Bindings` as no bindings (a plan authored while ON must not deploy
+ connectors after OFF).
+4. ALM — the `--connection-refs` branch of `add-page-to-solution.js`.
+5. Codegen — `genpage-page-builder` emits connector code only when the plan has an
+ actual binding table (never on an absent/sentinel section).
+
+The **`connectors`** flag currently ships OFF: GenPage connector support needs the
+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.
+
## Development Standards
- **React 17 + TypeScript** — all generated code
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index fcef6b4a5..c32559e3d 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -26,6 +26,25 @@ real and synthetic fixtures. Builds on v2.1; no breaking changes.
`contain: layout`, default dialogs to `modalType="non-modal"`, and never nest
dialogs — so a modal can't escape the preview and cover the designer /
coding-agent panel.
+- **Feature-flag gate for connectors (default OFF).** `feature-flags.json` at the
+ plugin root plus `scripts/lib/feature-flags.js` gate connector support so the
+ skill can ship ahead of its cross-repo dependencies (pac connector verbs, the
+ GenUX authoring control, and the maker/admin setting) reaching PROD. When OFF,
+ the planner skips connector discovery and records `No connector bindings.`, and
+ the connector scripts (`list-connections.js`, `create-connection-reference.js`)
+ fail closed with exit 3. Precedence: env `GENPAGE_ENABLE_CONNECTORS` overrides
+ the committed file; default is OFF (fail-closed). Flip the file to `true` once
+ the dependencies are GA.
+- **`genpage-connector-builder` agent — single owner of connector work.** Connector
+ discovery, connection-reference creation, the feature gate, and the
+ `## Connector Bindings` contract now live in one agent invoked from **both** the
+ create flow (planner) and the edit flow (edit-planner) — so edits can add/replace
+ connectors (previously only preserve/clear worked) and the gate can't drift across
+ markdown. Hardened per review: deploy (SKILL Phase 4.5) **re-probes** the flag and
+ treats an absent/malformed `## Connector Bindings` as no bindings; the page-builder
+ emits connector code only for an actual binding table; the `--connection-refs`
+ branch of `add-page-to-solution.js` is gated; scripts share `exitIfConnectorsDisabled()`;
+ and `feature-flags.js` gains `--list`, `describe()`, and config validation.
### Changed
- Spec tightening so workflow-logs are command-verbatim and `pageInput`
diff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.md
index 930976bcb..ff18734e2 100644
--- a/plugins/model-apps/README.md
+++ b/plugins/model-apps/README.md
@@ -27,6 +27,47 @@ claude --plugin-dir /path/to/power-platform-skills/plugins/model-apps
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.
+## Feature flags (experimental & in-progress)
+
+Some capabilities ship **OFF by default** while their cross-repo dependencies roll
+out to production. With a flag OFF, the skill behaves as if the feature doesn't
+exist and deployed pages are unchanged. Flags are catalogued (with lifecycle
+status) in `scripts/lib/feature-flags.js`; their on/off value lives in
+`feature-flags.json` at the plugin root.
+
+| Flag | Status | Enables | Depends on |
+|---|---|---|---|
+| `connectors` | in-progress | GenPage connector authoring (SharePoint, weather, Office 365, SQL, custom REST) + ALM packaging of connection references | pac CLI connector verbs, the GenUX authoring control, and the maker/admin ECS setting — all live in PROD |
+
+**See the current state** (status, whether each flag is on, and why):
+
+```bash
+node scripts/lib/feature-flags.js --list
+```
+
+**Enable a flag for a single run** via an environment variable (highest precedence):
+
+```powershell
+# Windows (PowerShell)
+$env:GENPAGE_ENABLE_CONNECTORS = "1"
+```
+
+```bash
+# macOS / Linux (bash)
+export GENPAGE_ENABLE_CONNECTORS=1
+```
+
+**Enable it persistently** by flipping the value in `feature-flags.json`:
+
+```json
+{ "connectors": true }
+```
+
+Precedence is **env var → `feature-flags.json` → default OFF** (fail-closed). Only
+turn a flag on once its "Depends on" items are actually available in your
+environment — otherwise the feature's commands will fail with a clear "disabled" or
+capability error. The env var name is always `GENPAGE_ENABLE_<FLAG>` (uppercased).
+
## Skills
The plugin provides a single skill that covers the full lifecycle of a generative page.
diff --git a/plugins/model-apps/agents/genpage-connector-builder.md b/plugins/model-apps/agents/genpage-connector-builder.md
new file mode 100644
index 000000000..d0e4d8950
--- /dev/null
+++ b/plugins/model-apps/agents/genpage-connector-builder.md
@@ -0,0 +1,203 @@
+---
+name: genpage-connector-builder
+description: >-
+ Owns ALL GenPage connector work: it is the single owner of the connectors
+ feature-flag gate, performs connector discovery (connections, connection
+ references, datasets, tables, operations, and schema), creates Dataverse
+ connection references when needed, and produces the ## Connector 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 Connector Builder
+
+You are the connector specialist for generative pages. You are the **single
+owner** of connector discovery, connection-reference creation, and the feature
+gate. Both the create flow (`genpage-planner`) and the edit flow
+(`genpage-edit-planner`) delegate ALL connector work to you so the gate and the
+discovery logic live in exactly one place.
+
+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`.
+- **Intent** — the source(s) the request implies (e.g. "SharePoint documents",
+ "current weather", "Office 365 users") and, for `edit`, whether the maker wants
+ to **add**, **replace**, or **remove** connector data.
+- **Existing bindings** (`edit` only) — the current
+ `config.json.connectorBindings` 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. **`connector-bindings.md`** — a markdown fragment whose entire body is the
+ value of the plan's `## Connector Bindings` section. It is **either** the exact
+ literal `No connector bindings.` **or** the binding table described below. The
+ caller splices this verbatim into `genpage-plan.md`.
+2. **`connectors.json`** — the working-dir binding file for
+ `pac model genpage upload --connectors`. It is a **bare JSON array** of
+ bindings (see `${PLUGIN_ROOT}/references/connectors.md`), or `[]` when there
+ are no bindings. Never the `{ "connectorBindings": [...] }` object wrapper —
+ that is the deployed page `config.json` shape, which `pac` writes.
+
+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" connectors
+```
+
+Record the result in `workflow-log.md` (e.g. `feature-flags.js connectors → disabled`).
+
+**If it prints `disabled` (exit 1)** — connector support is not live in PROD:
+
+- Do **not** run `list-connections.js` or any other connector discovery.
+- **create:** write `connector-bindings.md` containing exactly
+ `No connector bindings.` and `connectors.json` containing `[]`. Return
+ `connectors disabled — no bindings`.
+- **edit:** connectors are OFF, so you must **not add or discover** new bindings.
+ **Preserve** the existing bindings passed to you: write them unchanged to
+ `connectors.json` (bare array) and reproduce them in `connector-bindings.md`.
+ Return `connectors 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_CONNECTORS=1` for a single run) once the pac connector verbs, the
+GenUX control, and the maker/admin setting are all released.
+
+## Step 2 — Connection discovery (enabled only)
+
+If the intent implies a non-Dataverse source (SharePoint, Teams, weather, Office
+365, SQL via connector, a custom REST connector, …), enumerate what exists:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/list-connections.js" "<ENV_URL>"
+```
+
+The script returns `connections` sorted with `readyToBind: true` first and
+`connectionReferences` from Dataverse. `readyToBind` means a connection reference
+is actually bound to that connection (its `connectionId` matches) — prefer those.
+Present ready-to-bind choices first via `AskUserQuestion`, showing the
+connectionreference logical name, connector id, and connection display name.
+
+If the maker chooses a connection that has **no** connection reference, do not
+invent a logical name — create one:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/create-connection-reference.js" "<ENV_URL>" "<logicalName>" "<connectorId>" --connection-id "<connectionId>"
+```
+
+## Step 3 — Resolve dataset/table (tabular) or operation (REST/action)
+
+**Tabular connectors** (SharePoint, SQL, …): resolve the dataset and table.
+
+- Identify the connector from the chosen connection.
+- Enumerate datasets, then tables, for that connection (connector runtime
+ metadata discovery; `list-connector-tables` may help pick the table).
+- Store SharePoint datasets as the **site URL** and tables as **list GUIDs** (not
+ display names); put display names only in `Table Display Names`.
+
+**REST/action connectors** (weather, …): resolve the operation and its schema.
+
+- Pre-flight that `pac model genpage --help` lists `list-connector-operations`
+ and `get-connector-schema`.
+- Enumerate operations:
+ ```powershell
+ pac model genpage list-connector-operations --connector-id <apiId> --connection-id <connId>
+ ```
+- Let the maker pick via `AskUserQuestion` when the requirement doesn't imply
+ exactly one operation.
+- Discover the operation schema:
+ ```powershell
+ pac model genpage get-connector-schema --connector-id <apiId> --connection-id <connId> --operation <op>
+ ```
+- Parse `{ operation, parameters:[{ name, required }], response:{...} }` and
+ record `Operations`, `Parameters`, and `Response`.
+- If either verb is unavailable, fall back to asking the maker for the operation,
+ parameters, and expected response shape. Never fabricate names.
+
+## Step 4 — Column/schema discovery (every tabular binding)
+
+The binding tells the runtime *where* to fetch; `Fields` tells the page-builder
+*which* properties it may access without guessing. After resolving connector id,
+connection id, dataset, and table:
+
+```powershell
+pac model genpage get-connector-schema --connector-id <apiId> --connection-id <connId> --dataset <ds> --table <tableId>
+```
+
+Parse `{ table, columns:[{ name, type, required }] }` and record each column in
+the binding's `Fields` cell, e.g.
+`PetName (string), OwnerName (string), PetType ({Value:string}), Created (datetime)`.
+Treat all connector fields as **optional** — connector rows are dynamic; the
+generated TSX declares `field?` regardless of the discovery payload's `required`.
+
+For SharePoint, filter columns before recording `Fields`:
+
+- Keep maker-meaningful columns (`Title`, `PetName`, `OwnerName`, `PetType`,
+ `Created`, `Modified`, …).
+- Drop system/synthetic columns unless explicitly requested: `{...}`-wrapped
+ names (`{Identifier}`, `{IsFolder}`, `{Thumbnail}`), `ComplianceAssetId`,
+ `OData__*`, and `*#Id` / `*#Claims` variants.
+- Treat `type:"object"` choice columns as `{Value:string}` (SharePoint choice
+ values arrive as `{ Value }`).
+
+Fallback when the PAC verb is unavailable: sample the top 1 row and record its
+keys/observed shapes, or ask the maker via `AskUserQuestion`. **Never fabricate
+field names.** If fields cannot be discovered or supplied, keep the binding out of
+the result rather than letting the page-builder guess.
+
+## Step 5 — 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–4 for the new source and append the binding.
+- **Replace:** discover the replacement (Steps 2–4) and swap it in by logical
+ name; keep the same logical name only if it still points at the same
+ connection reference, otherwise use the newly resolved one.
+- **Remove:** drop the named binding(s).
+- Use ONLY logical names, datasets, table GUIDs, operations, and fields you
+ discovered or that were in the existing bindings. Never fabricate.
+
+## Step 6 — Write outputs
+
+Write the final binding set to both output files (Step "Outputs"):
+
+- **When there are bindings:** `connector-bindings.md` contains the table below;
+ `connectors.json` contains the equivalent bare JSON array.
+
+ ```markdown
+ | Logical Name | Connector Id | Dataset | Tables (GUIDs) | Table Display Names | Operations | Fields | Parameters | Response |
+ |--------------|--------------|---------|----------------|---------------------|------------|--------|------------|----------|
+ | new_uxtest_sharepoint | /providers/Microsoft.PowerApps/apis/shared_sharepointonline | https://host.sharepoint.com/sites/x | 5709dd6f-… | Documents | | Title (string), Modified (datetime) | | |
+ ```
+
+ `Fields` is required for tabular bindings; `Parameters` and `Response` for
+ REST/action bindings.
+
+- **When there are none:** `connector-bindings.md` contains exactly
+ `No connector bindings.` and `connectors.json` contains `[]`.
+
+Do **not** write connection IDs into `connectors.json` — env-specific
+`ConnectionId` values are filled by the importing maker/admin via deployment
+settings on the connection reference row.
+
+Return a concise summary: mode, gate result, and the logical names 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 d937af785..f8a81124a 100644
--- a/plugins/model-apps/agents/genpage-edit-planner.md
+++ b/plugins/model-apps/agents/genpage-edit-planner.md
@@ -118,6 +118,13 @@ Ask questions via `AskUserQuestion`, one at a time:
4. **"Any specific requirements for the changes?"** — styling, accessibility,
behavior, or preservation constraints not yet covered.
+> **Connector data changes** (SharePoint, weather, Office 365, SQL, custom REST):
+> if the edit adds, replaces, or removes connector-backed data, capture it in the
+> plan's `### Connector Changes` below. Do **not** run connector discovery here —
+> the orchestrator delegates that to the `genpage-connector-builder` agent (which
+> owns the feature gate). Preserving or clearing existing connectors needs no
+> discovery.
+
Mark "Analyze existing page" task complete.
## Step 3 — Present Edit Plan for Approval
@@ -138,6 +145,10 @@ Enter plan mode (`EnterPlanMode`) with:
1. [Change 1 — what to add / modify / remove]
2. [Change 2 — ...]
+### Connector Changes
+- [none | add <source> | replace <logicalName> with <source> | remove <logicalName>]
+ (the orchestrator delegates any add/replace/remove to genpage-connector-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 446904960..775a8f52e 100644
--- a/plugins/model-apps/agents/genpage-page-builder.md
+++ b/plugins/model-apps/agents/genpage-page-builder.md
@@ -26,13 +26,28 @@ You will be invoked with a prompt that includes:
- **Page name** — e.g., "Candidate Tracker"
- **Target file** — e.g., "candidate-tracker.tsx"
- **Plan document path** — absolute path to `genpage-plan.md`
-- **Data mode** — either `dataverse` or `mock`
+- **Data mode** — the **Dataverse axis**: `dataverse` (page reads Dataverse tables
+ via RuntimeTypes) or `mock` (no Dataverse tables). This is **orthogonal to
+ connectors**: a page may *also* carry connector bindings (the plan's
+ `## Connector Bindings`), which layer connector-backed data on top of either mode.
+ The effective shapes are `dataverse`, `mock`, `dataverse + connectors`, or
+ `mock + connectors` — a **connector-only page is `mock` data mode with connector
+ bindings**.
- **RuntimeTypes path** — absolute path to `RuntimeTypes.ts` (present only when Data mode is `dataverse`)
- **Working directory** — where to write the `.tsx` file
- **Plugin root** — `${PLUGIN_ROOT}` for reading references and samples
-The **Data mode** flag is authoritative — use it to decide whether to perform Step 2
-(read RuntimeTypes.ts) or skip it. Do not infer data mode from the plan document.
+The **Data mode** flag is authoritative for the Dataverse axis — use it to decide
+whether to perform Step 2 (read RuntimeTypes.ts) or skip it. Do not infer data mode
+from the plan document.
+
+**Connectors are decided separately from Data mode** by the plan's `## Connector
+Bindings` (see the connector-detection step below): when it has an actual binding
+table, the page uses `props.dataApi` connector methods (`queryConnectorTable` /
+`executeConnectorOperation`) **even in `mock` data mode** — the "mock data forbids
+`dataApi`" rule applies only to *non-connector* panels, which still use realistic
+inline data. Never fabricate connector rows/fields; use only the discovered
+`Fields`/`Parameters`/`Response` from the plan.
## Step 1 — Read the Plan Document
@@ -99,6 +114,18 @@ Read the code generation rules reference:
${PLUGIN_ROOT}/references/rules.md
```
+Only when the plan's `## Connector Bindings` section contains an actual binding
+table (a `| Logical Name | …` header with at least one data row) do you treat the
+page as connector-backed and also read:
+
+```
+${PLUGIN_ROOT}/references/connectors.md
+```
+
+If the `## Connector Bindings` section is the literal `No connector bindings.`, is
+empty, is missing entirely, or contains no binding row, the page has **no
+connectors** — do not read connectors.md and do not emit any connector code.
+
Read the relevant sample file identified in the plan:
```
@@ -287,6 +314,58 @@ const mockRecords = [
];
```
+### Connector-backed data
+
+When the plan has `## Connector Bindings`, use only the logical name, connector
+id, dataset, table GUID, display name, operation, Fields, Parameters, and
+Response values from that section. Never guess a `connectorLogicalName`,
+connector field name, parameter name, or response field name that is not in the
+plan. Read
+`${PLUGIN_ROOT}/references/connectors.md` and emit connector calls with the
+verified runtime patterns below. Connector methods are optional at runtime, so
+every call must be presence-checked and wrapped in `try`/`catch` with a graceful
+empty or error state.
+
+Connector rows are not covered by RuntimeTypes. Before using
+`queryConnectorTable`, declare an inline row interface from the plan's discovered
+`Fields` list and mark every property optional. Use the field spelling and types
+exactly as recorded in the plan; if a type is unclear, use `unknown`. SharePoint
+choice fields use the `{ Value?: string }` shape. Example:
+
+```typescript
+type PetRow = { ID?: number; PetName?: string; OwnerName?: string; PetType?: { Value?: string }; Created?: string };
+```
+
+Tabular connectors use `queryConnectorTable`. Tables must be the plan's list
+GUIDs, and datasets must be the plan's dataset value (SharePoint site URL):
+
+```typescript
+const connectorApi = dataApi as unknown as { queryConnectorTable?: (connectorLogicalName: string, dataset: string, table: string, options: Record<string, unknown>) => Promise<{ rows: PetRow[] }>; };
+if (typeof connectorApi.queryConnectorTable !== 'function') { return; }
+const result = await connectorApi.queryConnectorTable('new_uxtest_sharepoint', 'https://host.sharepoint.com/sites/x', '<list-guid>', { top: 50 });
+```
+
+REST/action connector operation names, parameter names, and response field names
+must come from the plan's discovered `Operations`, `Parameters`, and `Response`
+schema. Before calling `executeConnectorOperation`, declare the response
+interface from the plan and mark every response field optional. Build the
+parameter object from discovered parameters plus maker-provided values; never
+invent parameter or response field names. Check `response.ok` before casting or
+using the body:
+
+```typescript
+type WeatherResponse = { temperature?: number; conditions?: string; humidity?: number };
+const parameters: { Location: string; units?: string } = { Location: 'Seattle', units: 'C' };
+```
+
+```typescript
+const connectorApi = dataApi as unknown as { executeConnectorOperation?: (connectorLogicalName: string, operationName: string, parameters: Record<string, unknown>) => Promise<{ ok: boolean; body: unknown }>; };
+if (typeof connectorApi.executeConnectorOperation !== 'function') { return; }
+const response = await connectorApi.executeConnectorOperation('new_uxtest_msnweather', 'CurrentWeather', parameters);
+if (!response.ok) { return; }
+const weather = response.body as WeatherResponse;
+```
+
## 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 ea3cbea42..024ef8b2f 100644
--- a/plugins/model-apps/agents/genpage-planner.md
+++ b/plugins/model-apps/agents/genpage-planner.md
@@ -199,6 +199,35 @@ If any entities need creating, note that entity creation requires:
Detection uses `pac model list-tables` natively; creation runs through the
plugin's own Web API scripts under `${PLUGIN_ROOT}/scripts/`.
+### Connector Detection (delegated to genpage-connector-builder)
+
+If the request implies a non-Dataverse source (SharePoint, Teams, weather,
+Office 365, SQL via connector, or a custom REST connector), delegate ALL
+connector work to the `genpage-connector-builder` agent via the `Task` tool. Do
+**not** run the feature-gate probe or any connector discovery inline — that agent
+is the single owner of the connectors feature gate, connection / connection-ref
+discovery, connection-reference creation, and the binding contract.
+
+Invoke `genpage-connector-builder` with a prompt containing:
+
+- **Mode:** `create`
+- **Working directory**, **Plugin root** (`${PLUGIN_ROOT}`), **Environment URL**
+- **Intent:** the source(s) the request implies (e.g. "SharePoint documents",
+ "current weather")
+
+It writes two files into the working directory:
+
+- `connector-bindings.md` — the exact body for the plan's `## Connector Bindings`
+ section (either `No connector bindings.` or the binding table).
+- `connectors.json` — the bare-array binding file for deployment.
+
+Read `connector-bindings.md` and splice its contents verbatim into the
+`## Connector Bindings` section of `genpage-plan.md`.
+
+If the request implies **only** Dataverse and/or mock data (no connector source),
+skip the agent entirely and write `## Connector Bindings` as exactly
+`No connector bindings.`.
+
### App Detection
Run:
@@ -326,6 +355,7 @@ Enter plan mode (`EnterPlanMode`) and present:
- Entities needed: [list]
- Entities that exist: [list]
- Entities to create: [list — with columns, types, relationships, choices]
+- Connector bindings: [ready-to-bind connectionreference logical names, 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
new file mode 100644
index 000000000..6ebf4e8b2
--- /dev/null
+++ b/plugins/model-apps/feature-flags.json
@@ -0,0 +1,4 @@
+{
+ "_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
+}
diff --git a/plugins/model-apps/references/connectors.md b/plugins/model-apps/references/connectors.md
new file mode 100644
index 000000000..de19da6b2
--- /dev/null
+++ b/plugins/model-apps/references/connectors.md
@@ -0,0 +1,149 @@
+# Connector Bindings
+
+Connector-backed GenPages bind to Dataverse `connectionreference` rows by logical
+name. The `connectorLogicalName` string in TSX **MUST** equal a
+`connectorBindings[].logicalName` value in the page `config.json`, and that
+logical name must exist as a connection reference in the target environment.
+
+> **Gated behind the `connectors` feature flag (default OFF).** This reference is
+> only used when connector support is enabled — see the Feature Flags section in
+> the plugin `AGENTS.md` and `feature-flags.json`. When OFF, pages are Dataverse /
+> mock-data only and no connector code is emitted.
+
+## Binding shape: `connectors.json` (array) vs page `config.json` (object)
+
+The skill writes a **bare JSON array** of bindings to working-dir
+`connectors.json`. `pac model genpage upload --connectors <connectors.json>` then
+persists that array into the deployed page's `config.json` under a
+`connectorBindings` property. The two files therefore have **different shapes** —
+do not write the object wrapper to `connectors.json`.
+
+**`connectors.json`** — what the skill writes (a JSON array; no wrapper object):
+
+```json
+[
+ {
+ "logicalName": "new_uxtest_sharepoint",
+ "connectorId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline",
+ "dataset": "https://host.sharepoint.com/sites/x",
+ "tables": ["5709dd6f-c73e-4079-ad23-2334e45e0e13"],
+ "tableDisplayNames": ["Pet"]
+ },
+ {
+ "logicalName": "new_uxtest_msnweather",
+ "connectorId": "/providers/Microsoft.PowerApps/apis/shared_msnweather",
+ "dataset": "",
+ "operations": ["CurrentWeather"]
+ }
+]
+```
+
+**page `config.json`** — what `pac` writes into the deployed page (the same array
+wrapped under `connectorBindings`; the skill never writes this file directly):
+
+```json
+{
+ "connectorBindings": [ /* ...the identical array from connectors.json... */ ]
+}
+```
+
+- `logicalName`: Dataverse connectionreference logical name; this is the TSX
+ `connectorLogicalName` argument.
+- `connectorId`: Power Platform API id, for example
+ `/providers/Microsoft.PowerApps/apis/shared_sharepointonline`.
+- `dataset`: for tabular connectors, the dataset key. SharePoint uses the site
+ URL (for example `https://host.sharepoint.com/sites/x`).
+- `tables`: tabular table identifiers. For SharePoint, use the list GUID, not
+ the display name, so renames do not break the page.
+- `tableDisplayNames`: user-facing names aligned by index with `tables`.
+- `operations`: REST/action operation names for `executeConnectorOperation`.
+
+## Runtime requirements
+
+- Always cast `dataApi` to an optional connector-method shape.
+- Always presence-check the method before calling it.
+- Always wrap calls in `try`/`catch` and set a graceful empty/error state.
+- Never guess a logical name, dataset, table GUID, operation name, field name,
+ parameter name, or response field name. Use the plan's `## Connector Bindings`
+ values only.
+- Keep non-connector pages unchanged; only emit connector code when the plan has
+ connector bindings.
+
+## Field schema
+
+`config.json.connectorBindings` stores where to fetch connector data, not the
+table's column list. Connector rows are dynamically typed and passed through by
+the runtime; there is no connector equivalent of Dataverse `RuntimeTypes.ts`.
+Therefore the page-builder must declare the connector row interface inline from
+the plan's discovered `Fields` list.
+
+Rules:
+- Build row interfaces only from `## Connector Bindings` → `Fields`.
+- Mark every connector field optional with `?`; connector APIs can omit values
+ row-by-row.
+- Use the discovered field spelling exactly. Do not camel-case, singularize, or
+ infer alternate display names.
+- Use `unknown` for any field whose shape was not discovered with confidence.
+- SharePoint choice columns come back as objects with a `Value` property.
+- For SharePoint, record only maker/user-meaningful columns by default. Keep
+ fields such as `Title`, `PetName`, `OwnerName`, `PetType`, `Created`, and
+ `Modified`; drop system/synthetic fields unless the maker explicitly needs
+ them: `{...}`-wrapped names (`{Identifier}`, `{IsFolder}`, `{Thumbnail}`),
+ `ComplianceAssetId`, `OData__*`, and `*#Id` / `*#Claims` variants.
+- SharePoint `type:"object"` choice columns should be represented as
+ `{ Value?: string }`.
+
+Example discovered SharePoint fields:
+
+```typescript
+type PetRow = { ID?: number; PetName?: string; OwnerName?: string; PetType?: { Value?: string }; Created?: string };
+```
+
+`Created` is represented as a string because connector date/time values arrive
+serialized; parse/format it at the display boundary only when needed.
+
+## Operation schema
+
+REST/action connectors do not use `dataset`/`table`. The planner records the
+selected operation, discovered `Parameters`, and discovered `Response` shape in
+`## Connector Bindings` from `get-connector-schema --operation`.
+
+Rules:
+- Build request parameter objects only from discovered `Parameters` plus the
+ maker's provided values. Never invent parameter names.
+- Declare the response interface from the discovered `Response` schema. Mark
+ every field optional because connector responses are dynamic.
+- If a response field shape is unclear, use `unknown`; if a nested object is
+ discovered, model only the discovered nested properties.
+- Check `response.ok` before casting/reading `response.body`.
+
+Example:
+
+```typescript
+type WeatherResponse = { temperature?: number; conditions?: string; humidity?: number };
+const parameters: { Location: string; units?: string } = { Location: 'Seattle', units: 'C' };
+```
+
+## Verified tabular pattern
+
+```typescript
+const connectorApi = dataApi as unknown as { queryConnectorTable?: (connectorLogicalName: string, dataset: string, table: string, options: Record<string, unknown>) => Promise<{ rows: Row[] }>; };
+if (typeof connectorApi.queryConnectorTable !== 'function') { return; }
+const result = await connectorApi.queryConnectorTable('new_uxtest_sharepoint', 'https://host.sharepoint.com/sites/x', '<list-guid>', { top: 50 });
+```
+
+Use this for connectors exposed as tables/lists. The `dataset` and `table`
+arguments come from `## Connector Bindings` (`Dataset` and `Tables (GUIDs)`).
+
+## Verified REST/action pattern
+
+```typescript
+const connectorApi = dataApi as unknown as { executeConnectorOperation?: (connectorLogicalName: string, operationName: string, parameters: Record<string, unknown>) => Promise<{ ok: boolean; body: unknown }>; };
+if (typeof connectorApi.executeConnectorOperation !== 'function') { return; }
+const response = await connectorApi.executeConnectorOperation('new_uxtest_msnweather', 'CurrentWeather', { Location: 'Seattle', units: 'C' });
+```
+
+Use this for REST-style connector operations. Check `response.ok` before reading
+`response.body`, cast it to the response interface declared from the plan's
+`Response` schema, and keep the call inside the same `try`/`catch` as state
+updates.
diff --git a/plugins/model-apps/references/plan-schema.md b/plugins/model-apps/references/plan-schema.md
index b1246ce00..05646c881 100644
--- a/plugins/model-apps/references/plan-schema.md
+++ b/plugins/model-apps/references/plan-schema.md
@@ -17,7 +17,9 @@ Changing a heading name breaks downstream agents. Add new sections only.
## Required Structure
-All sections must appear in this exact order with these exact headings:
+All required sections must appear in this exact order with these exact headings.
+Optional sections marked opt-in may be omitted; if present, keep them in the
+same relative position so downstream parsers can find them predictably:
```markdown
# Genpage Plan
@@ -102,6 +104,30 @@ validation rejects values that look like `crb2b_playername` or even
Example: "account, contact, task"
OR "None" if all data is mock or all entities need creating.]
+## Connector Bindings
+[If NO connectors are used, the value is exactly:]
+No connector bindings.
+
+[Else, one row per binding. `Fields` is required for tabular connectors and
+records the authoring-time connector column/schema discovery used by the
+page-builder. `Parameters` and `Response` are required for REST/action
+connectors. All connector fields are treated as OPTIONAL in generated TSX
+because connector rows and responses are dynamically typed and may omit values
+at runtime.]
+| Logical Name | Connector Id | Dataset | Tables (GUIDs) | Table Display Names | Operations | Fields | Parameters | Response |
+|--------------|--------------|---------|----------------|---------------------|------------|--------|------------|----------|
+| 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) |
+
+## 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
+opt-in, unlike the always-present `## Connector Bindings` (which uses the "No
+connector bindings." sentinel).]
+- Package into solution: true / false (default false)
+- Solution unique name: [when true — the target solution for cross-env travel]
+- Connection references: [comma-separated connectionreference logical names to include, or "none"]
+
## Design Preferences
- Styling: [user's styling preferences — colors, theme, visual aesthetic]
- Features: [specific features mentioned — search, filtering, sorting, navigation, etc.]
@@ -146,6 +172,8 @@ validation rejects values that look like `crb2b_playername` or even
| `## Pages` | Orchestrator (page list for Phase 5 dispatch) | File names must be unique |
| `## 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` |
+| `## 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/` |
| `## Per-Page Specifications` | Page-builder | Each page gets one `### [Page Name]` subsection matching the Pages table |
@@ -159,6 +187,9 @@ Before the orchestrator fans out to builders in Phase 5, it should verify:
- [ ] Every page in `## Pages` has a unique file name
- [ ] 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 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
If validation fails, the orchestrator should surface a clear error to the user rather
than dispatching builders that will fail silently.
diff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.md
index ce2782f46..f7cfa5094 100644
--- a/plugins/model-apps/references/rules.md
+++ b/plugins/model-apps/references/rules.md
@@ -571,6 +571,14 @@ What you can rely on from RuntimeTypes:
- `BaseUxAgentDataApi<TR, ER>` — the dataApi interface with `createRow`,
`updateRow`, `deleteRow`, `retrieveRow`, `queryTable`, `getChoices`
+### Connector DataAPI (optional — only when the plan has Connector Bindings)
+
+When the plan's `## Connector Bindings` is non-empty, the page may call Power
+Platform connectors via `queryConnectorTable` (tabular) and
+`executeConnectorOperation` (REST). These are optional runtime methods — always
+presence-check before calling. See [connectors.md](./connectors.md) for the
+required patterns and the binding contract.
+
---
## DataAPI Usage Examples
diff --git a/plugins/model-apps/scripts/add-page-to-solution.js b/plugins/model-apps/scripts/add-page-to-solution.js
new file mode 100644
index 000000000..8e97af1a5
--- /dev/null
+++ b/plugins/model-apps/scripts/add-page-to-solution.js
@@ -0,0 +1,128 @@
+#!/usr/bin/env node
+
+// Adds a connector-bound GenPage and its connection references to a solution so it
+// travels cross-environment. Verified live 2026-07-10 on AuroraBAPEnv03468:
+// - The appmodule (type 80, AddRequiredComponents=true) pulls the sitemap (62) and
+// appmodulecomponent (10097) but does NOT pull the GenPage — so the GenPage's
+// uxagentproject row MUST be added explicitly (type 10372); adding it pulls its
+// uxagentprojectfile children (10373, incl. config.json with connectorBindings).
+// - connectionreference is its own component (type 10158) and is added explicitly so
+// the bindings resolve in the target env (at import the deployer supplies each
+// ConnectionId via `pac solution create-settings` + `pac solution import --settings-file`).
+//
+// Usage:
+// node add-page-to-solution.js <envUrl> <solutionUniqueName> <appId>
+// [--page-ids <uxagentprojectId1,uxagentprojectId2>]
+// [--connection-refs <logicalName1,logicalName2>]
+//
+// Output: { "ok": true, "added": [...] }
+
+const {
+ dataverseRequest,
+ ensureOk,
+ parseArgs,
+ emitResult,
+} = require('./lib/dataverse-auth');
+const { isConnectorsEnabled } = require('./lib/feature-flags');
+
+// Connection references are connector state. When the connectors flag is OFF, ALM
+// must not add them — but non-connector page packaging (appmodule + uxagentproject)
+// still proceeds. This is a defense-in-depth backstop: in the normal flow the plan
+// carries no connection-refs when OFF, but a direct/out-of-band call must not slip
+// connector state into a solution while the feature is disabled.
+function connectionRefsToAdd(refs, connectorsEnabled) {
+ return connectorsEnabled ? refs : [];
+}
+
+const APPMODULE_COMPONENT_TYPE = 80;
+// Solution component type for the GenPage itself. uxagentproject IS a registered
+// component type (10372 = its ObjectTypeCode), verified live 2026-07-10 on
+// AuroraBAPEnv03468. It does NOT auto-travel with the appmodule, so it is added
+// explicitly; AddRequiredComponents=true then pulls its uxagentprojectfile rows
+// (10373: page.tsx, page.compiled, config.json, firstPrompt.json).
+const UXAGENTPROJECT_COMPONENT_TYPE = 10372;
+// Solution component type for connectionreference. Verified live (2026-07-10) by
+// reading solutioncomponent.componenttype for an existing connection reference in the
+// Default/Active solutions on AuroraBAPEnv03468 (= 10158). Note: 371 is "Connector"
+// (msdyn_Connector), NOT a connection reference — AddSolutionComponent with 371 fails
+// with "entity ... 'msdyn_Connector' ... not found in MetadataCache".
+const CONNECTION_REFERENCE_COMPONENT_TYPE = 10158;
+
+function escapeODataString(value) {
+ return String(value).replace(/'/g, "''");
+}
+
+async function addComponent(envUrl, solutionUniqueName, componentId, componentType, addRequired) {
+ const body = {
+ ComponentId: componentId,
+ ComponentType: componentType,
+ SolutionUniqueName: solutionUniqueName,
+ AddRequiredComponents: addRequired,
+ };
+ const res = await dataverseRequest(envUrl, 'POST', 'AddSolutionComponent', body);
+ ensureOk(res, `Add component ${componentId} (type ${componentType}) to ${solutionUniqueName}`);
+}
+
+async function main() {
+ const { positional, flags } = parseArgs(process.argv.slice(2));
+ if (positional.length < 3) {
+ process.stderr.write(
+ 'Usage: node add-page-to-solution.js <envUrl> <solutionUniqueName> <appId> [--page-ids <id1,id2>] [--connection-refs <logicalName1,logicalName2>]\n'
+ );
+ process.exit(1);
+ }
+ const [envUrl, solutionUniqueName, appId] = positional;
+ const added = [];
+
+ try {
+ // The appmodule (type 80) with AddRequiredComponents=true pulls the sitemap and
+ // appmodulecomponent, but NOT the GenPage — the page is added explicitly below.
+ await addComponent(envUrl, solutionUniqueName, appId, APPMODULE_COMPONENT_TYPE, true);
+ added.push({ type: 'appmodule', id: appId });
+
+ // Add each GenPage (uxagentproject, type 10372) explicitly. AddRequiredComponents
+ // pulls its uxagentprojectfile rows (10373) — including config.json with the
+ // connectorBindings that must travel with the page.
+ const pageIds = (flags['page-ids'] || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+ for (const pageId of pageIds) {
+ await addComponent(envUrl, solutionUniqueName, pageId, UXAGENTPROJECT_COMPONENT_TYPE, true);
+ added.push({ type: 'uxagentproject', id: pageId });
+ }
+
+ const refs = (flags['connection-refs'] || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+ // Gate the connection-reference branch on the connectors flag (see above).
+ const connectorsOn = isConnectorsEnabled();
+ const refsToAdd = connectionRefsToAdd(refs, connectorsOn);
+ const skippedConnectionRefs = connectorsOn ? [] : refs;
+ for (const logicalName of refsToAdd) {
+ const query =
+ `connectionreferences?$filter=connectionreferencelogicalname eq '${escapeODataString(logicalName)}'` +
+ '&$select=connectionreferenceid&$top=1';
+ const lookup = await dataverseRequest(envUrl, 'GET', query);
+ ensureOk(lookup, `Lookup connection reference ${logicalName}`);
+ const id = lookup.data?.value?.[0]?.connectionreferenceid;
+ if (!id) throw new Error(`Connection reference '${logicalName}' not found in env`);
+
+ await addComponent(envUrl, solutionUniqueName, id, CONNECTION_REFERENCE_COMPONENT_TYPE, false);
+ added.push({ type: 'connectionreference', logicalName, id });
+ }
+
+ emitResult(true, { ok: true, added, skippedConnectionRefs });
+ } catch (e) {
+ emitResult(false, e);
+ }
+}
+
+// Only run when invoked directly as a CLI; requiring the module (e.g. from tests)
+// must not execute main().
+if (require.main === module) {
+ main();
+}
+
+module.exports = { connectionRefsToAdd };
diff --git a/plugins/model-apps/scripts/add-to-solution.js b/plugins/model-apps/scripts/add-to-solution.js
index 9a4b5b46b..ddb2d39e6 100644
--- a/plugins/model-apps/scripts/add-to-solution.js
+++ b/plugins/model-apps/scripts/add-to-solution.js
@@ -19,7 +19,19 @@
// 61 = Web Resource
// 62 = Site Map
// 65 = Hierarchy Rule
-// 80 = Model-driven App (appmodule)
+// 80 = Model-driven App (appmodule)
+// 10158 = Connection Reference (connectionreference) — verified live 2026-07-10 on
+// AuroraBAPEnv03468. NOTE: 371 is "Connector" (msdyn_Connector), NOT a
+// connection reference; AddSolutionComponent with 371 fails with a
+// MetadataCache 'msdyn_Connector' error.
+//
+// NOTE: a GenPage's uxagentproject IS a registered solution component type
+// (10372 = its ObjectTypeCode), but it does NOT auto-travel with the appmodule.
+// Adding the appmodule (type 80) with AddRequiredComponents=true pulls the sitemap
+// (62) and appmodulecomponent (10097) but NOT the GenPage, so the uxagentproject
+// row must be added EXPLICITLY (adding it then pulls its uxagentprojectfile
+// children, 10373, incl. config.json with connectorBindings). See
+// add-page-to-solution.js.
//
// Output: { "ok": true }
diff --git a/plugins/model-apps/scripts/create-connection-reference.js b/plugins/model-apps/scripts/create-connection-reference.js
new file mode 100644
index 000000000..addb0c35f
--- /dev/null
+++ b/plugins/model-apps/scripts/create-connection-reference.js
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+
+// Creates a Dataverse connectionreference row — the env-portable binding target
+// that a GenPage's config.json connectorBindings[].logicalName resolves to at
+// runtime. The runtime looks up the connectionreference by logical name to get
+// the env-specific connectionId, so the page travels cross-env while the
+// connection stays env-local.
+// See: https://learn.microsoft.com/power-apps/maker/data-platform/create-connection-reference
+//
+// Usage:
+// node create-connection-reference.js <envUrl> <logicalName> <connectorId>
+// [--connection-id <connectionId>] (bind to an existing connection now)
+// [--display-name <name>]
+//
+// <connectorId> is the API id, e.g.
+// /providers/Microsoft.PowerApps/apis/shared_sharepointonline
+//
+// Output: { "ok": true, "connectionReferenceId": "...", "logicalName": "..." }
+
+const {
+ dataverseRequest,
+ ensureOk,
+ parseArgs,
+ emitResult,
+} = require('./lib/dataverse-auth');
+const { exitIfConnectorsDisabled } = require('./lib/feature-flags');
+
+async function main() {
+ // Feature gate first (fail closed) — see lib/feature-flags.js. Exit 3 = "feature
+ // off", distinct from 1 = runtime/usage error, so callers can tell them apart.
+ exitIfConnectorsDisabled();
+
+ const { positional, flags } = parseArgs(process.argv.slice(2));
+ if (positional.length < 3) {
+ process.stderr.write(
+ 'Usage: node create-connection-reference.js <envUrl> <logicalName> <connectorId> [--connection-id <id>] [--display-name <name>]\n'
+ );
+ process.exit(1);
+ }
+ const [envUrl, logicalName, connectorId] = positional;
+
+ const body = {
+ connectionreferencelogicalname: logicalName,
+ connectionreferencedisplayname: flags['display-name'] || logicalName,
+ connectorid: connectorId,
+ };
+ // Binding is optional because ALM imports fill target-env ConnectionId values
+ // through deployment settings; same-env smoke runs can bind immediately.
+ if (flags['connection-id']) body.connectionid = flags['connection-id'];
+
+ try {
+ const res = await dataverseRequest(envUrl, 'POST', 'connectionreferences', body, { includeHeaders: true });
+ ensureOk(res, `Create connection reference ${logicalName}`);
+ const entityUrl = res.headers && (res.headers['odata-entityid'] || res.headers['OData-EntityId']);
+ let connectionReferenceId = null;
+ if (entityUrl) {
+ const m = String(entityUrl).match(/\(([0-9a-f-]{36})\)/i);
+ if (m) connectionReferenceId = m[1];
+ }
+ emitResult(true, { ok: true, connectionReferenceId, logicalName });
+ } catch (e) {
+ emitResult(false, e);
+ }
+}
+
+// Only run when invoked directly as a CLI; requiring the module (e.g. from tests)
+// must not execute main() and its gate/exit — mirrors list-connections.js.
+if (require.main === module) {
+ main();
+}
+
+module.exports = { main };
diff --git a/plugins/model-apps/scripts/lib/feature-flags.js b/plugins/model-apps/scripts/lib/feature-flags.js
new file mode 100644
index 000000000..5ae02cd9e
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/feature-flags.js
@@ -0,0 +1,210 @@
+#!/usr/bin/env node
+'use strict';
+
+// Central feature-flag gate for the /genpage skill.
+//
+// WHY: connector support spans three repos that ship on independent cadences —
+// the pac CLI connector verbs (PowerPlatform-Scale-AdminTools), the GenUX
+// authoring control (power-platform-ux), and the maker/admin ECS setting. Until
+// ALL of them are live in PROD, the skill must behave exactly as it did before
+// connectors existed. A committed, default-OFF flag lets us merge the skill code
+// ahead of GA and flip it on in a one-line follow-up PR (or per-run via env var)
+// once the dependencies are released — instead of carrying an un-merged branch.
+//
+// Precedence (highest first), mirroring the telemetry opt-out convention in
+// AGENTS.md where an env var overrides committed config:
+// 1. env var GENPAGE_ENABLE_<FLAG> (e.g. GENPAGE_ENABLE_CONNECTORS)
+// 2. committed feature-flags.json at the plugin root
+// 3. default: false (fail-closed — unknown/unset flags are OFF)
+//
+// CLI probe (so an LLM-driven skill step can gate on the exit code):
+// node scripts/lib/feature-flags.js <flag>
+// prints "enabled" + exit 0 when the flag is ON
+// prints "disabled" + exit 1 when the flag is OFF
+
+const fs = require('node:fs');
+const path = require('node:path');
+
+// The committed flag file lives at the plugin root; from scripts/lib that's two up.
+const FLAGS_PATH = path.resolve(__dirname, '..', '..', 'feature-flags.json');
+
+// Truthy env values follow the common CLI convention (dotnet/bash style):
+// 1/true/yes/on enable; 0/false/no/off disable; anything else (including unset
+// or empty) returns null so the caller defers to the next precedence layer
+// rather than guessing.
+function parseBool(value) {
+ if (value == null) return null;
+ const v = String(value).trim().toLowerCase();
+ if (v === '') return null;
+ if (['1', 'true', 'yes', 'on'].includes(v)) return true;
+ if (['0', 'false', 'no', 'off'].includes(v)) return false;
+ return null;
+}
+
+// 'connectors' -> GENPAGE_ENABLE_CONNECTORS. Non-alphanumeric runs in a flag name
+// collapse to a single '_' so multi-word flags still map to a legal env var name.
+function envVarName(flag) {
+ return 'GENPAGE_ENABLE_' + String(flag).toUpperCase().replace(/[^A-Z0-9]+/g, '_');
+}
+
+function readFlagsFile(flagsPath) {
+ try {
+ const parsed = JSON.parse(fs.readFileSync(flagsPath, 'utf8'));
+ return parsed && typeof parsed === 'object' ? parsed : {};
+ } catch {
+ // A missing, unreadable, or invalid config is fail-closed: treat as no flags
+ // set so a corrupt file can never silently enable an unreleased feature.
+ return {};
+ }
+}
+
+/**
+ * Returns whether a named feature flag is enabled.
+ *
+ * @param {string} flag Flag name (e.g. 'connectors').
+ * @param {object} [opts]
+ * @param {NodeJS.ProcessEnv} [opts.env] Env source (defaults to process.env).
+ * @param {object} [opts.flags] Pre-loaded flags map (skips file read).
+ * @param {string} [opts.flagsPath] Alternate flags file path (defaults to
+ * the committed plugin-root file).
+ * @returns {boolean}
+ */
+function isEnabled(flag, opts = {}) {
+ const env = opts.env || process.env;
+ const envValue = parseBool(env[envVarName(flag)]);
+ if (envValue !== null) return envValue; // env override wins
+
+ const flags = opts.flags || readFlagsFile(opts.flagsPath || FLAGS_PATH);
+ // Strictly === true; anything else (false, missing, non-boolean) is OFF.
+ return flags[flag] === true;
+}
+
+function isConnectorsEnabled(opts) {
+ return isEnabled('connectors', 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 —
+// feature-flags.json only carries the on/off value; this catalog carries the
+// metadata (what it enables, what it depends on, how to turn it on).
+const FLAGS = {
+ connectors: {
+ status: 'in-progress',
+ summary:
+ 'GenPage connector authoring (SharePoint, weather, Office 365, SQL, custom REST) ' +
+ 'and ALM packaging of connection references.',
+ dependencies:
+ 'pac CLI connector verbs (PowerPlatform-Scale-AdminTools), the GenUX authoring ' +
+ 'control (power-platform-ux), and the maker/admin ECS setting — all live in PROD.',
+ enableEnv: 'GENPAGE_ENABLE_CONNECTORS=1',
+ },
+};
+
+// Flag names the skill knows about, derived from the catalog. Used to validate the
+// committed file (catch typo'd keys that would silently stay OFF — or, after a flip
+// to true, an unintended key) and to enumerate state via `describe()`.
+const KNOWN_FLAGS = Object.keys(FLAGS);
+
+// Fail-closed gate shared by every connector script entry point. Centralizing it
+// (instead of each script inlining the same `if (!isConnectorsEnabled()) exit 3`)
+// keeps the disabled message and exit code (3 = "feature off", distinct from
+// 1 = runtime/usage error) consistent and prevents drift. `exit`/`write` are
+// injectable for unit testing.
+function exitIfConnectorsDisabled(opts = {}) {
+ const exit = opts.exit || process.exit;
+ const write = opts.write || ((s) => process.stderr.write(s));
+ if (!isConnectorsEnabled(opts)) {
+ write(connectorsDisabledMessage() + '\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.
+function describe(opts = {}) {
+ const env = opts.env || process.env;
+ const flags = opts.flags || readFlagsFile(opts.flagsPath || FLAGS_PATH);
+ return KNOWN_FLAGS.map((flag) => {
+ const envVal = parseBool(env[envVarName(flag)]);
+ const source = envVal !== null
+ ? 'env'
+ : Object.prototype.hasOwnProperty.call(flags, flag)
+ ? 'file'
+ : 'default';
+ return { flag, enabled: isEnabled(flag, { env, flags }), source, status: FLAGS[flag].status };
+ });
+}
+
+// Returns human-readable warnings for a flags object: unknown keys (typos that
+// would silently do nothing) and non-boolean values. Keys starting with '_' are
+// treated as documentation (the committed file uses `_comment`). Returns [] when
+// the file is clean.
+function validateFlags(flags) {
+ const warnings = [];
+ for (const [key, value] of Object.entries(flags || {})) {
+ if (key.startsWith('_')) continue;
+ if (!KNOWN_FLAGS.includes(key)) {
+ warnings.push(`unknown flag "${key}" (known flags: ${KNOWN_FLAGS.join(', ')})`);
+ } else if (typeof value !== 'boolean') {
+ warnings.push(`flag "${key}" should be a boolean, got ${typeof value} (${JSON.stringify(value)})`);
+ }
+ }
+ return warnings;
+}
+
+// Standard operator-facing message printed when a connector entrypoint is invoked
+// while the flag is OFF. Centralized so every connector script speaks with one voice.
+function connectorsDisabledMessage() {
+ return (
+ 'Connector support is disabled (feature flag "connectors" is OFF). ' +
+ 'GenPage connectors require the pac CLI connector verbs, the GenUX authoring ' +
+ 'control, and the maker/admin setting to all be live in PROD. To enable for a ' +
+ 'single run set GENPAGE_ENABLE_CONNECTORS=1, or flip "connectors" to true in ' +
+ 'plugins/model-apps/feature-flags.json once the dependencies are released.'
+ );
+}
+
+module.exports = {
+ isEnabled,
+ isConnectorsEnabled,
+ connectorsDisabledMessage,
+ exitIfConnectorsDisabled,
+ describe,
+ validateFlags,
+ envVarName,
+ parseBool,
+ FLAGS,
+ KNOWN_FLAGS,
+ FLAGS_PATH,
+};
+
+// CLI:
+// node feature-flags.js <flag> → exit 0 (enabled) / 1 (disabled) / 2 (usage)
+// node feature-flags.js --list → prints every known flag's state + source,
+// plus any validation warnings for the file.
+if (require.main === module) {
+ const arg = process.argv[2];
+ if (arg === '--list') {
+ for (const { flag, enabled, source, status } of describe()) {
+ process.stdout.write(
+ `${flag}: ${enabled ? 'enabled' : 'disabled'} (status: ${status}, source: ${source})\n`
+ );
+ process.stdout.write(` ${FLAGS[flag].summary}\n`);
+ process.stdout.write(` enable: ${FLAGS[flag].enableEnv} (or set "${flag}": true in feature-flags.json)\n`);
+ }
+ for (const w of validateFlags(readFlagsFile(FLAGS_PATH))) {
+ process.stderr.write(`warning: ${w}\n`);
+ }
+ process.exit(0);
+ }
+ if (!arg) {
+ process.stderr.write('Usage: node feature-flags.js <flag> | --list\n');
+ process.exit(2);
+ }
+ const on = isEnabled(arg);
+ process.stdout.write((on ? 'enabled' : 'disabled') + '\n');
+ process.exit(on ? 0 : 1);
+}
diff --git a/plugins/model-apps/scripts/list-connections.js b/plugins/model-apps/scripts/list-connections.js
new file mode 100644
index 000000000..a3bc09035
--- /dev/null
+++ b/plugins/model-apps/scripts/list-connections.js
@@ -0,0 +1,245 @@
+#!/usr/bin/env node
+
+// Lists maker connections and Dataverse connection references for connector
+// binding. Connections come from PAC because the Power Platform connection APIs
+// are outside Dataverse; connectionreferences come from Dataverse because the
+// GenPage runtime binds config.json connectorBindings[].logicalName to those rows.
+//
+// Usage:
+// node list-connections.js <envUrl>
+//
+// Output:
+// { "ok": true, "connections": [...], "connectionReferences": [...] }
+
+const { spawnSync } = require('node:child_process');
+const {
+ dataverseRequest,
+ ensureOk,
+ parseArgs,
+ emitResult,
+} = require('./lib/dataverse-auth');
+const { exitIfConnectorsDisabled } = require('./lib/feature-flags');
+
+function normalizeHeader(header) {
+ return String(header).toLowerCase().replace(/[^a-z0-9]/g, '');
+}
+
+function mapConnectionRow(row) {
+ const normalized = {};
+ for (const [key, value] of Object.entries(row)) {
+ normalized[normalizeHeader(key)] = value;
+ }
+
+ const connectionId =
+ normalized.connectionid ||
+ normalized.id ||
+ normalized.connection ||
+ '';
+ const connectorId =
+ normalized.connectorid ||
+ normalized.apiid ||
+ normalized.connector ||
+ extractConnectorId(connectionId) ||
+ '';
+ const displayName =
+ normalized.connectionname ||
+ normalized.displayname ||
+ normalized.name ||
+ connectorId ||
+ connectionId;
+
+ return { connectorId, connectionId, displayName };
+}
+
+function extractConnectorId(connectionId) {
+ const match = String(connectionId).match(/(\/providers\/Microsoft\.PowerApps\/apis\/[^/]+)\/connections/i);
+ return match ? match[1] : '';
+}
+
+function parseJsonConnections(raw) {
+ try {
+ const parsed = JSON.parse(raw);
+ const rows = Array.isArray(parsed) ? parsed : parsed?.value;
+ if (!Array.isArray(rows)) return null;
+ return rows.map(mapConnectionRow).filter((row) => row.connectorId || row.connectionId || row.displayName);
+ } catch {
+ return null;
+ }
+}
+
+function parseFixedWidthTable(raw) {
+ const lines = raw.replace(/\r/g, '').split('\n');
+ const separatorIndex = lines.findIndex((line) => {
+ const runs = line.match(/-{3,}/g) || [];
+ return runs.length >= 2;
+ });
+ if (separatorIndex <= 0) return [];
+
+ const headerLine = lines[separatorIndex - 1];
+ const ranges = [...lines[separatorIndex].matchAll(/-+/g)].map((match, index, matches) => ({
+ name: headerLine.slice(match.index, matches[index + 1]?.index).trim(),
+ start: match.index,
+ end: matches[index + 1]?.index,
+ }));
+
+ return lines
+ .slice(separatorIndex + 1)
+ .filter((line) => line.trim() && !/^-+$/.test(line.trim()))
+ .map((line) => {
+ const row = {};
+ for (const range of ranges) {
+ row[range.name] = line.slice(range.start, range.end).trim();
+ }
+ return mapConnectionRow(row);
+ })
+ .filter((row) => row.connectorId || row.connectionId || row.displayName);
+}
+
+function parseWhitespaceTable(raw) {
+ const lines = raw.replace(/\r/g, '').split('\n').filter((line) => line.trim());
+ const headerIndex = lines.findIndex((line) => /Connection Name|Connection Id|Connector/i.test(line));
+ if (headerIndex === -1) return [];
+ const headers = lines[headerIndex].trim().split(/\s{2,}/);
+ return lines
+ .slice(headerIndex + 1)
+ .filter((line) => !/^-+$/.test(line.trim()))
+ .map((line) => {
+ const values = line.trim().split(/\s{2,}/);
+ const row = {};
+ headers.forEach((header, index) => {
+ row[header] = values[index] || '';
+ });
+ return mapConnectionRow(row);
+ })
+ .filter((row) => row.connectorId || row.connectionId || row.displayName);
+}
+
+function parsePacConnectionList(raw) {
+ const jsonRows = parseJsonConnections(raw);
+ if (jsonRows) return jsonRows;
+
+ // PAC commonly emits a fixed-width table similar to:
+ // Connection Name Connector Id Connection Id
+ // --------------------- ----------------------------------------------------- ------------------------------------
+ // Contoso SharePoint /providers/Microsoft.PowerApps/apis/shared_sharepointonline /providers/.../connections/abc
+ // Some older builds wrap friendly names but keep 2+ spaces between columns, so
+ // parse fixed-width first and fall back to a whitespace table for simpler output.
+ const fixed = parseFixedWidthTable(raw);
+ return fixed.length ? fixed : parseWhitespaceTable(raw);
+}
+
+function sameConnectionId(a, b) {
+ const left = String(a || '').toLowerCase();
+ const right = String(b || '').toLowerCase();
+ return Boolean(left && right && (left === right || left.endsWith(`/${right}`) || right.endsWith(`/${left}`)));
+}
+
+function refsForConnection(connection, connectionReferences) {
+ return connectionReferences.filter((ref) => {
+ const sameConnection = sameConnectionId(connection.connectionId, ref.connectionId);
+ const sameConnector =
+ connection.connectorId &&
+ ref.connectorId &&
+ String(connection.connectorId).toLowerCase() === String(ref.connectorId).toLowerCase();
+ return sameConnection || sameConnector;
+ });
+}
+
+function sortReadyToBindFirst(connections, connectionReferences) {
+ return connections
+ .map((connection) => {
+ const refs = refsForConnection(connection, connectionReferences);
+ // "Ready to bind" means a connectionreference is actually bound to THIS
+ // connection (its connectionId matches). Matching only by connectorId is
+ // not enough — that reference may be bound to a different connection (or
+ // none), so binding a page to it here would not resolve at runtime. The
+ // broader `connectionReferences` list still includes connector-id matches
+ // for operator convenience.
+ const boundRefs = refs.filter((ref) => sameConnectionId(connection.connectionId, ref.connectionId));
+ return {
+ ...connection,
+ readyToBind: boundRefs.length > 0,
+ connectionReferences: refs.map((ref) => ref.logicalName),
+ };
+ })
+ .sort((a, b) => {
+ if (a.readyToBind !== b.readyToBind) return a.readyToBind ? -1 : 1;
+ return String(a.displayName).localeCompare(String(b.displayName));
+ });
+}
+
+function pacFailureMessage(pac) {
+ // spawnSync signals a failure to LAUNCH the process (e.g. `pac` not on PATH →
+ // ENOENT) via `pac.error`, leaving `status` null. A process that ran but exited
+ // non-zero has a numeric `status` (and maybe a `signal`). Distinguish the two so
+ // a missing PAC install produces an actionable message instead of "exit null".
+ if (pac.error) {
+ return `pac connection list could not run: ${pac.error.message}. Ensure the PAC CLI is installed and on PATH (dotnet tool install -g Microsoft.PowerApps.CLI.Tool).`;
+ }
+ const detail = String(pac.stderr || pac.stdout || '').trim();
+ const signal = pac.signal ? `, signal ${pac.signal}` : '';
+ return `pac connection list failed (exit ${pac.status}${signal})${detail ? `: ${detail}` : ''}`;
+}
+
+async function main() {
+ // Feature gate first (fail closed) — see lib/feature-flags.js. Exit 3 = "feature
+ // off", distinct from 1 = runtime/usage error, so callers can tell them apart.
+ exitIfConnectorsDisabled();
+
+ const { positional } = parseArgs(process.argv.slice(2));
+ if (positional.length < 1) {
+ process.stderr.write('Usage: node list-connections.js <envUrl>\n');
+ process.exit(1);
+ }
+ const [envUrl] = positional;
+
+ try {
+ const pac = spawnSync('pac', ['connection', 'list'], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ shell: process.platform === 'win32',
+ });
+ if (pac.error || pac.status !== 0) {
+ throw new Error(pacFailureMessage(pac));
+ }
+ const connections = parsePacConnectionList(pac.stdout);
+
+ // NB: on `connectionreference`, `connectionid` is a plain String attribute (not a Dataverse
+ // lookup), so it's selected as `connectionid` — `_connectionid_value` does not exist and 400s.
+ const refsRes = await dataverseRequest(
+ envUrl,
+ 'GET',
+ 'connectionreferences?$select=connectionreferencelogicalname,connectorid,connectionid'
+ );
+ ensureOk(refsRes, 'List connection references');
+ const connectionReferences = (refsRes.data?.value || [])
+ .map((row) => ({
+ logicalName: row.connectionreferencelogicalname,
+ connectorId: row.connectorid,
+ connectionId: row.connectionid || null,
+ }))
+ .filter((row) => row.logicalName)
+ .sort((a, b) => String(a.logicalName).localeCompare(String(b.logicalName)));
+
+ emitResult(true, {
+ ok: true,
+ connections: sortReadyToBindFirst(connections, connectionReferences),
+ connectionReferences,
+ });
+ } 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 side effects.
+if (require.main === module) {
+ main();
+}
+
+module.exports = {
+ sameConnectionId,
+ refsForConnection,
+ sortReadyToBindFirst,
+ pacFailureMessage,
+};
diff --git a/plugins/model-apps/scripts/tests/add-page-to-solution.test.js b/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
new file mode 100644
index 000000000..3ca4799f1
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/add-page-to-solution.test.js
@@ -0,0 +1,37 @@
+'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, '..', 'add-page-to-solution.js');
+const scriptSrc = fs.readFileSync(scriptPath, 'utf8');
+
+test('adds appmodule (80) with required components', () => {
+ assert.match(scriptSrc, /APPMODULE_COMPONENT_TYPE\s*=\s*80/);
+ assert.match(scriptSrc, /addComponent\([^)]*APPMODULE_COMPONENT_TYPE,\s*true\)/);
+});
+
+test('adds connection references by confirmed component type', () => {
+ assert.match(scriptSrc, /connectionreferences\?\$filter=connectionreferencelogicalname/);
+ assert.match(scriptSrc, /CONNECTION_REFERENCE_COMPONENT_TYPE\s*=\s*10158/);
+});
+
+test('adds the GenPage uxagentproject explicitly (type 10372)', () => {
+ assert.match(scriptSrc, /UXAGENTPROJECT_COMPONENT_TYPE\s*=\s*10372/);
+ assert.match(scriptSrc, /flags\['page-ids'\]/);
+});
+
+test('missing args exits 1 with usage', () => {
+ const res = spawnSync(process.execPath, [scriptPath], { encoding: 'utf8' });
+ assert.equal(res.status, 1);
+ assert.match(res.stderr, /Usage:/);
+});
+
+const { connectionRefsToAdd } = require(scriptPath);
+
+test('connection references are gated by the connectors flag (added only when ON)', () => {
+ assert.deepEqual(connectionRefsToAdd(['new_a', 'new_b'], true), ['new_a', 'new_b']);
+ assert.deepEqual(connectionRefsToAdd(['new_a', 'new_b'], false), []);
+});
diff --git a/plugins/model-apps/scripts/tests/add-to-solution.test.js b/plugins/model-apps/scripts/tests/add-to-solution.test.js
index 4ae080388..687015550 100644
--- a/plugins/model-apps/scripts/tests/add-to-solution.test.js
+++ b/plugins/model-apps/scripts/tests/add-to-solution.test.js
@@ -18,6 +18,14 @@ test('add-to-solution.js builds canonical request body', () => {
assert.match(scriptSrc, /SolutionUniqueName: solutionUniqueName/);
});
+test('add-to-solution.js documents connection reference component type', () => {
+ assert.match(scriptSrc, /10158\s*=\s*Connection Reference/);
+});
+
+test('add-to-solution.js notes uxagentproject travels via appmodule', () => {
+ assert.match(scriptSrc, /uxagentproject/i);
+});
+
test('add-to-solution.js: missing args exits 1 with usage', () => {
const res = spawnSync(process.execPath, [scriptPath], { encoding: 'utf8' });
assert.equal(res.status, 1);
diff --git a/plugins/model-apps/scripts/tests/create-connection-reference.test.js b/plugins/model-apps/scripts/tests/create-connection-reference.test.js
new file mode 100644
index 000000000..134d280d2
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/create-connection-reference.test.js
@@ -0,0 +1,39 @@
+'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, '..', 'create-connection-reference.js');
+const scriptSrc = fs.readFileSync(scriptPath, 'utf8');
+
+test('posts to connectionreferences', () => {
+ assert.match(scriptSrc, /connectionreferences/);
+});
+
+test('binds connectorid and logical name', () => {
+ assert.match(scriptSrc, /connectionreferencelogicalname/);
+ assert.match(scriptSrc, /connectorid/);
+});
+
+test('missing args exits 1 with usage', () => {
+ // Enable connectors so the run reaches arg validation instead of the feature gate.
+ const res = spawnSync(process.execPath, [scriptPath], {
+ encoding: 'utf8',
+ env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '1' },
+ });
+ assert.equal(res.status, 1);
+ assert.match(res.stderr, /Usage:/);
+});
+
+test('exits 3 with a disabled message when the connectors flag is OFF', () => {
+ // Gate runs before any Dataverse call, so complete args still bail out early.
+ const res = spawnSync(
+ process.execPath,
+ [scriptPath, 'https://example.crm.dynamics.com', 'new_x', '/providers/Microsoft.PowerApps/apis/shared_x'],
+ { encoding: 'utf8', env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '0' } }
+ );
+ assert.equal(res.status, 3);
+ assert.match(res.stderr, /disabled/i);
+});
diff --git a/plugins/model-apps/scripts/tests/feature-flags.test.js b/plugins/model-apps/scripts/tests/feature-flags.test.js
new file mode 100644
index 000000000..07a1e52d1
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/feature-flags.test.js
@@ -0,0 +1,191 @@
+'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 libPath = path.join(__dirname, '..', 'lib', 'feature-flags.js');
+const {
+ isEnabled,
+ isConnectorsEnabled,
+ connectorsDisabledMessage,
+ envVarName,
+ parseBool,
+ exitIfConnectorsDisabled,
+ describe,
+ validateFlags,
+ KNOWN_FLAGS,
+ FLAGS,
+} = require(libPath);
+
+// --- Default OFF (fail-closed) ---------------------------------------------
+
+test('connectors flag is OFF by default (no env override)', () => {
+ // Empty env → falls through to the committed feature-flags.json, which ships false.
+ assert.equal(isConnectorsEnabled({ env: {} }), false);
+});
+
+test('unknown flags are OFF (fail-closed)', () => {
+ assert.equal(isEnabled('does-not-exist', { env: {} }), false);
+});
+
+test('missing/invalid flags file is treated as all-OFF', () => {
+ assert.equal(
+ isEnabled('connectors', { env: {}, flagsPath: path.join(__dirname, 'no-such-flags.json') }),
+ false
+ );
+});
+
+// --- Env override precedence (env wins over committed config) ----------------
+
+test('env var enables a flag that is false in config', () => {
+ assert.equal(
+ isEnabled('connectors', { env: { GENPAGE_ENABLE_CONNECTORS: '1' }, flags: { connectors: false } }),
+ true
+ );
+});
+
+test('env var OFF overrides config true', () => {
+ assert.equal(
+ isEnabled('connectors', { env: { GENPAGE_ENABLE_CONNECTORS: '0' }, flags: { connectors: true } }),
+ false
+ );
+});
+
+test('unrecognized env value defers to config', () => {
+ assert.equal(
+ isEnabled('connectors', { env: { GENPAGE_ENABLE_CONNECTORS: 'maybe' }, flags: { connectors: true } }),
+ true
+ );
+});
+
+test('config true enables when env is unset', () => {
+ assert.equal(isEnabled('connectors', { env: {}, flags: { connectors: true } }), true);
+});
+
+// --- Helpers ----------------------------------------------------------------
+
+test('envVarName maps flag names to GENPAGE_ENABLE_<FLAG>', () => {
+ assert.equal(envVarName('connectors'), 'GENPAGE_ENABLE_CONNECTORS');
+ assert.equal(envVarName('multi-word flag'), 'GENPAGE_ENABLE_MULTI_WORD_FLAG');
+});
+
+test('parseBool recognizes common truthy/falsey tokens, defers otherwise', () => {
+ for (const v of ['1', 'true', 'TRUE', 'yes', 'on', ' On ']) assert.equal(parseBool(v), true, `truthy: ${v}`);
+ for (const v of ['0', 'false', 'no', 'off', 'OFF']) assert.equal(parseBool(v), false, `falsey: ${v}`);
+ for (const v of [undefined, null, '', ' ', 'maybe']) assert.equal(parseBool(v), null, `defer: ${String(v)}`);
+});
+
+test('connectorsDisabledMessage explains how to enable', () => {
+ const m = connectorsDisabledMessage();
+ assert.match(m, /GENPAGE_ENABLE_CONNECTORS/);
+ assert.match(m, /feature-flags\.json/);
+});
+
+// --- Committed config actually ships OFF ------------------------------------
+
+test('committed feature-flags.json ships connectors: false', () => {
+ const json = JSON.parse(
+ fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8')
+ );
+ assert.equal(json.connectors, false);
+});
+
+// --- CLI probe (deterministic gate for the skill markdown) ------------------
+
+test('CLI prints "disabled" and exits 1 when OFF', () => {
+ const res = spawnSync(process.execPath, [libPath, 'connectors'], {
+ encoding: 'utf8',
+ env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '' },
+ });
+ assert.equal(res.status, 1);
+ assert.match(res.stdout, /disabled/);
+});
+
+test('CLI prints "enabled" and exits 0 when env override ON', () => {
+ const res = spawnSync(process.execPath, [libPath, 'connectors'], {
+ encoding: 'utf8',
+ env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '1' },
+ });
+ assert.equal(res.status, 0);
+ assert.match(res.stdout, /enabled/);
+});
+
+test('CLI without a flag name exits 2 with usage', () => {
+ const res = spawnSync(process.execPath, [libPath], { encoding: 'utf8' });
+ assert.equal(res.status, 2);
+ assert.match(res.stderr, /Usage:/);
+});
+
+// --- exitIfConnectorsDisabled (DRY gate helper) -----------------------------
+
+test('exitIfConnectorsDisabled exits 3 and writes the message when OFF', () => {
+ let exitCode = null;
+ let written = '';
+ exitIfConnectorsDisabled({
+ env: {},
+ exit: (c) => { exitCode = c; },
+ write: (s) => { written += s; },
+ });
+ assert.equal(exitCode, 3);
+ assert.match(written, /disabled/i);
+});
+
+test('exitIfConnectorsDisabled is a no-op when ON', () => {
+ let exitCalled = false;
+ exitIfConnectorsDisabled({
+ env: { GENPAGE_ENABLE_CONNECTORS: '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('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');
+ assert.equal(c1.enabled, true);
+ assert.equal(c1.source, 'env');
+
+ const fileOn = describe({ env: {}, flags: { connectors: true } });
+ const c2 = fileOn.find((f) => f.flag === 'connectors');
+ assert.equal(c2.enabled, true);
+ assert.equal(c2.source, 'file');
+
+ const dflt = describe({ env: {}, flags: {} });
+ const c3 = dflt.find((f) => f.flag === 'connectors');
+ assert.equal(c3.enabled, false);
+ assert.equal(c3.source, 'default');
+});
+
+test('validateFlags warns on unknown keys and non-boolean values, ignores _comment', () => {
+ assert.deepEqual(validateFlags({ connectors: false, _comment: 'x' }), []);
+ assert.match(validateFlags({ conectors: true })[0], /unknown flag/i);
+ assert.match(validateFlags({ connectors: 'yes' })[0], /boolean/i);
+});
+
+// --- flag catalog: status tracking for experimental / in-progress features --
+
+test('FLAGS catalog documents connectors with a status and summary', () => {
+ assert.ok(FLAGS.connectors, 'connectors flag should be in the catalog');
+ assert.ok(['experimental', 'in-progress', 'ga'].includes(FLAGS.connectors.status));
+ assert.match(FLAGS.connectors.summary, /connector/i);
+ assert.ok(FLAGS.connectors.dependencies, 'should document what it depends on');
+});
+
+test('KNOWN_FLAGS is derived from the FLAGS catalog', () => {
+ assert.deepEqual(KNOWN_FLAGS, Object.keys(FLAGS));
+});
+
+test('describe includes the status for each known flag', () => {
+ const d = describe({ env: {}, flags: {} });
+ const c = d.find((f) => f.flag === 'connectors');
+ assert.equal(c.status, FLAGS.connectors.status);
+});
diff --git a/plugins/model-apps/scripts/tests/list-connections.test.js b/plugins/model-apps/scripts/tests/list-connections.test.js
new file mode 100644
index 000000000..67900a2ad
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/list-connections.test.js
@@ -0,0 +1,84 @@
+'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-connections.js');
+const scriptSrc = fs.readFileSync(scriptPath, 'utf8');
+
+test('reads connection references (ready-to-bind first)', () => {
+ assert.match(scriptSrc, /connectionreferences\?\$select=connectionreferencelogicalname,connectorid,connectionid/);
+ assert.match(scriptSrc, /readyToBind/);
+});
+
+test('invokes pac connection list', () => {
+ assert.match(scriptSrc, /connection['"\s,]+list/);
+});
+
+test('documents raw pac output parsed', () => {
+ assert.match(scriptSrc, /Connection Name/);
+});
+
+test('missing args exits 1 with usage', () => {
+ // Enable connectors so the run reaches arg validation instead of the feature gate.
+ const res = spawnSync(process.execPath, [scriptPath], {
+ encoding: 'utf8',
+ env: { ...process.env, GENPAGE_ENABLE_CONNECTORS: '1' },
+ });
+ assert.equal(res.status, 1);
+ assert.match(res.stderr, /Usage:/);
+});
+
+test('exits 3 with a disabled message when the connectors flag is OFF', () => {
+ // Gate runs before any pac/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_CONNECTORS: '0' },
+ });
+ assert.equal(res.status, 3);
+ assert.match(res.stderr, /disabled/i);
+});
+
+// --- Unit tests for the pure helpers (require.main guard keeps main() from running) ---
+const { sortReadyToBindFirst, pacFailureMessage } = require(scriptPath);
+
+const SP_API = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline';
+
+test('readyToBind requires a connectionreference bound to THIS connection (by connectionId), not just a connectorId match', () => {
+ const connections = [
+ { displayName: 'Bound SP', connectionId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline/connections/aaa', connectorId: SP_API },
+ { displayName: 'Unbound SP', connectionId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline/connections/bbb', connectorId: SP_API },
+ ];
+ const connectionReferences = [
+ // bound to connection aaa via connectionId
+ { logicalName: 'new_bound', connectorId: SP_API, connectionId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline/connections/aaa' },
+ // same connector, but not bound to any connection (connectionId null)
+ { logicalName: 'new_unbound', connectorId: SP_API, connectionId: null },
+ ];
+ const result = sortReadyToBindFirst(connections, connectionReferences);
+ const bound = result.find((c) => c.displayName === 'Bound SP');
+ const unbound = result.find((c) => c.displayName === 'Unbound SP');
+
+ // The connection that actually has a bound connectionreference is ready to bind.
+ assert.equal(bound.readyToBind, true);
+ // A connection matched only by connectorId (no connectionreference bound to it) is NOT ready.
+ assert.equal(unbound.readyToBind, false);
+ // ...but the broader connectionReferences list still surfaces connector-id matches.
+ assert.ok(unbound.connectionReferences.includes('new_bound'));
+ assert.ok(unbound.connectionReferences.includes('new_unbound'));
+ // Ready-to-bind connections sort first.
+ assert.equal(result[0].displayName, 'Bound SP');
+});
+
+test('pacFailureMessage distinguishes a missing PAC CLI (spawn error) from a command failure', () => {
+ const missing = pacFailureMessage({ error: new Error('spawn pac ENOENT'), status: null });
+ assert.match(missing, /ENOENT/);
+ assert.match(missing, /PATH/i);
+ assert.doesNotMatch(missing, /exit null/);
+
+ const failed = pacFailureMessage({ status: 1, stderr: 'Access denied', stdout: '' });
+ assert.match(failed, /exit 1/);
+ assert.match(failed, /Access denied/);
+});
diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.md
index c915f4cd9..4390ae83e 100644
--- a/plugins/model-apps/skills/genpage/SKILL.md
+++ b/plugins/model-apps/skills/genpage/SKILL.md
@@ -246,7 +246,53 @@ After generating, read the RuntimeTypes.ts file to verify it generated correctly
**For mock data pages only:** Skip this phase.
+### Phase 4.5: Connector 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 connectors after it is turned OFF:
+
+```powershell
+node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" connectors
+```
+
+**If it prints `disabled`:** connectors are OFF. Skip this phase entirely — do not
+create or pass `connectors.json`, and never add `--connectors` on upload —
+**regardless of what the plan's `## Connector Bindings` section says**. (Backstop:
+`list-connections.js` / `create-connection-reference.js` also fail closed with
+exit 3 if invoked while OFF.)
+
+**If it prints `enabled`:** read the plan's `## Connector Bindings` section and
+treat it as bindings **only when it contains an actual binding table** (a
+`| Logical Name | …` header with at least one data row). If the section is
+`No connector bindings.`, empty, missing, or malformed, treat the page as having
+no connectors and skip this phase.
+
+When there are real bindings, the `genpage-connector-builder` agent already wrote
+`<working-dir>/connectors.json` during planning — verify it exists and matches the
+plan table. If it is missing, derive it from the plan table as a **bare JSON
+array** (never the `{ "connectorBindings": [...] }` object wrapper — that is the
+deployed page `config.json` shape that `pac` writes):
+
+```json
+[
+ {
+ "logicalName": "new_uxtest_sharepoint",
+ "connectorId": "/providers/Microsoft.PowerApps/apis/shared_sharepointonline",
+ "dataset": "https://host.sharepoint.com/sites/x",
+ "tables": ["5709dd6f-c73e-4079-ad23-2334e45e0e13"],
+ "tableDisplayNames": ["Pet"]
+ },
+ {
+ "logicalName": "new_uxtest_msnweather",
+ "connectorId": "/providers/Microsoft.PowerApps/apis/shared_msnweather",
+ "dataset": "",
+ "operations": ["CurrentWeather"]
+ }
+]
+```
+
+Do **not** write connection IDs into `connectors.json` — the importing maker/admin
+fills env-specific `ConnectionId` values through solution deployment settings.
### Phase 5: Build Pages (Parallel)
Read `genpage-plan.md` and extract the pages table.
@@ -269,18 +315,23 @@ subagent. Inline the page-builder workflow directly in the orchestrator:
1. Read `${PLUGIN_ROOT}/references/rules.md`
2. Read the sample listed in the plan's `## Relevant Samples`
-3. If the plan's Per-Page Specification has `Needs caching: true`, also read
+3. Only when the plan's `## Connector Bindings` section contains an **actual
+ binding table** (a `| Logical Name | …` header with at least one data row),
+ also read `${PLUGIN_ROOT}/references/connectors.md`. Treat a
+ `No connector bindings.` sentinel, or an empty/missing/malformed section, as
+ having no connectors (same contract as Phase 4.5 and genpage-page-builder).
+4. If the plan's Per-Page Specification has `Needs caching: true`, also read
`${PLUGIN_ROOT}/references/data-caching.md`
-4. If the plan's `## Environment` indicates non-English languages, also read
+5. If the plan's `## Environment` indicates non-English languages, also read
`${PLUGIN_ROOT}/references/localization.md`
-5. Read `genpage-plan.md` (already in working directory) and `RuntimeTypes.ts`
+6. Read `genpage-plan.md` (already in working directory) and `RuntimeTypes.ts`
if Data mode is dataverse
-6. Write the `.tsx` file to `<working-dir>/<filename>.tsx` following all rules
-7. After writing, Grep every named import from `@fluentui/react-icons` against
+7. Write the `.tsx` file to `<working-dir>/<filename>.tsx` following all rules
+8. After writing, Grep every named import from `@fluentui/react-icons` against
`${PLUGIN_ROOT}/references/verified-icons.txt` (one Grep per name).
Rewrite any unverified names with the closest verified alternative; do not
load the full icon list into context
-8. Proceed to Phase 6
+9. Proceed to Phase 6
This saves ~5-15s of Task overhead and ~3K tokens that would otherwise be
duplicated in a subagent context.
@@ -333,6 +384,29 @@ Wait for all page-builder tasks to complete before proceeding.
For each `.tsx` file produced, deploy to Power Apps.
+If Phase 4.5 wrote `<working-dir>/connectors.json`, first pre-flight the active
+PAC CLI:
+
+```powershell
+pac model genpage upload --help
+```
+
+The help output must contain `--connectors`. If it does not, stop and surface:
+"connector deploy requires a pac build with `pac model genpage upload
+--connectors` — build from PowerPlatform-Scale-AdminTools or update pac." Do
+not silently drop bindings.
+
+Connector deployment matrix:
+- **Create (new page):** include `--connectors "<working-dir>/connectors.json"`
+ with the first `upload --add-to-sitemap`.
+- **Edit — connectors changed, added, or one removed:** write the full desired
+ binding set to `connectors.json` and include `--connectors` with
+ `upload --page-id <id>` (full replace).
+- **Edit — no connector change:** omit `--connectors`; pac preserves existing
+ bindings. Never pass a stale or empty file on an unrelated edit.
+- **Delete all connectors:** write `[]` to `connectors.json` and pass
+ `--connectors` so pac clears the page's `connectorBindings`.
+
**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:
@@ -343,6 +417,9 @@ For each `.tsx` file produced, deploy to Power Apps.
- Result: page-id = <returned-id>, status = success
```
+When connector bindings are present, the logged command must also include
+`--connectors "<working-dir>/connectors.json"`.
+
#### `--prompt` semantics
- **First upload** (`--add-to-sitemap`, no `--page-id`): full page description
@@ -362,12 +439,15 @@ pac model genpage upload `
--code-file <working-dir>/<file>.tsx `
--name "Page Display Name" `
--data-sources "entity1,entity2" `
+ --connectors "<working-dir>/connectors.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`.
+
**For mock data pages:** Same but omit `--data-sources`.
#### For updating existing pages (subsequent upload):
@@ -380,11 +460,16 @@ pac model genpage upload `
--page-id <page-id> `
--code-file <working-dir>/<file>.tsx `
--data-sources "entity1,entity2" `
+ --connectors "<working-dir>/connectors.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"
```
+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.
+
### Phase 6.5: Navigation Fix-Up (Multi-Page Only)
Runs only when the plan has 2+ pages AND any built `.tsx` contains a `PAGEREF_`
@@ -420,6 +505,26 @@ phase substitutes the real GUIDs.
Pages with no `PAGEREF_` strings need no second upload.
+### Phase 6.7: Solution Packaging (ALM, optional)
+
+Runs only when the plan's `## Solution Packaging` has `Package into solution: true`.
+Adds the deployed app, the GenPage(s), and any connection references to the
+target solution so they travel cross-environment.
+
+1. Ensure the solution exists (create via `scripts/create-solution.js` if needed).
+2. Add the app + GenPage(s) + connection references (pass the page-id(s) returned
+ by Phase 6 as `--page-ids` — the GenPage is added explicitly, it does NOT travel
+ with the app on its own):
+ `node ${PLUGIN_ROOT}/scripts/add-page-to-solution.js <envUrl> <solutionUniqueName> <app-id> --page-ids "<page-id1,page-id2>" --connection-refs "<logicalName1,logicalName2>"`
+3. Log the command + result to `workflow-log.md`.
+
+Cross-env note (verified 2026-07-10): the app (80) pulls the sitemap (62); the
+GenPage `uxagentproject` (10372) is added explicitly and pulls its
+`uxagentprojectfile` rows (10373, incl. `config.json` with `connectorBindings`);
+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`.
+
### Phase 7: Verify in Browser (Optional)
After successful deployment, ask the user via `AskUserQuestion`:
diff --git a/plugins/model-apps/skills/genpage/edit-flow.md b/plugins/model-apps/skills/genpage/edit-flow.md
index 9a67575d9..ae7a91c1e 100644
--- a/plugins/model-apps/skills/genpage/edit-flow.md
+++ b/plugins/model-apps/skills/genpage/edit-flow.md
@@ -78,7 +78,8 @@ pac model genpage download `
The download creates a `<working-dir>/<page-id>/` folder with fixed filenames:
`page.tsx` (source), `config.json` (entity list + model), `prompt.txt` (original
prompt). Downstream phases operate on `<working-dir>/<page-id>/page.tsx` for
-editing and uploading, and read `config.json.dataSources` in Phase 3.
+editing and uploading, and read `config.json.dataSources` plus
+`config.json.connectorBindings` in Phase 3.
## Edit Phase 3: Generate RuntimeTypes (Conditional)
@@ -94,6 +95,26 @@ pac model genpage generate-types `
Pass the exact entity list from `config.json.dataSources`. If `dataSources` is an
empty array, the page is mock-data only — skip this phase.
+Also read `config.json.connectorBindings`.
+
+> **Connectors are owned by `genpage-connector-builder`.** Read the existing
+> `config.json.connectorBindings` (the current bindings). If the edit intent
+> **adds, replaces, or discovers** connector data, do NOT run discovery inline —
+> delegate to the `genpage-connector-builder` agent (**Mode: `edit`**) via the
+> `Task` tool, passing the working directory, `${PLUGIN_ROOT}`, the environment
+> URL, the existing bindings, and the edit intent. That agent **owns the feature
+> gate**: when connectors are OFF it preserves the existing bindings and adds none;
+> when ON it discovers and returns the updated set. It writes
+> `<working-dir>/connectors.json` (bare array) and `<working-dir>/connector-bindings.md`.
+>
+> For edits that only **preserve** connectors (no connector change) you don't need
+> the agent — omit `--connectors` on upload so pac keeps the deployed bindings. To
+> **clear all** connectors, write `[]` to `<working-dir>/connectors.json` and pass
+> `--connectors`.
+
+- Do not add or persist connection IDs. Env-specific `ConnectionId` values belong
+ to the connectionreference row and ALM deployment settings, not the page config.
+
## Edit Phase 4: Plan the Edit
Invoke the `genpage-edit-planner` agent via the `Task` tool. Pass:
@@ -120,11 +141,15 @@ Also read:
- `<working-dir>/RuntimeTypes.ts` — if generated in Edit Phase 3, for verified
column names
- `<working-dir>/<page-id>/page.tsx` — the current source
+- `${PLUGIN_ROOT}/references/connectors.md` — if `config.json.connectorBindings`
+ is non-empty or the edit adds connector-backed data
Apply each change from the edit plan using targeted `Edit` operations on
`<working-dir>/<page-id>/page.tsx`. **Preserve the functionality** listed under
"Preservation Constraints" in the plan. Use ONLY verified column names from
-RuntimeTypes.ts when the edit touches data access.
+RuntimeTypes.ts when the edit touches Dataverse data access. Use ONLY logical
+names, datasets, table GUIDs, and operations from the seeded connector bindings
+or approved edit plan when the edit touches connector data access.
Do NOT rewrite the entire file. Use the minimum necessary `Edit` operations.
@@ -134,12 +159,25 @@ This is an **update** (existing page-id), so `--prompt` must describe the
**delta of changes only** — not a re-statement of the original page description.
See SKILL.md Phase 6 "`--prompt` semantics".
+Connector binding rules for edit deploy:
+- **Add / replace / discover connectors:** the `genpage-connector-builder` agent
+ (Mode: `edit`) has already gated on the flag and written the full desired binding
+ set to `<working-dir>/connectors.json`. Pre-flight that `pac model genpage upload
+ --help` contains `--connectors` and include `--connectors "<working-dir>/connectors.json"`
+ in the upload.
+- **Code/visual-only edit (connectors unchanged):** omit `--connectors`; pac
+ preserves existing bindings.
+- **Remove every connector:** write `[]` to `connectors.json` and pass
+ `--connectors` so pac clears `config.json.connectorBindings`.
+- Never write connection IDs.
+
```powershell
pac model genpage upload `
--app-id <app-id> `
--page-id <page-id> `
--code-file <working-dir>/<page-id>/page.tsx `
--data-sources "entity1,entity2" `
+ --connectors "<working-dir>/connectors.json" `
--prompt "<User's edit request — only the changes, not the full page>" `
--model "<current-model-id>" `
--agent-message "Description of what was changed in this upload"
@@ -148,6 +186,7 @@ pac model genpage upload `
Use `--page-id` for updates. Omit `--add-to-sitemap` (the page is already in
the sitemap).
Omit `--data-sources` when `config.json.dataSources` was empty.
+Omit `--connectors` when connector bindings are unchanged.
## Edit Phase 7: Verify (Optional)