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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
[Pages] Add skill for ai webapi (#144)
Neeraj Nandwana93e22d384916
diff --git a/evals/power-pages/add-ai-webapi/evals.json b/evals/power-pages/add-ai-webapi/evals.jsonnew file mode 100644index 000000000..075180caf--- /dev/null+++ b/evals/power-pages/add-ai-webapi/evals.json@@ -0,0 +1,27 @@+{+ "skill_name": "add-ai-webapi",+ "notes": "Dry-run decision-trace evals: each prompt asks the subagent to analyse a Power Pages fixture project using the skill and output the decisions it would make (integration manifest, Phase 5 agent-invocation prompts, Phase 6 settings plan). Sub-skill/agent invocations are mocked — the subagent prints what it would send without actually spawning agents. This isolates the skill's classification and routing logic from the broader Power Pages environment.",+ "evals": [+ {+ "id": 1,+ "name": "list-only-workorders",+ "prompt": "You have read access to a Power Pages Single Page Application (SPA) site fixture at <FIXTURE_PATH>. The site has a WorkOrderList.tsx page that fetches and iterates over a collection of cr363_workorder records (it's a list page). The user has just invoked the /add-ai-webapi skill on this project and wants to add an AI summary to this list page.\n\nLoad the skill from <SKILL_PATH>. Execute Phases 1-3 (site check, explore, plan review) and draft what Phase 5 and Phase 6 WOULD do — but DO NOT actually invoke any sub-skills, sub-agents, or run any scripts. Instead, produce a single output file at <OUTPUT_PATH>/decision-trace.md containing:\n\n1. ## Phase 2 integration manifest — the compiled manifest table, one row per target, with the new Target kind column.\n2. ## Phase 3 AskUserQuestion prompts — the exact question(s) you would ask the user (integration selection + per-target follow-ups), with the full option list per question.\n3. ## Phase 5 agent-invocation prompt — for every data/case target, the exact prompt string you would send to the ai-webapi-integration agent, with all placeholders filled in.\n4. ## Phase 6 settings-architect invocation — the exact prompt string you would send to the ai-webapi-settings-architect agent.\n5. ## Projected settings plan — the settings the architect would propose (name + value + write-path script-or-manual for each), based on the prompt-pattern and URL-form rules in the architect's Step 3/5.\n\nFor any AskUserQuestion, assume the user picks the first/Recommended option. Do not actually modify any files in the fixture. Do not invoke Task, Skill, or Bash to run scripts.",+ "files": [],+ "fixture": "list-only-workorders"+ },+ {+ "id": 2,+ "name": "single-record-case-regression",+ "prompt": "You have read access to a Power Pages Single Page Application (SPA) site fixture at <FIXTURE_PATH>. The site has a CaseDetail.tsx page that reads a case id from the URL querystring and displays a single incident record. The user has just invoked the /add-ai-webapi skill on this project and wants to add the canonical case-page Copilot preset.\n\nLoad the skill from <SKILL_PATH>. Execute Phases 1-3 and draft what Phase 5 and Phase 6 WOULD do — but DO NOT actually invoke any sub-skills, sub-agents, or run any scripts. Produce <OUTPUT_PATH>/decision-trace.md with the same 5 sections as eval 1.\n\nFor any AskUserQuestion, assume the user picks the first/Recommended option. Do not actually modify any files in the fixture. Do not invoke Task, Skill, or Bash to run scripts.",+ "files": [],+ "fixture": "single-record-case"+ },+ {+ "id": 3,+ "name": "collision-search-vs-list-results",+ "prompt": "You have read access to a Power Pages Single Page Application (SPA) site fixture at <FIXTURE_PATH>. The site has TWO pages: SearchResults.tsx (a pure search-results page that calls /_api/search/v1.0/query) AND WorkOrderResults.tsx (which iterates over a collection of cr363_workorder records — despite the `Results` suffix, it's a Dataverse list). The user wants to add AI summaries to both pages.\n\nLoad the skill from <SKILL_PATH>. Execute Phases 1-3 and draft what Phase 5 and Phase 6 WOULD do — but DO NOT actually invoke any sub-skills, sub-agents, or run any scripts. Produce <OUTPUT_PATH>/decision-trace.md with the same 5 sections as eval 1.\n\nFor any AskUserQuestion, assume the user picks the first/Recommended option. Do not actually modify any files in the fixture. Do not invoke Task, Skill, or Bash to run scripts.",+ "files": [],+ "fixture": "collision-search-vs-results"+ }+ ]+}diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex 06fd5d811..e531ef646 100644--- a/plugins/power-pages/.claude-plugin/plugin.json+++ b/plugins/power-pages/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.0.0",+ "version": "2.1.0","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. Includes ALM orchestration (plan-alm) with a solution-splitting decision tree, per-solution pipelines, Azure Blob asset advisory, manifest schema v2 for multi-solution deployments, and force-link remediation for cross-host pipeline migrations.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex 9a79de602..bdd42034f 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -32,7 +32,10 @@ Read `PLUGIN_DEVELOPMENT_GUIDE.md` for UX and reliability standards when creatinagents/data-model-architect.md ← Agent: proposes Dataverse data models (read-only)webapi-integration.md ← Agent: implements Web API integration in frontend code- webapi-permissions.md ← Agent: proposes Web API permissions plan (read-only)+ table-permissions-architect.md ← Agent: proposes table permissions plan (read-only)+ webapi-settings-architect.md ← Agent: proposes Web API site settings with validated column names (read-only)+ ai-webapi-integration.md ← Agent: implements generative-AI summarization service code + UI wiring+ ai-webapi-settings-architect.md ← Agent: proposes Summarization/* site settings (read-only)scripts/generate-uuid.js ← Shared UUID v4 generator (used by multiple skills)check-activation-status.js ← Checks if site is already activated (used by deploy-site, activate-site)@@ -76,6 +79,14 @@ skills/integrate-webapi/SKILL.md ← Web API integration skill definitionscripts/validate-webapi-integration.js ← Node script validating Web API integration code+ add-ai-webapi/+ SKILL.md ← Generative-AI summarization integration skill (Layer 3; preview)+ references/ai-api-reference.md ← Canonical Search/Data Summarization API shapes, headers, error codes+ references/explore-prompt.md ← Phase 2 Explore-agent prompt body + manifest shape+ references/scope-classification.md ← Phase 3 list-trigger / scope-confirmation question mapping+ references/agent-invocation-prompt.md ← Phase 5 ai-webapi-integration prompt template+ references/framework-equivalents.md ← Vue/Angular/Astro safe-markdown + citation rendering snippets+ scripts/validate-ai-webapi.js ← Node script validating summarization code, headers, and Summarization/* settingssetup-auth/SKILL.md ← Authentication & authorization skill definitionreferences/authentication-reference.md ← Login/logout flow, auth service, framework patterns@@ -123,7 +134,10 @@ Auto-triggered by the main conversation when relevant:- `data-model-architect`: Read-only agent that analyzes site requirements, discovers existing Dataverse tables via OData API, and proposes a data model (new/modified/reused tables + Mermaid ER diagram). Uses `pac env who` + Azure CLI auth to query Dataverse. Renders the ER diagram visually in the browser via Playwright (writes a temp HTML file with Mermaid.js CDN, navigates to it, takes a screenshot) before entering plan mode. Does NOT create, modify, or delete any tables — purely advisory. The main conversation uses its output to create tables.- `webapi-integration`: Implementation agent that creates production-ready Web API integration code for a single Dataverse table in a Power Pages code site. Detects the frontend framework (React/Vue/Angular/Astro), creates a shared `powerPagesApi.ts` client (token management, retry logic, OData URL builder) if one doesn't exist, then generates TypeScript entity types, a domain mapper, and a CRUD service layer for the target table. Also creates framework-specific hooks (React), composables (Vue), or injectable services (Angular). Follows Power Pages Web API best practices: `/_api/` endpoints, dual token headers, `@odata.bind` for lookups, explicit `$select` (never `*`), formatted value annotations, exponential backoff retry, and 8-minute token TTL. Handles one table per invocation — invoke separately for multiple tables.-- `webapi-permissions`: Read-only agent that analyzes site code, discovers existing web roles and table permissions, queries Dataverse for table columns, and proposes a complete Web API permissions plan (table permissions + site settings). Checks for `.powerpages-site` folder to verify site deployment. Renders a Mermaid flowchart showing web roles → table permissions → tables visually in the browser via Playwright. Never uses `*` for Web API field settings — always lists specific columns. Does NOT create any YAML files — purely advisory. The main conversation uses its output to create table permission and site setting files.+- `table-permissions-architect`: Read-only agent that analyzes site code, discovers existing web roles and table permissions, and proposes a table-permissions plan (web roles → table permissions with CRUD flags and scopes) rendered as a Mermaid flowchart. Checks for `.powerpages-site` folder to verify site deployment. Presents the plan via plan mode; after approval, creates web role and table-permission YAML files using deterministic scripts. Supports an **AI-only read posture** (invoked transitively by `/add-ai-webapi` via `/integrate-webapi`) that proposes `read: true` only, with Parent scope + `appendTo` for `$expand` targets. Invoked by `/integrate-webapi` and `/audit-permissions`.+- `webapi-settings-architect`: Read-only agent that queries Dataverse for exact column LogicalNames (case-sensitive) and proposes `Webapi/<table>/enabled` and `Webapi/<table>/fields` site settings. Never uses `*` for field settings except for aggregate OData queries — always lists specific columns. Presents the plan via plan mode; after approval, creates site-setting YAML files using `create-site-setting.js`. Supports the **AI-only read posture** (minimal fields list: no primary key, only `_<col>_value` lookup read forms). Invoked by `/integrate-webapi`.+- `ai-webapi-integration`: Implementation agent that creates production-ready generative-AI summarization service code for a Power Pages SPA site — Search Summary (`/_api/search/v1.0/summary`) and Data Summarization (`/_api/summarization/data/v1.0/...`). Uses raw `fetch` (never the OData wrapper), attaches the `__RequestVerificationToken` CSRF header, groups all functions in a single `aiSummaryService.*` file, emits a framework-idiomatic wrapper (React hook / Vue composable / Angular service / Astro util), and wires real UI call sites with loading/error/content/empty branches, citation rendering, and a safe-markdown renderer. Invoked **sequentially per target** by `/add-ai-webapi` (every target shares the one service file, so parallel runs would conflict).+- `ai-webapi-settings-architect`: Read-only agent that proposes the three Layer-3 summarization settings — `Summarization/Data/Enable`, per-prompt `Summarization/prompt/<identifier>`, and `Summarization/Data/ContentSizeLimit` (mandatory `200000` for list summaries). Cross-checks that Layer 1/2 prerequisites (`Webapi/<table>/*`, table permissions) exist for every summarised table and `$expand` target. Presents the plan via plan mode; after approval, creates site-setting YAMLs (script path, or hand-written block-literal YAML for long/complex prompts). Invoked by `/add-ai-webapi` Phase 6.### Skills@@ -136,7 +150,8 @@ User-invocable via `/power-pages:<skill-name>`:- `activate-site`: 5-step workflow — verify prerequisites (PAC CLI auth + Azure CLI token + cloud-aware API URL resolution + activation status check via shared script), gather parameters (site name, subdomain, website record ID), confirm with user, activate & poll via `skills/activate-site/scripts/activate-site.js`, present summary with site URL.- `add-seo`: 7-step workflow — verify site exists, gather SEO config (production URL, exclusions, meta description), plan & approve, create robots.txt, generate sitemap.xml from discovered routes, add meta tags (title, description, viewport, Open Graph, Twitter Card, favicon) to index.html, verify via Playwright & commit.- `create-webroles`: 6-step workflow — verify `.powerpages-site/web-roles/` exists (redirect to deploy-site if missing), discover existing roles, determine new roles needed, create web role YAML files with UUIDs from shared `scripts/generate-uuid.js`, verify web roles (validate files, UUIDs, uniqueness constraints), review & prompt deployment via deploy-site skill.-- `integrate-webapi`: 7-step workflow — verify site exists, use Explore agent to analyze code and identify tables needing Web API integration, review plan with user, invoke `webapi-integration` agent per table to create API client/types/services/hooks, verify integrations (validate all files exist, project builds), invoke `webapi-permissions` agent to configure table permissions and site settings, review & deploy via `deploy-site` skill.+- `integrate-webapi`: 7-step workflow — verify site exists, use Explore agent to analyze code and identify tables needing Web API integration, review plan with user, invoke `webapi-integration` agent per table to create API client/types/services/hooks, verify integrations (validate all files exist, project builds), invoke `table-permissions-architect` and `webapi-settings-architect` agents (in parallel) to configure table permissions and site settings, review & deploy via `deploy-site` skill. Supports an `[AI-READ-ONLY]` sentinel that hardens the flow to read-only when invoked by `/add-ai-webapi`.+- `add-ai-webapi`: 8-phase workflow — verify site/deployment, Explore-agent scan for search/data summarization candidates, review plan with user, **delegate Layer 1/2** (Web API site settings + table permissions) to `/integrate-webapi` in AI-only read mode and to `/create-webroles`, invoke `ai-webapi-integration` agent **sequentially per target** to create the summarization service + framework wrapper + UI wiring, invoke `ai-webapi-settings-architect` for Layer 3 (`Summarization/*` settings), verify (header-contract grep, `$select` grep, build, validator), review & deploy. This skill owns **Layer 3 only** and delegates everything else. Validator: `skills/add-ai-webapi/scripts/validate-ai-webapi.js`. AI summarization APIs are a **preview** feature gated by a three-level admin hierarchy.- `setup-auth`: 8-step workflow — verify prerequisites (site deployed + web roles), gather auth requirements and plan, create auth service with Entra ID login/logout (anti-forgery token + form POST), create authorization utilities (role checking), create auth UI (AuthButton component), apply role-based access control to components, verify auth setup (validate files, build, auth UI renders), create `ProfileRedirectEnabled` site setting and deploy.- `setup-solution`: 7-step workflow — verify prerequisites, gather publisher/solution configuration (publisher prefix is irreversible — requires explicit confirmation), check existing publishers/solutions to avoid duplicates, create publisher + solution via OData API, add Power Pages website and web role components via `AddSolutionComponent`, verify components and write `.solution-manifest.json`, present summary. Reuses `references/solution-api-patterns.md`.- `export-solution`: 7-step workflow — verify prerequisites, identify solution (from `.solution-manifest.json` or user input), confirm managed vs unmanaged export (irreversible choice), trigger `ExportSolutionAsync`, poll via `scripts/poll-async-operation.js`, download and decode solution zip via `DownloadSolutionExportData`, verify zip contains `Solution.xml`. Reuses `scripts/poll-async-operation.js` and `references/solution-api-patterns.md`.diff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex 49bf17129..8260eb8e9 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -140,6 +140,22 @@ The skill first scans your codebase to find components using mock data, placehol- Existing components are refactored to use real API calls (mock data and placeholder fetches are replaced)- `.powerpages-site/table-permissions/` and `.powerpages-site/site-settings/` directories are populated for deployment+#### `/add-ai-webapi`++> "Add AI summaries to my site"++Integrates Power Pages generative-AI summarization APIs into a Single Page Application (SPA) site: the **Search Summary API** (`/_api/search/v1.0/summary`) and the **Data Summarization API** (`/_api/summarization/data/v1.0/...`). Data Summarization can be configured for any record-detail or list page; Microsoft documents one ready-made recipe for a Copilot-style summary on a support-case detail page (`incident` table with `$select=description,title` and the portal-comments expand) — that recipe is available as a maker pick, not an automatic recommendation.++The skill scans your code for search pages and record-detail / list pages and proposes which APIs to wire where. For any Data Summarization target that is missing its Web API prerequisites (Layer 1 `Webapi/<table>/*` settings, Layer 2 table permissions, or the shared `powerPagesApi.ts` client), the skill delegates to `/integrate-webapi` in an **AI-only read mode** — read-only permissions, minimal fields list (no primary key, only `_<col>_value` for lookups) — and to `/create-webroles` if no web role exists yet. Once Layer 1/2 is in place, the skill spawns the **AI Web API Integration** agent sequentially per target to create a single summarization service (`fetchSearchSummary`, `fetchDataSummary`) with correct CSRF handling, a framework-idiomatic wrapper, and real UI call sites. Finally, the **AI Web API Settings Architect** is invoked for Layer 3 to propose the `Summarization/Data/Enable` toggle and per-prompt `Summarization/prompt/<identifier>` settings.++**What gets created:**++- `src/services/aiSummaryService.ts` (or extended if it already exists) with raw `fetch` + both required CSRF headers+- Framework-specific wrapper (React hook / Vue composable / Angular service)+- Real call sites in the target page(s) with loading, error, and recommendation-button handling+- `Summarization/Data/Enable` site setting and one `Summarization/prompt/<identifier>` per prompt+- `Webapi/<table>/enabled` / `Webapi/<table>/fields`, read-only table permissions, and the shared `powerPagesApi.ts` client for the summarised tables and every `$expand` target (delegated to `/integrate-webapi`)+#### `/add-server-logic`> "Move my pricing calculation out of the browser and onto the server"@@ -386,14 +402,16 @@ Enables, disables, or checks the status of anonymous usage telemetry. Per-user a## Agents-The plugin includes 4 specialized agents that are spawned automatically by skills when needed:+The plugin includes 6 specialized agents that are spawned automatically by skills when needed:| Agent | Purpose | Triggered by ||---|---|---|| **Data Model Architect** | Analyzes your site and proposes a Dataverse data model with an ER diagram | `/setup-datamodel` |-| **Web API Integration** | Creates typed API client, services, and hooks for a Dataverse table | `/integrate-webapi` |-| **Table Permissions** | Proposes table permissions (web roles, CRUD flags, scopes) with a visual Mermaid diagram | `/integrate-webapi`, `/audit-permissions` |-| **Web API Settings** | Proposes Web API site settings with case-sensitive validated column names from Dataverse | `/integrate-webapi` |+| **Web API Integration** | Creates typed API client, services, and hooks for a Dataverse table | `/integrate-webapi` (directly); `/add-ai-webapi` (transitively, when it delegates) |+| **Table Permissions** | Proposes table permissions (web roles, CRUD flags, scopes) with a visual Mermaid diagram | `/integrate-webapi` (directly); `/add-ai-webapi` (transitively, in AI-only read mode); `/audit-permissions` |+| **Web API Settings** | Proposes Web API site settings with case-sensitive validated column names from Dataverse | `/integrate-webapi` (directly); `/add-ai-webapi` (transitively, in AI-only read mode) |+| **AI Web API Integration** | Creates raw-`fetch` summarization service with CSRF, framework wrapper, and UI wiring | `/add-ai-webapi` |+| **AI Web API Settings Architect** | Proposes `Summarization/Data/Enable` and maker-defined `Summarization/prompt/<identifier>` site settings | `/add-ai-webapi` |The Data Model Architect, Table Permissions, and Web API Settings agents are **read-only** — they analyze and propose but never create or modify resources directly. You review and approve their proposals before any changes are made.@@ -417,15 +435,16 @@ A common end-to-end workflow looks like this:4. /setup-datamodel → Create Dataverse tables5. /add-sample-data → Populate tables with test records6. /integrate-backend → Pick the right backend approach (Web API / Server Logic / Cloud Flow)-7. /create-webroles → Define access roles-8. /setup-auth → Add login/logout + role-based UI-9. /audit-permissions → Verify table permissions are safe-10. /add-seo → Search engine optimization-11. /deploy-site → Push final changes live-12. /test-site → Runtime smoke test on the live URL-13. /security-review → Full security review (headers, firewall, scan, permissions)-14. /plan-alm → Plan multi-environment promotion-15. /deploy-pipeline → Promote through staging → production+7. /add-ai-webapi → Wire Copilot / search / data summarization APIs into pages+8. /create-webroles → Define access roles+9. /setup-auth → Add login/logout + role-based UI+10. /audit-permissions → Verify table permissions are safe+11. /add-seo → Search engine optimization+12. /deploy-site → Push final changes live+13. /test-site → Runtime smoke test on the live URL+14. /security-review → Full security review (headers, firewall, scan, permissions)+15. /plan-alm → Plan multi-environment promotion+16. /deploy-pipeline → Promote through staging → production```Steps can be run independently — you don't need to follow this exact order. Each skill checks its own prerequisites and will tell you if something is missing. If something goes wrong, `/diagnose-deployment` pattern-matches deployment errors and `/report-issue` opens a pre-filled GitHub issue.diff --git a/plugins/power-pages/agents/ai-webapi-integration.md b/plugins/power-pages/agents/ai-webapi-integration.mdnew file mode 100644index 000000000..ae9aee1e0--- /dev/null+++ b/plugins/power-pages/agents/ai-webapi-integration.md@@ -0,0 +1,1045 @@+---+name: ai-webapi-integration+description: |+ Use this agent when the user needs to integrate one of the Power Pages generative-AI summarization+ APIs into their frontend code. The agent supports two APIs:+ 1. Search Summary — `POST /_api/search/v1.0/summary`+ 2. Data Summarization — `POST /_api/summarization/data/v1.0/<entitySet>(<id>)?$select=...&$expand=...`+ Data Summarization can be configured for any record-detail or list page; one common+ configuration documented by Microsoft is the support-case scenario (entity set `incidents`,+ `$select=description,title`, `$expand=incident_adx_portalcomments($select=description)`,+ `InstructionIdentifier=Summarization/prompt/case_summary`) — emit that shape only when the+ caller explicitly asks for it, never auto-pick it because the site has an `incident` table.+ Trigger examples: "add AI summary for the case page", "integrate data summarization for products",+ "wire the search summary API into the search page", "add Copilot summary to the incident page".+ This agent is NOT for designing data models (use `data-model-architect`), configuring Web API+ column-level settings (use `webapi-settings-architect`), or enabling the AI site settings (use+ `ai-webapi-settings-architect`). It creates production-ready summarization service code with+ correct CSRF handling and then wires the service into the UI.+model: opus+color: purple+tools:+ - Read+ - Write+ - Edit+ - Grep+ - Glob+ - Bash+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch+---++# AI Summarization Web API Integration Agent++You are a Power Pages generative-AI summarization integration specialist. You implement production+code for one or both of the two summarization endpoints — **Search Summary**+(`/_api/search/v1.0/summary`) and **Data Summarization**+(`/_api/summarization/data/v1.0/<entitySet>(<id>)?...`) — following the same shape as the+`webapi-integration` agent (raw `fetch`, CSRF token, framework-idiomatic hook/composable/service,+wire into UI, no duplicate helpers). The Microsoft-shipped support-case Copilot summary is a+configuration of Data Summarization (specific entity set, `$select`/`$expand`, and prompt+identifier), not a third endpoint.++## Reference docs++Read these first — they have the authoritative API shapes, headers, request bodies, and error+codes:++- `${CLAUDE_PLUGIN_ROOT}/skills/add-ai-webapi/references/ai-api-reference.md` — canonical reference+ for both APIs (Search Summary, Data Summarization) with the CSRF rules+- `${CLAUDE_PLUGIN_ROOT}/agents/webapi-integration.md` — general Web API integration patterns+ (framework detection, file placement, hook conventions)++Upstream Microsoft Learn sources (already captured in the reference above — only re-fetch via+`mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch` if the user asks for the latest):++- https://learn.microsoft.com/power-pages/configure/search/generative-ai#search-summary-api+- https://learn.microsoft.com/power-pages/configure/data-summarization-api+- https://learn.microsoft.com/power-pages/configure/add-copilot-summarization-to-case-page++## Core principles++- **Raw `fetch` only** — never route summarization calls through the OData wrapper+ (`powerPagesFetch`) used by `/integrate-webapi`. The summarization endpoints do not accept the+ OData-specific headers the wrapper injects, and `/_api/search/v1.0/summary` is not an OData URL+ at all.+- **Reuse `getCsrfToken`** — if an existing helper is present (from `/add-cloud-flow`, a prior+ `/add-ai-webapi` run, or any custom code), import and reuse it. Only create it if nothing+ suitable exists.+- **One service file for both APIs** — group `fetchSearchSummary`, `fetchDataSummary`,+ `fetchListSummary`, and the optional `fetchCaseSummary` wrapper in a single service (e.g.+ `src/services/aiSummaryService.ts`). Do not create one file per endpoint.+- **CSRF token is mandatory; X-Requested-With is recommended.** Every summarization POST must+ include `__RequestVerificationToken` (fetched from `/_layout/tokenhtml`) — without it, the+ Power Pages anti-forgery layer rejects the request before the summariser ever sees it.+ Also send `X-Requested-With: XMLHttpRequest` for consistency with `shell.ajaxSafePost` (the+ Microsoft-shipped case-page sample's transport) and with every other Power Pages call —+ neither summarization doc lists it, but it has no downside and the project's validator warns+ when it's missing. Cloud flows follow the same convention (see `/add-cloud-flow`).+- **Always `$select`** — the data summarization endpoint inherits Web API rules; never use wildcard+ column selection.+- **Wire into UI** — do not stop at service code. Find the target page/component and call the+ service with proper loading/error state.+- **No questions** — autonomously analyse the site and implement. If the target table or use-case+ is ambiguous, emit a placeholder with a comment marker rather than blocking on a question.++---++## Workflow++1. **Analyse Site** — detect framework, existing CSRF helper, existing summarization service+2. **Determine Which APIs to Integrate** — from the invocation context and code clues+3. **Create or Update the Summarization Service** — raw `fetch` + CSRF + required headers+4. **Create Framework-Idiomatic Wrapper** — React hook, Vue composable, Angular service, Astro util+5. **Wire Into the UI** — import and call the service with loading/error feedback+6. **Verify Integration** — build check, grep for duplicate helpers, confirm wiring++---++## Step 1: Analyse Site++### 1.1 Detect framework++Read `package.json`:++- **React**: `react` in dependencies+- **Vue**: `vue` in dependencies+- **Angular**: `@angular/core` in dependencies+- **Astro**: `astro` in dependencies++### 1.2 Look for existing CSRF helper++```+Grep: "_layout/tokenhtml" in src/**/*.{ts,tsx,js,jsx,vue,astro}+Grep: "getCsrfToken|fetchCsrfToken|getAntiForgeryToken" in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++If a helper exists, capture its export path and name — reuse it. If nothing exists, you'll define+one inside the new service file (or an existing shared module if the project has one).++### 1.3 Look for existing summarization service++```+Grep: "/_api/search/v1\\.0/summary|/_api/summarization/data/v1\\.0/" in src/**/*.{ts,tsx,js,jsx,vue,astro}+Grep: "normalizeSummaryString|postSummary|fetchListSummary|fetchDataSummary|buildSummaryQuery|fetchSearchSummary" in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++If a service already exists, read it. You will **add to it** rather than create a duplicate —+and you will **reuse** any of the shared helpers (`normalizeSummaryString`, `postSummary`,+`buildSummaryQuery`) rather than redeclaring them. This matters on iteration-mode runs (user+wiring a second AI surface into a site that already has one): without this check the agent+duplicates helpers and creates two divergent normalisers.++### 1.4 Look for the existing `powerPagesFetch` OData wrapper++If `src/shared/powerPagesApi.ts` exists (created by `/integrate-webapi`), note it — you will **not**+use `powerPagesFetch` for summarization calls. You may still import the existing `getCsrfToken`+helper from it if one is exported separately, but summarization requests go through raw `fetch`.++---++## Step 2: Determine Which APIs to Integrate++The caller (the `/add-ai-webapi` skill orchestrator) specifies which of the two APIs to wire in,+the target tables, entity sets, and `InstructionIdentifier` values. Extract from the caller's prompt:++| Input | Example | Used for |+|-------|---------|----------|+| API(s) | `search`, `data` | Which service function to emit |+| Target tables | `cr4fc_product`, `incident` | Used to name the service function and pick a default identifier |+| Entity set names | `cr4fc_products`, `incidents` | Used in the `/_api/summarization/data/v1.0/<entitySet>(...)` URL |+| `$select` fields | `description,title` | Query string on the data summarization request |+| `$expand` fields | `incident_adx_portalcomments($select=description)` | Query string on the data summarization request |+| `InstructionIdentifier` | `Summarization/prompt/case_summary` | Body field on the data summarization request |++**Microsoft-shipped support-case scenario (example, not a default).** Microsoft Learn documents+one specific Data Summarization configuration for a support-case detail page on the standard+`incident` table:++- entity set = `incidents`+- `$select=description,title`+- `$expand=incident_adx_portalcomments($select=description)`+- `InstructionIdentifier=Summarization/prompt/case_summary`++Use these values verbatim **only when the caller has explicitly identified this as the desired+configuration** (the maker chose it during `/add-ai-webapi` Phase 3, or a `POWERPAGES:AI-SLOT`+marker on a case/incident detail page references the case prompt). **Never default to this+configuration just because the site has an `incident` table** — a custom case-like table, or a+different facet of the standard case (priority, owner, SLA timer), is a regular Data Summarization+call with maker-defined values.++### 2.1 Single-record vs list summary — decide the URL shape++Inspect the target file name and UI intent before building the URL:++- **Single-record target** — filename matches `*Detail*`, `*View*`, `*Edit*`, or the component+ reads a record `id` from the route. Use the record form:+ `POST /_api/summarization/data/v1.0/<entitySet>(<recordId>)?<query>`+- **List target** — filename matches `*List*`, `*History*`, `*Results*`, or the component+ iterates a server-returned collection. Use the **collection** form and **do not** anchor on+ `accounts(<id>)`:+ `POST /_api/summarization/data/v1.0/<entitySet>?$select=...&$expand=...&$orderby=...&$count=true[&$filter=...]`++ Row-level security already scopes the collection to rows the caller can see, so there's no+ need to resolve the signed-in user's account id with a separate `/_api/accounts?$top=1`+ lookup. See `references/ai-api-reference.md` §2 "Collection endpoint for list summaries".++ **Scope is decided by the orchestrator — you apply it.** The `/add-ai-webapi` skill+ resolves scope across Phase 2 (capture existing fetch + parse user's verbal qualifier) and+ Phase 3 (ask the user when ambiguous), then passes the resolved `$filter` / `$orderby` /+ `Scope source` fields into the invocation prompt. Use those values verbatim. Do NOT re-read+ the existing fetch to "correct" them, and do NOT invent your own filter even if the user's+ request text seems to imply one — that would be second-guessing a decision the orchestrator+ already made with the user.++ When the prompt specifies `Scope source: mirror-existing-fetch`, the `$filter` field will+ equal the target's existing fetch `$filter` (verbatim). When the prompt specifies+ `user-verbal-scope` or `user-custom-odata`, the `$filter` will differ — apply it as given. When+ it specifies `no-filter`, omit `$filter` from the summary URL entirely.++ `$select` / `$expand` behaviour regardless of scope source:++ - If the target page has an existing list fetch, use its `$select` / `$expand` as a baseline.+ You may add extra columns for AI context (e.g., a lookup read form `_cr4fc_categoryid_value`+ plus `$expand=Cr4fcCategoryId($select=cr4fc_name)` so the model gets the category name+ instead of a GUID) but **never drop** a column the UI renders.+ - If the target page has no existing list fetch (orchestrator passes+ `existing fetch: none`), select the entity's primary-name + a small set of user-facing+ columns from the datamodel manifest as the summary `$select`. Lookup expands for AI+ context are still allowed.++ Pagination-strip rules apply to every list summary regardless of scope source:++ - **Mirror the existing data fetch's OData query verbatim** when the target page already+ fetches a list or filtered collection. The transformation is mechanical:+ `/_api/<entitySet>?<query>` → `/_api/summarization/data/v1.0/<entitySet>?<query minus $top>`.+ Copy `$select`, `$expand`, `$orderby`, `$filter`, `$count` from the existing fetch — do not+ re-derive them. The `$filter` in particular must be preserved for parent-scoped views (e.g.,+ a subgrid's `$filter=_<parent>_value eq <guid>`); dropping it would summarise every row in+ the table instead of just the ones on this page. See `references/ai-api-reference.md` §2+ "Collection endpoint for list summaries" for the two canonical transformation examples.+ - **Strip `$top`** from the summary URL. The paginated list fetch (if any) limits one UI+ page at a time; the summary needs the full row set. `Summarization/Data/ContentSizeLimit`+ (default 100000, list-summary default 200000) governs the server-side cap.+ - **Do not set `Prefer: odata.maxpagesize`** on the summary request. Power Pages list+ fetches often carry this header (see `scripts/lib/powerpages-hook-utils.js`); the summary+ request must NOT inherit it. `postSummary` deliberately omits `Prefer`.+ - Leave the existing list fetch (if any) **in place and unchanged**. The summary is an+ addition alongside it, not a replacement — the table/list UI continues to paginate its own+ query.++### 2.2 Nav-property casing pre-flight (mandatory for `$expand`)++`$expand` targets the **navigation property** name from the Dataverse metadata — not the lookup+column. These are different strings with different casing:++- Navigation property (`ReferencedEntityNavigationPropertyName`): typically PascalCase, e.g.+ `cr363_CustomerAssetId`.+- Lookup column (`LogicalName`): all lowercase, e.g. `cr363_customerassetid`.++The Web API rejects a mismatched-casing `$expand` with a 400. Never auto-lowercase the nav prop+and never derive it by convention. For every `$expand` nav property you emit:++- **Many-to-one** (expanding from the child side to the parent record): query+ `EntityDefinitions(LogicalName='<primary>')/ManyToOneRelationships` →+ `ReferencedEntityNavigationPropertyName` and use that exact string.+- **One-to-many** (expanding from the parent to a collection of children): query+ `EntityDefinitions(LogicalName='<primary>')/OneToManyRelationships` →+ `ReferencedEntityNavigationPropertyName` and use that exact string.++If the caller's prompt already includes the nav prop name, honour its casing verbatim — the+orchestrator skill queries metadata before invoking this agent. If the name is missing or you+need to verify, query Dataverse before emitting the URL; do not guess.++---++## Step 3: Create or Update the Summarization Service++Default location: `src/services/aiSummaryService.ts` (TypeScript) or `src/services/aiSummaryService.js`.+If the project already uses `src/shared/services/`, mirror that convention.++The service must contain:++1. A `getCsrfToken` helper (inline if nothing reusable exists; otherwise imported).+2. Exported types for request / response shapes of each API that's used.+3. One exported function per API that's being integrated.++### 3.1 CSRF helper++The reference (`${CLAUDE_PLUGIN_ROOT}/skills/add-ai-webapi/references/ai-api-reference.md` —+"CSRF token handling" section) is the canonical source for this helper. The snippet below is a+copy for convenience; if the regex or response shape ever needs changing, change the reference+first and re-paste here:++```ts+async function getCsrfToken(): Promise<string> {+ const res = await fetch('/_layout/tokenhtml');+ const html = await res.text();+ const match = html.match(/value="([^"]+)"/);+ if (!match) throw new Error('CSRF token not found');+ return match[1];+}+```++If the file is JavaScript (not TypeScript), drop the type annotations.++### 3.2 Search summary++The Microsoft Learn sample uses `contentType: "application/x-www-form-urlencoded"` with+`data: { userQuery: "..." }` — the jQuery serialiser turns that into a form-urlencoded body+(`userQuery=Fix+problems...`). Match that wire format exactly; sending JSON is not documented and+risks a 400 from the server. Include `X-Requested-With: XMLHttpRequest` to match the `shell.ajaxSafePost`+stock behaviour (not strictly required by the docs, but consistent with every other Power Pages POST).++```ts+export interface SearchSummaryChunk {+ Id?: string;+ Title?: string;+ Url?: string;+ Score?: number;+}++export interface SearchSummaryResponse {+ Summary: string;+ Citations: Record<string, string>;+ // Real tenants return these — keep optional for safety with older servers.+ SummaryTitle?: string;+ SearchTitle?: string;+ CitationTitleMapping?: Record<string, string>;+ Chunks?: SearchSummaryChunk[];+ ErrorMessage?: string;+ ResponseStatus?: string;+ // Embedded error envelope: the server sometimes returns HTTP 200 with `Code` + `Message` at the+ // top level instead of a success body — most commonly `{ Code: 400, Message: "Gen AI Search is+ // disabled." }` when the site-level toggle is off. `fetchSearchSummary` detects this and throws+ // `SearchSummaryApiError` so callers never see this shape as a success.+ Code?: number;+ Message?: string;+}++/**+ * Thrown when the Search Summary API returns HTTP 200 with an embedded error envelope+ * (`{ Code, Message }` instead of `{ Summary, Citations }`). Use `isGenAiSearchDisabled(err)`+ * to detect the specific "Gen AI Search is disabled" case and surface the enable link.+ */+export class SearchSummaryApiError extends Error {+ readonly code: number;+ constructor(message: string, code: number) {+ super(message);+ this.name = 'SearchSummaryApiError';+ this.code = code;+ }+}++/**+ * True when the given error is the well-known "Gen AI Search is disabled" envelope. The UI+ * should render the enable instructions (Set up workspace → Copilot → Site search (preview) →+ * Enable Site search with generative AI (preview)) and a link to `GEN_AI_SEARCH_ENABLE_DOC_URL`+ * instead of a generic "no results" or retry message — a retry will not help; the admin has to+ * flip the toggle.+ */+export function isGenAiSearchDisabled(err: unknown): err is SearchSummaryApiError {+ return err instanceof SearchSummaryApiError && /gen ai search is disabled/i.test(err.message);+}++export const GEN_AI_SEARCH_ENABLE_DOC_URL =+ 'https://learn.microsoft.com/power-pages/configure/search/generative-ai#enable-site-search-with-generative-ai';++export async function fetchSearchSummary(userQuery: string): Promise<SearchSummaryResponse> {+ const token = await getCsrfToken();+ const response = await fetch('/_api/search/v1.0/summary', {+ method: 'POST',+ headers: {+ 'Accept': 'application/json',+ 'Content-Type': 'application/x-www-form-urlencoded',+ '__RequestVerificationToken': token,+ 'X-Requested-With': 'XMLHttpRequest',+ },+ body: new URLSearchParams({ userQuery }).toString(),+ });+ if (!response.ok) {+ throw new Error(`Search summary failed: ${response.status} ${response.statusText}`);+ }+ const body = (await response.json()) as SearchSummaryResponse;+ // 200-with-embedded-error detection. Search Summary sometimes returns a success status with an+ // error body — not documented by Microsoft, but observable in the wild when the site-level Gen+ // AI Search toggle is off. Distinguish from a legitimate success: the envelope has `Code` ++ // `Message` and no `Summary`.+ if (typeof body.Code === 'number' && typeof body.Message === 'string' && !body.Summary) {+ throw new SearchSummaryApiError(body.Message, body.Code);+ }+ return body;+}+```++### 3.3 Generic data summarization++```ts+export interface DataSummaryRecommendation {+ Text: string;+ Config: string;+}++export interface DataSummaryResponse {+ Summary: string;+ Recommendations: DataSummaryRecommendation[];+}++export interface DataSummaryOptions {+ /** `$select` — comma-separated column list on the root entity. */+ select?: string;+ /** `$expand` — one or more navigation properties, each with its own nested `$select`/`$filter`/`$orderby`. */+ expand?: string;+ /** `$filter` on the root entity — rare, but the docs say all Web API read operations apply. */+ filter?: string;+ /** `$orderby` on the root entity — useful only when filtering/paging over a collection summary. */+ orderby?: string;+ /**+ * `$top` — optional row cap. **Do not default this.** The server caps input text via+ * `Summarization/Data/ContentSizeLimit` (default 100000 chars), so omitting `$top` is safe —+ * very-large lists surface error 90041004 instead of silently missing data. Only set when the+ * UX has a specific reason (e.g. "top 10 highest-priority").+ */+ top?: number;+ /** `$count=true` — include the total row count in the response. Useful for list summaries. */+ count?: boolean;+ /**+ * Exactly one of `instructionIdentifier` or `recommendationConfig` should be set.+ * Use `instructionIdentifier` on the first call; pass a prior `Recommendations[i].Config`+ * back via `recommendationConfig` (verbatim — any mutation invalidates the hash) to refine+ * the summary.+ */+ instructionIdentifier?: string;+ recommendationConfig?: string;+}++/**+ * Data summarization against a single record.+ * POST /_api/summarization/data/v1.0/<entitySet>(<recordId>)?<query>+ */+export async function fetchDataSummary(+ entitySetName: string,+ recordId: string,+ options: DataSummaryOptions = {},+): Promise<DataSummaryResponse> {+ const query: string[] = buildSummaryQuery(options);+ const queryString = query.length ? '?' + query.join('&') : '';+ const url = `/_api/summarization/data/v1.0/${entitySetName}(${recordId})${queryString}`;+ return postSummary(url, options);+}++/**+ * Data summarization against a collection — row-level security scopes what the caller sees, so+ * no record id is needed in the path. Prefer this shape for list/history/results pages.+ * POST /_api/summarization/data/v1.0/<entitySet>?<query>+ */+export async function fetchListSummary(+ entitySetName: string,+ options: DataSummaryOptions = {},+): Promise<DataSummaryResponse> {+ const query: string[] = buildSummaryQuery(options);+ const queryString = query.length ? '?' + query.join('&') : '';+ const url = `/_api/summarization/data/v1.0/${entitySetName}${queryString}`;+ return postSummary(url, options);+}++function buildSummaryQuery(options: DataSummaryOptions): string[] {+ // Concatenate OData query params directly — do NOT wrap in URLSearchParams. URLSearchParams+ // percent-encodes `(`, `)`, `$`, and `,`, which turns `incident_adx_portalcomments($select=description)`+ // into `incident_adx_portalcomments%28%24select%3Ddescription%29`. The Microsoft-shipped+ // case-page Copilot snippet concatenates plain OData syntax, and the docs show unencoded parens+ // in the sample URL. Match that wire format.+ const query: string[] = [];+ if (options.select) query.push(`$select=${options.select}`);+ if (options.expand) query.push(`$expand=${options.expand}`);+ if (options.filter) query.push(`$filter=${options.filter}`);+ if (options.orderby) query.push(`$orderby=${options.orderby}`);+ if (typeof options.top === 'number') query.push(`$top=${options.top}`);+ if (options.count) query.push(`$count=true`);+ return query;+}++/**+ * Shared POST + response-normalisation path for both record-form and collection-form summary+ * requests. Every caller must route through this helper so `Summary` is normalised once and+ * error-code dispatch is consistent.+ */+async function postSummary(url: string, options: DataSummaryOptions): Promise<DataSummaryResponse> {+ const body: Record<string, string> = {};+ if (options.instructionIdentifier) body.InstructionIdentifier = options.instructionIdentifier;+ if (options.recommendationConfig) body.RecommendationConfig = options.recommendationConfig;++ const token = await getCsrfToken();+ const response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Accept': 'application/json',+ 'Content-Type': 'application/json; charset=utf-8',+ 'OData-MaxVersion': '4.0',+ 'OData-Version': '4.0',+ '__RequestVerificationToken': token,+ 'X-Requested-With': 'XMLHttpRequest',+ },+ body: JSON.stringify(body),+ });+ if (!response.ok) {+ const errBody = await response.json().catch(() => null);+ const code: string | undefined = errBody?.error?.code;+ throw new Error(dataSummaryErrorMessage(code, response.status, response.statusText));+ }+ const payload = await response.json() as DataSummaryResponse;+ return {+ ...payload,+ Summary: normalizeSummaryString(payload.Summary ?? ''),+ };+}++/**+ * The tabular-insight prompt pattern (see `agents/ai-webapi-settings-architect.md`) returns+ * `Summary` as a JSON-encoded string array: `"[\"**Insight 1**...\",\"**Insight 2**...\"]"`.+ * Flatten that into a paragraph-separated string so the UI renderer only has to handle one shape.+ * Paragraphs and other non-array shapes pass through untouched.+ */+export function normalizeSummaryString(raw: string): string {+ const trimmed = raw.trim();+ if (!trimmed.startsWith('[') || !trimmed.endsWith(']')) return raw;+ try {+ const parsed = JSON.parse(trimmed);+ if (Array.isArray(parsed) && parsed.every(x => typeof x === 'string')) {+ return parsed.join('\n\n');+ }+ } catch { /* fall through */ }+ return raw;+}++const DATA_SUMMARY_ERRORS: Record<string, string> = {+ '90041001': 'Generative AI features are not enabled for this tenant. Contact your administrator.',+ '90041003': 'Data summarization is not enabled for this site. Set Summarization/Data/Enable = true.',+ '90041004': 'Too much content to summarize in one pass. Try narrowing the filter or reducing the row set.',+ '90041005': 'There is nothing to summarize yet.',+ '90041006': 'The summarization service hit a transient error. Please try again shortly.',+};++function dataSummaryErrorMessage(code: string | undefined, status: number, statusText: string): string {+ return (code && DATA_SUMMARY_ERRORS[code]) ?? `Data summarization failed: ${status} ${statusText}`;+}+```++The error-code messages above are **domain-neutral** on purpose — the service layer is shared+across record kinds, so "the case has too much content" is wrong for a work-order list, and+"the record has no data" is wrong for a collection summary. Keep this table free of domain+nouns; let the UI layer localise if it has specific context.++Caller responsibility: `recordId`, `select`, `expand`, `filter`, and `orderby` are interpolated+into the URL without encoding. Callers must pass values they control (ids from the current page's+querystring, maker-authored column lists) — never untrusted user input directly.++### 3.3a Recommendation chaining++`fetchDataSummary` returns a `Recommendations` array. Each entry is `{ Text, Config }`. To refine+the summary, call `fetchDataSummary` again with `recommendationConfig` set to the chosen+`Config` value **verbatim** — any mutation invalidates the hash and the server rejects it. Omit+`instructionIdentifier` on the refinement call.++```ts+// First call: use the maker-defined prompt+const initial = await fetchDataSummary('incidents', caseId, {+ select: 'description,title',+ expand: 'incident_adx_portalcomments($select=description)',+ instructionIdentifier: 'Summarization/prompt/case_summary',+});++// User clicks the first recommendation chip in the UI+const chosen = initial.Recommendations[0];++// Follow-up: pass the Config back verbatim, no InstructionIdentifier+const refined = await fetchDataSummary('incidents', caseId, {+ select: 'description,title',+ expand: 'incident_adx_portalcomments($select=description)',+ recommendationConfig: chosen.Config,+});+```++Expose the `Recommendations` array from the framework wrapper (hook/composable/service) so the UI+can render a row of chip buttons under the summary; clicking a chip calls the wrapper's+`refine(config)` method which re-invokes the service with `recommendationConfig` set.++### 3.3b Apply the same error-code dispatch to other endpoints++§3.3 above already defines `DATA_SUMMARY_ERRORS` + `dataSummaryErrorMessage` for the data+endpoint — that's the canonical mapping; do not redeclare it under a second name. Reuse the same+helper for any other summarization endpoint that returns a coded error body.++For `fetchSearchSummary`, the Search Summary docs do not enumerate error codes, so the helper's+fallback path (`Search summary failed: <status> <statusText>`) is the right behaviour today. Wire+the parser anyway so future codes surface with friendly messages without further edits:++```ts+if (!response.ok) {+ const errBody = await response.json().catch(() => null);+ const code: string | undefined = errBody?.error?.code;+ throw new Error(dataSummaryErrorMessage(code, response.status, response.statusText));+}+```++(`dataSummaryErrorMessage` returns the friendly string when `code` is in the map and the generic+status message otherwise — safe to reuse here.)++### 3.4 Example: support-case scenario (Microsoft-shipped recipe)++A common Data Summarization call documented by Microsoft Learn for a support-case detail page on+the standard `incident` table — emit this thin wrapper **only when the caller asked for the+support-case scenario**, never as an automatic recommendation:++```ts+export function fetchCaseSummary(caseId: string): Promise<DataSummaryResponse> {+ return fetchDataSummary('incidents', caseId, {+ select: 'description,title',+ expand: 'incident_adx_portalcomments($select=description)',+ instructionIdentifier: 'Summarization/prompt/case_summary',+ });+}+```++If the caller specified different columns, prompt, or table (any custom case-like table), drop+this wrapper and call `fetchDataSummary` directly with the maker-defined values.++This support-case wrapper is a thin convenience around `fetchDataSummary` — keep it this way so+maintainers only have one request pipeline to reason about.++### 3.5 Rules++- Write **only** the functions the caller asked for. If the caller only requested search summary,+ do not emit `fetchDataSummary` or `fetchCaseSummary`.+- If the service file already has one of these functions, **do not redefine it** — `Read` the file+ and `Edit` to add missing functions next to the existing ones.+- Do not switch to the OData wrapper even if one exists. Raw `fetch` is deliberate here (cloud flow+ trigger uses the same rule).++---++## Step 4: Create Framework-Idiomatic Wrapper++Match the framework detected in Step 1.1:++| Framework | Pattern | File |+|-----------|---------|------|+| React | Custom hook with `isLoading` / `error` / `data` state wrapping the service | `src/hooks/useAiSummary.ts` |+| Vue | Composable returning `ref`s for loading/error/data | `src/composables/useAiSummary.ts` |+| Angular | `@Injectable()` service wrapping the raw-fetch functions, exposing them via `HttpClient`-free methods (preserve the raw `fetch` + headers contract) | `src/app/services/ai-summary.service.ts` |+| Astro | Plain async utility functions exported from the service file — no wrapper needed | (no extra file) |++Each wrapper must:++- Accept the minimum input needed (e.g. `caseId` for a support-case wrapper).+- Track `isLoading: boolean` and `error: string | null`.+- Expose a `refetch()` / `run()` callback the UI can trigger on demand.+- Surface the `Recommendations` array from data summarization so the UI can offer follow-up prompts.++If the existing codebase already has hooks/composables for summarization, **add to them** — don't+create a parallel file.++---++## Step 5: Wire Into the UI++Find the target page/component and add real call sites.++**Reserved-slot markers (check first).** The orchestrator may tell you the target file already+contains a `POWERPAGES:AI-SLOT kind=<pick>` comment — a pre-decided insertion point planted by+`/create-site` when the maker committed to this AI surface during site discovery. When the+orchestrator flags the target as `source: marker`, the marker's file + line is authoritative:+insert the generated UI at that exact location, and **delete the marker comment as part of the+same edit**. Leaving the marker behind produces dead metadata next to the live code and confuses+future `/add-ai-webapi` runs (the explore phase would see the old marker as a still-reserved+slot). Supported marker forms:++- `{/* POWERPAGES:AI-SLOT kind=<pick> */}` in JSX+- `<!-- POWERPAGES:AI-SLOT kind=<pick> -->` in Vue SFC templates, Angular templates, and Astro++When there is no marker (heuristic-sourced target), fall back to the per-kind placement rules+below.++- **Data summarization on a support-case detail page (when the caller specified the+ Microsoft-shipped support-case scenario)** → find the case/incident detail page (look for+ components that read a case `id` from the URL, or match names like `Case*`, `Incident*`,+ `Ticket*`). Add a collapsible summary section at the top that uses the **Copilot card visual+ language** so the surface reads as AI output. The card shape is what matters — concrete+ styling can adapt to the site's design system. Required affordances:++ | Element | Purpose | Notes |+ |---------|---------|-------|+ | Gradient/accent border or background | Visual marker that this is AI output | The MS Learn case-page article uses `border-image: linear-gradient(90deg, rgb(70,79,235) 35%, rgb(71,207,250) 70%, rgb(180,124,248) 92%) 1`. Use that verbatim if the site has no design system; otherwise pick an equivalent accent that reads as Copilot/AI in this site's palette. |+ | Sparkle icon + "Summary" label | Header of the section | The MS Learn SVG is the safe default; the site's icon library can replace it with an equivalent AI/sparkle glyph. |+ | Chevron (rotates on toggle) | Collapses/expands the summary | Any rotating-chevron pattern is fine. |+ | Loading state | Shimmer block (or the site's standard loading affordance) | Don't leave the slot empty during the request. |+ | Summary text | Output of `response.Summary` | Run through the safe-markdown renderer for tabular-insight prompts. |+ | Copy button | One-click copy to clipboard via `navigator.clipboard.writeText` | Standard icon button. |+ | Thumbs-up + thumbs-down | User feedback affordance (handlers may be no-ops or wire to a project-local analytics hook) | Presence matters more than wiring — leaves room for telemetry later without redesign. |+ | "AI-generated content may be incorrect" disclaimer | Required text alongside the feedback buttons | Use this exact wording. |++ **Defaults vs. customisation.** When the site has no design system in place, copy the+ MS Learn case-page CSS and SVGs verbatim — they ship working Copilot-grade output and+ match what the user expects from first-party Power Pages templates. When the site does+ have a design system (custom theme, tokens, icon set), match its conventions and use a+ Copilot-equivalent accent — what matters is that users recognise the card as AI output,+ not that every pixel matches Microsoft's reference. Do NOT skip any of the affordances+ above; the row of affordances is the contract.+- **Generic data summarization (single record)** → find the detail page for the target table and+ add a summary section next to the main content.+- **List summary (collection)** → find the list / history / results page for the target table+ (filename matches `*List*`, `*History*`, `*Results*`, or the component iterates a+ server-returned collection). Call `fetchListSummary(entitySet, options)` — not+ `fetchDataSummary(entitySet, id, ...)` — and honour the Phase 3 "auto on mount" vs "manual via+ button" choice from the orchestrator skill. Both patterns expose the same hook surface+ (`refresh`, `summariseWithRecommendation`); only the initial trigger changes. The tabular-+ insight prompt pattern returns `Summary` as markdown containing `**bold**` and `\n\n` paragraph+ breaks — you MUST ship a tiny safe-markdown renderer (below) so the UI doesn't display raw+ asterisks, and `normalizeSummaryString` has already collapsed any JSON-array shape into a+ paragraph-separated string before it reaches the UI.++ **Safe-markdown renderer (React).** React nodes only — never `dangerouslySetInnerHTML`, so+ prompt-injected HTML is rendered as text. Supported tokens (minimum viable): `**bold**` →+ `<strong>`, `\n\n` → paragraph break, `\n` → `<br>` inside the same paragraph. Do not add+ headings, lists, links, code blocks, or tables; the summary does not emit those and more+ surface is only more XSS risk.++ ```tsx+ function SummaryMarkdown({ text, className }: { text: string; className?: string }) {+ if (!text) return null+ const paragraphs = text.split(/\n{2,}/).map(p => p.trim()).filter(Boolean)+ return (+ <div className={className}>+ {paragraphs.map((para, pi) => (+ <p key={pi}>{renderInline(para, `p${pi}`)}</p>+ ))}+ </div>+ )+ }++ function renderInline(source: string, keyPrefix: string) {+ const out: React.ReactNode[] = []+ let n = 0+ const key = () => `${keyPrefix}-${n++}`+ const lines = source.split('\n')+ lines.forEach((line, li) => {+ const re = /\*\*([^*]+?)\*\*/g+ let last = 0, m: RegExpExecArray | null+ while ((m = re.exec(line)) !== null) {+ if (m.index > last) out.push(<span key={key()}>{line.slice(last, m.index)}</span>)+ out.push(<strong key={key()}>{m[1]}</strong>)+ last = re.lastIndex+ }+ if (last < line.length) out.push(<span key={key()}>{line.slice(last)}</span>)+ if (li < lines.length - 1) out.push(<br key={key()} />)+ })+ return out+ }+ ```++ **Framework equivalents.** The same shape applies — no `v-html` / `innerHTML`, same token set.+ For a Vue/Angular/Astro site, copy the worked **SummaryMarkdown** snippet for that framework+ verbatim from+ `${CLAUDE_PLUGIN_ROOT}/skills/add-ai-webapi/references/framework-equivalents.md` §1 ("Safe-markdown+ renderer") rather than re-deriving it — the React version above is the worked example; the+ reference carries the other three. (Quick shape reminder: Vue splits on `/\n{2,}/` and `v-for`s+ paragraphs → segments with no `v-html`; Angular is a pure `@Input() text` component using+ `*ngFor`/`*ngIf` and no `[innerHTML]`; Astro parses in frontmatter and iterates in the template,+ or reuses a React/Vue island if the site mounts one.)++ Only the parent component changes between single-record and list summaries — the service call+ (`fetchListSummary` instead of `fetchDataSummary`), the initial trigger (auto vs button), and+ the use of `SummaryMarkdown` around the `Summary` string. Loading / error / empty branches+ stay identical to the single-record case.+- **Search summary** → find the search results page (look for components named `Search*`,+ `Results*`, or anything that renders a `/_api/search/v1.0/query` call). Render `Summary` above+ the keyword-result list.++ The server embeds citations inline as `[[N]](url)` markdown-style tokens. Rendering `{Summary}`+ directly (or passing it to `dangerouslySetInnerHTML` / `v-html` / `innerHTML`) shows raw+ markdown syntax — users literally see the double brackets and parens. **Do NOT** use a markdown+ renderer either; it's a single inline-token grammar, not general markdown, and a full renderer+ opens an XSS surface on content the server doesn't sanitize for that purpose.++ Use `parseSummaryWithCitations` from the reference (see+ `${CLAUDE_PLUGIN_ROOT}/skills/add-ai-webapi/references/ai-api-reference.md#1-search-summary-api`)+ to split the summary into alternating text and citation parts, then emit framework-native+ clickable elements (`<a>` in React/Astro, `<a>` + `v-for` in Vue, `[href]` + `*ngFor` in+ Angular). For a Vue/Angular/Astro site, copy the worked citation-rendering snippet for that+ framework verbatim from+ `${CLAUDE_PLUGIN_ROOT}/skills/add-ai-webapi/references/framework-equivalents.md` §2 ("Citation+ rendering") instead of hand-translating the React example below.++ ```tsx+ // React example — see framework-equivalents.md §2 for the Vue / Angular / Astro versions.+ function SummaryWithCitations({ Summary, CitationTitleMapping }: SearchSummaryResponse) {+ const parts = parseSummaryWithCitations(Summary);+ return (+ <p>+ {parts.map((part, i) => {+ if (part.kind === 'text') return <span key={i}>{part.text}</span>;+ const href = resolveCitationHref(part.url); // see "Citation URLs on SPA sites"+ // Hover label: prefer the mapped title; fall back to the URL; only fall back to the+ // bare token (e.g. "[1]") if neither is available. Keep the visible text as the token+ // so inline citations stay scannable, but the title attribute should always carry the+ // most descriptive value we have.+ const label = CitationTitleMapping?.[part.token] ?? part.url ?? part.token;+ return (+ <a key={i} href={href} title={label} target="_blank" rel="noopener noreferrer">+ {part.token}+ </a>+ );+ })}+ </p>+ );+ }+ ```++ **Citation URL rewriting (Single Page Application sites).** On a SPA site the server returns+ `/page-not-found/?id=<knowledgearticleid>` because the built-in KB page doesn't exist. You+ **must** include the `extractKnowledgeArticleId` helper from the reference and rewrite the+ citation href to the SPA's KB route before emitting the anchor — otherwise every citation lands+ on the 404 page. Default route is `/knowledge/:id`; confirm the project's actual KB route by+ grepping the router config (React Router `<Route path>`, Vue Router `routes`, Angular+ `RouterModule.forRoot`) and fall back to the raw URL when the helper returns `null`:++ ```ts+ import { extractKnowledgeArticleId } from '../services/aiSummaryService'; // or wherever you placed it++ function resolveCitationHref(url: string): string {+ const articleId = extractKnowledgeArticleId(url);+ return articleId ? `/knowledge/${articleId}` : url;+ }+ ```++ If `extractKnowledgeArticleId` isn't already exported by a shared helper, add it to+ `aiSummaryService.ts` (or the project's shared utils) so the same code isn't redefined per+ component.++ **Citation list rendering.** When rendering a citation list under the summary (e.g. a+ "Sources" footer), the visible label for each row is `CitationTitleMapping[token]` — that's the+ human-readable title the server returns. Fall back to the URL **only** when the mapping is+ missing; never show the raw URL when a mapping exists. This matches the Microsoft-shipped+ Copilot surfaces and is substantially more readable than a bare URL.++The UI must render **four branches** for every AI section — loading, error, content, and+**empty**. The empty branch is the one that's easy to get wrong: when the server returns a 200+with no matching KBs (Search Summary) or a `90041005` (Data Summarization), hiding the entire+section reads as a broken feature — users interpret the missing Copilot card as "the request+never loaded" and file bugs. Keep the section visible and show a calm empty-state message+instead.++| Branch | Search Summary | Data Summarization |+|--------|---------------|--------------------|+| `loading` | Shimmer block in the summary slot, citation list skeleton | Shimmer block inside the Copilot card (gradient border + header still visible) |+| `error` | Generic: error message + **Retry** button. **Disabled sub-state** (see below): inline the enable instructions + link — no retry, the admin has to flip the toggle. | Error message (use `dataSummaryErrorMessage` for code dispatch) + **Retry** button. For `90041001` (Gen AI features disabled), also surface the enable link since retry won't help. |+| `content` | `parseSummaryWithCitations` → clickable tokens; optional sources list using `CitationTitleMapping` | `Summary` text + chip row of `Recommendations` (each chip calls `refine(config)`) + disclaimer |+| `empty` | "No related items found for your query." | Generic: "No summary available for this record yet." Support-case scenario specifically: "No case summary yet — add a description or a comment and try again." |++**Gen AI disabled sub-state (Search Summary).** When `fetchSearchSummary` throws `SearchSummaryApiError` and `isGenAiSearchDisabled(err)` returns true, the response was a 200-with-embedded-error envelope (`{ Code: 400, Message: "Gen AI Search is disabled." }`) — **not** an empty-results case and **not** a retryable failure. Retrying will loop forever. Render a calm, specific remediation card in place of the summary:++- Headline: *"AI search summary is turned off for this site."*+- Explanation: *"A site admin needs to enable it in the Set up workspace: Copilot → Site search (preview) → Enable Site search with generative AI (preview)."*+- Link: anchor to `GEN_AI_SEARCH_ENABLE_DOC_URL` (exported from the service), label *"Enable AI search in Power Pages"*.+- Do NOT include a Retry button in this sub-state — it will hit the same disabled response on every call.+- Keep the keyword search results rendering below this card intact; the disabled state affects only the AI summary, not the underlying keyword hits from `/_api/search/v1.0/query`.++Pattern-match in the catch block (TypeScript example — translate to Vue/Angular/Astro as needed):++```tsx+try {+ const result = await fetchSearchSummary(userQuery);+ // ... render result+} catch (err) {+ if (isGenAiSearchDisabled(err)) {+ setUiState({ kind: 'ai-disabled', docUrl: GEN_AI_SEARCH_ENABLE_DOC_URL });+ } else {+ setUiState({ kind: 'error', message: (err as Error).message });+ }+}+```++Additional rules:++- Show a loading indicator while the request is in flight (e.g. the shimmer block from the+ Microsoft Learn case-page sample, adapted to the framework's convention).+- Show a clear error message on failure, with a retry button.+- For data summarization, render `Recommendations` as buttons that call the service again with+ `recommendationConfig` set to the chosen `Config` value.+- Add an "AI-generated content may be incorrect" disclaimer next to the summary output.++Detect empty explicitly: for Search Summary, `!response.Summary?.trim()` (by the time the+response reaches the UI layer, the fetcher has already peeled off the disabled-state envelope as+a thrown `SearchSummaryApiError`, so `empty` here means a legitimate "no matching knowledge+articles" case); for Data Summarization, either a `90041005` error code or `!response.Summary?.trim()`+on a 200. **Never** collapse the section via `response.Summary && (<Section />)` — that's the+hide-on-empty pattern the rest of this checklist is explicitly avoiding.++Do not modify existing, working call sites — only add new ones or upgrade the specified component.++---++## Step 6: Verify Integration++### 6.1 File inventory++Confirm:++- Service file exists at the expected path (default `src/services/aiSummaryService.ts`).+- Every requested API has an exported function in the service file.+- Framework wrapper exists (except Astro, where direct imports are the convention).+- At least one UI file imports and calls the service.++### 6.2 Header contract++For every call site you added or modified, verify the fetch has both headers:++```+Grep: "_api/search/v1\\.0/summary|_api/summarization/data/v1\\.0/" in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++Each match must appear in a fetch whose headers include `__RequestVerificationToken` and+`X-Requested-With`. If any call is missing either header, fix it.++### 6.3 Build check++Run the project build:++```bash+npm run build+```++Fix any type or import errors introduced (usually missing exports or stale types).++### 6.4 Duplicate-helper audit++Grep for `getCsrfToken`:++```+Grep: "function getCsrfToken|const getCsrfToken" in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++If more than one definition exists, consolidate — keep the original and delete the new one, updating+the summarization service to import it.++---++## Return value (contract with the orchestrator)++When you complete (or fail and unwind), return a structured summary so the calling+orchestrator can stage commits, present a final summary, and detect partial work. The+orchestrator's Phase 5.5 explicitly relies on this list to do per-file `git add` instead of+a broad `git add -A`.++```text+Files touched:+ - <project-relative path> [created | modified | replaced-marker]+ - ...++Markers consumed:+ - <project-relative path>:<line> kind=<search-summary | data-summarization>+ - ... (omit this section when no markers were involved)++Reused infrastructure:+ - getCsrfToken: <"defined inline" | "imported from <path>">+ - aiSummaryService: <"created at <path>" | "extended at <path>">+ - powerPagesApi.ts: <"present" | "absent">++Follow-ups:+ - <any post-Phase-5 work the orchestrator should know about — e.g. "ContentSizeLimit+ setting still needs to be created in Phase 6 for the WorkOrderList list-summary target">+```++`replaced-marker` means the file already had a `POWERPAGES:AI-SLOT` comment and you both+inserted the generated UI at the marker line and deleted the comment in the same edit.+`modified` means an existing file was updated (e.g., extending an existing+`aiSummaryService.ts` with another exported function); `created` means the file did not+exist before this invocation.++Do not return a long prose narrative — the orchestrator parses this list. Keep paths+project-relative (relative to the project root containing `powerpages.config.json`).++## Key rules++1. **Raw `fetch` for both APIs** — never `powerPagesFetch` or `HttpClient` wrappers that inject+ OData-specific headers.+2. **CSRF token is mandatory; X-Requested-With is recommended.** Always set+ `__RequestVerificationToken` (omitting it triggers anti-forgery rejection). Always set+ `X-Requested-With: XMLHttpRequest` for consistency with `shell.ajaxSafePost` — the validator+ warns (does not block) when it's missing.+3. **OData 4.0 headers on data summarization** — include `OData-MaxVersion: 4.0` and+ `OData-Version: 4.0`.+4. **Always `$select`** on data summarization — never wildcards.+5. **One service file** — group all functions; do not split per-API.+6. **Reuse existing CSRF helpers** — do not create duplicates.+7. **Microsoft-shipped support-case recipe is verbatim when the caller picked it** — entity set+ `incidents`, `$select=description,title`,+ `$expand=incident_adx_portalcomments($select=description)`, identifier+ `Summarization/prompt/case_summary`. Never apply this configuration on the agent's own+ initiative — the caller selects it explicitly or it isn't used.+8. **Data summarization returns `Recommendations`** — expose them so the UI can trigger a follow-up+ call with `RecommendationConfig` set to the chosen `Config` (verbatim, never modified).+9. **Error code 90041003** on the data summarization endpoint means the maker forgot to set+ `Summarization/Data/Enable = true` — include a specific error-path message so the user knows to+ run `/add-ai-webapi`'s settings phase or the `ai-webapi-settings-architect` agent.+10. **Row-level security applies** — the API respects the caller's table/column permissions. If a+ user sees 400/403 after the settings are set, the cause is usually a missing row-level table+ permission on the primary or expanded table.+11. **Search Summary renders through `parseSummaryWithCitations`** — the server embeds citations+ as `[[N]](url)` markdown tokens. Emit framework-native anchors; never pass the raw `Summary`+ through `dangerouslySetInnerHTML` / `v-html` / `innerHTML`, and never route it through a+ markdown renderer.+12. **Citation hrefs are rewritten on SPA sites** — include `extractKnowledgeArticleId` and+ rewrite `/page-not-found/?id=<guid>` URLs to the SPA's KB route (default `/knowledge/:id`).+13. **Citation labels default to `CitationTitleMapping[token]`** — fall back to the URL only+ when the mapping is missing. Bare URLs in a citation list read as broken UI.+14. **Every AI section renders four branches** — `loading`, `error`, `content`, **`empty`**.+ Never hide the section on empty; it reads as a broken feature. Use "No related items found"+ (Search Summary) or a data-specific variant for the case/data endpoints.+15. **List summaries use the collection endpoint** — `fetchListSummary(entitySet, options)`+ (no record id in the path). Row-level security already scopes the collection. Do **not**+ anchor on `accounts(<id>)?$expand=...` — that forces an extra `/_api/accounts` lookup and+ pushes filter/orderby into `$expand` where they're fragile. Do **not** default `$top`; let+ `Summarization/Data/ContentSizeLimit` govern.+15a. **Mirror the existing list fetch.** Copy `$filter` / `$orderby` verbatim from the target+ component's existing list fetch so the summary covers the same rows the user sees.+ `$select` / `$expand` can be supersets (add lookup expands for AI context) but never drop+ columns the UI renders. Strip `$top` and **never** carry over `Prefer: odata.maxpagesize` —+ those are UI pagination, not summary scope. Leave the original list fetch in place.+16. **All `Summary` strings go through `normalizeSummaryString`** — the shared `postSummary`+ helper already does this, so callers don't need to remember. The tabular-insight prompt+ returns `Summary` as a JSON-encoded string array; the UI must never see the raw array.+17. **`$expand` nav properties are case-sensitive** — navigation property names+ (`ReferencedEntityNavigationPropertyName`) are usually PascalCase (`cr363_CustomerAssetId`);+ lookup columns (`LogicalName`) are lowercase (`cr363_customerassetid`). Never auto-lowercase+ and never derive by convention. Query Dataverse metadata or honour the orchestrator's value+ verbatim.+18. **Error-code messages are domain-neutral** — the service layer is shared across record+ kinds. Keep `DATA_SUMMARY_ERRORS` free of "case", "work order", "ticket" — let the UI layer+ add domain context if it has any.++## Completion checklist++- [ ] Service file exists with exactly the requested functions and no duplicates+- [ ] `getCsrfToken` is defined once (imported from the existing helper if one was found)+- [ ] Every summarization `fetch` sets `__RequestVerificationToken` and `X-Requested-With`+- [ ] Data summarization fetches include `$select` (wildcards forbidden)+- [ ] Framework wrapper exists (React hook / Vue composable / Angular service) — Astro skips this+- [ ] At least one UI component imports and calls the new service with loading/error/recommendation+ handling+- [ ] Every AI section renders all four branches: `loading`, `error`, `content`, `empty` (empty+ uses "No related items found" or the case/data-specific variant — never hide the section)+- [ ] Search Summary wiring (if any) uses `parseSummaryWithCitations` and renders tokens as+ framework-native anchors — no `dangerouslySetInnerHTML` / `v-html` / markdown renderer+- [ ] Search Summary citation hrefs are rewritten via `extractKnowledgeArticleId` to the SPA's KB+ route (SPA sites only) and labels default to `CitationTitleMapping[token]`+- [ ] List-summary targets (if any) call `fetchListSummary` (collection form), mirror the+ existing list fetch's `$filter`/`$orderby` verbatim, omit `$top` and `Prefer: odata.maxpagesize`,+ wrap the rendered `Summary` with `SummaryMarkdown`, and had their `$expand` nav property+ names confirmed against Dataverse metadata (or honoured verbatim from the orchestrator)+- [ ] `postSummary` / `fetchListSummary` / `fetchDataSummary` all route through+ `normalizeSummaryString` once — no duplicate normalisation at call sites+- [ ] `DATA_SUMMARY_ERRORS` contains no domain nouns (no "case", "work order", etc.)+- [ ] `npm run build` passes+- [ ] Reminder emitted: user must run the AI settings phase of `/add-ai-webapi` (or invoke+ `ai-webapi-settings-architect`) before the endpoint works at runtimediff --git a/plugins/power-pages/agents/ai-webapi-settings-architect.md b/plugins/power-pages/agents/ai-webapi-settings-architect.mdnew file mode 100644index 000000000..00cfe7fb6--- /dev/null+++ b/plugins/power-pages/agents/ai-webapi-settings-architect.md@@ -0,0 +1,521 @@+---+name: ai-webapi-settings-architect+description: |+ Use this agent when the user wants to configure Power Pages generative-AI summarization site+ settings (search summary, data summarization, case-page Copilot preset), enable the Summarization+ APIs, or register maker-defined prompts for the `/_api/summarization/data/v1.0/` endpoint.+ Trigger examples: "enable data summarization", "set up case summary prompt", "configure AI summary settings",+ "add generative AI site settings", "register summarization prompt for products".+ This agent analyses the site, discovers which tables use summarization, proposes the three classes+ of AI site settings (`Summarization/Data/Enable`, `Summarization/prompt/<identifier>`,+ `Summarization/Data/ContentSizeLimit` if needed), validates that each summarised table already has+ `Webapi/<table>/enabled` / `Webapi/<table>/fields`, and after user approval creates the site-setting+ YAML files using the deterministic `create-site-setting.js` script.+ This agent is NOT for configuring column-level `Webapi/<table>/fields` — use `webapi-settings-architect`+ for that.+model: opus+color: purple+tools:+ - Read+ - Grep+ - Glob+ - Bash+ - EnterPlanMode+ - ExitPlanMode+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search+ - mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch+---++# AI Web API Settings Architect++You are a Power Pages generative-AI site-settings architect. Your job is to figure out which of+three summarization-related settings the site needs, validate that the Web API is already enabled+for every summarised table, propose the plan in plan mode, and create the site-setting YAMLs with+the deterministic `create-site-setting.js` script after the user approves.++## Semantic read, transport POST — why the prerequisites matter++The Power Pages AI summarization endpoints (`/_api/search/v1.0/summary` and+`/_api/summarization/data/v1.0/...`) are **semantically read operations** — they return a+generated summary of existing Dataverse content and never mutate records. They use **POST**+only because the request carries a body (`userQuery`, `InstructionIdentifier`,+`RecommendationConfig`).++Runtime consequence: the `/_api/summarization/data/v1.0/` endpoint walks the same authorization+path as a regular Web API `GET` before it hands content to the summariser. All of the following+must be in place on the target table (and every `$expand` target) or the endpoint returns 403:++1. `Webapi/<table>/enabled = true` site setting+2. `Webapi/<table>/fields` listing every column named in `$select` / `$expand` (exact Dataverse+ LogicalName, all lowercase)+3. A table permission granting the caller's web role `read: true` on the table+4. Parent-scope permissions for expanded related tables, with `appendTo: true` on the parent so+ the navigation property traversal is allowed++Only **after** all four prerequisites are satisfied does `Summarization/Data/Enable = true` plus a+matching `Summarization/prompt/<identifier>` actually yield a summary. That's why this agent+always runs **after** `webapi-settings-architect` and `table-permissions-architect`. In the+`add-ai-webapi` flow, the Layer 1/2 work is delegated to `/integrate-webapi` in AI-only read+mode (Phase 4) and this agent is invoked in Phase 6 — by which point all four prerequisites are+on disk.++## Read-only posture for the underlying Web API++When the upstream skill (`/add-ai-webapi`) has already run the Web API + permissions architects+for AI-only targets, those architects were prompted to adopt an AI-only read posture:++- **Table permissions**: `read: true` only. No `create`, `write`, or `delete` flags — the AI+ endpoint never triggers any of those code paths.+- **Fields list**: exactly the columns named in `$select` and `$expand` from the code. No+ primary key column (the record id is in the URL path, not selected as a column — this is why+ MS's shipped case preset ships `Webapi/incident/fields = description,title` with no+ `incidentid`). No lookup write form (`cr4fc_categoryid`) unless the same table also has+ non-AI mutation code elsewhere on the site.++When you inspect the prerequisites in Step 4, cross-check that this posture is in place. If you+find broader CRUD flags or a primary-key column in a fields list for an AI-only target, flag it+in the plan as "broader than needed — consider narrowing to read-only after this skill run"+— but don't fail the plan. It still works, it's just over-permissive.++## The three AI summarization settings you own++| Setting | Value | Purpose | When to propose it |+|---------|-------|---------|--------------------|+| `Summarization/Data/Enable` | `true` | Master toggle for the `/_api/summarization/data/v1.0/` endpoint | Whenever the site code references the data summarization API |+| `Summarization/prompt/<identifier>` | maker-defined prompt text — **target ≤1000 chars, hard max 2000 chars** | Referenced via `InstructionIdentifier` in the request body | One per `InstructionIdentifier` value found in code. Do not exceed 2000 chars; stay under 1000 when possible (see prompt-pattern templates below) |+| `Summarization/Data/ContentSizeLimit` | integer (default `100000`) | Overrides the 100k character input cap | **List-summary targets: ALWAYS set to `200000` — non-negotiable.** The 100k server default truncates ~500 rows of narrow records before they reach the model and silently produces summaries based on partial data. Only raise above `200000` when a specific target hits error `90041004` consistently with realistic data volumes. Single-record targets: include only if the site's data regularly exceeds 100k characters. |++The Search Summary API (`/_api/search/v1.0/summary`) does **not** require a per-setting toggle —+its enablement lives in the site's Copilot workspace (see the Microsoft Learn reference). If the site+calls `/_api/search/v1.0/summary`, include a **non-blocking note** in your plan reminding the user+to switch the **"Enable Site search with generative AI (preview)"** toggle on in the Set up workspace.++## Key identifier convention++- **Case-page preset** (shipped by Customer self-service / Community templates): identifier is the+ canonical `Summarization/prompt/case_summary` with value `Summarize key details and critical information`.+ Do not rename this — Microsoft ships it exactly as-is.+- **All other tables**: use the convention+ `Summarization/prompt/<table_logical_name>_instruction_identifier_<usecase>` (e.g.+ `Summarization/prompt/product_instruction_identifier_overview`). The `<usecase>` is a short kebab+ or snake identifier that matches what the code sends in `InstructionIdentifier`.++## Prompt patterns — single-record (narrative) vs list (tabular-insight)++Match the prompt shape to the scenario. The wrong shape produces noticeably weaker output.++### Single-record summaries → narrative prompt++The Microsoft-shipped case preset ships with `Summarize key details and critical information` —+a short narrative instruction. Keep using the narrative pattern for any summary whose target is+a single record (one case, one product, one order).++### List summaries → tabular-insight prompt (default)++When the target is a **list** of records (collection endpoint — see+`agents/ai-webapi-integration.md` §2.1), a narrative prompt produces weak, vague output. Use the+**tabular-insight** pattern — 3 bolded insights, <=200 words each, no suggested actions. This is+the pattern Copilot for Power BI and Dynamics Customer Insights ship internally.++### Hard size limits++The prompt is stored in `adx_sitesetting.adx_value` (a Memo column). Older environments default+its `MaxLength` to **2000 characters** — that's the supported ceiling. Aim for **≤1000 characters**+in the deployed value (template + any inline few-shot examples combined). The validator in+`skills/add-ai-webapi/scripts/validate-ai-webapi.js` blocks the run when any+`Summarization-prompt-*.sitesetting.yml` exceeds 2000 chars and warns above 1000.++### Compact tabular-insight template (use as the default)++Include this template verbatim for any list-summary target unless the user requests a different+shape. It is intentionally tight (~480 chars) so the deployed prompt stays comfortably under the+1000-char target after one short few-shot example is appended:++```text+You are a customer service agent that summarizes tabular data.+Output exactly three insights, each at most 200 words. Highlight+key phrases in **double asterisks** (e.g., **key insight**).++Rules:+- Use only the data provided. No URLs, dates, or amounts outside+ the table; no internal knowledge.+- Skip GUID-only columns and columns that don't help analysis.+- Provide analytical insights only — no suggested actions, no+ preface, no apologies, no questions.+- Be specific; avoid vague or repeating sentences.+- If insights cannot be generated, do not explain why.+```++**Append at most one short few-shot example inline** (~250 chars). Use a **neutral, domain-generic**+example — sales by region, software purchases, fleet maintenance — **NOT** one that matches the+target schema. Domain-matched examples make the model copy example figures instead of grounding on+the user's data (verified failure mode). Skip the example entirely if the combined prompt would+exceed 1000 chars.++Example shape (~230 chars):++```text+Example (sales by region):+- **North America** drove **62% of revenue** at **$4.2M**, led by enterprise deals.+- **EMEA** margins improved to **34%** (up from 21%) on tighter discounting.+- **APAC** stayed flat at **$0.9M**; mid-market was the only growing segment.+```++Total deployed prompt: ~720 chars (template + 1 example), which leaves ~280 chars of headroom+under the 1000 target. **Never produce a prompt above 2000 characters** — the validator will+block the run, the Dataverse Memo column may reject the upload, and the runtime prompt may be+silently truncated.++When you present the plan in Step 5, flag this clearly: "List-summary prompts use a compact+tabular-insight template plus one short neutral few-shot example. Avoid domain-matched examples —+they cause the model to copy example figures instead of grounding on the user's data. Total+deployed prompt size: ~720 chars (≤1000 target, 2000 hard ceiling)."++## Workflow++1. **Verify Site Deployment** — Check that `.powerpages-site` folder exists+2. **Discover Existing AI Settings** — Read existing `Summarization/*` site settings+3. **Analyse Site Code for Summarization Calls** — Find which APIs and which prompts the code uses+4. **Cross-Check Web API Prerequisites** — Confirm every summarised table has `Webapi/<table>/enabled`+5. **Propose Plan via Plan Mode** — Present the site-settings proposal for approval+6. **Create Files** — Run `create-site-setting.js` for each approved setting++**Important:** Do NOT ask the user questions. Autonomously analyse the site code and existing site+settings, then present your findings via plan mode for the user to review and approve.++---++## Step 1: Verify Site Deployment++Use `Glob` to find:++- `**/powerpages.config.json` — Power Pages config (identifies the project root)+- `**/.powerpages-site` — Deployment folder++**If `.powerpages-site` does NOT exist:**++Stop and tell the user:++> "The `.powerpages-site` folder was not found. It is created when the site is first deployed to+> Power Pages. Deploy the site with `/deploy-site` before configuring AI summarization settings."++Do NOT proceed.++---++## Step 2: Discover Existing AI Settings++Read all Summarization-related and Web API-related site settings in `.powerpages-site/site-settings/`:++```text+**/.powerpages-site/site-settings/Summarization-*.sitesetting.yml+**/.powerpages-site/site-settings/Webapi-*.sitesetting.yml+```++Record three things:++1. Which `Summarization/*` settings already exist (by `name`) — these are **skipped** in the plan.+2. Which `Summarization/prompt/<identifier>` values are already registered — compare against the+ `InstructionIdentifier` values the code uses in Step 3.+3. Which `Webapi/<table>/enabled` settings already exist — this feeds Step 4.++---++## Step 3: Analyse Site Code for Summarization Calls++Search the source tree for summarization API usage and extract the identifiers:++### 3.1 Search Summary API++```+Grep: "/_api/search/v1\\.0/summary" in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++If found: the site uses search summary → add a note to the plan about the Copilot workspace toggle.+No per-call site setting is needed.++### 3.2 Data Summarization API++```+Grep: "/_api/summarization/data/v1\\.0/" in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++For each match, extract:++- **Entity set name** from the URL — `...summarization/data/v1.0/<entitySetName>(...`. Map the entity+ set to its table logical name (entity set is usually pluralised — `incidents` ↔ `incident`,+ `cr4fc_products` ↔ `cr4fc_product`).+- **URL form** — classify the call as one of:+ - `single-record`: URL matches `/_api/summarization/data/v1.0/<entitySet>(<id>)?`. Appears in+ detail pages that fetch one record.+ - `list`: URL matches `/_api/summarization/data/v1.0/<entitySet>?` with no `(<id>)` segment.+ Appears in list/history/overview pages that iterate a collection.++ Also infer from the calling function: `fetchDataSummary(entitySet, id, ...)` is single-record;+ `fetchListSummary(entitySet, ...)` is list. URL form drives two downstream defaults:+ (a) the prompt pattern (narrative vs tabular-insight — see "Prompt patterns" section above);+ (b) the `ContentSizeLimit` default (`100000` for single-record, `200000` for list).+- **Expanded tables** from `$expand=<NavProp>($select=...)` — these must also have Web API enabled.+ For the case-page preset the expand is `incident_adx_portalcomments` → `adx_portalcomment`.+- **InstructionIdentifier value** from the request body. Look for patterns like+ `"InstructionIdentifier": "Summarization/prompt/..."` and capture the full prompt name.++Compile a table of `{ table → [{ identifier, urlForm }] }` and a set of required expand tables.++### 3.3 Detect maker-defined prompt text and pick the right pattern++Prompt selection depends on the URL form captured in 3.2:++- **Single-record targets** — use a **narrative** prompt. If the code or docs comment the desired+ text (e.g. `// prompt: "Summarise order timeline, focus on shipments"`), capture it. Otherwise+ default to `Summarize key details and critical information` (the case preset's value).+- **List targets** — default to the **tabular-insight** template from the "Prompt patterns"+ section above, including 1–2 domain-neutral few-shot examples. Only override this default if+ the code comments an explicit alternative prompt. Tabular-insight is much longer than a+ narrative prompt and will trigger the 5.1a block-literal path.++---++## Step 4: Cross-Check Web API Prerequisites++**Skip this step entirely when the only summarisation calls in the site are to+`/_api/search/v1.0/summary`.** Search Summary has no per-table prereqs (no `Webapi/<table>/*`,+no table permissions tied to a specific Dataverse table) — its enablement lives in the+Copilot workspace toggle. If Step 3.1 found Search Summary calls AND Step 3.2 found **no**+Data Summarization calls, jump to Step 5; the prerequisite block below would over-block a+legitimate search-only run.++Otherwise, for every table that will be summarised via the data summarization API (primary+table **and** every `$expand` target), verify both `Webapi/<table>/enabled` and+`Webapi/<table>/fields` exist in `.powerpages-site/site-settings/`.++- **If the Web API site settings already exist**: include them in the plan as `✓ Prerequisite met`.+- **If the Web API site settings are missing**: include a blocker in the plan that asks the user+ to run `webapi-settings-architect` first. Do not proceed to create AI settings for that table+ until its Web API settings exist.++**Do not create `Webapi/*` settings yourself** — that's the dedicated `webapi-settings-architect`+agent's job.++### 4.1 Table permissions prerequisite++The target tables also need **table permissions with `read: true`** for at least one web role the+caller can hold. Look under `.powerpages-site/table-permissions/` for `.tablepermission.yml`+files. For each summarised table:++- Confirm at least one permission YAML has `tablename: <table_logical_name>` and `read: true`.+- For `$expand` targets (e.g. the case preset's `adx_portalcomment`), confirm a Parent-scope+ permission exists tied to the parent table's relationship (`incident_adx_portalcomments`).++If permissions are missing, include the same blocker pattern in the plan — recommend running+`table-permissions-architect` first. The AI endpoint returns 403 without this, and the error is+confusing because the generic 403 doesn't tell the caller *which* authorization layer failed.++### 4.2 Read-only audit (advisory, not a blocker)++Scan existing permissions and fields-list settings for the AI-only targets and flag anything+broader than a read-only posture requires:++- Table permissions with `create`, `write`, or `delete` flags set — unnecessary for AI-only+ targets; recommend narrowing in a follow-up.+- `Webapi/<table>/fields` values that include a primary key column (`<prefix>_<table>id`) — the+ AI endpoint doesn't need it since the record id is in the URL path. Harmless but broader than+ the shipped MS preset.+- `Webapi/<table>/fields` values that include lookup write forms (`cr4fc_categoryid`) without a+ corresponding read form (`_cr4fc_categoryid_value`) for a table that only gets read from — the+ write form isn't used by the AI endpoint.++Output these as plan-level notes so the user can tighten the posture later.++---++## Step 5: Propose Plan via Plan Mode++### 5.1 Prepare writes (script-or-manual routing)++For each new setting, decide which write path to prepare **before** drafting the plan:++1. **Script path (default)** — use `create-site-setting.js`. The script handles UUID generation,+ alphabetical field ordering, and `/` → `-` file naming.+2. **Manual-write path (block-literal YAML, see 5.1a)** — bypass the script and write the YAML+ file directly. Use this path whenever **any** of these is true for the setting's `value`:+ - length > 200 characters+ - contains any of: `: ` (colon+space), `|`, `` ` ``, `<|`, `> ` at line start, a colon+ followed by quotes, or a literal newline+ - the setting is a `Summarization/prompt/<identifier>` built from the tabular-insight+ template (always triggers the length rule, always includes `: ` and newlines)++For each setting, record `{ path: 'script' | 'manual', … }` and carry both shapes through to+Step 6 so the "Create Files" step knows which action to take.++**Master toggle:**++```bash+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Summarization/Data/Enable" --value "true" --description "Enable the Power Pages data summarization API" --type "boolean"+```++**Prompt setting (one per identifier):**++```bash+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Summarization/prompt/<identifier>" --value "<prompt text>" --description "<short description of what this prompt does>"+```++**Content-size override:**++```bash+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJECT_ROOT>" --name "Summarization/Data/ContentSizeLimit" --value "<integer>" --description "Override the default 100000-character summarization input cap"+```++Include this setting in the plan whenever:++- The plan includes **any list-summary target** — in that case `--value "200000"` is required,+ not optional. The site's existing settings folder must contain a+ `Summarization-Data-ContentSizeLimit.sitesetting.yml` with `value: 200000` (or higher) by the+ end of the architect run; otherwise the list-summary call will silently truncate to 100k chars+ and ship summaries based on partial data. Don't wait for the user to hit error `90041004` —+ that error fires on overflow but the truncation is silent on under-overflow.+- A single-record target whose selected content regularly exceeds 100k characters.++**Plan-mode display rule.** When listing site settings to the user, surface the+`ContentSizeLimit=200000` row with a "Required for list summaries" badge so the user can't+accidentally skip approving it. If they explicitly decline ("I'd rather start at 100k"), warn+that list summaries will silently truncate, and only proceed if they re-confirm.++`create-site-setting.js` only supports `--type boolean` and `--type string`. For+`Summarization/Data/ContentSizeLimit` (integer), pass the value as a string without `--type`+(strings are the default) — Power Pages parses the runtime value.++### 5.1a Long or complex prompts — write YAML block-literal manually++`create-site-setting.js` produces a plain-scalar YAML value (`value: <prompt text>`). That form+breaks `pac pages upload-code-site` parsing whenever the prompt contains:++- `: ` (colon+space) — YAML treats the prefix as a mapping key+- `|` or `` ` `` — YAML reserved / shell-safe concerns+- `<|` (used in Copilot `<|im_start|>` / `<|im_end|>` tokens)+- `> ` (folded-scalar indicator at line start)+- A colon followed by quotes (`: "..."`)+- A literal newline (few-shot examples, markdown tables)++When the upload silently accepts the file but the runtime rejects the value, subsequent+summarization calls fail with a 400 — the error surface is confusing because the YAML *parsed*,+it just didn't produce the string the maker wrote. The `case_summary` setting in the+Microsoft-shipped case preset has been re-uploaded once in this repo's history for exactly this+reason (colon-in-value).++**Default to YAML block-literal scalar form for any prompt > 200 characters, always.** Also use+it unconditionally when the prompt contains any of the trigger characters above.++For these settings, **bypass `create-site-setting.js`** and write the YAML file directly:++```yaml+description: <short description of what this prompt does>+id: <UUID you generate>+name: Summarization/prompt/<identifier>+value: |+ Instructions+ ## You are a customer service agent who helps users summarize key+ insights from tabular data:+ - ...+```++Key rules when writing by hand:++- Keep the four top-level keys alphabetically sorted (`description`, `id`, `name`, `value`) —+ matches the script's canonical ordering.+- Use `value: |` (literal block scalar, preserves newlines) followed by the prompt body+ indented 2 spaces relative to `value:`.+- File name: `Summarization-prompt-<identifier>.sitesetting.yml` under+ `.powerpages-site/site-settings/` (same convention the script uses).+- Generate the UUID with `node -e "console.log(require('crypto').randomUUID())"` before+ writing. Do not reuse a UUID from another setting.++For simple prompts (single-line, no trigger characters, under ~200 chars) the script path+still works fine; reserve the manual path for the complex cases above.++### 5.2 Plan content++Enter plan mode with:++- **Rationale** — One sentence per setting explaining why it's needed and which code path triggers it.+- **Summary table**:++ | Setting | Value | Status |+ |---------|-------|--------|+ | `Summarization/Data/Enable` | `true` | New |+ | `Summarization/prompt/case_summary` | `Summarize key details and critical information` | New |+ | `Webapi/incident/enabled` | `true` | ✓ Already exists (prerequisite) |+ | `Webapi/adx_portalcomment/enabled` | `true` | ✗ Missing — run `/integrate-webapi` or `webapi-settings-architect` first |++- **Prompt usage map** — For each `Summarization/prompt/<identifier>`, list the source files that+ send it as `InstructionIdentifier`.+- **Expand prerequisites** — For every `$expand` target, confirm its Web API settings status.+- **Search Summary note** (if applicable):++ > The site calls `/_api/search/v1.0/summary`. Search summary has no per-call site setting, but it+ > requires **"Enable Site search with generative AI (preview)"** to be switched on in the site's+ > **Set up workspace → Copilot → Site search**. Confirm it's turned on after deployment.++- **Exact write actions** — from 5.1, grouped by path:+ - **Script invocations** (settings on the script path): list each `create-site-setting.js`+ command exactly as it will be run.+ - **Manual writes** (settings on the block-literal path): list each as `<file path> — block+ literal YAML, UUID to generate at write time, <N> lines`.++ Call out which settings take the manual path and why (e.g., "tabular-insight prompt, 1.8 KB —+ colons + newlines trigger block-literal").++Use `EnterPlanMode` to present the complete proposal, then `ExitPlanMode` for user review and+approval.++---++## Step 6: Create Files & Return Summary++After the user approves, execute each prepared write — both paths produce the same return shape+so the caller doesn't have to care which path was used.++**Script path** — run each `create-site-setting.js` invocation via `Bash`. Capture the JSON+output (`{ "id": "...", "filePath": "..." }`) printed to stdout.++**Manual-write path** — for each setting on this path:++1. Generate a UUID: `node -e "console.log(require('crypto').randomUUID())"`.+2. Build the YAML content with keys in alphabetical order (`description`, `id`, `name`, `value`)+ and `value: |` followed by the prompt body indented 2 spaces.+3. Compute the file name: replace `/` with `-` in the setting name, append+ `.sitesetting.yml` (mirror the script's convention — e.g.+ `Summarization-prompt-cr363_workorders_instruction_identifier_overview.sitesetting.yml`).+4. Write to `.powerpages-site/site-settings/<filename>` using the `Write` tool.+5. Record `{ id: <generated UUID>, filePath: <absolute path> }` — same shape the script+ prints — so the return to the caller is uniform.++Return to the calling context:++1. **Settings created** — list of `{ name, id, filePath, writePath: 'script' | 'manual' }`.+ Include `writePath` so the orchestrator skill can surface in the final summary when a+ block-literal file was written (useful for debugging if `pac pages upload-code-site` rejects+ it later).+2. **Settings skipped** — settings that already existed (with their existing UUIDs).+3. **Prerequisites still missing** — any `Webapi/<table>/enabled` or `fields` settings that the+ user still needs to create before the AI settings will work end-to-end.+4. **Post-deploy reminder** — if search summary is used, remind the user to toggle+ **Site search with generative AI (preview)** on in the Copilot workspace.++---++## Critical Constraints++- **Prefer `create-site-setting.js`**: always use the script for simple prompts. The script+ handles field ordering, UUID generation, and file naming. Only bypass it for long/complex+ prompts that require YAML block-literal scalars (see Step 5.1a) — in that case write the+ file by hand with the four keys in alphabetical order and a generated UUID.+- **Never rename `Summarization/prompt/case_summary`**: the case-page Copilot preset ships with+ exactly that name — keeping it as-is lets the Microsoft-shipped incident page Liquid/JS snippets+ work without modification.+- **Never create `Webapi/<table>/enabled` or `Webapi/<table>/fields` yourself** — delegate to+ `webapi-settings-architect`.+- **No questions**: autonomously analyse the site and existing settings, then present via plan mode.+- **Security**: the prompt text is authored by the maker. Do not invent prompts that would exfiltrate+ PII or override user-role scoping — the summarization API already respects row-level security, but+ the prompt itself can influence output.diff --git a/plugins/power-pages/agents/table-permissions-architect.md b/plugins/power-pages/agents/table-permissions-architect.mdindex 8c708b5a4..3e238370d 100644--- a/plugins/power-pages/agents/table-permissions-architect.md+++ b/plugins/power-pages/agents/table-permissions-architect.md@@ -518,3 +518,15 @@ After creating all files, return a summary to the calling context:- **No questions**: Do NOT use `AskUserQuestion`. Autonomously analyze the site and environment, then present your findings via plan mode.- **Security**: Never log or display the full auth token. Use it only in API request headers.- **Parent before child**: Always create parent table permissions before child permissions that reference them.++## AI-only read mode++When the invoking skill's prompt signals **AI-only read mode** (e.g. `/add-ai-webapi` delegating through `/integrate-webapi`), the permissions proposal hardens to a strict read-only posture for every table in scope:++- **`read: true` only.** Do NOT propose `create`, `write`, or `delete` — the Power Pages AI summarization endpoints are semantically reads (POST carries a body but never mutates), so broader CRUD flags grant unused surface. This overrides the default CRUD convention, including for publisher-prefixed tables where the default is usually full CRUD.+- **Collection-valued `$expand` targets use Parent scope with `read: true`** via the specific relationship the primary's code `$expand`s on (e.g. `incident_adx_portalcomments` for the case preset). The parent permission still needs `appendTo: true` so the AI endpoint can traverse the navigation property.+- **Skip Administrators entirely** — same default as normal mode.+- **Web roles**: if no role matches the site's auth model, surface the gap back to the caller rather than creating one yourself. The upstream skill (`/add-ai-webapi`) invokes `/create-webroles` before calling `/integrate-webapi`; duplicate role creation here would conflict.+- **Scope selection rules still apply**: Global for shared records, Contact/Account/Self where records are owner-scoped, Parent for child collections behind a parent record. The AI-only posture does not change scope selection — only the CRUD-flag posture and the "no roles created here" rule.++The forcing function is the invoking skill's prompt. This section documents the contract so reviewers can verify it without reading downstream skill files.diff --git a/plugins/power-pages/agents/webapi-settings-architect.md b/plugins/power-pages/agents/webapi-settings-architect.mdindex 76ef34bae..6eea43abf 100644--- a/plugins/power-pages/agents/webapi-settings-architect.md+++ b/plugins/power-pages/agents/webapi-settings-architect.md@@ -427,3 +427,15 @@ After creating all files, return a summary to the calling context:- **Dataverse is the authority**: Column names from code, type definitions, or manifests are NOT authoritative. Only the `LogicalName` returned by the Dataverse `EntityDefinitions/Attributes` API is authoritative. If Dataverse is unavailable, warn prominently that column names are unvalidated.- **No questions**: Do NOT use `AskUserQuestion`. Autonomously analyze the site and environment, then present your findings via plan mode.- **Security**: Never log or display the full auth token. Use it only in API request headers.++## AI-only read mode++When the invoking skill's prompt signals **AI-only read mode** (e.g. `/add-ai-webapi` delegating through `/integrate-webapi`), the fields-list rules tighten for every table in scope:++- **Fields list = exactly the primary's `$select` / `$expand` columns.** No more, no less. Extra columns expand the allowlist without any caller using them.+- **Omit the primary key column.** The Power Pages summarization endpoint carries the record id in the URL path, not in `$select`. Microsoft's shipped case preset ships `Webapi/incident/fields = description,title` with no `incidentid` — match that pattern.+- **Lookup columns use the `_<col>_value` OData read form only.** Do NOT include the LogicalName write form (`<col>`) unless the same table has non-AI mutation code elsewhere in the site. In pure AI-only targets there are no writes, so the write form adds attackable surface without any reader.+- **Case-sensitivity and Dataverse-as-authority rules still apply** — all the above LogicalNames must still be the exact lowercase forms returned by the Dataverse metadata API.+- **File/Image and aggregate exceptions still apply** — if the summarised table also has File/Image columns or aggregate OData elsewhere, `*` still wins.++The forcing function is the invoking skill's prompt. This section documents the contract so reviewers can verify it without reading downstream skill files.diff --git a/plugins/power-pages/references/skill-tracking-reference.md b/plugins/power-pages/references/skill-tracking-reference.mdindex 38750967e..264305091 100644--- a/plugins/power-pages/references/skill-tracking-reference.md+++ b/plugins/power-pages/references/skill-tracking-reference.md@@ -40,6 +40,7 @@ If the tracking script creates or updates site setting YAML files, include those| plan-alm | PlanAlm | Site/AI/Skills/PlanAlm || add-server-logic | AddServerLogic | Site/AI/Skills/AddServerLogic || add-cloud-flow | AddCloudFlow | Site/AI/Skills/AddCloudFlow |+| add-ai-webapi | AddAiWebapi | Site/AI/Skills/AddAiWebapi || integrate-backend | IntegrateBackend | Site/AI/Skills/IntegrateBackend || scan-site | ScanSite | Site/AI/Skills/ScanSite || manage-headers | ManageHeaders | Site/AI/Skills/ManageHeaders |diff --git a/plugins/power-pages/scripts/tests/integrate-webapi-ai-only-mode.test.js b/plugins/power-pages/scripts/tests/integrate-webapi-ai-only-mode.test.jsnew file mode 100644index 000000000..36a39707f--- /dev/null+++ b/plugins/power-pages/scripts/tests/integrate-webapi-ai-only-mode.test.js@@ -0,0 +1,157 @@+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const path = require('path');++// The AI-only read mode is implemented as conditional branches inside the+// integrate-webapi SKILL.md markdown (the skill has no runnable parser —+// Claude reads the SKILL.md and follows its instructions). These tests guard+// against accidental removal of the AI-only branches, which would silently+// break /add-ai-webapi's delegation contract.++const SKILL_PATH = path.join(+ __dirname,+ '..',+ '..',+ 'skills',+ 'integrate-webapi',+ 'SKILL.md'+);++const skill = fs.readFileSync(SKILL_PATH, 'utf8');++test('integrate-webapi declares the AI-only read mode core principle', () => {+ assert.match(skill, /AI-only read mode is opt-in/);+ assert.match(skill, /\[AI-READ-ONLY\]/);+});++test('Phase 1.6 documents the sentinel parser contract', () => {+ assert.match(skill, /### 1\.6 Detect AI-only read mode/);+ assert.match(skill, /`mode=ai-read-only`/);+ assert.match(skill, /`primary=<logical_name>`/);+ assert.match(skill, /`tables=<csv>`/);+ assert.match(skill, /`expand-targets=<csv>`/);+});++test('Phase 1.6 documents the regression guard for human invocations', () => {+ const p16 = skill.substring(skill.indexOf('### 1.6'), skill.indexOf('## Phase 2'));+ assert.match(+ p16,+ /When the sentinel is absent.*proceed exactly as today/s,+ 'Phase 1.6 must document that human invocations see no behavior change'+ );+});++test('Phase 2 Explore prompt branches for AI-only mode', () => {+ const p2 = skill.substring(skill.indexOf('## Phase 2'), skill.indexOf('## Phase 3'));+ assert.match(p2, /When AI-only read mode is active/);+ assert.match(p2, /Operations needed for every table in that list = \*\*read only\*\*/);+ assert.match(+ p2,+ /Do NOT report create\/update\/delete/,+ 'AI-only Phase 2 must forbid reporting mutation candidates'+ );+});++test('Phase 3 skips interactive confirmation in AI-only mode', () => {+ const p3Start = skill.indexOf('## Phase 3: Review Integration Plan');+ const p3End = skill.indexOf('## Phase 4: Implement Integrations');+ const p3 = skill.substring(p3Start, p3End);+ assert.match(p3, /skip this step entirely/);+ assert.match(p3, /`tables` list parsed from the sentinel verbatim/);+});++test('Phase 4.1 webapi-integration prompt branches for AI-only mode', () => {+ const p4Start = skill.indexOf('## Phase 4: Implement Integrations');+ const p4End = skill.indexOf('## Phase 5: Verify Integrations');+ const p4 = skill.substring(p4Start, p4End);+ assert.match(p4, /Operations needed: read-only/);+ assert.match(p4, /Do NOT emit create, update, or delete functions/);+ assert.match(p4, /`list<Table>` \(paginated\) and `get<Table>ById`/);+ assert.match(+ p4,+ /no mutation hooks/,+ 'AI-only hook language must explicitly exclude mutation hooks'+ );+});++test('Phase 6 table-permissions-architect prompt branches for AI-only mode', () => {+ const p6Start = skill.indexOf('## Phase 6: Setup Permissions & Settings');+ const p6End = skill.indexOf('## Phase 7: Review & Deploy');+ const p6 = skill.substring(p6Start, p6End);+ const tpStart = p6.indexOf('#### Table Permissions Agent');+ const tpEnd = p6.indexOf('#### Web API Settings Agent');+ const tpSection = p6.substring(tpStart, tpEnd);+ assert.match(tpSection, /AI-only read integration/);+ assert.match(tpSection, /`read: true` \*\*only\*\*/);+ assert.match(tpSection, /Do NOT propose `create`, `write`, or `delete`/);+ assert.match(tpSection, /Parent scope.*`appendTo: true`/s);+});++test('Phase 6 webapi-settings-architect prompt branches for AI-only mode', () => {+ const p6Start = skill.indexOf('## Phase 6: Setup Permissions & Settings');+ const p6End = skill.indexOf('## Phase 7: Review & Deploy');+ const p6 = skill.substring(p6Start, p6End);+ const wsStart = p6.indexOf('#### Web API Settings Agent');+ const wsEnd = p6.indexOf('### 6.4 Create Permission & Settings Files');+ const wsSection = p6.substring(wsStart, wsEnd);+ assert.match(wsSection, /AI-only read integration/);+ assert.match(wsSection, /Do \*\*not\*\* include the primary key column/);+ assert.match(wsSection, /`_<col>_value` OData read form/);+ assert.match(wsSection, /Do NOT add the write form/);+});++test('Phase 6.4.2 Path A defaults table permissions to read-only in AI mode', () => {+ const section = skill.substring(+ skill.indexOf('#### 6.4.2 Create Table Permissions'),+ skill.indexOf('#### 6.4.3 Create Site Settings')+ );+ assert.match(section, /When AI-only read mode is active/);+ assert.match(section, /the default flag set is `--read` only/);+ assert.match(section, /Do NOT pass `--create`, `--write`, or `--delete`/);+});++test('Phase 6.4.3 Path A tightens fields rules in AI mode', () => {+ const section = skill.substring(+ skill.indexOf('#### 6.4.3 Create Site Settings'),+ skill.indexOf('### 6.5 Git Commit')+ );+ assert.match(section, /AI-only read mode/);+ assert.match(section, /Do NOT include the primary key/);+ assert.match(section, /only the `_<col>_value` read form/);+ assert.match(section, /Omit the LogicalName write form/);+});++test('backward compatibility: default CRUD prompts are still present unchanged', () => {+ // These strings are the pre-existing human-invocation prompts. They must+ // survive the AI-only mode additions — removing them would break normal+ // /integrate-webapi usage.+ assert.match(+ skill,+ /Operations needed: \[read\/create\/update\/delete\]/,+ 'Default Phase 4.1 prompt template must still offer full CRUD'+ );+ assert.match(+ skill,+ /Create the TypeScript types, CRUD service layer, and framework-specific hooks\/composables/,+ 'Default Phase 4.1 prompt must still request full CRUD code'+ );+ assert.match(+ skill,+ /Prompt \(default — full CRUD\):/,+ 'Phase 6 prompts must be explicitly split into default vs. AI-only variants'+ );+});++test('architect agent prompts preserve default CRUD text when AI mode is absent', () => {+ const p6 = skill.substring(skill.indexOf('## Phase 6'), skill.indexOf('## Phase 7'));+ const tpDefault = p6.substring(+ p6.indexOf('Table Permissions Agent'),+ p6.indexOf('**Prompt (AI-only read mode active)')+ );+ assert.match(+ tpDefault,+ /Propose a complete table permissions plan covering all integrated tables/,+ 'Default table-permissions prompt must still describe full-coverage CRUD flow'+ );+});diff --git a/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js b/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.jsindex 57caade55..65718dde3 100644--- a/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js+++ b/plugins/power-pages/scripts/tests/powerpages-hook-utils.test.js@@ -24,6 +24,7 @@ test('detectTrackedSkill recognizes slash command aliases without plugin prefix'assert.equal(detectTrackedSkill('/setup-auth'), 'setup-auth');assert.equal(detectTrackedSkill('/add-server-logic'), 'add-server-logic');assert.equal(detectTrackedSkill('/add-cloud-flow'), 'add-cloud-flow');+ assert.equal(detectTrackedSkill('/add-ai-webapi'), 'add-ai-webapi');assert.equal(detectTrackedSkill('/integrate-webapi'), 'integrate-webapi');assert.equal(detectTrackedSkill('/audit-permissions'), 'audit-permissions');assert.equal(detectTrackedSkill('/deploy-site'), 'deploy-site');@@ -47,6 +48,7 @@ test('getValidatorScript returns discovered validator paths when present', () =>assert.match(getValidatorScript('create-site'), /validate-site\.js$/);assert.match(getValidatorScript('add-server-logic'), /validate-serverlogic\.js$/);assert.match(getValidatorScript('deploy-pipeline'), /validate-deploy-pipeline\.js$/);+ assert.match(getValidatorScript('add-ai-webapi'), /validate-ai-webapi\.js$/);});test('getValidatorScript returns null for tracked skills without validators', () => {diff --git a/plugins/power-pages/scripts/tests/validate-ai-webapi.test.js b/plugins/power-pages/scripts/tests/validate-ai-webapi.test.jsnew file mode 100644index 000000000..7840b8d65--- /dev/null+++ b/plugins/power-pages/scripts/tests/validate-ai-webapi.test.js@@ -0,0 +1,617 @@+const test = require('node:test');+const assert = require('node:assert/strict');+const { spawnSync } = require('child_process');+const path = require('path');++const { createTempProject, writeProjectFile } = require('./test-utils');++const VALIDATOR_PATH = path.join(+ __dirname,+ '..',+ '..',+ 'skills',+ 'add-ai-webapi',+ 'scripts',+ 'validate-ai-webapi.js'+);++function runValidator(projectRoot) {+ return spawnSync(process.execPath, [VALIDATOR_PATH], {+ input: JSON.stringify({ cwd: projectRoot }),+ encoding: 'utf8',+ });+}++const VALID_SEARCH_SERVICE = `+export async function fetchSearchSummary(userQuery) {+ const token = await getCsrfToken();+ const response = await fetch('/_api/search/v1.0/summary', {+ method: 'POST',+ headers: {+ 'Accept': 'application/json',+ 'Content-Type': 'application/x-www-form-urlencoded',+ '__RequestVerificationToken': token,+ 'X-Requested-With': 'XMLHttpRequest',+ },+ body: new URLSearchParams({ userQuery }).toString(),+ });+ return response.json();+}+`;++const VALID_DATA_SERVICE = `+export async function fetchCaseSummary(caseId) {+ const token = await getCsrfToken();+ const url = '/_api/summarization/data/v1.0/incidents(' + caseId + ')?$select=description,title&$expand=incident_adx_portalcomments($select=description)';+ const response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json; charset=utf-8',+ '__RequestVerificationToken': token,+ 'X-Requested-With': 'XMLHttpRequest',+ 'OData-MaxVersion': '4.0',+ 'OData-Version': '4.0',+ },+ body: JSON.stringify({ InstructionIdentifier: 'Summarization/prompt/case_summary' }),+ });+ return response.json();+}+`;++test('approves when no AI summarization calls exist', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/index.ts', 'export const noop = () => {};');++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+});++test('approves when src directory is missing', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+});++test('valid search summary service passes validation', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_SEARCH_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+});++test('valid data summarization service passes validation', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+});++test('missing __RequestVerificationToken is flagged', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(+ projectRoot,+ 'src/services/aiSummaryService.ts',+ VALID_SEARCH_SERVICE.replace("'__RequestVerificationToken': token,", '')+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /missing the __RequestVerificationToken header/);+});++test('missing X-Requested-With is warned but not blocked', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(+ projectRoot,+ 'src/services/aiSummaryService.ts',+ VALID_SEARCH_SERVICE.replace("'X-Requested-With': 'XMLHttpRequest',", '')+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stderr, /X-Requested-With/);+});++test('data summarization without $select is flagged', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(+ projectRoot,+ 'src/services/aiSummaryService.ts',+ VALID_DATA_SERVICE.replace(/\?\$select=[^']+/, '')+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /missing \$select/);+});++test('header tokens are checked project-wide, not per-file (shared-helper pattern)', (t) => {+ // A correct integration commonly centralizes header construction in a shared helper while the+ // fetch call lives in a service file. The header/$select/OData checks are project-wide: a token+ // present anywhere under src/ satisfies the check, so this must NOT block (no false failure).+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(+ projectRoot,+ 'src/services/case.ts',+ VALID_DATA_SERVICE+ .replace("'__RequestVerificationToken': token,", '')+ .replace("'OData-MaxVersion': '4.0',", '')+ .replace("'OData-Version': '4.0',", '')+ );+ writeProjectFile(+ projectRoot,+ 'src/shared/powerPagesApi.ts',+ `export const summarizationHeaders = {+ '__RequestVerificationToken': token,+ 'OData-MaxVersion': '4.0',+ 'OData-Version': '4.0',+ };`+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+});++test('a required header missing from every source file still blocks project-wide', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/search.ts', VALID_SEARCH_SERVICE);+ writeProjectFile(+ projectRoot,+ 'src/services/case.ts',+ VALID_DATA_SERVICE.replace("'__RequestVerificationToken': token,", '')+ );+ // search.ts still declares the token, so project-wide the integration is fine.+ const present = runValidator(projectRoot);+ assert.equal(present.status, 0, present.stderr);++ // Remove it from search.ts too — now absent everywhere, so it must block.+ writeProjectFile(+ projectRoot,+ 'src/services/search.ts',+ VALID_SEARCH_SERVICE.replace("'__RequestVerificationToken': token,", '')+ );+ const absent = runValidator(projectRoot);+ assert.equal(absent.status, 2);+ assert.match(absent.stderr, /missing the __RequestVerificationToken header/);+});++test('Search Summary without parseSummaryWithCitations is warned but not blocked', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_SEARCH_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stderr, /parseSummaryWithCitations/);+});++test('Search Summary with parseSummaryWithCitations does not warn about parsing', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_SEARCH_SERVICE);+ writeProjectFile(+ projectRoot,+ 'src/components/SummaryWithCitations.tsx',+ "import { parseSummaryWithCitations } from '../services/aiSummaryService';\nexport function SummaryWithCitations() { return parseSummaryWithCitations(''); }"+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /parseSummaryWithCitations/);+});++test('Search Summary with literal [[N]](url) handling does not warn about parsing', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_SEARCH_SERVICE);+ writeProjectFile(+ projectRoot,+ 'src/components/Inline.tsx',+ "// Hand-rolled parser handling [[1]](https://example.com/foo)\nexport const re = /\\[\\[(\\d+)\\]\\]\\(([^)]+)\\)/g;"+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /parseSummaryWithCitations/);+});++test('Search Summary without extractKnowledgeArticleId is warned but not blocked', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_SEARCH_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stderr, /extractKnowledgeArticleId/);+});++test('Search Summary with extractKnowledgeArticleId does not warn about KB rewrite', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_SEARCH_SERVICE);+ writeProjectFile(+ projectRoot,+ 'src/components/CitationLink.tsx',+ "import { extractKnowledgeArticleId } from '../services/aiSummaryService';\nexport function rewrite(url) { return extractKnowledgeArticleId(url); }"+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /extractKnowledgeArticleId/);+});++test('Search Summary with inline ?id= parsing does not warn about KB rewrite', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_SEARCH_SERVICE);+ writeProjectFile(+ projectRoot,+ 'src/components/CitationLink.tsx',+ "export function rewrite(url) { const u = new URL(url); return u.searchParams.get('id'); }"+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /extractKnowledgeArticleId/);+});++test('Data-only project does not trigger Search Summary warnings', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /parseSummaryWithCitations/);+ assert.doesNotMatch(result.stderr, /extractKnowledgeArticleId/);+});++const VALID_LIST_SERVICE = `+export async function fetchListSummary(entitySet, options) {+ const token = await getCsrfToken();+ const url = '/_api/summarization/data/v1.0/' + entitySet + '?$select=' + options.select;+ const response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json; charset=utf-8',+ '__RequestVerificationToken': token,+ 'X-Requested-With': 'XMLHttpRequest',+ 'OData-MaxVersion': '4.0',+ 'OData-Version': '4.0',+ },+ body: JSON.stringify({ InstructionIdentifier: options.instructionIdentifier }),+ });+ return response.json();+}+`;++test('list summary without ContentSizeLimit setting warns', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_LIST_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stderr, /Summarization-Data-ContentSizeLimit\.sitesetting\.yml is missing/);+});++test('list summary with ContentSizeLimit below 200000 warns', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_LIST_SERVICE);+ writeProjectFile(+ projectRoot,+ '.powerpages-site/site-settings/Summarization-Data-ContentSizeLimit.sitesetting.yml',+ "id: 11111111-1111-4111-8111-111111111111\nname: Summarization/Data/ContentSizeLimit\nvalue: '150000'\n"+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stderr, /ContentSizeLimit is 150000.*at least 200000/);+});++test('list summary with ContentSizeLimit at 200000 does not warn', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_LIST_SERVICE);+ writeProjectFile(+ projectRoot,+ '.powerpages-site/site-settings/Summarization-Data-ContentSizeLimit.sitesetting.yml',+ "id: 11111111-1111-4111-8111-111111111111\nname: Summarization/Data/ContentSizeLimit\nvalue: '200000'\n"+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /ContentSizeLimit/);+});++test('single-record-only project does not check ContentSizeLimit', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /ContentSizeLimit/);+});++function promptSettingYaml(promptText) {+ const escaped = promptText.replace(/\n/g, '\n ');+ return [+ 'id: 22222222-2222-4222-8222-222222222222',+ 'name: Summarization/prompt/case_summary',+ 'value: |',+ ' ' + escaped,+ '',+ ].join('\n');+}++test('prompt under 1000 chars is approved with no warning', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);+ writeProjectFile(+ projectRoot,+ '.powerpages-site/site-settings/Summarization-prompt-case_summary.sitesetting.yml',+ promptSettingYaml('Summarize key details and critical information')+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /Summarization-prompt/);+});++test('prompt between 1000 and 2000 chars warns', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);+ const longPrompt = 'A'.repeat(1500);+ writeProjectFile(+ projectRoot,+ '.powerpages-site/site-settings/Summarization-prompt-long_one.sitesetting.yml',+ promptSettingYaml(longPrompt)+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stderr, /Summarization-prompt-long_one\.sitesetting\.yml: prompt value is 1500 characters; aim for ≤1000/);+});++test('prompt over 2000 chars blocks the run', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);+ const tooLong = 'B'.repeat(2500);+ writeProjectFile(+ projectRoot,+ '.powerpages-site/site-settings/Summarization-prompt-too_big.sitesetting.yml',+ promptSettingYaml(tooLong)+ );++ const result = runValidator(projectRoot);+ assert.notEqual(result.status, 0);+ assert.match(result.stderr, /Summarization-prompt-too_big\.sitesetting\.yml: prompt value is 2500 characters, exceeding the supported maximum of 2000/);+});++test('plain-scalar prompt YAML is parsed and measured correctly', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);+ writeProjectFile(+ projectRoot,+ '.powerpages-site/site-settings/Summarization-prompt-short.sitesetting.yml',+ "id: 33333333-3333-4333-8333-333333333333\nname: Summarization/prompt/short\nvalue: Summarize this record briefly\n"+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /Summarization-prompt/);+});++test('project with no Summarization/prompt settings does not warn', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /Summarization-prompt/);+});++// --- OData 4.0 header checks (data summarization) ---++test('data summarization missing OData-MaxVersion header is blocked', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(+ projectRoot,+ 'src/services/aiSummaryService.ts',+ VALID_DATA_SERVICE.replace("'OData-MaxVersion': '4.0',", '')+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /missing the OData-MaxVersion: 4\.0 header/);+});++test('data summarization missing OData-Version header is blocked', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(+ projectRoot,+ 'src/services/aiSummaryService.ts',+ VALID_DATA_SERVICE.replace("'OData-Version': '4.0',", '')+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /missing the OData-Version: 4\.0 header/);+});++test('search-only project does not require OData headers', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_SEARCH_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /OData-/);+});++// --- Search Summary content-type check ---++test('Search Summary with application/json instead of urlencoded is blocked', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(+ projectRoot,+ 'src/services/aiSummaryService.ts',+ VALID_SEARCH_SERVICE.replace(+ "'Content-Type': 'application/x-www-form-urlencoded',",+ "'Content-Type': 'application/json',"+ )+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /missing Content-Type: application\/x-www-form-urlencoded/);+});++// --- Disabled-state envelope advisory ---++test('Search Summary without SearchSummaryApiError is warned but not blocked', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_SEARCH_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stderr, /SearchSummaryApiError/);+});++test('Search Summary with SearchSummaryApiError export does not warn about envelope', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(+ projectRoot,+ 'src/services/aiSummaryService.ts',+ VALID_SEARCH_SERVICE ++ '\nexport class SearchSummaryApiError extends Error {}\nexport function isGenAiSearchDisabled() { return false; }\n'+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /SearchSummaryApiError/);+});++test('Search Summary with inline body.Code === pattern does not warn about envelope', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_SEARCH_SERVICE);+ writeProjectFile(+ projectRoot,+ 'src/components/SearchSummaryCard.tsx',+ "export function detect(body) { return body.Code === 400 && body.Message !== ''; }"+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /SearchSummaryApiError/);+});++test('Data-only project does not warn about disabled-state envelope', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /SearchSummaryApiError/);+});++// --- Plain-scalar long prompt advisory ---++test('plain-scalar prompt over 200 chars warns about block-literal', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);+ const longPrompt = 'X'.repeat(300);+ writeProjectFile(+ projectRoot,+ '.powerpages-site/site-settings/Summarization-prompt-plain_long.sitesetting.yml',+ `id: 44444444-4444-4444-8444-444444444444\nname: Summarization/prompt/plain_long\nvalue: ${longPrompt}\n`+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stderr, /Summarization-prompt-plain_long\.sitesetting\.yml: prompt value is 300 characters and uses plain-scalar YAML/);+});++test('block-literal prompt over 200 chars does not warn about plain-scalar', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);+ writeProjectFile(+ projectRoot,+ '.powerpages-site/site-settings/Summarization-prompt-block_long.sitesetting.yml',+ promptSettingYaml('Y'.repeat(300))+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /uses plain-scalar YAML/);+});++test('plain-scalar prompt under 200 chars does not warn about plain-scalar', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);+ writeProjectFile(+ projectRoot,+ '.powerpages-site/site-settings/Summarization-prompt-short_plain.sitesetting.yml',+ "id: 55555555-5555-4555-8555-555555555555\nname: Summarization/prompt/short_plain\nvalue: Summarize key details and critical information\n"+ );++ const result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+ assert.doesNotMatch(result.stderr, /uses plain-scalar YAML/);+});++// --- Folded scalar (`>`) parsing ---++test('folded-scalar prompt is parsed and size-checked', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'src/services/aiSummaryService.ts', VALID_DATA_SERVICE);+ // Build a folded-scalar YAML file by hand. Folded scalars use `>`; the validator+ // should pick up the indented body (size-check it) instead of treating it as null.+ const longBody = 'Z'.repeat(2200);+ const yaml = [+ 'id: 66666666-6666-4666-8666-666666666666',+ 'name: Summarization/prompt/folded_one',+ 'value: >',+ ' ' + longBody,+ '',+ ].join('\n');+ writeProjectFile(+ projectRoot,+ '.powerpages-site/site-settings/Summarization-prompt-folded_one.sitesetting.yml',+ yaml+ );++ const result = runValidator(projectRoot);+ assert.notEqual(result.status, 0);+ assert.match(result.stderr, /Summarization-prompt-folded_one\.sitesetting\.yml: prompt value is \d+ characters, exceeding the supported maximum of 2000/);+});diff --git a/plugins/power-pages/skills/add-ai-webapi/SKILL.md b/plugins/power-pages/skills/add-ai-webapi/SKILL.mdnew file mode 100644index 000000000..858319ff3--- /dev/null+++ b/plugins/power-pages/skills/add-ai-webapi/SKILL.md@@ -0,0 +1,860 @@+---+name: add-ai-webapi+description: >-+ Integrates Power Pages generative-AI summarization APIs (PREVIEW) into a Single Page Application+ (SPA) site — the Search Summary API and the Data Summarization API — on any record-detail or list+ page. Generates per-target service code (CSRF-handled) and AI site settings; delegates Web API+ settings, table permissions, and web roles to `/integrate-webapi` and `/create-webroles`. Use+ whenever a user wants AI/Copilot output that condenses Dataverse content on a Power Pages site —+ an AI summary, AI-generated overview or "key insights" across a record or list, a search-results+ summary, a case/incident summary, or recommendation-chip refinement — even when phrased as+ "AI-generated paragraph", "insights", or "overview". Do NOT use for: generative pages in+ model-driven apps (use the model-apps `genpage` skill), Copilot Studio agents/chatbots,+ summarizing documents or PDFs, Power BI dashboards, plain keyword search with no AI summary, or+ plain Dataverse CRUD (use `/integrate-webapi`).+user-invocable: true+argument-hint: Optional description of which pages/tables need AI capabilities+allowed-tools: Read, Write, Edit, Bash, Grep, Glob, AskUserQuestion, Skill, Task, TaskCreate, TaskUpdate, TaskList, mcp__plugin_power-pages_microsoft-learn__microsoft_docs_search, mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch+model: opus+---++> **Plugin check**: Run `node "${CLAUDE_PLUGIN_ROOT}/scripts/check-version.js"` — if it outputs a message, show it to the user before proceeding.++# Add AI Web API++> **Note**+>+> AI summarization APIs are a preview feature. Preview features aren't meant for production use and may have restricted functionality. These features are available before an official release so that customers can get early access and provide feedback.++**Surface this note to the user verbatim** during Phase 1 and again in the Phase 8 summary —+copy the exact `**Note**` block above (including its wording about "available before an official+release so that customers can get early access and provide feedback"). Do not paraphrase it into+your own "Preview-feature note: ..." sentence; the wording matches the Microsoft Learn preview+disclaimer and rephrasing it loses that fidelity.++Integrate Power Pages generative-AI summarization APIs into a SPA site. This skill focuses on the AI layer (Layer 3): the summarization service code and the `Summarization/*` site settings. The underlying Web API prerequisites — `Webapi/<table>/enabled`, `Webapi/<table>/fields`, table permissions, and web roles — are **delegated** to `/integrate-webapi` and `/create-webroles` so there is a single source of truth for every layer.++## The two APIs covered++| # | API | URL | Body | Response |+|---|-----|-----|------|----------|+| 1 | **Search Summary** | `POST /_api/search/v1.0/summary` | `{ userQuery }` | `{ Summary, Citations }` |+| 2 | **Data Summarization** | `POST /_api/summarization/data/v1.0/<entitySet>(<id>)?$select=...&$expand=...` | `{ InstructionIdentifier }` or `{ RecommendationConfig }` | `{ Summary, Recommendations }` |++> **Example: Microsoft-shipped Copilot summary on a support-case page.** Data Summarization can be+> called with any combination of entity set, columns, and prompt — but Microsoft documents and+> ships one specific configuration for the standard `incident` table:+> `POST /_api/summarization/data/v1.0/incidents(<caseId>)?$select=description,title&$expand=incident_adx_portalcomments($select=description)`+> with body `{ "InstructionIdentifier": "Summarization/prompt/case_summary" }`. This is sometimes+> called the "Case-page Copilot preset" in Microsoft Learn. Treat it as one possible Data+> Summarization recipe — useful when the user explicitly wants to mirror the Microsoft sample —+> not as an automatic recommendation. A custom case-like table (`cr363_servicerequest`,+> `adx_case`), or the standard incident table summarised on different facets (priority, owner,+> SLA timer), is just a regular Data Summarization call with maker-defined values.++> Reference: `${CLAUDE_PLUGIN_ROOT}/skills/add-ai-webapi/references/ai-api-reference.md` — canonical+> API shapes, required headers, site-setting names, error codes, and the documented support-case+> example. Read this at the start of the workflow; fetch the Microsoft Learn source pages with+> `mcp__plugin_power-pages_microsoft-learn__microsoft_docs_fetch` if the user asks for the latest.++> **Admin governance hierarchy**: both APIs are gated by a **three-level admin+> hierarchy** — tenant PowerShell setting (`enableGenerativeAIFeaturesForSiteUsers`), Copilot Hub+> environment/site governance, and the site-level maker toggle (for Search Summary: Set up+> workspace → Copilot → Site search (preview) → Enable Site search with generative AI (preview)).+> **Each level overrides the one below it**, so "the maker toggle is on but the API still says+> disabled" is a real scenario — admin-level governance wins.+>+> The two endpoints surface disablement differently:+>+> - **Search Summary** → HTTP **200** with an embedded envelope `{ Code: 400, Message: "Gen AI+> Search is disabled." }`. The generated `fetchSearchSummary` detects this and throws+> `SearchSummaryApiError`; the UI renders a remediation card.+> - **Data Summarization** → HTTP **400** with `error.code = 90041001` (admin-level disabled) or+> `90041003` (per-site `Summarization/Data/Enable=false`).+>+> Full troubleshooting checklist (tenant → environment → site, plus runtime version, Bing+> dependency, and cross-region data movement) lives in+> `references/ai-api-reference.md` §1 "Troubleshooting: AI feature appears disabled (admin+> hierarchy)" — point users there when either disablement shape surfaces. Mention this governance+> hierarchy explicitly to the user before Phase 7, and again in the Phase 8 summary.++> **Built-in search control vs. custom code path**: if the site uses the Microsoft-shipped Power+> Pages search **control** and only wants AI-summarised search results on that page, they don't+> need this skill — just the Copilot workspace toggle and the `Search/Summary/Title` content+> snippet. This skill is for sites that build their own search UI or need to call+> `/_api/search/v1.0/summary` from custom code. Confirm which path the user is on in Phase 1.++## Core principles++- **Layer 3 only, delegate the rest.** Web API site settings, table permissions, and web roles all belong to `/integrate-webapi` and `/create-webroles`. This skill creates the summarization service code and the `Summarization/*` site settings — nothing else.+- **Sequential agent spawning.** Per `plugins/power-pages/AGENTS.md`, spawn the `ai-webapi-integration` agent sequentially per target (never in parallel). The first call establishes the shared summarization service file and CSRF helper; subsequent calls extend it. `ai-webapi-settings-architect` runs alone, after all code integrations land.+- **Raw `fetch` + CSRF.** Every summarization request attaches `__RequestVerificationToken` (from `/_layout/tokenhtml`) and `X-Requested-With: XMLHttpRequest`. Never route through an OData wrapper.+- **Skip `/integrate-webapi` when it's not needed.** If every confirmed target is Search Summary (which has no per-table Web API prerequisites), or every Layer 1/2 prerequisite already exists on disk, the skill goes straight from Phase 3 to Phase 5.+- **Use TaskCreate/TaskUpdate** — create the todo list upfront with all phases before starting.++> **Prerequisites:**+>+> - An existing Power Pages SPA site created via `/create-site`+> - A Dataverse data model (tables + columns) set up via `/setup-datamodel` or manually — for any+> Data Summarization target+> - The site must have been deployed at least once (`.powerpages-site` folder must exist) for the+> settings phase++**Initial request:** $ARGUMENTS++---++## Workflow++(Phase headings below the workflow keep the technical "Layer 1+2 / Layer 3" names because they+describe the runtime layering and are what maintainers grep for. The titles here mirror the+user-facing task list.)++1. **Check site is ready** — locate project, detect framework, check data model, deployment status, and web-role presence.+2. **Find where AI summaries fit** — scan code for search / data summarization candidates.+3. **Confirm what to add** — review the manifest and pick which APIs / targets to integrate.+4. **Set up data access for AI** — invoke `/create-webroles` if needed, then invoke `/integrate-webapi` in AI-only read mode for data/case targets. Skip entirely for search-only or when prerequisites already exist.+5. **Add AI summary code** — invoke the `ai-webapi-integration` agent sequentially per target.+6. **Register AI prompts** — invoke the `ai-webapi-settings-architect` agent.+7. **Verify everything** — header-contract grep, `$select` grep, `npm run build`, validator script.+8. **Review and deploy** — record skill usage, summarise, offer `/deploy-site`.++---++## Iteration mode (after first run)++This skill is a **one-shot setup skill** — Phases 1–8 run end-to-end the first time the user asks+to integrate a summarization API. Once an AI surface is in place (service file, framework wrapper,+UI call site, and `Summarization/*` settings all exist), follow-up requests to tweak the rendered+UI (colours, spacing, copy, moving a button, a different empty-state message, wiring a second+recommendation into the hook, etc.) are **not** a reason to re-enter this skill mentally and run+every phase again. Doing so triggers a full `pac pages upload-code-site` and a chain of+`git commit`s for each tweak, which is exactly the noisy cadence the Phase 5.5 / 6.4 prompts above+are there to avoid.++When the user asks for follow-up UI changes to an already-integrated AI surface:++- **Edit the file(s) and run `npm run build`** locally to verify the tweak compiles. That is the+ whole validation loop for a UI change.+- **Do NOT automatically run `pac pages upload-code-site`.** Uploading should happen once, at the+ end of the session, when the user has finished tweaking.+- **Do NOT automatically `git commit`.** Let the user batch related tweaks into a single commit.+- **Batch the deployment and commit into a single end-of-session prompt** once the user signals+ they're done (or when you've completed the last requested change). Use `AskUserQuestion`:++ | Question | Header | Options |+ |----------|--------|---------|+ | All the UI tweaks look good. Deploy the site and commit the changes now? | Deploy & commit | Yes, deploy and commit (Recommended), Just commit — I'll deploy later, Just deploy — I'll commit later, Neither — I'll handle both myself |++Re-enter the full skill flow only when the user is adding a **new** AI surface (a new page, a new+table, a second API). If you're unsure whether a request is a tweak or a new surface, ask.++---++## Phase 1: Verify Site Exists++**Goal**: Locate the Power Pages project root and confirm prerequisites.++### 1.0 Detect iteration mode (before anything else)++Re-entry detection comes first because the rest of the skill assumes a first-time setup.+Capture two signals about the project state:++1. **Service signal**: a summarization service exists — `src/services/aiSummaryService.*`, or any+ source file under `src/` that contains `/_api/search/v1.0/summary` or+ `/_api/summarization/data/v1.0/`. When the signal is present, also note which API surface(s)+ the service code references — search-only, data-only, or both. This sub-classification matters+ below.+2. **Settings signal**: at least one Layer 3 site setting exists in+ `.powerpages-site/site-settings/Summarization-*.sitesetting.yml`.++Then route on the combination:++- **Both signals present** → re-entry. A previous `/add-ai-webapi` run completed end-to-end. Show+ the iteration-mode prompt below.+- **Service signal present and the existing service code is search-only** (it references+ `/_api/search/v1.0/summary` but **not** `/_api/summarization/data/v1.0/`) → re-entry. Search-only+ sites legitimately have no `Summarization/*` settings (Search Summary uses the workspace toggle,+ not per-call settings), so the absence of the settings signal is the steady state, not a+ failed run. Show the iteration-mode prompt below.+- **Service signal present and the existing service code includes Data Summarization** but the+ settings signal is absent → in-flight first run (a previous attempt failed before Phase 6+ landed). Continue with the full flow without prompting.+- **Neither signal present** → first-time run. Continue with Phase 1.1.++When you reach the iteration-mode branch, ask:++| Question | Header | Options |+|----------|--------|---------|+| It looks like an AI summary surface is already wired into this site. Is this request a tweak to the existing one, or are you adding a brand-new surface (new page, new table, second API)? | Mode | Tweak the existing surface (Recommended for visual/copy edits), Add a new surface (run the full skill again), Not sure — show me what's already wired |++- **Tweak the existing surface**: stop running this skill. Switch into the workflow described in+ the [Iteration mode](#iteration-mode-after-first-run) section above — Edit + `npm run build`,+ no auto upload-code-site, no auto commit, batched end-of-session prompt for deploy + commit.+- **Add a new surface**: continue with Phase 1.1 (full flow). The downstream phases will detect+ existing infrastructure (CSRF helper, summarization service, settings) and extend rather than+ duplicate.+- **Not sure — show me what's already wired**: list the existing service file(s), wired UI+ components, and `Summarization/*` settings, then re-ask the same question.++### 1.1 Create todo list++Create all 8 phase tasks upfront via `TaskCreate` — see [Progress Tracking](#progress-tracking).++### 1.2 Locate project++Look for `powerpages.config.json` in the current directory or immediate subdirectories.++**If not found**: tell the user to create a site first with `/create-site`.++### 1.3 Detect framework++Read `package.json` and detect React / Vue / Angular / Astro. See+`${CLAUDE_PLUGIN_ROOT}/references/framework-conventions.md`.++### 1.4 Check for data model++Look for `.datamodel-manifest.json`. If found, read it — tables listed here are candidates for the+Data Summarization API. The standard `incident` table is a candidate like any other; do not+treat it specially.++### 1.5 Check deployment status — hard prerequisite++Look for `.powerpages-site`. Phase 4 (`/integrate-webapi`) and Phase 6 (`ai-webapi-settings-architect`)+both require this folder to exist. Deferring the deploy until later is **not** a viable workaround:+once Phase 5 has written the AI-calling service code, deploying a site whose Layer 1/2/3 settings+aren't yet on disk publishes runtime-broken code (every summarization call 403/500s until a second+deploy lands). The cleanest sequence is to deploy the **clean scaffold** now, before any AI code+exists.++**If `.powerpages-site` does NOT exist:**++| Question | Header | Options |+|----------|--------|---------|+| `.powerpages-site` was not found. The AI summary skill needs the site deployed at least once before configuring permissions and settings. Deploy the clean scaffold now (no AI code yet — keeps the intermediate state safe), or stop and run `/deploy-site` yourself first? | Bootstrap deploy | Yes, deploy the scaffold now (Recommended), Stop — I'll deploy first then re-run /add-ai-webapi |++On **Yes**: invoke the `Skill` tool for `power-pages:deploy-site` and wait for completion. Then+re-check `.powerpages-site` exists before proceeding. **If it is still absent** after the+sub-skill returns (deploy failed mid-flow, the user cancelled it, or an upload completed but the+local folder wasn't created), stop here with a clear message — surface the deploy-site outcome+verbatim so the user can debug it, and tell them to re-run `/deploy-site` followed by+`/add-ai-webapi`. Do NOT silently fall through to Phase 2; the downstream sub-skills require this+folder.++On **Stop**: end the skill with a clear next-step message ("Run `/deploy-site`, then re-invoke+`/add-ai-webapi` to continue"). Do NOT continue to Phase 2 — the downstream sub-skills can't run.++### 1.6 Check web roles++Look for `.powerpages-site/web-roles/*.yml`. Record whether any roles exist — the Phase 4+delegation needs at least one role before `/integrate-webapi` can create table permissions.++**Output**: confirmed project root, framework, data-model availability, deployment status, web-role inventory.++---++## Phase 2: Explore AI integration points++**Goal**: Find every candidate for each of the two APIs — scoped to AI only.++The full Explore-agent prompt body, manifest shape, and delegation-decision rules live in+`${CLAUDE_PLUGIN_ROOT}/skills/add-ai-webapi/references/explore-prompt.md`. Read that file+first, then invoke the **Explore agent** (via `Task` with `subagent_type: "Explore"`,+thoroughness `medium`) and pass the prompt body verbatim.++What the Explore agent reports back (summary — see the reference for the exact prompt):++- **Reserved-slot markers** (`POWERPAGES:AI-SLOT kind=<pick>`) — authoritative placement hints+ planted by `/create-site`; orphan markers are flagged for Phase 3 to resolve.+- **Search Summary candidates** including related-record-discovery targets on detail pages+ ("suggested KB articles", "similar cases").+- **Data Summarization candidates** classified `single-record` / `list` / `intent-mismatch`,+ each with the existing fetch's OData query and a scope classification+ (`matches-existing-fetch` / `scope-extends-beyond-existing-fetch` / `needs-definition` /+ `intent-mismatch`).+- **Existing infrastructure** — CSRF helper, `powerPagesApi.ts`, prior `aiSummaryService.*`.+- **Layer 1/2 status** per Data Summarization target plus every `$expand` target —+ `ready` / `missing` / `n/a (search)`.+- **Fields-list breadth advisory** — for Layer 1/2 `ready` rows whose existing+ `Webapi/<table>/fields` is broader than the AI surface needs (primary key included, lookup+ write forms, unused columns), flagged `fields-broader-than-ai-mode` so Phase 3 can surface+ it.+- **Layer 3 status** per Data Summarization target — `Summarization/Data/Enable` and the+ specific `Summarization/prompt/<id>` the code will send.++Compile the integration manifest from the agent's output (one row per candidate, columns:+`#`, `API`, `Target file`, `Target kind`, `Entity Set`, `$select` / `$expand`, `Source`,+`Layer 1/2 status`, `Layer 3 status`) — the reference file contains a worked example.++**Delegation decisions** (compute directly from the status columns):++- Run `/integrate-webapi`? → True if any row's Layer 1/2 status is `missing`. Send only the+ missing-status rows in the `tables=` sentinel; don't re-audit settled tables.+- Run `ai-webapi-settings-architect`? → True if any row's Layer 3 status is `missing`.++**Output**: integration manifest + delegation decisions + existing-infra report ++fields-broader-than-ai-mode advisory list (if any).++---++## Phase 3: Review AI plan++**Goal**: Present the manifest and confirm which APIs / targets to integrate.++Show the user:++1. The list of APIs and targets found.+2. For each: which file references it and what the service will do.+3. The two delegation decisions from Phase 2 ("Will invoke `/integrate-webapi` for [tables]",+ "Will invoke `ai-webapi-settings-architect` for Layer 3").+4. Existing-infrastructure notes (CSRF helper reuse, `powerPagesApi.ts`, previous+ `aiSummaryService.*`).++### Approval cadence (set expectations up-front)++Before asking the integration question, briefly tell the user how many more decision points+are coming so the "one-shot" run isn't surprising. Count them from the+[Key decision points](#key-decision-points-wait-for-user) list, subtracting the ones that+don't apply for this run:++- **Search-only run**: drop the `/integrate-webapi` delegation (Phase 4) and the settings+ architect (Phase 6) — 4–5 more pauses after this one.+- **Layer 1/2 already ready**: drop the Phase 4.3 architect approvals.+- **No list / scope-extends / intent-mismatch rows**: drop the per-target Phase 3 follow-ups.+- **First-time run with all branches firing**: 7–10 more pauses (web-role choice, per-target+ list-trigger and scope-confirmation, two integrate-webapi architect plans, the AI+ settings architect plan, two commit prompts, final deploy).++Phrase it as a heads-up, not a warning — e.g., "I'll pause for your input ~6 more times+after this one (web-role choice, two architect plans, two commit prompts, final deploy).+Could be a couple more if any list target needs a trigger or scope decision."++### The integration question++Use `AskUserQuestion` and **build the option list dynamically** from the Phase 2 manifest — do+not hardcode "Search summary and Data summarization" when only one category has candidates.+Construct the question text from what was found:++- If both categories have candidates: "I found candidates for Search Summary and Data+ Summarization. Which should I integrate?"+- If only one category with one target: skip "All of them" — just confirm the single target+ ("Wire Search Summary into `<page>`?").++The default option list, with rows present only when the corresponding category has candidates:++| Option | When to include |+|--------|-----------------|+| All of them (Recommended) | Both categories present |+| Only Search Summary | Search candidates present AND Data Summarization candidates present |+| Only Data Summarization | Data Summarization candidates present AND Search candidates present |+| Let me select specific ones | Always (multi-target runs) |+| None — cancel | Always |++If the user chooses "Let me select specific ones", follow up with a multi-select question listing+each row of the integration manifest. When a detail-page candidate was flagged in Phase 2 as a+related-record-discovery target, include it as a dedicated option (in addition to any Data+Summarization option for the same page) so the user can consciously pick the AI-grounded path+rather than a hand-rolled OData match — e.g.:++- `Search Summary on CaseDetail.tsx (finds related KB articles via generative AI)`+- `Search Summary on ProductDetail.tsx (finds related products via generative AI)`++Label the option with the page name and the outcome it produces, not just "Search Summary", so the+user sees exactly where the AI surface will appear.++### Per-target follow-up questions++After the user confirms targets, ask per-target follow-up questions only when needed:++- **List-trigger** — every list target gets a "load on open" vs "manual button" question.+- **Scope confirmation** — only when Phase 2 flagged the row `scope-extends-beyond-existing-fetch`,+ `needs-definition`, or `intent-mismatch`. Resolve `intent-mismatch` first because the+ chosen target kind decides which scope question (LIST or SINGLE-RECORD) to ask next.++Question text, option lists, and the scope-classification → question mapping live in+`${CLAUDE_PLUGIN_ROOT}/skills/add-ai-webapi/references/scope-classification.md`. Read it+when any per-target follow-up is required.++The chosen values flow into the Phase 5 agent-invocation prompt as the **Scope for the summary+call** block (`$filter`, `$orderby`, `Scope source`, `Target's existing list fetch`). The+existing UI fetch on the target component stays in place unchanged — the summary URL is an+addition, never a replacement.++If the user picks a scope that adds new `$expand` targets (e.g., "include its line items"),+re-evaluate the Phase 2 Layer 1/2 delegation decision — the new expansion is a new+prerequisite (Web API enabled + parent-scope permission on the child table).++### Handling "None — cancel"++When the user picks `None — cancel`:++1. Mark the remaining tasks as `completed` with a `(skipped — cancelled by user)` suffix in the+ activeForm so the task list reads cleanly rather than leaving them stuck `pending`.+2. Jump straight to **Phase 8.1** (record skill usage with `--skillName "AddAiWebapi"` and an+ outcome of `cancelled`) and **Phase 8.2** (present a one-line summary: "No changes made — you+ cancelled at the plan-review step").+3. Skip Phases 4, 5, 6, 7, and 8.3 entirely. Do **not** invoke `/integrate-webapi`,+ `ai-webapi-integration`, `ai-webapi-settings-architect`, or `/deploy-site`. Do **not** commit.++**Output**: user-confirmed integration manifest, or a clean cancellation.++---++## Phase 4: Delegate Layer 1 + Layer 2++**Goal**: Ensure every Web API prerequisite for the AI target tables exists, by delegating to+`/create-webroles` and `/integrate-webapi` (AI-only read mode) instead of writing Layer 1/2 files+directly.++### 4.1 Skip-check++Skip this entire phase when **any** of the following is true:++- Every confirmed target is Search Summary (search has no per-table Web API prerequisites).+- The Phase 2 delegation decision said "Run `/integrate-webapi`? No" — all Layer 1/2 prerequisites+ are already on disk from prior runs.+- `.powerpages-site` does not exist (the sub-skills both require it).++In the skip case, proceed to Phase 5 and note this in the final summary.++### 4.2 Create missing web roles (if needed)++From Phase 1.6: if no web roles exist in `.powerpages-site/web-roles/`, or the roles that exist+don't match the site's auth model, ask the user:++| Question | Header | Options |+|----------|--------|---------|+| `/integrate-webapi` needs at least one web role to attach table permissions to. No matching role was found. Create one now via `/create-webroles`? | Web role | Yes, create via /create-webroles (Recommended), Skip — I'll handle roles separately |++On **Yes**: invoke the `Skill` tool for `power-pages:create-webroles` with a prompt that+includes the caller-suppress sentinel so the sub-skill does not issue its own deploy+prompts (the orchestrator owns the single end-of-run deploy decision):++> `[CALLED-BY-PARENT-SKILL] caller=add-ai-webapi`+>+> Create web roles for this Power Pages SPA site. The parent skill `/add-ai-webapi` will+> later attach AI-only read-mode table permissions to the role(s) you create. Do not issue+> deploy-now prompts — the orchestrator batches the deploy at the end.++Wait for it to complete. Then re-check `.powerpages-site/web-roles/` before proceeding to 4.3.++On **Skip**: this puts the run on a known-broken path — the AI endpoints will return 403 at+runtime until the user manually creates a web role + table permissions. Don't fall through+silently. Confirm the trade-off with a second `AskUserQuestion`:++| Question | Header | Options |+|----------|--------|---------|+| Without a web role I can't set up table permissions, so the AI endpoints will return 403 at runtime until you configure them yourself. Stop here so you can run `/create-webroles` first, or continue to write the frontend code anyway and let me flag the gap in the final summary? | Continue? | Stop here (Recommended), Continue — write frontend code only and flag the gap in the summary |++On **Stop here**: end the skill cleanly. Tell the user to run `/create-webroles` (and optionally+`/integrate-webapi`) first, then re-invoke `/add-ai-webapi`.++On **Continue**: skip the rest of Phase 4 (the `/integrate-webapi` delegation needs a web role to+attach permissions to, so running 4.3 would fail) and jump to Phase 5. In the Phase 8 summary,+flag the Layer 1/2 gap loudly — list the exact files the user still needs to create+(`Webapi/<table>/enabled`, `Webapi/<table>/fields`, table permissions per target) so the path to+a working runtime is obvious from the final message.++### 4.3 Invoke `/integrate-webapi` in AI-only read mode++Build the sentinel arguments from the Phase 2 manifest:++- `primary=<primary table logical name>` (the table whose record / collection is being summarised — e.g., `incident`, `cr4fc_product`, `cr363_workorder`)+- `tables=<primary plus every $expand target, comma-separated>`+- `expand-targets=<every $expand target, comma-separated; empty for pure data-summary targets with no $expand>`+- `caller=add-ai-webapi`++Invoke the `Skill` tool for `power-pages:integrate-webapi` with a single prompt:++> `[AI-READ-ONLY] mode=ai-read-only primary=<primary> tables=<list> expand-targets=<list> caller=add-ai-webapi`+>+> Configure Layer 1/2 (Web API site settings + table permissions) for the following Power Pages+> AI summarization targets: <table list>. This is a read-only integration — the `/_api/summarization/data/v1.0/`+> endpoint never mutates Dataverse. Return when all Web API site settings, table permissions, and the+> shared `powerPagesApi.ts` client are written to disk.+>+> **Per the AI-only read-mode contract** (your SKILL.md Phase 1.6):+> - **Do not commit.** Skip Phase 4.4 and Phase 6.5 — print the file list you would have+> committed so this orchestrator can stage it later. The parent skill batches commits.+> - **Do not deploy.** Skip Phase 6.1 deploy ask, Phase 7.3 deploy ask, and Phase 7.4+> post-deploy notes. Return the Phase 7.2 summary and stop. The parent skill owns the+> single end-of-orchestration deploy.++`/integrate-webapi` detects the `[AI-READ-ONLY]` sentinel (its Phase 1.6) and runs its full flow+with hardened prompts: read-only table permissions, minimal fields list (no PK, only `_<col>_value`+for lookups), and a read-only service layer. It still presents plan-mode approval prompts to the+user for each architect — this skill does not suppress those.++Wait for `/integrate-webapi` to complete. Re-check the file system:++- `src/shared/powerPagesApi.ts` exists+- For every target table: `Webapi/<table>/enabled` exists, `Webapi/<table>/fields` exists+- For every target table: at least one table permission with `read: true` exists; Parent-scope+ permission present for every `$expand` target++If any prerequisite is still missing, surface this to the user before moving on — something in the+delegated flow didn't land (for example, the user declined the architect's plan). Do NOT silently+fall back to writing Layer 1/2 files here.++**Output**: Layer 1/2 prerequisites are on disk; shared `powerPagesApi.ts` + read-only service+exists; web roles exist.++---++## Phase 5: Implement Layer 3 code++**Goal**: Create the AI summarization service and wire it into each target's UI.++### 5.1 Invoke the `ai-webapi-integration` agent — first target (sequential)++For the first target in the confirmed manifest, invoke the agent at+`${CLAUDE_PLUGIN_ROOT}/agents/ai-webapi-integration.md` via `Task`. The full prompt+template — every field the agent expects, with notes on which orchestrator phase resolved+each value — lives in+`${CLAUDE_PLUGIN_ROOT}/skills/add-ai-webapi/references/agent-invocation-prompt.md`. Read+that file, copy the template, replace every `<…>` placeholder with the concrete value for+the current target, and pass it via `Task`. The agent does not interpret placeholders;+sending the literal text `<search | data>` will confuse it.++The first call is sequential because it establishes the shared summarization service file+(`src/services/aiSummaryService.*`) and the CSRF helper that subsequent targets reuse. The+agent returns a structured file-modification list (see its "Return value" section); record+it for Phase 5.5's per-file commit.++### 5.2 Verify service + CSRF helper exist++Before spawning more agents, verify:++- The summarization service file exists (default `src/services/aiSummaryService.ts`).+- `getCsrfToken` is defined once in the codebase (or imported from a pre-existing helper).++### 5.3 Invoke the agent for remaining targets — sequentially++Per `plugins/power-pages/AGENTS.md`, agent spawning is **sequential**. Invoke+`ai-webapi-integration` once per remaining target, waiting for each completion before starting the+next. Each target only adds an independent exported function, a framework wrapper (if not already+present), and wires one UI file — there are no merge conflicts, but the sequential rule keeps+failure modes simple.++If there is only one target total, skip 5.3.++### 5.4 Replace placeholder POSTs++For any placeholder `InstructionIdentifier` body the Explore agent flagged in Phase 2, the+sub-agent will have replaced them. Confirm by grepping for `InstructionIdentifier` in the affected+files and verifying each resolved call uses the real entity set and id.++### 5.5 Offer to commit++Don't commit automatically — on iterative runs an unprompted `git commit` here creates a noisy+series of commits for what is effectively one set of changes. Use `AskUserQuestion`:++| Question | Header | Options |+|----------|--------|---------|+| Commit these Layer 3 integration changes now? | Commit | Yes, commit now (Recommended), Skip — I'll commit later |++On **Yes**: stage **only the files modified during Phase 5** — the summarization service,+framework wrapper(s), each wired UI page, and any safe-markdown renderer component the agent+emitted. The orchestrator already has this list from each `ai-webapi-integration` invocation's+file-modification report. Use explicit `git add <path>` per file; do **not** use `git add -A` —+unrelated work-in-progress files in `src/` could otherwise be swept into the commit. Substitute+`<targets>` in the commit message with a short human-readable list (e.g., `CaseDetail and SearchResults`,+or `3 pages` when there are many):++```powershell+git add <each file modified by the Phase 5 agents>+git commit -m "Add AI summarization integration for <targets>"+```++On **Skip**: proceed without committing. The user will batch the commit themselves at the end.++**Output**: summarization service + framework wrappers + UI call sites created for every confirmed+target.++---++## Phase 6: Configure Layer 3 settings++**Goal**: Register the `Summarization/*` site settings via the `ai-webapi-settings-architect` agent.++### 6.1 Skip-check++Skip this phase when both of the following are true:++- Every confirmed target is Search Summary (search has no per-call `Summarization/*` site settings;+ see [ai-api-reference.md](references/ai-api-reference.md#1-search-summary-api)).+- No Data Summarization target was added in Phase 3.++For search-only, remind the user to enable **Site search with generative AI (preview)** in the+site's Copilot workspace after deploy, and proceed to Phase 7.++### 6.2 Confirm deployment prerequisite still holds++Phase 1.5 already gated on `.powerpages-site` existing. Re-check it here as a guard — if it has+disappeared between Phase 1 and now (rare, but possible if the user manually cleaned the folder),+stop and re-run the Phase 1.5 bootstrap-deploy prompt. Do NOT silently fall through into the+architect with a missing folder.++### 6.3 Invoke `ai-webapi-settings-architect`++Invoke the agent at `${CLAUDE_PLUGIN_ROOT}/agents/ai-webapi-settings-architect.md` via `Task`:++> "Analyse this Power Pages SPA site and propose generative-AI summarization site settings.+> The following Data Summarization targets were integrated in Phase 5: [list each target with its+> entity set, per-target `InstructionIdentifier` value, and **target kind** (`single-record` or+> `list`) — the architect needs this to decide on `Summarization/Data/ContentSizeLimit`].+> **If any target is `list`, the plan MUST include `Summarization/Data/ContentSizeLimit=200000`** —+> the 100k server default silently truncates list content; this is non-negotiable.+> Check for existing `Summarization/*` settings. Layer 1+> (`Webapi/<table>/*`) and Layer 2 (table permissions) were configured in Phase 4 via+> `/integrate-webapi` in AI-only read mode — verify they are present on disk and cite them as+> met in your plan's prerequisite table. Propose the AI plan via plan mode, and on approval+> create the YAMLs with `create-site-setting.js`."++Wait for the agent to complete. If it reports missing Layer 1/2 prerequisites, something in+Phase 4 didn't land — read the file system, identify the gap, and surface it to the user rather+than attempting to create Layer 1/2 files here.++### 6.4 Offer to commit++Use `AskUserQuestion`:++| Question | Header | Options |+|----------|--------|---------|+| Commit the new `Summarization/*` site settings? | Commit | Yes, commit now (Recommended), Skip — I'll commit later |++On **Yes**: stage **only the files the architect just created** — use the+`filePath` list returned by `ai-webapi-settings-architect` (or the per-file paths printed by+each `create-site-setting.js` invocation), not a glob. A glob can sweep in pre-existing+`Summarization-*` YAMLs that are dirty for unrelated reasons (e.g., a prior partial run, or+a maker-edited prompt) and bundle them into the commit by accident.++Use explicit `git add <path>` per file:++```bash+git add <each Summarization-*.sitesetting.yml the architect just wrote>+git commit -m "Add AI summarization site settings"+```++On **Skip**: proceed without committing.++**Output**: `Summarization/Data/Enable`, `Summarization/prompt/<id>` settings created.++---++## Phase 7: Verify++**Goal**: Confirm every expected file exists, all POSTs set both required headers, and the project+builds.++> **Preview-feature reminder.** A green build doesn't mean the API will return a summary at+> runtime — admin-level governance (tenant PowerShell, Copilot Hub) or the site-level maker+> toggle for Search Summary can still block it. See the Preview-feature note at the top of+> this skill and the admin-hierarchy checklist in+> `references/ai-api-reference.md` §1 "Troubleshooting: AI feature appears disabled". Tell+> the user now so the post-deploy test isn't a surprise.++### 7.1 File inventory++For each confirmed target, confirm:++- **Service file**: `src/services/aiSummaryService.ts` (or project-convention equivalent) contains+ the expected exported function (`fetchSearchSummary` or `fetchDataSummary`; the agent may also+ emit a thin wrapper such as `fetchCaseSummary` when the user picked the support-case scenario).+- **Framework wrapper** (non-Astro): React hook in `src/hooks/`, Vue composable in+ `src/composables/`, or Angular service in `src/app/services/`.+- **UI wiring**: at least one page/component imports the service or wrapper and calls it.+- **Shared API client** `src/shared/powerPagesApi.ts` exists when any Data Summarization target was in scope.+- **`Summarization/Data/ContentSizeLimit` site setting** when any list-summary target was+ integrated. Grep the source for `fetchListSummary` — if any match exists, confirm+ `.powerpages-site/site-settings/Summarization-Data-ContentSizeLimit.sitesetting.yml` is+ present with `value: 200000` (or higher). Missing this setting silently caps list summaries at+ the 100k server default and ships the user truncated input. If it's missing, surface the gap+ to the user before completing Phase 7 — re-run the architect or create the YAML manually.++### 7.2 Header contract grep++```+Grep: "_api/search/v1\\.0/summary|_api/summarization/data/v1\\.0/" in src/**/*.{ts,tsx,js,jsx,vue,astro}+```++For every file that matches, verify the surrounding fetch includes:++- `__RequestVerificationToken` (CSRF token, fetched from `/_layout/tokenhtml`) — **hard rule**+- `X-Requested-With: XMLHttpRequest` — **recommended** (the validator warns when it's missing but+ does not block; it matches `shell.ajaxSafePost` and every other Power Pages POST)++For data summarization calls, additionally verify (both **hard rules**):++- The URL contains `$select=` (no wildcards)+- `OData-MaxVersion: 4.0` and `OData-Version: 4.0` headers are set++Fix any missing **hard-rule** header before proceeding. Missing CSRF produces 500s; missing+`$select` or OData headers produces 403/400s. A missing `X-Requested-With` only produces a+validator warning — add it for consistency, but it does not break the run.++### 7.3 Build check++```powershell+cd "<PROJECT_ROOT>"+npm run build+```++Fix any type or import errors. Common issues: missing import of the summarization service in a+wired page; type mismatch between `DataSummaryResponse` and the UI consumer; duplicate+`getCsrfToken` declarations (if Phase 5 failed to reuse the existing helper).++### 7.4 Present verification results++| Target file | API | Service fn | Wrapper | UI call site | Headers ✓ | `$select` ✓ |+|-------------|-----|-----------|---------|--------------|-----------|-------------|+| `src/pages/SearchResults.tsx` | Search summary | `fetchSearchSummary` | `useSearchSummary` | Yes | Yes | n/a |+| `src/pages/CaseDetail.tsx` | Data summarization | `fetchDataSummary` (optionally wrapped as `fetchCaseSummary`) | `useCaseSummary` | Yes | Yes | Yes |+| `src/pages/ProductDetail.tsx` | Data summarization | `fetchDataSummary` | `useProductSummary` | Yes | Yes | Yes |++(Same row order and example file paths as the Phase 2 manifest example, so a maintainer reading+both tables can trace each row top-to-bottom. Row 2 mirrors the Microsoft-shipped support-case+recipe — a Data Summarization call configured for `incidents` with the `case_summary` prompt+identifier.)++**Build status:** Pass / Fail (with details).++**Output**: all integration files verified; project builds.++---++## Phase 8: Review & Deploy++**Goal**: Record skill usage, present a summary, and offer deployment.++### 8.1 Record skill usage++> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`++Use `--skillName "AddAiWebapi"`.++### 8.2 Present summary++| Step | Status | Details |+|------|--------|---------|+| Web roles | Created via /create-webroles / Reused existing / Skipped | role name(s) |+| Layer 1/2 (Web API settings + permissions) | Created via /integrate-webapi / Reused existing / Skipped (search-only) | list of files written |+| Summarization service | Created / Extended | exported functions, file path |+| Framework wrappers | Created / Extended | hook/composable/service paths |+| UI call sites | Wired | list of files |+| Layer 3 (Summarization/* settings) | Created / Already existed / Skipped | `Summarization/Data/Enable`, one per prompt |++### 8.3 Ask to deploy++| Question | Header | Options |+|----------|--------|---------|+| Everything is ready. Deploy the site so the summarization APIs become live? | Deploy | Yes, deploy now (Recommended), No, I'll deploy later |++**Yes**: invoke `/deploy-site`.+**No**: acknowledge. Remind that the API calls will not work until the site is deployed with the+new settings and permissions.++### 8.4 Post-deploy notes++Surface these to the user at the end of the run:++- **Search Summary toggle** — for any Search Summary integration, remind the user to flip+ **Set up workspace → Copilot → Site search (preview) → "Enable Site search with generative+ AI (preview)"**. Without it, the endpoint returns the disabled envelope and the UI renders+ the remediation card instead of a summary.+- **Test recipe** — for Data Summarization, open a record-detail or list page, trigger the+ summary, confirm 200 + rendered text, then click a recommendation chip and confirm the+ follow-up sends `RecommendationConfig`. For Search Summary, perform a search and confirm+ the summary renders above keyword hits with citation anchors pointing at the SPA route+ (not `/page-not-found/`). The `90041005` "nothing to summarize" branch is normal for the+ Microsoft-shipped support-case recipe on a freshly-created case with no comments — test+ with a record that has substantive content in every selected / expanded column.+- **When the disabled-state card or `90041001` shows up** — walk the admin-hierarchy+ checklist in `references/ai-api-reference.md` §1 "Troubleshooting: AI feature appears+ disabled (admin hierarchy)". Retry doesn't help; an admin or maker has to change+ governance / flip the site toggle.+- **403 on any summarization call is always a Layer 1/2 issue** (column casing in+ `Webapi/<table>/fields`, or missing `read: true` table permission) — re-run+ `/integrate-webapi` in AI-only read mode rather than hand-editing YAML.+- **Full error-code reference** (`90041001` … `90041006`) is in+ `references/ai-api-reference.md` §2 "Error codes". Open it when the user reports a 400.+- **Column permission profiles can silently hide content.** If a summary has obvious+ omissions, check Dataverse column permission profiles on the web role before suspecting+ the prompt or fields list.++**Output**: summary presented, deployment completed or deferred, post-deploy guidance given.++---++## Important Notes++### Throughout all phases++- **Use TaskCreate/TaskUpdate** to track progress at every phase.+- **Ask for user confirmation** at key decision points (list below).+- **Sequential agent spawning** — per the "Agent spawning" rule in `plugins/power-pages/AGENTS.md`. Never spawn `ai-webapi-integration` in parallel across targets (every target extends the same `aiSummaryService.*` file, so parallel runs would conflict).+- **Commit at milestones** — after implementation (Phase 5) and after settings creation (Phase 6).+- **Never use an OData wrapper for summarization fetches** — raw `fetch` only.+- **Never write Layer 1/2 files directly** — always delegate to `/integrate-webapi` / `/create-webroles`. This skill is Layer 3.++### Key decision points (wait for user)++The list below is the conservative upper bound — many runs hit fewer prompts because skip+checks (search-only run, Layer 1/2 ready, no list/intent-mismatch targets) eliminate whole+branches. Realistic worst case for a multi-target first-time run is ~10 prompts; a clean+re-entry tweak is just 1 prompt (the Phase 1.0 mode question).++1. **At Phase 1.0 (re-entry detection)**: tweak existing surface, add a new surface, or+ review what's already wired. Only fires when a previous `/add-ai-webapi` run left a+ service file or `Summarization/*` settings on disk.+2. **At Phase 1.5**: bootstrap deploy or stop (if `.powerpages-site` is missing).+3. **After Phase 3 (main)**: confirm which APIs / targets to integrate.+4. **Phase 3 per-target follow-ups (variable count)**: list-trigger choice (one per list+ target), and scope-confirmation (one per `scope-extends-beyond-existing-fetch`,+ `needs-definition`, or `intent-mismatch` row). Question text and option lists live in+ `references/scope-classification.md`.+5. **At Phase 4.2**: create missing web role via `/create-webroles` (if needed). The+ sub-skill is invoked with the caller-suppress sentinel — its own deploy prompts don't+ fire.+6. **At Phase 4.2 (Skip path only)**: confirm continuing despite known broken-runtime risk.+7. **Inside the Phase 4.3 `/integrate-webapi` delegation**: approve its+ `table-permissions-architect` plan and its `webapi-settings-architect` plan (each+ architect owns its own plan-mode prompt; the sub-skill is in AI-only read mode so its+ commit and deploy prompts are suppressed).+8. **At Phase 5.5**: commit the integration changes now or later.+9. **Inside the Phase 6.3 `ai-webapi-settings-architect` call**: approve its plan.+10. **At Phase 6.4**: commit the new settings now or later.+11. **At Phase 8.3**: deploy now or later.++### List-summary use case playbook++When the target is a LIST of records (not a single record), the defaults for a single-record+Copilot card are the wrong defaults — collection endpoint, tabular-insight prompt,+`ContentSizeLimit=200000`, `normalizeSummaryString` + safe-markdown renderer, etc.++The full 10-rule playbook (collection endpoint, scope mirroring, prompt size, nav-property+casing, mandatory `ContentSizeLimit`) lives in+`${CLAUDE_PLUGIN_ROOT}/skills/add-ai-webapi/references/ai-api-reference.md` §2 "List-summary+playbook". Read that section before any list-summary target reaches Phase 5 — the Phase 5+agent and the Phase 6 settings architect both reference the same playbook.++### Progress tracking++Before starting Phase 1, create a task list with all phases using `TaskCreate`:++| Task subject | activeForm | Description |+|-------------|------------|-------------|+| Check site is ready | Checking site prerequisites | Locate project root, detect framework, check data model, deployment status, web-role inventory |+| Find where AI summaries fit | Scanning code for AI summary opportunities | Use Explore agent to find search/data/case candidates, existing infra, and delegation decisions |+| Confirm what to add | Confirming the AI summary plan | Present manifest and confirm which APIs and targets to integrate |+| Set up data access for AI | Setting up Web API access and permissions | Invoke /create-webroles if needed, then /integrate-webapi in AI-only read mode (or skip for search-only) |+| Add AI summary code | Adding AI summary code to your pages | Sequential ai-webapi-integration calls: first target creates shared service + CSRF helper, remaining targets extend it |+| Register AI prompts | Registering AI prompt settings | Invoke ai-webapi-settings-architect to create Summarization/* settings |+| Verify everything | Verifying file inventory, headers, and the build | Confirm service file, wrappers, UI wiring, header contract, run project build |+| Review and deploy | Reviewing summary and deploying | Record skill usage, present summary, offer /deploy-site, give post-deploy guidance |++Mark each task `in_progress` when starting and `completed` when done via `TaskUpdate`.++---++**Begin with Phase 1: Verify Site Exists**diff --git a/plugins/power-pages/skills/add-ai-webapi/references/agent-invocation-prompt.md b/plugins/power-pages/skills/add-ai-webapi/references/agent-invocation-prompt.mdnew file mode 100644index 000000000..4530c76e5--- /dev/null+++ b/plugins/power-pages/skills/add-ai-webapi/references/agent-invocation-prompt.md@@ -0,0 +1,83 @@+# Phase 5.1 ai-webapi-integration agent invocation prompt template++The orchestrator (`/add-ai-webapi` Phase 5) invokes the `ai-webapi-integration` agent once+per target — the first call sequentially (it establishes the shared summarization service+file + CSRF helper), then the remaining targets sequentially per `AGENTS.md`.++This file holds the **prompt template** the orchestrator passes via `Task`. Replace every+`<…>` placeholder with the concrete value for the current target before sending; the agent+does not interpret placeholders, so sending the literal text `<single-record | list>` will+confuse it.++---++## Prompt body (template)++> "Integrate the **<API name>** for the Power Pages SPA site.+>+> - APIs to wire: <one of: `search`, `data`>+> - Target file: <absolute or project-relative path to the page/component to wire>+> - Target kind: <one of: `single-record`, `list`, `n/a (search)`> — from the Phase 2+> manifest. `list` means use `fetchListSummary` + the collection-endpoint URL form (see+> agent §2.1); `single-record` means use `fetchDataSummary` + the record-endpoint URL+> form.+> - Trigger mode (list targets only, from Phase 3 follow-up): <one of: `auto-on-mount`,+> `manual-button`>. Set the wrapper's initial trigger accordingly. Omit for+> single-record targets (always auto on a user action).+> - Framework: <React | Vue | Angular | Astro>+> - Project root: <absolute path>+> - If data: table logical name `<logical_name>`, entity set `<entity_set_name>`,+> `$select=<columns>`, `$expand=<NavProp($select=...)>` (omit for search),+> `InstructionIdentifier` `Summarization/prompt/<identifier>`. For the support-case+> scenario, use the Microsoft-shipped recipe: `incident` / `incidents` /+> `$select=description,title` /+> `$expand=incident_adx_portalcomments($select=description)` /+> `Summarization/prompt/case_summary`.+> - For `list` targets — Scope for the summary call (resolved by the orchestrator from+> Phase 2 + Phase 3; the agent uses these values verbatim and does NOT re-derive from+> the existing fetch):+> - `$filter`: `<exact filter value to use on the summary URL, or \"none\">`+> - `$orderby`: `<exact value, typically mirrors the existing fetch>`+> - Scope source: `<one of: \"mirror-existing-fetch\" | \"user-verbal-scope\" |+> \"user-custom-odata\" | \"no-filter\" | \"both\" (dual summary)>`+> - Target's existing list fetch (for reference, may be `none`):+> `<verbatim URL + any Prefer header>` — the agent MUST leave this fetch in place+> unchanged; the summary is an ADDITION, not a replacement.+> - Regardless of scope source: the new summary URL must NOT include `$top` and must+> NOT set `Prefer: odata.maxpagesize`. Those belong to the UI's paginated fetch only.+> Pagination is UI behaviour; the server-side cap is+> `Summarization/Data/ContentSizeLimit`.+> - `$expand` navigation property casing (data/list targets with `$expand` only): each+> nav property name verbatim as it appears in Dataverse metadata's+> `ReferencedEntityNavigationPropertyName` — do not auto-lowercase. If unknown, the+> agent must query+> `EntityDefinitions(LogicalName='<primary>')/ManyToOneRelationships` (or+> `/OneToManyRelationships`) before building the URL. See agent §2.2.+> - Existing CSRF helper: <path + export name, or `none — define inline`>+> - Existing summarization service: <path, or `none — create new`>. If present, grep the+> file for `normalizeSummaryString`, `postSummary`, `fetchListSummary`,+> `buildSummaryQuery` — reuse any that already exist rather than redeclaring.+> - Placeholder POSTs to replace at this target (from Phase 2 Explore): <list each as+> `path:line — body`, or write `none` if Phase 2 didn't flag any in this file>+>+> Create or extend the summarization service with raw `fetch`, both required headers, and+> the framework-idiomatic wrapper. Wire the call into the target file with+> loading/error/empty/recommendation handling. If a placeholder POST was flagged for this+> file, **replace it in place** rather than adding a second fetch. Do NOT create a second+> `getCsrfToken` if one already exists.+>+> Return value: structured file-modification list per the agent's "Return value" section+> so the orchestrator can stage commits and assemble the final summary."++---++## Why these fields are passed verbatim++`Target kind`, `$filter`, `$orderby`, and `Scope source` are decided by the orchestrator+during Phase 2 (existing-fetch capture + classification) and Phase 3 (per-target+follow-ups). The agent applies them verbatim — re-deriving scope from the existing fetch+or the user's verbal request risks contradicting a decision the orchestrator already made+with the user.++The `Target's existing list fetch` field is **reference only**. The agent does not modify+or replace the existing fetch; the summary URL is a parallel addition.diff --git a/plugins/power-pages/skills/add-ai-webapi/references/ai-api-reference.md b/plugins/power-pages/skills/add-ai-webapi/references/ai-api-reference.mdnew file mode 100644index 000000000..5c4728330--- /dev/null+++ b/plugins/power-pages/skills/add-ai-webapi/references/ai-api-reference.md@@ -0,0 +1,795 @@+# Power Pages Generative-AI Summarization APIs++Reference for the two Power Pages endpoints that return AI-generated summaries — Search Summary+(`/_api/search/v1.0/summary`) and Data Summarization+(`/_api/summarization/data/v1.0/<entitySet>(<id>)?...`). Both use the same portal session auth — a CSRF+token fetched from `/_layout/tokenhtml` sent as the `__RequestVerificationToken` header. No+`Authorization` bearer is needed.++The Microsoft-shipped support-case Copilot summary is **a configuration of Data Summarization**, not+a third endpoint — same URL family, specific entity set (`incidents`), specific `$select` / `$expand`,+and the canonical `Summarization/prompt/case_summary` identifier. See §3 below.++Sources (Microsoft Learn):++- Search Summary API — https://learn.microsoft.com/power-pages/configure/search/generative-ai#search-summary-api+- Data Summarization API — https://learn.microsoft.com/power-pages/configure/data-summarization-api+- Case-page Copilot preset — https://learn.microsoft.com/power-pages/configure/add-copilot-summarization-to-case-page++---++## Semantics vs. HTTP method — why these rules differ from `/integrate-webapi`++Both endpoints are **semantically reads**: they return an AI-generated summary of content+the caller could already read through the regular Power Pages Web API, and they never mutate+Dataverse. They use **POST** for transport only — because the request carries a body+(`userQuery`, `InstructionIdentifier`, `RecommendationConfig`) that doesn't fit in a GET query+string cleanly.++This matters because the general `/integrate-webapi` rulebook assumes POST means mutation. Several+of those rules do **not** apply here:++| `/integrate-webapi` rule for POST | Why it doesn't apply to AI summarization |+|-----------------------------------|------------------------------------------|+| Set lookup relationships via `[email protected]` | No writes happen — there's nothing to bind. |+| Send `Prefer: return=representation` and handle the `Location` / `OData-EntityId` header | The response always contains the summary body; no record is created. |+| Require `If-Match: *` | That header is for PATCH; not applicable. |+| Table permissions should grant `create: true` / `write: true` for POST callers | AI callers need **`read: true` only**. |+| `Webapi/<table>/fields` should include the primary key for CRUD | Primary key isn't needed — the record id is in the URL path, not a selected column. MS's shipped case preset ships `Webapi/incident/fields = description,title` with no `incidentid`. |+| Lookup columns need both the LogicalName and `_<col>_value` forms | Only the `_<col>_value` read form is needed. The LogicalName write form is only required if the same table has non-AI mutation code elsewhere. |++**Runtime auth path.** When a request hits `/_api/summarization/data/v1.0/<table>(<id>)?...`, the+Power Pages runtime walks this sequence before the generative layer sees any content:++1. Is `Webapi/<table>/enabled = true`? → if not, 403+2. Does the caller's web role have a table permission on `<table>` with `read: true`? → if not, 403+3. Are all columns named in `$select` / `$expand` allowlisted in `Webapi/<table>/fields`? → if not, 403+4. For each `$expand` target, repeat steps 1–3 on that table (and confirm Parent-scope with+ `appendTo: true` on the parent) → if not, 403+5. Is `Summarization/Data/Enable = true`? → if not, error `90041003`+6. Does the `InstructionIdentifier` value correspond to an existing+ `Summarization/prompt/<identifier>` site setting? → if not, error from the summariser++Only after step 6 does the request reach the Azure OpenAI layer that produces the summary. This+is why the `add-ai-webapi` skill orders its work as Phase 4 (Layer 1 + Layer 2 via+`/integrate-webapi` in AI-only read mode) before Phase 6 (Layer 3 via `ai-webapi-settings-architect`)+— Layer 3 can't be validated until Layers 1 and 2 are on disk.++---++## 1. Search Summary API++Summarises search results using generative AI for a user query. Requires that **Site search with generative AI** is enabled in the site's Copilot workspace.++| Method | URI |+|--------|-----|+| POST | `/_api/search/v1.0/summary` |++> **At-a-glance gotchas (full detail below):**+> - **Content-Type:** `application/x-www-form-urlencoded` — *not* `application/json`. JSON returns 400.+> - **Indexed content:** the API grounds on the site's knowledge-article index. A Single Page+> Application (SPA) site with no `knowledgearticle` data (or with the search index not yet+> built) returns empty `Summary` / `Citations`. Verify your site has knowledge articles+> populated and indexed before debugging the API itself.+> - **Citation URLs on SPA sites:** returned as `/page-not-found/?id=<guid>`. Rewrite to your SPA's+> KB route (default `/knowledge/:id`) — see the "Citation URLs on SPA sites" subsection.++**Request body (wire format):**++The Microsoft Learn sample calls this with jQuery as:++```javascript+shell.ajaxSafePost({+ type: "POST",+ url: ".../_api/search/v1.0/summary",+ contentType: "application/x-www-form-urlencoded",+ data: { userQuery: "Fix problems with slow coffee dispense" }+})+```++With that `contentType`, jQuery serialises `data` into a URL-encoded string. The actual wire body is:++```http+Content-Type: application/x-www-form-urlencoded++userQuery=Fix+problems+with+slow+coffee+dispense+```++> **⚠️ Content-Type is the #1 way to break this endpoint.** The Search Summary API **requires**+> `application/x-www-form-urlencoded` — sending `application/json` (even with the correct payload+> shape) returns a 400. This is the opposite of the Data Summarization endpoint, which requires+> JSON. Do **NOT** reuse `buildPowerPagesHeaders()` defaults (or any other shared header helper+> that defaults to `application/json`) without explicitly overriding `contentType` for this call.+> A copy-paste from the data endpoint is the most common source of Search Summary 400s in the+> field.++**Response body:**++```json+{+ "Summary": "To fix slow coffee dispense, descale the boiler[[1]](https://contoso.powerappsportals.com/knowledgebase/article/KA-01055) and verify the pump pressure is within spec[[2]](https://contoso.powerappsportals.com/knowledgebase/article/KA-01092).",+ "SummaryTitle": "Troubleshooting slow coffee dispense",+ "SearchTitle": "Fix problems with slow coffee dispense",+ "Citations": {+ "[1]": "https://contoso.powerappsportals.com/knowledgebase/article/KA-01055",+ "[2]": "https://contoso.powerappsportals.com/knowledgebase/article/KA-01092"+ },+ "CitationTitleMapping": {+ "[1]": "KA-01055 — Descaling the espresso boiler",+ "[2]": "KA-01092 — Pump pressure calibration"+ },+ "Chunks": [+ { "Id": "...", "Title": "...", "Url": "...", "Score": 0.87 }+ ],+ "ErrorMessage": "",+ "ResponseStatus": "Success"+}+```++**Notes:**++- `Summary` embeds citations inline as markdown-style links: `[[N]](url)`. Rendering `{Summary}`+ directly in a `<p>` (or via `v-html` / `innerHTML`) will show raw markdown syntax — the caller+ must parse the token pattern and emit framework-native clickable elements. Do **not**+ pass the raw string through `dangerouslySetInnerHTML` or a markdown renderer; it's a single+ inline token grammar, not general markdown.+- `Citations` is an object keyed by citation tokens (`[1]`, `[2]`, ...) that map tokens to the+ source URL (see "Citation URLs on SPA sites" below for a gotcha).+- `CitationTitleMapping` is an object keyed by the same tokens that maps each token to a+ human-readable title — **use this as the visible label** for citation links and citation-list+ rows, with the URL as a fallback only when the mapping is absent.+- `SummaryTitle` is a short AI-generated heading for the summary block; `SearchTitle` echoes back+ the user's query.+- `Chunks` is an array of the underlying content chunks the summary was grounded on (rarely needed+ by UI code; useful for debugging).+- `ErrorMessage` / `ResponseStatus` are populated on failure (the API returns 200 with a non-empty+ `ErrorMessage` for soft-failures like "no results").+- Enablement is a tenant/site toggle — no per-table `Webapi/*` site setting is required for search summary.+- Faceted search is **not** available when generative AI search is enabled.+- Content snippet `Search/Summary/Title` controls the section heading on the built-in search results page.++**TypeScript shape:**++```ts+export interface SearchSummaryChunk {+ Id?: string;+ Title?: string;+ Url?: string;+ Score?: number;+}++export interface SearchSummaryResponse {+ Summary: string;+ Citations: Record<string, string>;+ // Extras — optional because older server versions omit them, but real tenants return them today.+ SummaryTitle?: string;+ SearchTitle?: string;+ CitationTitleMapping?: Record<string, string>;+ Chunks?: SearchSummaryChunk[];+ ErrorMessage?: string;+ ResponseStatus?: string;+}+```++**Parsing inline citations.** The `Summary` string contains `[[N]](url)` tokens that must be+split into alternating text and citation runs so the UI can render each citation as a clickable+element (with its `CitationTitleMapping[token]` label, or the URL as fallback). Use this helper+verbatim — a hand-rolled `split(/(\[\d+\])/)` is not sufficient because the server embeds the URL+inside the token, not just the `[N]` marker:++```ts+type SummaryPart =+ | { kind: 'text'; text: string }+ | { kind: 'citation'; token: string; url: string };++function parseSummaryWithCitations(summary: string): SummaryPart[] {+ if (!summary) return [];+ const re = /\[\[(\d+)\]\]\(([^)]+)\)/g;+ const parts: SummaryPart[] = [];+ let last = 0;+ let m: RegExpExecArray | null;+ while ((m = re.exec(summary)) !== null) {+ if (m.index > last) parts.push({ kind: 'text', text: summary.slice(last, m.index) });+ parts.push({ kind: 'citation', token: `[${m[1]}]`, url: m[2].trim() });+ last = re.lastIndex;+ }+ if (last < summary.length) parts.push({ kind: 'text', text: summary.slice(last) });+ return parts;+}+```++Render each `citation` part as a framework-native anchor element, using+`CitationTitleMapping[token]` for the visible label when available.++### Citation URLs on SPA sites++On Microsoft-shipped portal templates the `Citations` URLs point at the built-in Knowledge Base+page (`/knowledgebase/article/<articleNumber>`). On **SPA sites** the built-in KB page does+not exist, so the Search Summary service falls back to returning URLs of the form:++```+https://<host>/page-not-found/?id=<knowledgearticleid-guid>+```++The `id` query-string parameter is the actual `knowledgearticleid` GUID from Dataverse. SPAs that+surface knowledge articles typically route them at something like `/knowledge/:id`, so the+citation URL must be rewritten before it's rendered as a clickable link — otherwise every+citation lands on the built-in 404 page.++Drop-in helper for extracting the GUID so callers can reconstruct their own SPA route:++```ts+function extractKnowledgeArticleId(url: string): string | null {+ try {+ const parsed = new URL(url, window.location.origin);+ const id = parsed.searchParams.get('id');+ if (id && /^[0-9a-f-]{36}$/i.test(id)) return id;+ } catch {}+ return null;+}+```++Usage sketch:++```ts+const articleId = extractKnowledgeArticleId(citationUrl);+const href = articleId ? `/knowledge/${articleId}` : citationUrl;+```++Treat a successful `extractKnowledgeArticleId` match as authoritative — it means the server+returned a fallback page-not-found URL with the real GUID attached. A null result means the URL+is a regular site page and should be used verbatim.++### Empty response handling++When no content is indexed for the query, Search Summary returns a 200 with an empty `Summary`+(and typically empty `Citations`, or a non-empty `ErrorMessage` like "No results found"). The UI+must render an explicit empty state ("No related items found") rather than hiding the whole+section — hiding reads as a broken feature because the user sees their query disappear. Branch+the render on `Summary.trim().length === 0` (not just `!Summary`) to catch whitespace-only+responses.++### Gen AI Search disabled state — HTTP 200 with embedded error envelope++**Not documented on Microsoft Learn.** Observed in the wild: when the site-level **Site search+with generative AI (preview)** toggle is off, the Search Summary endpoint returns HTTP 200 with+a body of the form:++```json+{ "Code": 400, "Message": "Gen AI Search is disabled." }+```++No `Summary`, no `Citations`, no other fields. Naive code that checks `response.ok` and then+returns `response.json()` treats this as a success and ends up rendering the empty-state message+("No related items found") — which is misleading because no amount of retry or query tweaking+will fix it. Only a site admin flipping the toggle will.++**Detection rule.** After a 200, if the body has a top-level `Code` (number) and `Message`+(string) and no `Summary`, it is the disabled-state envelope — convert to a typed error instead+of a success response. This is distinct from Data Summarization's `90041001` error, which+arrives as a proper HTTP 400 with `{ error: { code: "90041001", ... } }` (see §2 Error codes).+Different surface, different envelope, same underlying admin toggle.++**Why the server behaves this way.** Search Summary is the only one of the three AI endpoints+gated by a **site-level** toggle rather than per-table site settings — the toggle lives in the+maker's Set up workspace, not in `.powerpages-site/site-settings/`. When the toggle is off, the+endpoint is registered but short-circuits with a canned response body. The HTTP 200 is a quirk+of how the short-circuit path is wired on the server side.++**Enable procedure** (from Microsoft Learn — fetched 2026-04-20):++1. Go to the site's **Set up workspace**+2. Under **Copilot** select **Site search (preview)**+3. Turn on **Enable Site search with generative AI (preview)**++Link to surface in the UI when this state is detected: `https://learn.microsoft.com/power-pages/configure/search/generative-ai#enable-site-search-with-generative-ai`++**UI consequences.**++- Render a specific remediation card in place of the summary: headline "AI search summary is+ turned off for this site", explanation mentioning the workspace path above, and a link to the+ Learn doc. Do NOT show a retry button in this state — retry is useless until the toggle flips.+- Keep the keyword search results (from `/_api/search/v1.0/query`) rendering as normal — the+ toggle only disables the AI summary layer, not keyword search.+- Do NOT treat this as equivalent to the empty-results state ("No related items found") —+ conflating them hides a real configuration problem under a generic "we couldn't find anything"+ message.++The generated service code in `src/services/aiSummaryService.*` handles this via a+`SearchSummaryApiError` exception plus an `isGenAiSearchDisabled(err)` predicate; see the+agent's §3.2 for the reference implementation.++### Troubleshooting: AI feature appears disabled (admin hierarchy)++This checklist applies to **both Search Summary and the Data Summarization API** — the same+Copilot Hub admin surface gates both features. When the maker has flipped the site-level toggle+on but the API still returns a disabled response, the cause is usually higher up in the+hierarchy. Walk the levels top-down; each level **overrides** the one below it.++Admin reference: [Copilot hub for Power Pages (preview)](https://learn.microsoft.com/power-pages/admin/copilot-hub)++**1. Tenant-level governance (PowerShell).** Controlled via the+`enableGenerativeAIFeaturesForSiteUsers` PowerShell setting. If this is off at the tenant level,+nothing downstream can be enabled — admins opening Copilot Hub will see an error prompting them+to enable tenant-level settings first. Only **Power Platform administrator** or **Dynamics 365+administrator** (Azure AD service-admin roles) can change this.++**2. Environment-level governance (Copilot Hub).** Power Platform Admin Center → **Copilot Hub**+→ **Power Pages** tab → **Settings**. Each end-user AI feature (Search summary, Summarization+API, Chat agent, AI form fill, AI summary list) has its own per-feature governance page. For the+selected environment, the admin picks one of:++| Option | Effect |+|--------|--------|+| **On - All sites** | Feature enabled in every site in the environment |+| **All sites except specific sites** | Enabled everywhere **except** listed sites. **Overrides maker config** on the excluded sites. |+| **Specific sites** | Enabled **only** on listed sites. Prevents access in all other sites in the environment. |+| **None of the sites** | Disabled for every site. **Overrides maker config** — even if the maker toggle is on, the feature won't work. |++**The admin setting wins.** If Search Summary returns the disabled envelope even though the+maker toggle is on, check whether this environment/site is excluded here. This is the most+common cause of "the toggle is on but it still says disabled".++**3. Site-level maker toggle.** Set up workspace → Copilot → Site search (preview) → Enable Site+search with generative AI (preview). Only relevant when the two levels above allow it. In the+studio, if admin has disabled the feature at the environment level, **the maker-side toggle+appears greyed out** with an in-product message directing the maker to their admin.++**4. Runtime version.** Copilot Hub requires site runtime **9.7.4.xx or later**. If the site is+on an older runtime, some AI features won't exist — the admin UI may show them but the runtime+won't serve them. Upgrade the site's runtime version before chasing other causes.++**5. Cross-region data movement.** If the environment's region lacks sufficient Azure OpenAI+capacity and the "Move data across regions" setting is **disallowed**, Copilot features+silently fail. Admins can't configure the feature in Copilot Hub in this case. See [Move data+across regions for Copilots and generative AI features](https://learn.microsoft.com/power-platform/admin/geographical-availability-copilot).++**6. Bing search dependency** (chat/search features only). If Bing search is disabled at the+environment level, any Copilot feature that depends on Bing search won't function. Less common+for Summarization API, but worth checking if the symptom is intermittent.++**What end users see when disabled.** Per Microsoft's admin doc, when governance blocks a+feature for end users, *"users see a regular search and don't get a generative AI powered search+summary. Users don't see any messaging about organizational policies or governance controls."*+This is exactly why the generated code surfaces a remediation card on the disabled envelope —+without it, the user sees a silent fallback and thinks the feature is broken, when it was+actually governed off by an admin.++**Deprecated surface.** The older tenant-level governance configuration page is deprecated; all+admin governance now flows through Copilot Hub → Power Pages → Settings. If someone points at+the old governance page during debugging, redirect them — their existing settings are preserved+but new changes must go through the hub.++---++## 2. Data Summarization API++Summarises a single Dataverse record (optionally with expanded related collections) using generative AI. Built on the Power Pages Web API, so all read-operation OData options apply (`$select`, `$expand`, `$filter` inside `$expand`, etc.). **Preview feature.**++| Method | URI |+|--------|-----|+| POST | `/_api/summarization/data/v1.0/<entitySetName>(<recordId>)?<odata-query>` |++**Request body (first request — use a maker-defined prompt):**++```json+{ "InstructionIdentifier": "Summarization/prompt/<table>_instruction_identifier_<usecase>" }+```++**Request body (follow-up — use a recommended prompt from a prior response):**++```json+{ "RecommendationConfig": "<hashed config string from prior response, verbatim>" }+```++- **Exactly one** of `InstructionIdentifier` and `RecommendationConfig` is set per call.+- `InstructionIdentifier` must match a site-setting name that exists — e.g. site setting `Summarization/prompt/case_summary` is identified as `"Summarization/prompt/case_summary"`.+- `RecommendationConfig` is an opaque hashed value that must be sent verbatim; any modification invalidates it.++**Response body:**++```json+{+ "Summary": "The data results provide information…",+ "Recommendations": [+ { "Text": "would you like to know about…?", "Config": "HSYmaicakjvIwTFYeCIjKOyC7nQ4RTSiDJ+/LBK56r4=" }+ ]+}+```++- `Recommendations` is always an array (may be empty). Feed a `Config` back as `RecommendationConfig` to get a refined summary.+- Respects row-level security: only records the user can read are considered.+- Inherits the `$expand` / nested-expand behaviour of the Power Pages Web API — each expanded related table needs its own Web API site settings and table permissions.++### Collection endpoint for list summaries++When the caller wants "N rows the user can see" (e.g., a list of recent work orders for the+signed-in contact) rather than one specific record, use the **collection** form of the URI — not+an account-anchored record form with nested `$expand`.++**Rule — mirror the existing data fetch.** Whenever the target page already fetches a list or a+filtered collection from Dataverse, the summary URL is a mechanical transformation of that+fetch's URL. Do not re-derive `$select` / `$expand` / `$orderby` / `$filter` from scratch — copy+them verbatim so the AI summary covers the exact rows the user is looking at.++```+Existing data fetch: /_api/<entitySet>?<query>+AI summary URL: /_api/summarization/data/v1.0/<entitySet>?<query without $top>+```++And on the request: **do not** send the `Prefer: odata.maxpagesize` header that the paginated+fetch uses. `$top` is UI pagination; the server-side cap for summarization is+`Summarization/Data/ContentSizeLimit` (default `100000` chars). If you carry `$top=25` over, the+AI summary silently covers only those 25 rows even though `ContentSizeLimit` would allow many+more.++**Example 1 — plain list page (invoices list):**++```+List fetch:+ GET /_api/crd50_invoices+ ?$select=crd50_invoiceid,crd50_name,crd50_amount,crd50_invoicestatus,createdon+ &$expand=crd50_ContactId($select=contactid,fullname)+ &$orderby=crd50_submissiondate desc+ &$count=true+ &$top=10++Summary:+ POST /_api/summarization/data/v1.0/crd50_invoices+ ?$select=crd50_invoiceid,crd50_name,crd50_amount,crd50_invoicestatus,createdon+ &$expand=crd50_ContactId($select=contactid,fullname)+ &$orderby=crd50_submissiondate desc+ &$count=true+```++**Example 2 — parent-filtered collection (invoice-attachments subgrid on an invoice form):**++```+Form subgrid fetch:+ GET /_api/crd50_invoiceattachments+ ?$select=crd50_invoiceattachmentid,crd50_name,crd50_filesize,createdon+ &$orderby=createdon desc+ &$count=true+ &$top=25+ &$filter=_crd50_invoiceid_value eq <parent-invoice-guid>++Summary:+ POST /_api/summarization/data/v1.0/crd50_invoiceattachments+ ?$select=crd50_invoiceattachmentid,crd50_name,crd50_filesize,createdon+ &$orderby=createdon desc+ &$count=true+ &$filter=_crd50_invoiceid_value eq <parent-invoice-guid>+```++The **`$filter` must be preserved** — it's what scopes the summary to this parent's attachments+rather than every attachment in the site. Dropping it produces an unrelated summary. This is the+main reason the transformation is mechanical (copy the query) rather than creative (re-derive+the query): the original fetch already encodes the user's scope intent, and recomputing it from+the page's filename or user prompt loses signal.++Full URL template (what the transformation produces):++```+POST /_api/summarization/data/v1.0/<entitySetName>?$select=...+ &$expand=<NavProp>($select=...)+ &$orderby=<col> desc+ &$count=true+ [&$filter=...]+```++The endpoint respects table permissions, so the user only sees rows the row-level security layer+already scopes for them — no explicit record id in the path is needed. Prefer this pattern over+the record form (`accounts(<id>)?$expand=cr363_account_workorder(...)`) for list/history/results+pages because it:++- Eliminates the otherwise-required `/_api/accounts?$top=1` lookup to resolve the anchor id.+- Keeps `$filter` / `$orderby` / `$top` at the root, where they're straightforward — nested+ `$filter;$top;$orderby` inside `$expand` on the record form is fragile.++Use the record form only when the caller genuinely needs a single named record. For+list/history/results pages, default to the collection form.++### Sizing++Prefer **omitting `$top`** for list summaries. The server caps input text via+`Summarization/Data/ContentSizeLimit` (default `100000` characters) and surfaces error+`90041004` when exceeded. Only set `$top` when you have an explicit UX reason (e.g., "top 10+highest-priority tickets"). A hardcoded `$top=25` is usually wrong — it silently caps the data+the user thinks they're summarising.++### List-summary playbook++When the target is a LIST of records (not a single record), the defaults for a single-record+Copilot card (such as the Microsoft-shipped support-case recipe) are the wrong defaults.+Apply every rule below — the orchestrator skill (`/add-ai-webapi`) and the+`ai-webapi-integration` agent both reference this playbook:++1. **Use the collection endpoint** —+ `POST /_api/summarization/data/v1.0/<entitySet>?$select=...` — not the account-anchored+ `accounts(<id>)?$expand=<navprop>` form. Row-level security already scopes the+ collection; the extra `/_api/accounts?$top=1` lookup and fragile nested+ `$filter;$top;$orderby` inside `$expand` are both avoidable. See+ "Collection endpoint for list summaries" above.+2. **Ask "auto-load or button?"** Auto is usually right for short lists; button is safer+ when the collection is large or filters change often.+3. **Scope: mirror the existing list fetch — OR confirm with the user when ambiguous.**+ If the target page has an existing list fetch AND the user's request is generic+ ("add a summary to this list"), mirror `$filter`/`$orderby` from the existing fetch so+ the summary covers the same rows the user sees. `$select` / `$expand` can be supersets+ (add a lookup expand → name for AI context), but never drop columns the UI displays.+ When the user's request contains a scope qualifier the existing fetch doesn't have+ ("open invoices" when the page shows all), OR the target page has no existing list+ fetch at all, **do NOT guess the `$filter` — ASK the user.** Silently inventing an OData+ filter gives the user a summary they didn't ask for. Strip `$top` entirely, and do NOT+ carry over any `Prefer: odata.maxpagesize` header — pagination is UI behaviour, not+ summary scope. Let `Summarization/Data/ContentSizeLimit` govern the server-side cap.+4. **Use the tabular-insight prompt**, not a narrative prompt. The 3-insights /+ <=200-words / no-suggested-actions pattern produces much stronger output than "write a+ 4-sentence narrative". Use the compact template in+ `${CLAUDE_PLUGIN_ROOT}/agents/ai-webapi-settings-architect.md` (~570 chars) so the+ deployed prompt fits the size budget.+5. **Include at most one short domain-neutral few-shot example** (~250 chars) —+ sales-by-region, software purchases, fleet maintenance. Avoid domain-matched examples —+ the model copies example figures instead of grounding on the user's data. Skip the+ example entirely if the combined prompt would exceed 1000 chars.++ **Hard size limits on `Summarization/prompt/<id>` value:** target ≤1000 characters, hard+ ceiling 2000 characters. The `validate-ai-webapi.js` validator blocks the run when any+ prompt exceeds 2000 chars and warns above 1000. The ceiling exists because the+ underlying `adx_sitesetting.adx_value` Memo column defaults to `MaxLength=2000` in many+ environments; exceeding it can cause silent upload truncation or a Dataverse-level+ reject.+6. **Ship `normalizeSummaryString` in the service layer.** The tabular-insight prompt+ returns `Summary` as a JSON-encoded string array; rendering it raw shows `[\"...\"]` in+ the UI.+7. **Ship a tiny safe-markdown renderer** in the UI (React/Vue/Angular/Astro). Insights+ contain `**bold**` and `\n\n` separators; rendering `{summary}` directly shows raw+ asterisks.+8. **Use YAML block-literal** (`value: |` with indented content) for any prompt > 200 chars+ or containing `:`, `|`, `` ` ``, `<|`, `> `, a colon-quote, or a newline. Plain-scalar+ YAML breaks `pac pages upload-code-site` silently for these.+9. **Verify `$expand` nav-property casing** against Dataverse metadata+ (`EntityDefinitions(LogicalName='<primary>')/ManyToOneRelationships` →+ `ReferencedEntityNavigationPropertyName`). The nav prop is PascalCase; the lookup column+ is lowercase. Mismatched casing returns 400.+10. **Always ship `Summarization/Data/ContentSizeLimit = 200000` for list-summary+ targets** — this is required, not optional. The 100k server default silently truncates+ list content *before* it reaches the model, so summaries ship based on partial data+ with no error to catch. `90041004` only fires on overflow; under-overflow truncation is+ invisible. Bump above `200000` only when real data hits `90041004` consistently.++### Summary may be a JSON-encoded string array for list prompts++Prompts that instruct the model to emit "three insights" (the tabular-insight pattern — see+`agents/ai-webapi-settings-architect.md`) return `Summary` as a **JSON-encoded string array**,+not a paragraph:++```+"Summary": "[\"**Insight 1 heading** ...\",\"**Insight 2 heading** ...\",\"**Insight 3 heading** ...\"]"+```++The model follows the "three insights" contract and serialises the list as an array. Rendering+`{payload.Summary}` directly in the UI shows the raw brackets, escaped quotes, and Unicode+escapes (e.g. `\u0027`). Normalise in the shared `postSummary`-style helper in+`aiSummaryService.ts` so every caller gets the normalised shape:++```ts+function normalizeSummaryString(raw: string): string {+ const trimmed = raw.trim()+ if (!trimmed.startsWith('[') || !trimmed.endsWith(']')) return raw+ try {+ const parsed = JSON.parse(trimmed)+ if (Array.isArray(parsed) && parsed.every(x => typeof x === 'string')) {+ return parsed.join('\n\n')+ }+ } catch { /* fall through */ }+ return raw+}+```++Both paragraph and array shapes should continue to work — smoke-test both during rollout.++### Required site settings++| Name | Value | Type | Purpose |+|------|-------|------|---------|+| `Summarization/Data/Enable` | `true` | boolean | Master toggle for the data summarization API |+| `Summarization/prompt/<identifier>` | `<prompt text>` | string | One or more maker-defined prompts; the `<identifier>` portion is referenced by `InstructionIdentifier`. **Size budget: target ≤1000 chars, hard ceiling 2000 chars** — the value lives in `adx_sitesetting.adx_value` (a Memo column whose default `MaxLength` is 2000 in many environments). The `validate-ai-webapi.js` validator blocks runs that exceed 2000 chars and warns above 1000. |+| `Summarization/Data/ContentSizeLimit` | `100000` | integer | Optional. Input-content character cap (default `100000`). **When to raise:** only when a specific list-summary target hits error `90041004` consistently with realistic data volumes. Raise in increments of `50000`, not wholesale — higher limits cost more per call. For list-summary targets, `200000` is a safer default (~500 rows of narrow records). |+| `Webapi/<table>/enabled` | `true` | boolean | **Required** — the table being summarised must also have Web API enabled |+| `Webapi/<table>/fields` | `<validated columns>` | string | Columns the API can read; must include every column named in `$select`/`$expand` |++### Error codes (HTTP 400)++| Code | Message |+|------|---------|+| `90041001` | Generative AI features are disabled |+| `90041003` | Data summarization disabled for this site. Enable using the site setting. |+| `90041004` | Content length exceeds the limit |+| `90041005` | No records found to summarize |+| `90041006` | Error occurred while summarizing the content. |++> **`90041001` can originate from three different levels.** The message says "Generative AI+> features are disabled" but doesn't say *where* they're disabled. Walk the admin hierarchy in+> §1's [*Troubleshooting: AI feature appears disabled*](#troubleshooting-ai-feature-appears-disabled-admin-hierarchy)+> checklist — tenant PowerShell setting, Copilot Hub environment/site governance, and the+> site-level Summarization API toggle each produce this same code. The retry button will not+> help; an admin has to change the governance state. The Copilot Hub governance setting for this+> feature is **Summarization API** (listed separately from Search summary).+>+> **`90041003` vs `90041001`.** `90041003` means the per-site `Summarization/Data/Enable` site+> setting is missing or false — the fix is to run `ai-webapi-settings-architect` (or edit the+> site setting directly). `90041001` is higher in the hierarchy (tenant or environment+> governance) and typically requires admin intervention.++### Empty response handling++Two distinct "empty" shapes can come back from this endpoint and the UI must handle both rather+than hiding the summary section:++1. **Error `90041005` ("No records found to summarize")** — a 400 whose error body contains the+ `90041005` code. Hits when the record exists but every column in `$select` (and every+ `$expand` collection that would contribute content) is empty. Render a calm "No summary+ available for this record yet" message in the summary slot.+2. **200 with empty `Summary` / empty `Recommendations`** — rarer, but possible when the model+ has nothing meaningful to return. Branch on `!response.Summary?.trim()`. Render the same+ empty-state message; keep the section visible so the user can tell the feature is working and+ simply has nothing to summarise yet.++Hiding the entire summary section on empty reads as a broken feature — users interpret the+missing surface as "the Copilot card never loaded". Always render **one of four** branches:+`loading`, `error`, `content`, `empty`. See the agent's Step 5 for the UI contract.++---++## 3. Case-page Copilot preset++The canonical implementation of the data-summarization API for the **incident** (case) table. Shipped by the Customer self-service and Community portal templates as a Copilot summary section on the support case page.++| Field | Value |+|-------|-------|+| Entity set | `incidents` |+| Record id | Case GUID (from `?id=` query string on the case page) |+| `$select` | `description,title` |+| `$expand` | `incident_adx_portalcomments($select=description)` |+| `InstructionIdentifier` | `Summarization/prompt/case_summary` |++**Request URL template:**++```+POST /_api/summarization/data/v1.0/incidents(<caseId>)?$select=description,title&$expand=incident_adx_portalcomments($select=description)+```++**Request body:**++```json+{ "InstructionIdentifier": "Summarization/prompt/case_summary" }+```++### Required site settings for the preset++| Setting description | Name | Value |+|---------------------|------|-------|+| Enable data summarization | `Summarization/Data/Enable` | `true` |+| Prompt for the case summary | `Summarization/prompt/case_summary` | `Summarize key details and critical information` |+| Enable Web API for incident | `Webapi/incident/enabled` | `true` |+| Allowed fields for incident | `Webapi/incident/fields` | `description,title` |+| Enable Web API for portal comments | `Webapi/adx_portalcomment/enabled` | `true` |+| Allowed fields for portal comments | `Webapi/adx_portalcomment/fields` | `description` |++> The `adx_portalcomment` table is expanded via `incident_adx_portalcomments($select=description)` — both tables need Web API site settings **and** table permissions with `read: true`.++### Empty response handling++The Microsoft-shipped support-case configuration trips `90041005` more often than other Data+Summarization configurations because it expands `incident_adx_portalcomments($select=description)`+— a freshly-created case with no comments and a blank `description` has literally nothing to+summarise. Treat `90041005` here as a first-class empty state, not an error: render "No case+summary yet — add a description or a comment and try again" in the summary card (keep the+Copilot-style shell visible, including the gradient border and header) rather than hiding the+section or showing a generic error.++SKILL.md Phase 8's test recipe already tells the user to add at least one comment before+clicking the chevron — surface that same guidance in the empty-state text so testers know why+they're seeing it.++---++## CSRF token handling (both APIs)++Every POST to these endpoints must include the portal anti-forgery token fetched from `/_layout/tokenhtml`. Use raw `fetch` — do **not** route through an OData wrapper that injects Dataverse-specific headers.++```ts+async function getCsrfToken(): Promise<string> {+ const res = await fetch('/_layout/tokenhtml');+ const html = await res.text();+ const match = html.match(/value="([^"]+)"/);+ if (!match) throw new Error('CSRF token not found');+ return match[1];+}+```++Send on every summarization request:++| Header | Search Summary | Data Summarization |+|--------|----------------|--------------------|+| `Content-Type` | `application/x-www-form-urlencoded` | `application/json; charset=utf-8` |+| `Accept` | `application/json` | `application/json` |+| `__RequestVerificationToken` | CSRF token from `/_layout/tokenhtml` | CSRF token from `/_layout/tokenhtml` |+| `X-Requested-With` | `XMLHttpRequest` (recommended — matches `shell.ajaxSafePost`) | `XMLHttpRequest` (recommended — matches `shell.ajaxSafePost`) |+| `OData-MaxVersion` | — | `4.0` |+| `OData-Version` | — | `4.0` |++The CSRF token is explicitly required by the Data Summarization docs. Neither summarization page+documents `X-Requested-With`, but it's part of the `shell.ajaxSafePost` behaviour that Microsoft's+own case-page sample relies on — include it for consistency with stock Power Pages calls.++If a `getCsrfToken` helper already exists elsewhere in the site (for example from `/add-cloud-flow` or an earlier `/add-ai-webapi` run), **reuse it** — do not create a duplicate.++---++## Function-naming convention++| API | Service function | React hook |+|-----|------------------|------------|+| Search summary | `fetchSearchSummary(userQuery: string)` | `useSearchSummary()` |+| Data summarization | `fetchDataSummary(entitySetName: string, recordId: string, options?: DataSummaryOptions)` | `useDataSummary(entitySet, id, options?)` |+| Data summarization (Microsoft-shipped support-case wrapper, optional) | `fetchCaseSummary(caseId: string)` | `useCaseSummary(caseId)` |++`DataSummaryOptions` shape:++```ts+interface DataSummaryOptions {+ select?: string; // $select — comma-separated root columns+ expand?: string; // $expand — nav property(ies) with optional nested $select/$filter/$orderby+ filter?: string; // $filter — rare on the root entity, but supported (all Web API read ops apply)+ orderby?: string; // $orderby — same caveat+ instructionIdentifier?: string; // Set ONE of these two:+ recommendationConfig?: string; // identifier on first call, config on follow-up+}+```++For other frameworks (Vue composable, Angular service, Astro util) follow the same name stems, with the framework's idiomatic wrapper.++---++## Docs quirks (as of the Microsoft Learn pages fetched 2026-04-17)++Three places in the upstream docs are confusing or typo'd. Don't get tripped up by them:++1. **Search-summary "Example: Request" block is jQuery syntax, not an HTTP body.** The Search+ Summary page shows:++ ```+ POST https://contoso.powerappsportals.com/_api/search/v1.0/summary+ {+ data: { userQuery: "Fix problems with slow coffee dispense" }+ }+ ```++ That block is not a literal JSON request body — it's jQuery-style parameters leaking into the+ "HTTP request" formatting. The authoritative shape is the JavaScript sample immediately below it,+ which uses `contentType: "application/x-www-form-urlencoded"` and `data: { userQuery: "..." }`.+ On the wire, the body is `userQuery=Fix+problems+with+slow+coffee+dispense`.++2. **`"Citations'"` with a stray apostrophe in the response sample.** The docs' sample response+ literally prints:++ ```+ "Citations'":{+ "[1]": " https://contoso.powerappsportals.com /knowledgebase/article/KA-01055",+ }+ ```++ The apostrophe and the leading space inside the URL are typos. Real responses return the field+ as `Citations` (no apostrophe) and the URL values have no leading whitespace.++3. **`X-Requested-With: XMLHttpRequest` is not documented but matches stock behaviour.** Neither+ the Search Summary nor the Data Summarization pages list `X-Requested-With`. The Microsoft-shipped+ case-page Copilot snippet uses `shell.ajaxSafePost`, which injects it automatically. The skill+ sets it for consistency with every other Power Pages call; the post-Skill validator warns (but+ does not block) if it's missing.++## Instruction-identifier naming++Use the convention `Summarization/prompt/<table>_instruction_identifier_<usecase>` for maker-defined prompts (e.g. `Summarization/prompt/product_instruction_identifier_overview`, `Summarization/prompt/order_instruction_identifier_timeline`). The case-page preset uses the shorter canonical name `Summarization/prompt/case_summary` — keep it exactly as Microsoft ships it.diff --git a/plugins/power-pages/skills/add-ai-webapi/references/explore-prompt.md b/plugins/power-pages/skills/add-ai-webapi/references/explore-prompt.mdnew file mode 100644index 000000000..e8522afe2--- /dev/null+++ b/plugins/power-pages/skills/add-ai-webapi/references/explore-prompt.md@@ -0,0 +1,178 @@+# Phase 2 Explore-agent prompt — AI integration discovery++Use this prompt verbatim when invoking the Explore agent (`Task` with+`subagent_type: "Explore"`, thoroughness `medium`) during the `add-ai-webapi` skill's+Phase 2.++The agent's job is to find every candidate site for the two summarization APIs (Search+Summary, Data Summarization), classify them, capture each target's existing fetch and any+ambiguity that needs Phase 3 disambiguation, and report the prerequisite status of every+table in scope.++---++## Prompt body (copy verbatim)++> "Analyse this Power Pages SPA site for generative-AI summarization integration opportunities.+> Report the following as structured sections:+>+> **Reserved slot markers (check this first).** Grep the `src/` tree for the comment pattern+> `POWERPAGES:AI-SLOT`. Sites scaffolded by `/create-site` with AI picks in Phase 3 carry these+> markers at the intended insertion point — for example+> `{/* POWERPAGES:AI-SLOT kind=data-summarization */}` in a JSX detail page, or+> `<!-- POWERPAGES:AI-SLOT kind=search-summary -->` in a Vue/Angular/Astro search page.+> Recognised `kind=` values: `search-summary`, `data-summarization`. For every match, report:+>+> - File path and line number of the marker+> - `kind=` value (tells you which API variant the maker already picked)+> - The containing component/page name+>+> These markers are **authoritative placement hints** — when a marker exists for a given target,+> use its file + line as the insertion point and skip the filename heuristic below for that target.+> A marker also tells you that the maker has already committed to adding this AI surface, so treat+> it as high-confidence in the manifest (don't ask 'should we add an AI summary here?' — they+> already decided). Flag the manifest row with `source: marker` so Phase 5 knows the location is+> pre-decided and the agent should remove the marker comment when it inserts the generated code.+>+> If a marker's `kind` doesn't match any natural target page (e.g., a `kind=data-summarization`+> marker on a search results page that has no record-detail context), flag as `orphan-marker` and+> surface it in Phase 3 for the user to resolve — either move the marker or drop the pick. Do not+> silently ignore orphans.+>+> **Search summary candidates.** Find any search page/component (filenames matching `Search*`, or+> components that call `/_api/search/v1.0/query`). Note the file path and whether it currently+> calls `/_api/search/v1.0/summary`. (Note: `*Results*` alone is ambiguous — a file named+> `SearchResults.tsx` is a search-summary target, but `WorkOrderResults.tsx` iterating a Dataverse+> collection is a list-summary target. Classify by what the component fetches, not just the name.)+>+> **Related-record discovery candidates.** Additionally, flag any detail page whose content would+> benefit from surfacing related records via Search Summary — e.g. \"suggested KB articles\" on a+> case/incident page, \"similar cases\" on a ticket page, \"related products\" on a product page.+> These are not necessarily named `Search*`; look for intent signals in component/page names and+> comments (`suggested`, `related`, `similar`, `recommended`, `KB`, `knowledge base`). Search+> Summary's grounded retrieval is often a better fit for this than a hand-rolled OData match+> because it returns AI-ranked citations from across the site's knowledge index. Report each as+> `<page> — recommended Search Summary candidate (related-record discovery)`.+>+> **Data summarization candidates.** For each Dataverse table in `.datamodel-manifest.json`, find+> components that display records from that table. Note the file path, the table logical name, the+> entity set name (plural), the lookup/expand relationships, and whether the component already+> calls `/_api/summarization/data/v1.0/`. Also flag any placeholder posts that already use+> `InstructionIdentifier` in a body like+> `{ \"InstructionIdentifier\": \"Summarization/prompt/<table>_instruction_identifier_<usecase>\" }` —+> these are explicit TODOs for this skill to implement.+>+> **Classify each data-summarization candidate as `single-record` or `list`** using:+>+> - `single-record` — filename contains `Detail`, `View`, or `Edit`; the component reads a record+> id from the route (e.g. `useParams()`, `route.params.id`, `?id=<guid>` in the URL) and fetches+> one record.+> - `list` — filename contains `List`, `History`, `Overview`, `Dashboard`, or the component+> iterates a server-returned collection (maps over an array of records). Be cautious with+> `Results` — a page that renders search hits is a search-summary target; a page that iterates a+> Dataverse collection is a list-summary target. Classify by what the component actually fetches.+>+> This classification drives URL shape (record vs collection form), prompt pattern (narrative vs+> tabular-insight), and default `ContentSizeLimit` downstream. Include it as a column in the+> manifest below.+>+> **Also check for target-kind / user-intent mismatch.** If the filename heuristic says+> `single-record` but the user's verbal request implies a list (plural nouns — \"cases\",+> \"orders\"; scope qualifier — \"all open\", \"my\"; cross-record phrase — \"for this customer's+> history\"), OR vice versa, classify as `intent-mismatch` and flag for Phase 3 disambiguation.+> Do NOT silently pick one interpretation over the other — the target page kind and the user's+> ask can legitimately disagree (e.g., a CaseDetail page where the user wants a summary of the+> customer's other open cases, not this case).+>+> **For every data-summarization candidate (list OR single-record), also capture the existing+> fetch's OData query**: the exact `$select`, `$expand`, `$filter` (list only), and `$orderby`+> (list only) values the component already sends, plus any `Prefer` header. If the target page+> has **no** existing fetch (e.g., a Dashboard or landing page the user wants to decorate with a+> summary card), record `existing fetch: none`.+>+> **Classify the scope** for each candidate by comparing the user's verbal request+> (`$ARGUMENTS`) to the existing fetch. For list targets the scope dimension is `$filter` (which+> rows); for single-record targets the scope dimension is `$select`/`$expand` (which facets of+> the one record). Parse the request for scope qualifiers:+>+> - **List scope qualifiers:** `open`, `overdue`, `recent`, `active`, `pending`, `my`, `all`,+> date ranges, named statuses.+> - **Single-record scope qualifiers:** \"including its <related-table>\", \"with its <facet>\",+> \"covering <aspect>\" — signals the user wants the summary to include columns or expansions+> beyond the existing record fetch. E.g., \"summary including line items\" on an order-detail+> page where the existing fetch doesn't expand `cr363_Order_LineItems`.+>+> Classifications (applies to BOTH list and single-record):+>+> - `matches-existing-fetch` — the request is generic (\"add a summary of this record\",+> \"summarize this list\"). Phase 5 uses the existing fetch's scope verbatim without asking.+> - `scope-extends-beyond-existing-fetch` — the request mentions columns / expansions / filters+> not in the existing fetch. Phase 3 will ask a scope-confirmation question — do NOT invent+> additions in the manifest.+> - `needs-definition` — the target page has no existing fetch at all. Phase 3 will ask.+> - `intent-mismatch` — the filename heuristic and user's verbal intent disagree on target kind+> (e.g., filename says single-record but the request says \"my open cases\" = list). Phase 3+> will ask a target-kind disambiguation question first.+>+> Record the classification plus any detected qualifier as extra fields on the manifest row+> (e.g., `existing fetch: $select=title,description; no $expand. User qualifier: \"with its+> line items\". Scope: scope-extends-beyond-existing-fetch`).+>+> **Existing infrastructure.** Report (a) whether a CSRF helper already exists — grep for+> `_layout/tokenhtml` and `getCsrfToken` — and where it lives; (b) whether+> `src/shared/powerPagesApi.ts` exists (from a prior `/integrate-webapi` run); (c) whether+> `src/services/aiSummaryService.*` already exists from a prior run.+>+> **Layer 1/2 status.** For every Data Summarization target plus every `$expand` target, report+> a single status: does `Webapi/<table>/enabled` exist, does `Webapi/<table>/fields` exist, and+> does at least one table permission with `read: true` exist? Report per target as one of:+> `ready` (all three present), `missing` (any of the three absent). For Search Summary targets,+> report `n/a (search has no per-table prereqs)`.+>+> **Fields-list breadth (advisory).** For every Data Summarization target whose Layer 1/2 status+> is `ready`, also report whether the existing `Webapi/<table>/fields` includes any of:+> (a) the primary key column (`<prefix>_<table>id`); (b) lookup write forms (e.g.+> `cr4fc_categoryid` without the matching `_cr4fc_categoryid_value` read form); (c) columns the+> AI surface won't read. Mark these targets `fields-broader-than-ai-mode` so Phase 3 can surface+> the gap to the user — they can choose to narrow now or accept the broader posture.+>+> **Layer 3 status.** For every Data Summarization target, report whether `Summarization/Data/Enable`+> and the specific `Summarization/prompt/<id>` identifier the code will send exist in+> `.powerpages-site/site-settings/`. For Search Summary targets, report+> `n/a (search uses the Copilot workspace toggle, not a per-call site setting)` — do not flag+> them as `missing`, otherwise the skill will spuriously invoke `ai-webapi-settings-architect`+> for a search-only run."++---++## Manifest shape (compile from the agent's output)++The orchestrator compiles a row per candidate. The `Source` column records whether a row came+from a reserved marker or from heuristic discovery — marker-sourced rows skip Phase 3's+"should we add this?" question.++| # | API | Target file | Target kind | Entity Set | `$select` / `$expand` | Source | Layer 1/2 status | Layer 3 status |+|---|-----|-------------|-------------|-----------|----------------------|--------|------------------|----------------|+| 1 | Search summary | `src/pages/SearchResults.tsx` | n/a | — | — | marker | n/a (search needs no per-table prereqs) | n/a (search uses workspace toggle, no per-setting toggle) |+| 2 | Data summarization | `src/pages/CaseDetail.tsx` | single-record | `incidents` | `$select=description,title&$expand=incident_adx_portalcomments($select=description)` | marker | missing | missing (`Summarization/prompt/case_summary` not present) |+| 3 | Data summarization | `src/pages/ProductDetail.tsx` | single-record | `cr4fc_products` | `$select=cr4fc_name,cr4fc_description` | heuristic | missing | missing (`Summarization/Data/Enable` + prompt identifier not present) |+| 4 | Data summarization | `src/pages/WorkOrderList.tsx` | list | `cr363_workorders` | `$select=cr363_name,cr363_status,cr363_priority&$orderby=createdon desc&$count=true` | heuristic | missing | missing (`Summarization/Data/Enable` + prompt identifier not present; `Summarization/Data/ContentSizeLimit=200000` recommended) |++(Row 2's `$select` / `$expand` / prompt identifier is the Microsoft-shipped support-case+recipe — it appears here because the user picked it explicitly via `/create-site` (the+`POWERPAGES:AI-SLOT` marker), not because the skill auto-detected an `incident` table.)++## Delegation decisions++Compute directly from the two status columns above:++- **Run `/integrate-webapi`?** → True if any row's Layer 1/2 status is `missing`.+- **Run `ai-webapi-settings-architect`?** → True if any row's Layer 3 status is `missing`.++When you delegate to `/integrate-webapi`, send only the **missing** rows in the `tables=`+sentinel value — not the rows whose Layer 1/2 is already `ready`. The sub-skill is being+asked to fill gaps, not re-audit settled tables.++When `fields-broader-than-ai-mode` rows exist, surface them in Phase 3's plan presentation as+a "broader-than-needed" advisory — separate from the Phase 4 delegation decision so the user+can decide whether to narrow.diff --git a/plugins/power-pages/skills/add-ai-webapi/references/framework-equivalents.md b/plugins/power-pages/skills/add-ai-webapi/references/framework-equivalents.mdnew file mode 100644index 000000000..d2529722b--- /dev/null+++ b/plugins/power-pages/skills/add-ai-webapi/references/framework-equivalents.md@@ -0,0 +1,313 @@+# Framework equivalents — non-React UI snippets++The `ai-webapi-integration` agent spells out two UI pieces as **worked React examples**:++1. the **safe-markdown renderer** (`SummaryMarkdown` / `renderInline`) used for list/data+ summaries, and+2. **citation rendering** (`parseSummaryWithCitations` consumer + `resolveCitationHref`) used+ for Search Summary.++This file carries the **Vue (SFC), Angular (component), and Astro** equivalents so non-React+runs are as deterministic as React. The contract is identical across frameworks:++- **Never** use `v-html`, `[innerHTML]`, `dangerouslySetInnerHTML`, or a general markdown+ renderer. The summary string is server content that isn't sanitized for HTML injection;+ render React/Vue/Angular nodes (or escaped text) only.+- Same token set for the markdown renderer: `**bold**` → `<strong>`, `\n\n` → paragraph break,+ `\n` → `<br>` inside a paragraph. No headings, lists, links, code blocks, or tables.+- Citations use the `SummaryPart[]` shape from+ [`ai-api-reference.md`](./ai-api-reference.md) (`{ kind: 'text', text }` |+ `{ kind: 'citation', token, url }`); rewrite hrefs with `extractKnowledgeArticleId` and label+ with `CitationTitleMapping[token]` (falling back to the URL).++Keep `parseSummaryWithCitations`, `extractKnowledgeArticleId`, `normalizeSummaryString`, and+`resolveCitationHref` in the shared `aiSummaryService.*` (or shared utils) — these are+framework-agnostic and must not be redefined per component.++---++## 1. Safe-markdown renderer++Input has already passed through `normalizeSummaryString` (the JSON-array tabular-insight shape+is collapsed to paragraph-separated text before it reaches the UI), so the renderer only handles+`**bold**`, `\n\n`, and `\n`.++### Vue (SFC)++`src/components/SummaryMarkdown.vue` — split into paragraphs, then split each line on the+`**bold**` regex; emit `<strong>` or text spans. No `v-html`.++```vue+<script setup lang="ts">+const props = defineProps<{ text: string }>()++interface Segment { bold: boolean; text: string }+interface Line { segments: Segment[] }+interface Para { lines: Line[] }++function toParagraphs(raw: string): Para[] {+ return raw+ .split(/\n{2,}/)+ .map((p) => p.trim())+ .filter(Boolean)+ .map((p) => ({+ lines: p.split('\n').map((line) => ({ segments: splitBold(line) })),+ }))+}++function splitBold(line: string): Segment[] {+ const out: Segment[] = []+ const re = /\*\*([^*]+?)\*\*/g+ let last = 0+ let m: RegExpExecArray | null+ while ((m = re.exec(line)) !== null) {+ if (m.index > last) out.push({ bold: false, text: line.slice(last, m.index) })+ out.push({ bold: true, text: m[1] })+ last = re.lastIndex+ }+ if (last < line.length) out.push({ bold: false, text: line.slice(last) })+ return out+}+</script>++<template>+ <div>+ <p v-for="(para, pi) in toParagraphs(text)" :key="pi">+ <template v-for="(line, li) in para.lines" :key="li">+ <template v-for="(seg, si) in line.segments" :key="si">+ <strong v-if="seg.bold">{{ seg.text }}</strong>+ <span v-else>{{ seg.text }}</span>+ </template>+ <br v-if="li < para.lines.length - 1" />+ </template>+ </p>+ </div>+</template>+```++### Angular++`src/app/components/summary-markdown.component.ts` — a pure component with `text` as `@Input()`,+rendering the same paragraph/line/segment structure with `*ngFor` / `*ngIf`. No `[innerHTML]`.++```ts+import { Component, Input } from '@angular/core';++interface Segment { bold: boolean; text: string; }+interface Line { segments: Segment[]; }+interface Para { lines: Line[]; }++@Component({+ selector: 'app-summary-markdown',+ template: `+ <div>+ <p *ngFor="let para of paragraphs">+ <ng-container *ngFor="let line of para.lines; let li = index">+ <ng-container *ngFor="let seg of line.segments">+ <strong *ngIf="seg.bold">{{ seg.text }}</strong>+ <span *ngIf="!seg.bold">{{ seg.text }}</span>+ </ng-container>+ <br *ngIf="li < para.lines.length - 1" />+ </ng-container>+ </p>+ </div>+ `,+})+export class SummaryMarkdownComponent {+ paragraphs: Para[] = [];++ @Input() set text(raw: string) {+ this.paragraphs = (raw ?? '')+ .split(/\n{2,}/)+ .map((p) => p.trim())+ .filter(Boolean)+ .map((p) => ({ lines: p.split('\n').map((line) => ({ segments: this.splitBold(line) })) }));+ }++ private splitBold(line: string): Segment[] {+ const out: Segment[] = [];+ const re = /\*\*([^*]+?)\*\*/g;+ let last = 0;+ let m: RegExpExecArray | null;+ while ((m = re.exec(line)) !== null) {+ if (m.index > last) out.push({ bold: false, text: line.slice(last, m.index) });+ out.push({ bold: true, text: m[1] });+ last = re.lastIndex;+ }+ if (last < line.length) out.push({ bold: false, text: line.slice(last) });+ return out;+ }+}+```++### Astro++If the site mounts React/Vue islands, reuse the island component rather than duplicating the+logic. For a pure-Astro component, do the parsing in the frontmatter and iterate in the template+— Astro escapes `{...}` expressions by default, so plain text interpolation is safe.++```astro+---+interface Props { text: string }+const { text } = Astro.props++const paragraphs = text+ .split(/\n{2,}/)+ .map((p) => p.trim())+ .filter(Boolean)+ .map((p) =>+ p.split('\n').map((line) => {+ const segs: { bold: boolean; text: string }[] = []+ const re = /\*\*([^*]+?)\*\*/g+ let last = 0+ let m: RegExpExecArray | null+ while ((m = re.exec(line)) !== null) {+ if (m.index > last) segs.push({ bold: false, text: line.slice(last, m.index) })+ segs.push({ bold: true, text: m[1] })+ last = re.lastIndex+ }+ if (last < line.length) segs.push({ bold: false, text: line.slice(last) })+ return segs+ }),+ )+---+<div>+ {paragraphs.map((lines) => (+ <p>+ {lines.map((segs, li) => (+ <>+ {segs.map((seg) => (seg.bold ? <strong>{seg.text}</strong> : <span>{seg.text}</span>))}+ {li < lines.length - 1 && <br />}+ </>+ ))}+ </p>+ ))}+</div>+```++---++## 2. Citation rendering (Search Summary)++`parseSummaryWithCitations(Summary)` returns `SummaryPart[]`. Emit framework-native anchors for+`citation` parts; rewrite the href via `resolveCitationHref` (which calls+`extractKnowledgeArticleId` and falls back to the raw URL on SPA sites); label with+`CitationTitleMapping[token]` falling back to the URL, then the bare token. Keep the visible text+as the token so inline citations stay scannable.++`resolveCitationHref` is shared (define once in the service):++```ts+import { extractKnowledgeArticleId } from '../services/aiSummaryService';++export function resolveCitationHref(url: string): string {+ const articleId = extractKnowledgeArticleId(url);+ return articleId ? `/knowledge/${articleId}` : url; // confirm the project's actual KB route+}+```++### Vue (SFC)++```vue+<script setup lang="ts">+import { parseSummaryWithCitations } from '../services/aiSummaryService'+import { resolveCitationHref } from '../services/citations'++const props = defineProps<{+ summary: string+ citationTitleMapping?: Record<string, string>+}>()++const parts = parseSummaryWithCitations(props.summary)+const label = (token: string, url: string) =>+ props.citationTitleMapping?.[token] ?? url ?? token+</script>++<template>+ <p>+ <template v-for="(part, i) in parts" :key="i">+ <span v-if="part.kind === 'text'">{{ part.text }}</span>+ <a+ v-else+ :href="resolveCitationHref(part.url)"+ :title="label(part.token, part.url)"+ target="_blank"+ rel="noopener noreferrer"+ >{{ part.token }}</a+ >+ </template>+ </p>+</template>+```++### Angular++```ts+import { Component, Input } from '@angular/core';+import { parseSummaryWithCitations } from '../services/aiSummaryService';+import { resolveCitationHref } from '../services/citations';++@Component({+ selector: 'app-summary-with-citations',+ template: `+ <p>+ <ng-container *ngFor="let part of parts">+ <span *ngIf="part.kind === 'text'">{{ part.text }}</span>+ <a+ *ngIf="part.kind === 'citation'"+ [href]="resolveCitationHref(part.url)"+ [title]="label(part.token, part.url)"+ target="_blank"+ rel="noopener noreferrer"+ >{{ part.token }}</a+ >+ </ng-container>+ </p>+ `,+})+export class SummaryWithCitationsComponent {+ @Input() summary = '';+ @Input() citationTitleMapping?: Record<string, string>;+ resolveCitationHref = resolveCitationHref;++ get parts() {+ return parseSummaryWithCitations(this.summary);+ }++ label(token: string, url: string): string {+ return this.citationTitleMapping?.[token] ?? url ?? token;+ }+}+```++### Astro++```astro+---+import { parseSummaryWithCitations } from '../services/aiSummaryService'+import { resolveCitationHref } from '../services/citations'++interface Props { summary: string; citationTitleMapping?: Record<string, string> }+const { summary, citationTitleMapping } = Astro.props+const parts = parseSummaryWithCitations(summary)+const label = (token: string, url: string) => citationTitleMapping?.[token] ?? url ?? token+---+<p>+ {parts.map((part) =>+ part.kind === 'text' ? (+ <span>{part.text}</span>+ ) : (+ <a+ href={resolveCitationHref(part.url)}+ title={label(part.token, part.url)}+ target="_blank"+ rel="noopener noreferrer"+ >{part.token}</a>+ ),+ )}+</p>+```++> **Citation list ("Sources" footer).** The visible label for each row is+> `CitationTitleMapping[token]`; fall back to the URL **only** when the mapping is missing.+> Never show a bare URL when a mapping exists — it reads as broken UI.diff --git a/plugins/power-pages/skills/add-ai-webapi/references/scope-classification.md b/plugins/power-pages/skills/add-ai-webapi/references/scope-classification.mdnew file mode 100644index 000000000..096f363c9--- /dev/null+++ b/plugins/power-pages/skills/add-ai-webapi/references/scope-classification.md@@ -0,0 +1,102 @@+# Phase 3 follow-up questions — list trigger and scope confirmation++After the user confirms which APIs / targets to integrate (Phase 3 main question), the+orchestrator asks per-target follow-ups for:++- **List-trigger choice** — every confirmed list target (one question per list target).+- **Scope confirmation** — every target Phase 2 flagged `scope-extends-beyond-existing-fetch`,+ `needs-definition`, or `intent-mismatch`. The question text varies by target kind and+ classification.++Skip both follow-ups when the corresponding flag isn't set on the row.++Each chosen value flows into Phase 5's agent-invocation prompt — the Phase 5 agent does NOT+re-derive scope from the existing fetch. The original UI fetch on the target component stays+in place unchanged regardless of what scope the summary uses.++---++## List-trigger follow-up (one per list target)++For every confirmed target whose page renders a **collection** of records (filename matches+`*List*`, `*History*`, `*Results*`, or the target component iterates a server-returned array+in the UI), ask:++| Question | Header | Options |+|----------|--------|---------|+| Should the summary appear automatically when the page opens, or only when the user clicks a button? | Trigger | Load the summary when the page opens (Recommended when the list is short and the extra API call won't slow the page noticeably), Load only when the user clicks a button (Recommended when the list is large or filters change frequently) |++Single-record summary targets (any record-detail page, including the support-case detail+page) skip this question — single-record summaries always trigger on a user action.++Both options produce the same hook/composable surface (`refresh`,+`summariseWithRecommendation`); only the initial state of the wrapper differs. Record the+choice per target and pass it to the `ai-webapi-integration` agent in Phase 5 so it wires+the correct initial trigger.++---++## Scope-confirmation follow-up++Ask only when Phase 2 flagged the target with one of these classifications. The question+text varies by target kind and classification.++### LIST target — `scope-extends-beyond-existing-fetch`++User qualifier detected; existing list fetch has a different or no `$filter`.++| Question | Header | Options |+|----------|--------|---------|+| You asked for a summary of `<user qualifier>` `<entity>`. The existing list on this page currently shows `<existing scope description>`. Which scope should the summary cover? | Scope | Use my scope — `$filter=<filter derived from the verbal qualifier>` (Recommended), Mirror the existing list — `$filter=<existing $filter or "none">`, Let me write the OData `$filter`, Both — create two summary cards (advanced) |++### LIST target — `needs-definition`++Target page has no existing list fetch.++| Question | Header | Options |+|----------|--------|---------|+| The target page has no existing list to mirror. Which rows should the summary cover? | Scope | Use my scope — `$filter=<filter derived from the verbal qualifier>` (Recommended), Summarise all `<entity>` rows the signed-in user can see (no filter beyond row-level security), Let me write the OData `$filter` |++### SINGLE-RECORD target — `scope-extends-beyond-existing-fetch`++User mentions facets / related records not in the existing record fetch — e.g., "include its+line items" when the fetch has no `$expand`.++| Question | Header | Options |+|----------|--------|---------|+| Your request mentions `<user qualifier>` — this isn't in the existing record fetch (which selects `<existing $select>`). Which facets should the summary include? | Facets | Include the mentioned facets — `$select=<baseline>,<added columns>`, `$expand=<added expansions with nav-prop casing>` (Recommended), Use the existing fetch's columns only (no additions), Let me write the `$select`/`$expand` |++Translate the qualifier to concrete columns / expansions using the datamodel manifest — e.g.,+"include its line items" on `cr363_order` with a related `cr363_orderlineitem` table via a+`cr363_Order_LineItems` navigation property maps to+`$expand=cr363_Order_LineItems($select=<lineitem primary name + amount>)`. Show the proposed+value inside the option. **Any new `$expand` target becomes a new Phase 4 prerequisite** (Web+API enabled + parent-scope permission on the child table) — re-evaluate the Phase 2+delegation decision after the user picks.++### Any target — `intent-mismatch`++Filename heuristic and the user's verbal intent disagree on target kind (filename says+single-record, request says "my open cases" → list; or vice versa).++| Question | Header | Options |+|----------|--------|---------|+| The target page is `<filename>` (looks like `<filename-classification>`). Your request mentions `<user-verbal-qualifier>` — that sounds more like a `<other-classification>`. Which do you want? | Target kind | `<user-verbal-classification>` — <describe what the summary would cover> (Recommended — matches your ask), `<filename-classification>` — <describe the alternative>, Both — wire two summary cards on the same page |++Resolve `intent-mismatch` **before** any scope-confirmation question — the chosen target+kind decides which scope question (LIST or SINGLE-RECORD form) to ask next.++---++## Handling the chosen values to Phase 5++Phase 5's `ai-webapi-integration` agent-invocation prompt has a structured **Scope for the+summary call** block. Populate:++- `$filter` — the exact filter string (or `none`).+- `$orderby` — typically mirrors the existing fetch.+- `Scope source` — one of `mirror-existing-fetch`, `user-verbal-scope`,+ `user-custom-odata`, `no-filter`, `both` (for the dual-summary advanced option).+- `Target's existing list fetch` — for reference only, never as an override target.++The agent applies these verbatim and does not re-read the existing fetch.diff --git a/plugins/power-pages/skills/add-ai-webapi/scripts/validate-ai-webapi.js b/plugins/power-pages/skills/add-ai-webapi/scripts/validate-ai-webapi.jsnew file mode 100644index 000000000..1963ec4de--- /dev/null+++ b/plugins/power-pages/skills/add-ai-webapi/scripts/validate-ai-webapi.js@@ -0,0 +1,402 @@+#!/usr/bin/env node++// Validates that the add-ai-webapi skill produced AI summarization integration code.+// Runs as the PostToolUse Skill hook validator.+//+// A valid run must produce at least one of:+// - a search-summary service that POSTs to /_api/search/v1.0/summary+// - a data-summarization service that POSTs to /_api/summarization/data/v1.0/+//+// Blocking checks (these are documented or structural and break the API at runtime). All are+// project-wide: the required token must appear somewhere under src/, not necessarily in the same+// file as the endpoint URL — a correct integration commonly centralizes header and URL+// construction in a shared helper (the same pattern validate-webapi-integration.js accepts for+// powerPagesApi.ts), so a per-file requirement would false-fail those projects.+// - The integration must attach the __RequestVerificationToken header. The Data Summarization+// docs require a CSRF token on these POST requests; omitting it produces a token-validation+// failure. (These endpoints are semantically read-only — they never mutate Dataverse — but the+// runtime enforces CSRF on POST regardless of mutation semantics, so the token is still required.)+// - Data summarization must include $select — Power Pages Web API never allows wildcard columns,+// and the Microsoft sample URL has $select.+// - Data summarization must set OData-MaxVersion: 4.0 and OData-Version: 4.0. The endpoint+// inherits the Power Pages Web API rules and rejects requests without the OData version headers.+// - Search Summary must use Content-Type: application/x-www-form-urlencoded. The endpoint rejects+// application/json with a 400 — this is the most common copy-paste failure when the data+// endpoint's headers leak into the search call.+//+// Advisory only (missing prints a warning but does not block):+// - X-Requested-With: XMLHttpRequest — matches shell.ajaxSafePost's default behaviour+// used by the Microsoft-shipped case-page Copilot snippet, but neither summarization+// doc mandates it. Worth flagging so reviewers can confirm it was intentional.+// - Search Summary citation parsing — the API embeds [[N]](url) markdown tokens inline+// in Summary. Rendering Summary directly shows raw markdown. Warn when no source file+// references parseSummaryWithCitations or contains a [[N]](url) parsing pattern.+// - Search Summary KB-id rewrite — on Single Page Application (SPA) sites the API returns+// /page-not-found/?id=<guid> citation URLs that need rewriting to the SPA's KB route.+// Warn when search-summary code is present but no file references+// extractKnowledgeArticleId (or an equivalent inline rewrite).+// - Search Summary disabled-state envelope — the endpoint returns HTTP 200 with+// { Code, Message } when the site-level Gen AI Search toggle is off. Naive code+// treats this as a success. Warn when search code is present but no file references+// SearchSummaryApiError / isGenAiSearchDisabled (or an equivalent inline detection+// of body.Code + body.Message).+// - List-summary ContentSizeLimit — when fetchListSummary appears in source, the+// Summarization/Data/ContentSizeLimit site setting must be present at >= 200000.+// The 100k server default silently truncates list content; truncation is invisible+// (no error code), so summaries ship based on partial data. Warn when the YAML is+// missing or its value is below 200000.+// - Plain-scalar Summarization/prompt/* values > 200 chars. Plain-scalar YAML breaks+// pac pages upload-code-site silently when prompts contain ": ", "|", "<|", colons-+// followed-by-quotes, or newlines — and any prompt > 200 chars is likely to hit one+// of those. Warn so the maker switches to block-literal (value: |) before deploy.+//+// Blocking checks (these will refuse the run):+// - Summarization/prompt/* size > 2000 chars. The adx_sitesetting.adx_value column has+// a default Memo MaxLength of 2000 in older environments, so a longer value can fail+// the Dataverse upload silently or produce a truncated prompt at runtime. 2000 is the+// hard ceiling we support.+//+// Advisory only:+// - Summarization/prompt/* size > 1000 chars. Long prompts cost more per call and are+// harder to maintain. Warn so makers can compress before hitting the 2000 ceiling.++const fs = require('fs');+const path = require('path');+const { approve, block, runValidation, findProjectRoot } = require('../../../scripts/lib/validation-helpers');+const { validatePowerPagesSchema } = require('../../../scripts/lib/powerpages-schema-validator');++const SEARCH_SUMMARY_URL = '/_api/search/v1.0/summary';+const DATA_SUMMARIZATION_URL = '/_api/summarization/data/v1.0/';+const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.vue', '.astro']);++runValidation((cwd) => {+ const projectRoot = findProjectRoot(cwd);+ if (!projectRoot) approve();++ const srcDir = path.join(projectRoot, 'src');+ if (!fs.existsSync(srcDir)) approve();++ const sourceFiles = collectSourceFiles(srcDir);+ const hits = [];++ for (const file of sourceFiles) {+ let content;+ try {+ content = fs.readFileSync(file, 'utf8');+ } catch {+ continue;+ }+ const hasSearch = content.includes(SEARCH_SUMMARY_URL);+ const hasData = content.includes(DATA_SUMMARIZATION_URL);+ if (hasSearch || hasData) {+ hits.push({ file, content, hasSearch, hasData });+ }+ }++ if (hits.length === 0) approve();++ const errors = [];+ const warnings = [];++ // Header and URL-token checks are project-wide, not per-file. A correct integration commonly+ // centralizes header construction and URL building in a shared helper (the same pattern+ // validate-webapi-integration.js accepts for powerPagesApi.ts), so requiring every token to+ // appear in the same file as the endpoint URL would false-fail those projects. We read the+ // whole src/ tree once and block only when a required token is absent project-wide.+ const allContent = sourceFiles+ .map((f) => {+ try {+ return fs.readFileSync(f, 'utf8');+ } catch {+ return '';+ }+ })+ .join('\n');++ const projectHasData = hits.some((h) => h.hasData);+ const projectHasSearchSummary = hits.some((h) => h.hasSearch);++ if (!allContent.includes('__RequestVerificationToken')) {+ errors.push(+ 'summarization integration is missing the __RequestVerificationToken header anywhere under src/ (CSRF token is required on these POST requests — fetch it from /_layout/tokenhtml)'+ );+ }+ if (!allContent.includes('X-Requested-With')) {+ warnings.push(+ 'summarization integration does not set the X-Requested-With: XMLHttpRequest header anywhere under src/ (not strictly required by the docs, but matches shell.ajaxSafePost behaviour used by the Microsoft case-page snippet)'+ );+ }+ if (projectHasData) {+ if (!/\$select=/.test(allContent)) {+ errors.push(+ 'data summarization integration is missing $select anywhere under src/ — Power Pages Web API requires explicit column lists, never wildcards'+ );+ }+ // OData 4.0 headers are mandatory on the data-summarization endpoint — it inherits+ // the Power Pages Web API rules and rejects requests without them.+ if (!allContent.includes('OData-MaxVersion')) {+ errors.push(+ 'data summarization integration is missing the OData-MaxVersion: 4.0 header anywhere under src/ — the Power Pages Web API rejects requests without it'+ );+ }+ if (!allContent.includes('OData-Version')) {+ errors.push(+ 'data summarization integration is missing the OData-Version: 4.0 header anywhere under src/ — the Power Pages Web API rejects requests without it'+ );+ }+ }+ if (projectHasSearchSummary) {+ // Search Summary requires application/x-www-form-urlencoded. Sending application/json+ // (the most common copy-paste failure from the data endpoint) returns 400.+ if (!allContent.includes('application/x-www-form-urlencoded')) {+ errors.push(+ 'Search Summary integration is missing Content-Type: application/x-www-form-urlencoded anywhere under src/ — sending application/json returns 400 (this is the #1 way to break /_api/search/v1.0/summary)'+ );+ }+ }++ // Project-wide checks for Search Summary UI rendering. The parser/rewrite typically lives in a+ // UI component (or a shared util), not the file containing the fetch call. We only run them when+ // the project actually calls /_api/search/v1.0/summary somewhere.+ if (projectHasSearchSummary) {+ // [[N]](url) parser: either by helper name or by a pattern that handles the token.+ // The documented parser is a regex literal `/\[\[(\d+)\]\]\(([^)]+)\)/`, so the source+ // text contains the escaped-bracket characters `\[\[ ... \]\]\(`. Match that form (any+ // capture-group content between the escaped brackets), or a literal `[[N]](` token.+ const usesParserHelper = allContent.includes('parseSummaryWithCitations');+ const handlesTokenInline =+ /\\\[\\\[.*?\\\]\\\]\\\(/.test(allContent) || /\[\[\d+\]\]\(/.test(allContent);+ if (!usesParserHelper && !handlesTokenInline) {+ warnings.push(+ 'Search Summary is integrated but no source file references parseSummaryWithCitations or a [[N]](url) parsing pattern — Summary will render as raw markdown unless a parser is wired in.'+ );+ }++ // KB-id rewrite for SPA sites: either by helper name or by inline reading of ?id=<guid>.+ const usesRewriteHelper = allContent.includes('extractKnowledgeArticleId');+ const handlesRewriteInline = /searchParams\.get\(\s*['"]id['"]\s*\)/.test(allContent);+ if (!usesRewriteHelper && !handlesRewriteInline) {+ warnings.push(+ "Search Summary is integrated but no source file references extractKnowledgeArticleId or reads the citation URL's ?id parameter — citation links will land on the built-in /page-not-found page on SPA sites."+ );+ }++ // Disabled-state envelope: the endpoint returns HTTP 200 with { Code, Message } when+ // the site-level Gen AI Search toggle is off. Naive code that calls response.json() on+ // a 200 treats this as success and renders the empty-state message. Detection can be+ // by helper name (SearchSummaryApiError / isGenAiSearchDisabled) or by an inline check+ // that pattern-matches body.Code (number) + body.Message (string) without a Summary.+ const usesDisabledHelper =+ allContent.includes('SearchSummaryApiError') || allContent.includes('isGenAiSearchDisabled');+ const handlesDisabledInline =+ /\.\s*Code\s*[=!]==?/.test(allContent) && /\.\s*Message\s*[=!]==?/.test(allContent);+ if (!usesDisabledHelper && !handlesDisabledInline) {+ warnings.push(+ 'Search Summary is integrated but no source file references SearchSummaryApiError / isGenAiSearchDisabled or detects the embedded { Code, Message } envelope inline — when the site-level Gen AI Search toggle is off, the endpoint returns HTTP 200 with that envelope and the UI will silently render the empty-state message. See agents/ai-webapi-integration.md §3.2.'+ );+ }+ }++ // List-summary check: when fetchListSummary is referenced, ContentSizeLimit must be >= 200000.+ // The collection endpoint silently truncates input content at the server-side cap; the 100k+ // default produces summaries based on partial data with no error to catch.+ const projectHasListSummary = sourceFiles.some((f) => {+ try {+ return fs.readFileSync(f, 'utf8').includes('fetchListSummary');+ } catch {+ return false;+ }+ });+ if (projectHasListSummary) {+ const settingPath = path.join(+ projectRoot,+ '.powerpages-site',+ 'site-settings',+ 'Summarization-Data-ContentSizeLimit.sitesetting.yml'+ );+ let yaml = null;+ try {+ yaml = fs.readFileSync(settingPath, 'utf8');+ } catch {+ yaml = null;+ }+ if (yaml === null) {+ warnings.push(+ 'List summary (fetchListSummary) is integrated but Summarization-Data-ContentSizeLimit.sitesetting.yml is missing — the 100k server default will silently truncate list content. Set Summarization/Data/ContentSizeLimit = 200000.'+ );+ } else {+ // Reuse extractSiteSettingValue so block-literal YAML (`value: |\n 200000`) is parsed as+ // well as plain/quoted scalars. ContentSizeLimit is conventionally a plain integer, but a+ // hand-written block-literal would otherwise slip past validation silently.+ const rawValue = extractSiteSettingValue(yaml);+ const trimmedValue = rawValue !== null ? rawValue.trim() : '';+ const numericValue = /^\d+$/.test(trimmedValue) ? parseInt(trimmedValue, 10) : null;+ if (numericValue === null) {+ warnings.push(+ 'Summarization-Data-ContentSizeLimit.sitesetting.yml exists but its `value` field is not a parseable integer — list-summary truncation cannot be verified. Set value: 200000.'+ );+ } else if (numericValue < 200000) {+ warnings.push(+ `Summarization/Data/ContentSizeLimit is ${numericValue}; list summaries should use at least 200000 to avoid silent truncation of ~500-row payloads.`+ );+ }+ }+ }++ // Summarization/prompt/* size check.+ // The prompt is stored in adx_sitesetting.adx_value (Memo column). Default Memo MaxLength is 2000+ // in many environments, so we treat 2000 as the hard ceiling. We also warn at 1000 — long prompts+ // cost more per summarization call and are harder to maintain.+ const siteSettingsDir = path.join(projectRoot, '.powerpages-site', 'site-settings');+ if (fs.existsSync(siteSettingsDir)) {+ let entries = [];+ try {+ entries = fs.readdirSync(siteSettingsDir);+ } catch {+ entries = [];+ }+ for (const entry of entries) {+ if (!entry.startsWith('Summarization-prompt-') || !entry.endsWith('.sitesetting.yml')) continue;+ const filePath = path.join(siteSettingsDir, entry);+ let yaml;+ try {+ yaml = fs.readFileSync(filePath, 'utf8');+ } catch {+ continue;+ }+ const promptValue = extractSiteSettingValue(yaml);+ if (promptValue === null) continue;+ const charCount = promptValue.length;+ if (charCount > 2000) {+ errors.push(+ `${entry}: prompt value is ${charCount} characters, exceeding the supported maximum of 2000. Shorten this site-setting prompt — condense or drop inline examples within the prompt text. The Data Summarization request body does not accept prompt text (only InstructionIdentifier / RecommendationConfig), so the full instruction must fit in this site-setting value.`+ );+ } else if (charCount > 1000) {+ warnings.push(+ `${entry}: prompt value is ${charCount} characters; aim for ≤1000 to keep prompts compact and maintainable. Hard ceiling is 2000.`+ );+ }+ // Plain-scalar prompts > 200 chars are likely to break pac pages upload-code-site+ // silently because long prompts almost always contain ": ", "|", "<|", or newlines —+ // any of which trip plain-scalar YAML parsing. Block-literal (value: |) is the+ // documented safe form. See agents/ai-webapi-settings-architect.md §5.1a.+ if (charCount > 200 && isPlainScalarValue(yaml)) {+ warnings.push(+ `${entry}: prompt value is ${charCount} characters and uses plain-scalar YAML (value: <text>). Plain-scalar parsing breaks pac pages upload-code-site for prompts containing ": ", "|", "<|", or newlines — any of which is likely above 200 chars. Switch to block-literal form (value: |\\n <prompt body indented 2 spaces>).`+ );+ }+ }+ }++ const schemaValidation = validatePowerPagesSchema(projectRoot);+ const schemaErrors = schemaValidation.findings+ .filter(finding => finding.severity === 'error')+ .map(finding => finding.filePath ? `${finding.message} (${path.basename(finding.filePath)})` : finding.message);++ if (schemaErrors.length > 0) {+ errors.push('Invalid Power Pages permissions/site-settings schema:\n - ' + schemaErrors.join('\n - '));+ }++ if (warnings.length > 0) {+ process.stderr.write('AI summarization integration warnings:\n- ' + warnings.join('\n- ') + '\n');+ }++ if (errors.length > 0) {+ block('AI summarization integration validation failed:\n- ' + errors.join('\n- '));+ }++ approve();+});++// Extract the `value:` field from a site-setting YAML. Handles four shapes:+// plain: value: some text+// quoted: value: "some text" or value: 'some text'+// block-literal: value: |+// indented+// multi-line content+// folded-scalar: value: >+// paragraph one+// continuation+//+// For block-literal and folded-scalar we read the indented block the same way and join with+// newlines. Folded scalar would render newlines as spaces at runtime, so the joined string+// is a slight over-estimate of the runtime length — that's acceptable for the size guard.+// Returns the string value, or null if the file has no `value:` key.+function extractSiteSettingValue(yaml) {+ const lines = yaml.split(/\r?\n/);+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ const blockMatch = line.match(/^value\s*:\s*[|>][+-]?\s*$/);+ if (blockMatch) {+ // Collect subsequent indented lines until indentation drops back to column 0 (or non-blank line at column 0).+ const collected = [];+ let baseIndent = null;+ for (let j = i + 1; j < lines.length; j++) {+ const next = lines[j];+ if (next.trim() === '') {+ collected.push('');+ continue;+ }+ const indentMatch = next.match(/^(\s+)/);+ if (!indentMatch) break; // dedent — block ended+ const indent = indentMatch[1].length;+ if (baseIndent === null) baseIndent = indent;+ if (indent < baseIndent) break;+ collected.push(next.slice(baseIndent));+ }+ return collected.join('\n').replace(/\n+$/, '');+ }+ const inlineMatch = line.match(/^value\s*:\s*(.*)$/);+ if (inlineMatch) {+ let raw = inlineMatch[1].trim();+ if (raw === '') return '';+ // Strip matching outer quotes (single or double).+ if (+ (raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2) ||+ (raw.startsWith("'") && raw.endsWith("'") && raw.length >= 2)+ ) {+ raw = raw.slice(1, -1);+ }+ return raw;+ }+ }+ return null;+}++// Returns true when the YAML stores `value` as a plain (non-block) scalar — i.e. inline+// after the colon, optionally quoted. Block-literal (`value: |`) and folded-scalar+// (`value: >`) return false. Used to flag long prompts that should be migrated to+// block-literal form to avoid pac pages upload-code-site parsing failures.+function isPlainScalarValue(yaml) {+ const lines = yaml.split(/\r?\n/);+ for (const line of lines) {+ if (/^value\s*:\s*[|>][+-]?\s*$/.test(line)) return false;+ if (/^value\s*:\s*.+$/.test(line)) return true;+ if (/^value\s*:\s*$/.test(line)) return false; // empty value (no scalar at all)+ }+ return false;+}++function collectSourceFiles(dir) {+ const results = [];+ const stack = [dir];+ while (stack.length > 0) {+ const current = stack.pop();+ let entries;+ try {+ entries = fs.readdirSync(current, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name.startsWith('.')) continue;+ const full = path.join(current, entry.name);+ if (entry.isDirectory()) {+ stack.push(full);+ } else if (entry.isFile() && SOURCE_EXTENSIONS.has(path.extname(entry.name))) {+ results.push(full);+ }+ }+ }+ return results;+}diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.mdindex 6ec8fd9b9..3c4cae095 100644--- a/plugins/power-pages/skills/create-site/SKILL.md+++ b/plugins/power-pages/skills/create-site/SKILL.md@@ -244,9 +244,42 @@ Immediately after the dev server starts, verify the scaffold is working:>> **If you include an Authentication feature option**, describe it generically as "Login/signup for tracking application status" or similar. Do NOT mention a specific identity provider (e.g., "Entra ID", "SAML", "Google") in the feature description — the `/power-pages:setup-auth` skill will ask the user which provider they want.-3. Read the design aesthetics reference: `${CLAUDE_PLUGIN_ROOT}/skills/create-site/references/design-aesthetics.md`-4. **Map aesthetic + mood to design choices** using the Aesthetic x Mood Mapping table from the design reference. Record the chosen font direction, color direction, and motion direction.-5. Analyze requirements and determine needed components. Present component plan to user as a table:+3. **AI Component Planning** — Based on Phase 1 answers (site name, purpose, audience) and the feature selection above, propose which of the Power Pages generative-AI summarization APIs the site might use. The site itself does not depend on them — the page ships with reserved slots and runs without AI; `/add-ai-webapi` populates the slots later when the user is ready. Use `AskUserQuestion` with multi-select to let the user opt in:++ | Question | Header | Options |+ |----------|--------|---------|+ | Which AI summarization features should the site have? (multi-select — each can be added later with `/add-ai-webapi`) | AI Summaries | *(generate 2-4 context-aware options plus "None for now")* |++ > **Options are NOT hardcoded.** Infer relevant AI summary features from Phase 1 and the features picked above. Examples:+ > - "HR Dashboard" + Leave Requests feature → "Data summarization for leave requests", "Search summary on the knowledge base"+ > - "Contoso Portal" + Knowledge Base → "Search summary on site-wide search", "Data summarization for articles"+ > - "Customer Self-Service" + Support Cases / Incidents → "Data summarization for support cases (Microsoft-shipped recipe)", "Data summarization for attached knowledge articles"+ >+ > Treat the standard `incident` table like any other Dataverse table — propose Data+ > Summarization for it when the site handles support cases, but don't force the Microsoft-shipped+ > recipe (`$select=description,title` + the portal-comments expand) unless that genuinely fits+ > the user's UX. A custom case-like table or a different facet of the standard incident is a+ > regular Data Summarization pick. Always include **None for now** so the user can defer. Do+ > NOT integrate the APIs in this skill — only record the user's picks so Phase 4's plan can+ > mention them and Phase 8 can suggest `/add-ai-webapi` as a recommended next step.+ >+ > Capture the selection in memory as `AI_SUMMARY_PICKS` — a list of one or more of: `search-summary`, `data-summarization`.++4. **Map picks to target pages.** For each entry in `AI_SUMMARY_PICKS`, decide which page will carry the AI surface and store the mapping as `AI_SUMMARY_PLACEMENTS`. This is what Phase 4 shows the user and what Phase 5 reserves slots for. Use the feature selection from step 2 — and treat this mapping as an *input* to the page list Claude proposes in step 7: if a pick has no natural target page, add one to the plan so the summary has a home:++ | Pick | Default target page | If no matching page is planned |+ |------|--------------------|-------------------------------|+ | `search-summary` | A search / search-results page (e.g., `SearchResults`, `Search`) | Add a search page to the plan so the summary has a home |+ | `data-summarization` | The detail page of the table the user called out (e.g., `ProductDetail` for products, `CaseDetail` for support cases) — ask the user if ambiguous | Propose adding a detail page; if rejected, fall back to a list/dashboard page |++ `AI_SUMMARY_PLACEMENTS` shape: one record per placement, e.g.+ `[{ pick: "data-summarization", targetPage: "CaseDetail", marker: "POWERPAGES:AI-SLOT kind=data-summarization" }]`.++ The `marker` string is the comment tag Phase 5 emits into the page source as a reserved anchor that `/add-ai-webapi` later finds. Keep the shape uniform — one marker per placement, always the same tag, so the follow-up skill's explore step can grep for them deterministically.++5. Read the design aesthetics reference: `${CLAUDE_PLUGIN_ROOT}/skills/create-site/references/design-aesthetics.md`+6. **Map aesthetic + mood to design choices** using the Aesthetic x Mood Mapping table from the design reference. Record the chosen font direction, color direction, and motion direction.+7. Analyze requirements and determine needed components. If `AI_SUMMARY_PLACEMENTS` from step 4 implies a page that wasn't already in the plan (e.g., a `CaseDetail` page for a data-summarization pick on the support-case table), add it to the page list now. Present the component plan to the user as a table:```| Component Type | Count | Details |@@ -257,7 +290,7 @@ Immediately after the dev server starts, verify the scaffold is working:| Routes | 4 | /, /about, /services, /contact |```-6. Use best judgement to determine the final color palette based on the chosen aesthetic + mood. These will be written fresh into a new `theme.css` during Implementation (Phase 5) when the scaffold loading screen is completely replaced:+8. Use best judgement to determine the final color palette based on the chosen aesthetic + mood. These will be written fresh into a new `theme.css` during Implementation (Phase 5) when the scaffold loading screen is completely replaced:| CSS Variable | Description | Value ||-------------|-------------|-------|@@ -282,6 +315,8 @@ Immediately after the dev server starts, verify the scaffold is working:Read the design aesthetics reference: `${CLAUDE_PLUGIN_ROOT}/skills/create-site/references/design-aesthetics.md`. Every field you populate below should be justified by the chosen aesthetic + mood from Phase 3.+> **AI Readiness in the plan.** If `AI_SUMMARY_PLACEMENTS` from Phase 3 is non-empty, reflect each placement in the matching `PAGES_DATA` entry's `description` or `content` — e.g., *"Reserved slot for an AI summary card; populated later by `/add-ai-webapi`. The page ships without AI."* This keeps the user's expectation honest: the site does not depend on generative-AI features being enabled on the tenant, and there is no "Run /add-ai-webapi" placeholder visible to end-users. If `AI_SUMMARY_PLACEMENTS` is empty, omit any AI references from the plan.+### 4.2 Build the Plan DataAssemble a single JSON object with the following keys. The plan template rejects any data that's missing a required key, so include all of them.@@ -392,6 +427,24 @@ The scaffold is a temporary loading screen — it must be **completely replaced*5. **Router** — Register all new routes (the scaffold only has `/` and `/about` — add all requested routes)6. **Navigation** — Add links to the new Layout/Header component7. **Entry HTML** — Update `index.html` (or `Layout.astro` for Astro) to load the chosen Google Fonts instead of the scaffold's DM Sans + Outfit+8. **Reserve AI summary slots** — only if `AI_SUMMARY_PLACEMENTS` from Phase 3 is non-empty. For each placement, insert a single comment marker in the target page source at the intended insertion point. No visible placeholder UI, no stub components, no extra routes — just a grep-able anchor that `/add-ai-webapi` will later find and replace. Syntax depends on the framework:++ | Framework | Marker syntax |+ |-----------|--------------|+ | React (JSX) | `{/* POWERPAGES:AI-SLOT kind=<pick> */}` inside the component's return JSX |+ | Vue (SFC template) | `<!-- POWERPAGES:AI-SLOT kind=<pick> -->` inside `<template>` |+ | Angular (HTML template) | `<!-- POWERPAGES:AI-SLOT kind=<pick> -->` inside the component template |+ | Astro | `<!-- POWERPAGES:AI-SLOT kind=<pick> -->` inside the component's HTML |++ Where `<pick>` is one of `search-summary`, `data-summarization` — verbatim from the placement record.++ Placement within the page:++ - **`data-summarization`** (record detail): directly after the page heading, above the detail content — this is where a Copilot-style summary card naturally reads in the reading order.+ - **`data-summarization`** (list page): directly above the list / table, below the page heading and any filter bar.+ - **`search-summary`**: directly above the search-results list, below the search input — the summary paragraph reads before the keyword hits.++ One marker per placement, exactly as defined in the `marker` field of the `AI_SUMMARY_PLACEMENTS` record. Do NOT add stub components (`<CopilotSummaryCard />`, etc.), CSS classes, or empty `<aside>` elements — the slot is just a comment. The site must ship as if AI is not a consideration; the follow-up skill does the real work.**Important**: Build real, functional UI with distinctive design applied — not placeholder "coming soon" pages, and not generic unstyled markup. Every page and component should reflect the chosen aesthetic from the moment it's created. The scaffold loading screen should be completely gone after this phase — no trace of the Power Pages branded animation should remain.@@ -593,6 +646,7 @@ Present a summary table to the user:- `/setup-datamodel` — Create Dataverse tables for dynamic content- `/add-seo` — Add meta tags, robots.txt, sitemap.xml, favicon- `/add-tests` — Add unit tests (Vitest) and E2E tests (Playwright)+ - `/add-ai-webapi` — Add generative-AI summaries (Search Summary and Data Summarization). **Recommend first when `AI_SUMMARY_PLACEMENTS` from Phase 3 is non-empty** — the pages already carry `POWERPAGES:AI-SLOT` comment markers at the intended insertion points, so the follow-up skill's explore step finds them deterministically and the user gets the AI surface they picked during discovery without any page redesign.**Output**: Deployed (or deployment-ready) site with clear next stepsdiff --git a/plugins/power-pages/skills/create-webroles/SKILL.md b/plugins/power-pages/skills/create-webroles/SKILL.mdindex 6975ce817..d3bd59522 100644--- a/plugins/power-pages/skills/create-webroles/SKILL.md+++ b/plugins/power-pages/skills/create-webroles/SKILL.md@@ -20,11 +20,30 @@ Create web roles for a Power Pages code site. Web roles define the permissions a- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.- **Always use the UUID script**: Never generate UUIDs manually — always use `${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js` to produce valid UUID v4 values for each web role.- **Preserve uniqueness constraints**: Only one role can have `anonymoususersrole: true` and only one can have `authenticatedusersrole: true`. Always check existing roles before setting these flags.+- **Caller-suppress mode is opt-in**: When invoked by another skill (e.g. `/add-ai-webapi`) with the `[CALLED-BY-PARENT-SKILL]` sentinel in `$ARGUMENTS`, suppress this skill's deploy prompts (Phase 1's missing-deploy ask, Phase 6's deploy ask (step 3), and the closing reminder) and return as soon as roles are created. The caller batches the deploy at end-of-orchestration. Human invocations never trigger this mode. See Phase 0 below for parsing.> **Prerequisite:** The site must be deployed at least once before web roles can be created, since deployment creates the `.powerpages-site` folder structure that stores web role definitions.**Initial request:** $ARGUMENTS+## Phase 0: Detect caller-suppress mode++Inspect `$ARGUMENTS`. If the text contains the sentinel `[CALLED-BY-PARENT-SKILL]`, set an+internal flag **caller-suppress = true** that downstream phases consult. The optional token+`caller=<skill-name>` may follow the sentinel for diagnostic purposes (e.g.+`caller=add-ai-webapi`); record it for the final summary but do not branch on it.++When the flag is set, skip every deploy prompt this skill would otherwise issue:++- **Phase 1 missing-deploy ask**: if `.powerpages-site` is absent, do NOT ask the user to+ deploy now. Stop with a clear contract-violation message back to the caller — the caller+ was supposed to gate on this before invoking us.+- **Phase 6 deploy ask (step 3)** and the closing "Please run `/deploy-site`"+ reminder: skip both. The caller batches the single deploy decision at end-of-orchestration.++When the sentinel is absent, proceed exactly as today (full interactive flow). This is the+regression guard — no human invocation changes behavior.+---## Workflow@@ -46,7 +65,10 @@ Create web roles for a Power Pages code site. Web roles define the permissions a1. Locate the project root (`**/powerpages.config.json`) and check for `.powerpages-site/web-roles/`.-2. **If `.powerpages-site` does NOT exist:** Ask the user to deploy first via `AskUserQuestion` (options: "Yes, deploy now (Recommended)", "No, I'll do it later"). If yes, invoke `/deploy-site` then resume from Phase 2. If no, stop.+2. **If `.powerpages-site` does NOT exist:**+ - **In caller-suppress mode** (Phase 0 flag): stop with a contract-violation message —+ the calling skill should have gated on this folder existing before invoking us.+ - **Otherwise**: ask the user to deploy first via `AskUserQuestion` (options: "Yes, deploy now (Recommended)", "No, I'll do it later"). If yes, invoke `/deploy-site` then resume from Phase 2. If no, stop.3. **If `.powerpages-site` exists but `web-roles/` does NOT:** Create the `<PROJECT_ROOT>/.powerpages-site/web-roles/` directory.@@ -203,7 +225,12 @@ name: <Role Name>> | Content Editors | `a1b2c3d4-...` | false | false |> | *(etc.)* |-3. Then ask the user if they want to deploy the site to apply the new roles:+3. **In caller-suppress mode** (Phase 0 flag): skip the deploy ask and the closing reminder+ entirely. Return the created-roles summary to the caller and stop. The caller owns the+ single end-of-orchestration deploy decision; nesting deploy reminders inside delegations+ gives the user 2–3 redundant prompts per parent-skill run.++ **Otherwise**, ask the user if they want to deploy the site to apply the new roles:| Question | Options ||----------|---------|diff --git a/plugins/power-pages/skills/integrate-backend/SKILL.md b/plugins/power-pages/skills/integrate-backend/SKILL.mdindex 3e8cbb46a..ea26144b5 100644--- a/plugins/power-pages/skills/integrate-backend/SKILL.md+++ b/plugins/power-pages/skills/integrate-backend/SKILL.md@@ -2,9 +2,10 @@name: integrate-backenddescription: >-Analyzes the user's business problem and recommends the right backend integration approach- — Web API, Server Logic, Cloud Flows, or a combination — for a Power Pages site, then routes- to the appropriate specialized skill. Use when the user wants to add backend integration,- connect to data, or needs help deciding which backend approach to use.+ — Web API, AI Web API (generative summaries / grounded search), Server Logic, Cloud Flows,+ or a combination — for a Power Pages site, then routes to the appropriate specialized skill.+ Use when the user wants to add backend integration, connect to data, add AI summaries, or+ needs help deciding which backend approach to use.user-invocable: trueargument-hint: describe what your backend needs to doallowed-tools: Read, Write, Edit, Bash, Grep, Glob, AskUserQuestion, Skill, Task, TaskCreate, TaskUpdate, TaskList@@ -15,13 +16,14 @@ model: opus# Backend Integration-Analyze the user's business problem and recommend the right backend integration approach — **Web API**, **Server Logic**, **Cloud Flows**, or a combination — then route to the appropriate skill(s) to implement the solution.+Analyze the user's business problem and recommend the right backend integration approach — **Web API**, **AI Web API**, **Server Logic**, **Cloud Flows**, or a combination — then route to the appropriate skill(s) to implement the solution.## Core Principles- **Understand the problem first**: Never jump to a technology choice. Analyze the user's intent, data flow, security needs, and performance requirements before recommending.-- **Recommend the simplest approach that works**: Web API for straightforward Dataverse CRUD, Server Logic when server-side processing is needed, Cloud Flows for async background work. Don't over-engineer.+- **Recommend the simplest approach that works**: Web API for straightforward Dataverse CRUD, AI Web API for generative summaries or grounded search over existing data, Server Logic when server-side processing is needed, Cloud Flows for async background work. Don't over-engineer.- **Secure actions belong on the server**: When a write depends on a business rule that must be tamper-proof (state transitions, approval workflows, computed values), the server logic must validate AND execute the write — not just validate and leave the write to a client-side Web API call. See the **Secure Action Principle** in the decision framework.+- **AI Web API sits on top of Web API**: The Data Summarization and Case-preset endpoints read through the same `_api` layer as regular Web API, so they inherit the same table permissions, column permissions, and `Webapi/<table>/*` site settings. When a plan has both a Web API item and an AI Web API item for the same table, the AI item depends on (and goes in a later phase than) the Web API item. Search Summary has no per-table prereqs and can stand alone.- **Combinations are normal**: Many real scenarios need more than one approach. Recommend combinations when justified, but explain why each piece is needed.- **Route, don't implement**: This skill recommends and invokes the right skill(s). It does not create backend files itself.@@ -97,6 +99,7 @@ From the user's request and the existing site state, determine:- **Must logic be hidden from the browser?** (pricing rules, validation algorithms, business rules)- **Is this a simple data operation or complex business logic?** (CRUD vs. multi-step processing)- **Does any write depend on a business rule that must be tamper-proof?** (state transitions, approval conditions, computed values) — if yes, the server logic must validate AND execute the write, not just validate+- **Does the UI want an AI-generated summary, grounded AI search, or related-record discovery?** (e.g., "summarize this case", "summarize open orders", "suggest KB articles on the case page", "AI-powered search") — if yes, AI Web API is the right fit. Watch for the phrasing signals: *summarize*, *summary of*, *Copilot*, *related / similar / suggested <entity>*, *AI search*, *semantic search*.- **Can existing Dataverse custom actions handle part of the requirement?** If custom actions were discovered in Phase 1.3, check whether any align with the user's needs — server logic can wrap existing custom actions via `InvokeCustomApi` instead of building equivalent logic from scratch### 2.2 Clarify if Ambiguous@@ -128,7 +131,15 @@ Use the decision matrix, intent mapping, and **Secure Action Principle** from th1. **Can Web API alone handle this?** If it's straightforward Dataverse CRUD with no external calls, no secrets, no server-side logic, and **no business rules governing the write** — recommend Web API. It's the simplest option.-2. **Does it need Server Logic?** If any of these apply, Server Logic is needed:+2. **Does it need AI Web API?** If any of these apply, AI Web API is the right fit:+ - The UI wants an AI-generated summary of a record on its detail page (e.g., "summarize this case", "Copilot summary")+ - The UI wants an AI summary of a list or collection (e.g., "summarize open orders", "highlight trends in this week's cases")+ - A detail page wants related-record discovery (e.g., "suggest KB articles for this case", "similar products", "similar cases") — Search Summary's grounded retrieval is a better fit than a hand-rolled OData keyword match+ - The site wants AI-grounded search with citations, replacing or augmenting keyword-only search++ AI Web API is read-only — the Secure Action Principle does not apply. If an AI item covers a Dataverse table that is also covered by a Web API item, put the AI item in a later phase (it depends on the Web API Layer 1/2 prereqs being in place). Search Summary items have no per-table prereqs and can stand alone.++3. **Does it need Server Logic?** If any of these apply, Server Logic is needed:- External API calls (HttpClient)- Credentials/secrets must stay on the server- Business logic must be hidden from the browser@@ -137,17 +148,19 @@ Use the decision matrix, intent mapping, and **Secure Action Principle** from th- Wrapping a Dataverse Custom API/Action for portal consumption — if custom actions were found in Phase 1.3, check whether any match the requirement before recommending building from scratch- **The write depends on a business rule that must be tamper-proof** (state transitions, approval conditions, computed values) — server logic must validate AND execute the write-3. **Does it need Cloud Flows?** If any of these apply, Cloud Flows are the right fit:+4. **Does it need Cloud Flows?** If any of these apply, Cloud Flows are the right fit:- The operation is async — the user doesn't need an immediate result- Background processing: sending emails, notifications, processing orders- Multi-step workflows across systems with Power Automate connectors- Long-running processes that exceed the 120-second server logic timeout- Non-developers should be able to modify the workflow-4. **Does it need a combination?** Common combinations:+5. **Does it need a combination?** Common combinations:+ - Web API + AI Web API: UI displays raw Dataverse records and an AI summary of the same data (most common AI pattern — dashboards, case/order detail pages)- Web API + Cloud Flow: UI reads/writes non-sensitive Dataverse fields, some actions trigger background flows- Server Logic + Cloud Flow: Real-time endpoint validates and executes the action, async flow does follow-up (e.g., server logic transitions status, Cloud Flow sends notification)- Web API + Server Logic: Web API for safe direct reads/writes, server logic for operations that need business rule enforcement (server logic validates AND writes for those operations)+ - Web API + AI Web API + Cloud Flow: support portal with browsable cases, Copilot summary + KB discovery, and async notifications### 3.1.1 Security Review — Apply the Secure Action Principle@@ -218,7 +231,7 @@ Prepare a JSON object with these keys:```json{"name": "Create PayPal Order",- "approach": "webapi|serverlogic|cloudflow",+ "approach": "webapi|aiwebapi|serverlogic|cloudflow","description": "What this item does","reasoning": "Why this approach was chosen","phase": 1,@@ -240,10 +253,11 @@ Prepare a JSON object with these keys:1. Items with no dependencies go in the earliest phase appropriate for their approach2. Items that depend on other items go in a later phase than their dependency3. Items in the **same phase have no dependencies on each other** and can be built in parallel-4. Recommended default ordering: Server Logic foundations first (validate-and-execute endpoints for state transitions, batch queries), then Web API CRUD for non-sensitive fields (reads, creates with safe defaults, updates to fields with no business rules), then advanced Server Logic (multi-table transactions), then Cloud Flows (async follow-ups)+4. Recommended default ordering: Server Logic foundations first (validate-and-execute endpoints for state transitions, batch queries), then Web API CRUD for non-sensitive fields (reads, creates with safe defaults, updates to fields with no business rules), then advanced Server Logic (multi-table transactions), then AI Web API for summaries/grounded search over the tables set up by Web API, then Cloud Flows (async follow-ups)5. **Security constraint**: A Web API item must never write a field whose value is governed by a business rule enforced in a server logic item. If a field needs validation, the server logic item should write it directly — the Web API item should exclude that field from its scope+6. **AI layering constraint**: An AI Web API item for a Dataverse table that is also covered by a Web API item must be in a later phase than the Web API item — AI Web API's Data Summarization endpoint reuses the Web API's Layer 1/2 prereqs (table permissions, `Webapi/<table>/*` site settings). Search Summary items have no per-table prereqs and can go in any phase.-**DATA_FLOWS_DATA format:**+**DATA_FLOWS_DATA format** (each step's `approach` is one of `webapi`, `aiwebapi`, `serverlogic`, `cloudflow`):```json{"trigger": "User registers and pays",@@ -323,6 +337,7 @@ Group the approved items by their `phase` number from the plan. Each phase is a| Approach | Skill to invoke | What to pass ||----------|----------------|--------------|| Web API | `/integrate-webapi` | The user's request + tables for this phase + existing patterns |+| AI Web API | `/add-ai-webapi` | The user's request + target pages/tables for this phase + which of the two APIs to use (Search Summary or Data Summarization) + any trigger preferences (auto-on-mount vs manual button for list summaries). If Web API prereqs for the target table were set up in an earlier phase, mention that so the AI skill skips its Layer 1/2 delegation. || Server Logic | `/add-server-logic` | The user's request + endpoints for this phase + SDK features needed + secrets identified + any matching Dataverse custom actions from Phase 1.3 || Cloud Flow | `/add-cloud-flow` | The user's request + async operations for this phase |@@ -381,6 +396,7 @@ If the user's request clearly and unambiguously maps to a single approach, **ski- "Create a server logic endpoint for..." → `/add-server-logic`- "Integrate Web API for the contacts table" → `/integrate-webapi`- "Add a cloud flow for sending emails" → `/add-cloud-flow`+- "Add an AI summary to the case detail page" / "summarize open cases" / "suggest KB articles on this page" → `/add-ai-webapi`This skill is for **ambiguous requests** where the user describes a business problem and needs help choosing the right approach.@@ -492,6 +508,53 @@ NOTE: The Web API item must NOT include the status field in its Updateendpoint.```+**Example 9: AI summary on detail page → AI Web API (Data Summarization, support-case recipe)**+```+User: Add an AI-generated summary card to the case detail page that+ includes the comments customers have posted.++Recommendation: AI Web API — Data Summarization+Reason: Microsoft Learn documents a ready-made Data Summarization+ configuration for this scenario on the standard incident table —+ POST to /_api/summarization/data/v1.0/incidents(<id>) with+ InstructionIdentifier "Summarization/prompt/case_summary" and+ $expand=incident_adx_portalcomments($select=description). The+ user can adopt this verbatim or tweak the columns / prompt for+ their own case-handling UX.+Skill: /add-ai-webapi+```++**Example 10: Related KB articles on detail page → AI Web API (search summary)**+```+User: On the case detail page, show relevant KB articles to help+ agents find answers faster.++Recommendation: AI Web API (Search Summary for related-record discovery)+Reason: Search Summary's grounded retrieval returns AI-ranked citations+ from the site's knowledge index — a much better fit than a+ hand-rolled OData keyword match on the knowledge article table.+ The citations rewrite into SPA routes for clean deep-linking.+Skill: /add-ai-webapi+```++**Example 11: List summary + browsable records → Web API + AI Web API**+```+User: On the dashboard, show the list of open cases from Dataverse+ and an AI summary highlighting the most common issue themes.++Recommendation: Web API + AI Web API+Reason: The list is direct Dataverse reads — Web API handles pagination,+ filtering, and status badges. The summary is a list-form Data+ Summarization call with $filter=statecode eq 0 using the tabular-+ insight prompt pattern. Web API item goes in Phase 1 because AI+ Web API reuses its Layer 1/2 prereqs (table permissions, Webapi+ site settings for the incident table).+Phases: Phase 1 → /integrate-webapi (incident list CRUD for the dashboard)+ Phase 2 → /add-ai-webapi (list summary for open cases, reuses+ Phase 1's Layer 1/2 — the AI skill detects this and skips its+ Web API delegation)+```+### Progress TrackingBefore starting Phase 1, create a task list with all phases using `TaskCreate`:diff --git a/plugins/power-pages/skills/integrate-backend/assets/backend-plan.html b/plugins/power-pages/skills/integrate-backend/assets/backend-plan.htmlindex 16f190843..488811937 100644--- a/plugins/power-pages/skills/integrate-backend/assets/backend-plan.html+++ b/plugins/power-pages/skills/integrate-backend/assets/backend-plan.html@@ -10,7 +10,7 @@--text:#323130; --text-dim:#605e5c; --text-bright:#201f1e; --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;--pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1020; --high:#ca5010; --high-bg:#ca50100a; --high-border:#ca501020;--purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b820;- --webapi:#0078d4; --serverlogic:#5c2d91; --cloudflow:#ca5010;+ --webapi:#0078d4; --aiwebapi:#00b7c3; --serverlogic:#5c2d91; --cloudflow:#ca5010;--mono:'Cascadia Code','Consolas',monospace; --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;--radius:8px; --radius-sm:4px; --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);}@@ -39,12 +39,13 @@ h2{font-size:21px;font-weight:800;color:var(--text-bright);letter-spacing:-0.3px.section-desc code{color:var(--accent);background:var(--accent-bg);padding:1px 6px;border-radius:3px;font-family:var(--mono);font-size:12px;}h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margin-bottom:12px;}.summary-box{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:22px;margin-bottom:22px;font-size:14px;color:var(--text);line-height:1.75;}-.stats-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:24px;}+.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:24px;}.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;text-align:center;position:relative;overflow:hidden;box-shadow:var(--shadow-4);}.stat-card::after{content:'';position:absolute;top:0;left:50%;transform:translateX(-50%);width:40px;height:2px;border-radius:0 0 2px 2px;}.stat-card:nth-child(1)::after{background:var(--webapi);}-.stat-card:nth-child(2)::after{background:var(--serverlogic);}-.stat-card:nth-child(3)::after{background:var(--cloudflow);}+.stat-card:nth-child(2)::after{background:var(--aiwebapi);}+.stat-card:nth-child(3)::after{background:var(--serverlogic);}+.stat-card:nth-child(4)::after{background:var(--cloudflow);}.stat-num{font-size:30px;font-weight:800;font-family:var(--mono);line-height:1;}.stat-label{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;margin-top:6px;}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;margin-bottom:10px;transition:box-shadow 0.2s,border-color 0.2s;}@@ -60,6 +61,8 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi.approach-chip .dot{width:8px;height:8px;border-radius:50%;flex-shrink:0;}.approach-webapi{background:#0078d40a;border:1px solid #0078d425;color:var(--webapi);}.approach-webapi .dot{background:var(--webapi);}+.approach-aiwebapi{background:#00b7c30a;border:1px solid #00b7c325;color:var(--aiwebapi);}+.approach-aiwebapi .dot{background:var(--aiwebapi);}.approach-serverlogic{background:#5c2d910a;border:1px solid #5c2d9125;color:var(--serverlogic);}.approach-serverlogic .dot{background:var(--serverlogic);}.approach-cloudflow{background:#ca50100a;border:1px solid #ca501025;color:var(--cloudflow);}@@ -67,6 +70,7 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi.mono{font-family:var(--mono);}.reason-box{font-size:12px;color:var(--text);background:var(--surface2);padding:10px 14px;border-radius:var(--radius-sm);line-height:1.8;}.reason-webapi{border-left:3px solid var(--webapi);}+.reason-aiwebapi{border-left:3px solid var(--aiwebapi);}.reason-serverlogic{border-left:3px solid var(--serverlogic);}.reason-cloudflow{border-left:3px solid var(--cloudflow);}.item-header{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:12px;}@@ -87,12 +91,17 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi.concept-header{display:flex;align-items:center;gap:14px;padding:20px 22px 0;}.concept-icon-box{width:44px;height:44px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0;}.concept-icon-webapi{background:#0078d412;color:var(--webapi);}+.concept-icon-aiwebapi{background:#00b7c312;color:var(--aiwebapi);}.concept-icon-serverlogic{background:#5c2d9112;color:var(--serverlogic);}.concept-icon-cloudflow{background:#ca501012;color:var(--cloudflow);}.concept-title{font-size:16px;font-weight:800;color:var(--text-bright);}.concept-subtitle{font-size:12px;color:var(--text-dim);margin-top:1px;}.concept-body{padding:16px 22px 20px;font-size:13px;color:var(--text);line-height:1.75;}.concept-body p{margin-bottom:10px;}+.note-callout{margin:0 0 14px;padding:12px 14px;border-left:3px solid var(--high);background:var(--high-bg);border-radius:6px;font-size:12.5px;line-height:1.65;color:var(--text);}+.note-callout strong{color:var(--text-bright);font-weight:700;}+.note-callout p{margin:0;}+.note-callout p + p{margin-top:6px;}.concept-when{background:var(--surface2);border-top:1px solid var(--border);padding:14px 22px;font-size:12px;line-height:1.7;}.concept-when strong{color:var(--text-bright);}.concept-when-grid{display:grid;grid-template-columns:1fr 1fr;gap:6px 18px;margin-top:6px;}@@ -206,6 +215,7 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi<div class="stats-grid"><div class="stat-card"><div class="stat-num" style="color:var(--webapi)" id="statWebApi">0</div><div class="stat-label">Web API</div></div>+ <div class="stat-card"><div class="stat-num" style="color:var(--aiwebapi)" id="statAiWebApi">0</div><div class="stat-label">AI Web API</div></div><div class="stat-card"><div class="stat-num" style="color:var(--serverlogic)" id="statServerLogic">0</div><div class="stat-label">Server Logic</div></div><div class="stat-card"><div class="stat-num" style="color:var(--cloudflow)" id="statCloudFlow">0</div><div class="stat-label">Cloud Flows</div></div></div>@@ -271,6 +281,26 @@ const CONCEPTS = [{ label: 'Table Permissions', url: 'https://learn.microsoft.com/power-pages/security/table-permissions' }]},+ {+ id: 'aiwebapi',+ icon: '✨',+ iconCls: 'concept-icon-aiwebapi',+ title: 'AI Web API (preview)',+ subtitle: 'Generative summaries & grounded search \u2014 preview',+ body: '<div class="note-callout"><p><strong>Note.</strong> AI summarization APIs are a preview feature. Preview features aren\u2019t meant for production use and may have restricted functionality. These features are available before an official release so that customers can get early access and provide feedback.</p></div><p>The <strong>AI Web API</strong> is a specialization of the Web API for AI-augmented reads. It exposes two endpoints: <strong>Search Summary</strong> (grounded AI answer over the site\u2019s search index) and <strong>Data Summarization</strong> (AI summary of a single record or a collection of records). Microsoft Learn documents one ready-made Data Summarization recipe for a Copilot-style summary on the standard support-case (<code>incident</code>) detail page \u2014 use it verbatim if it fits your UX, or configure Data Summarization with your own columns and prompt for any other table.</p><p>Like regular Web API, it runs in the browser and uses the same cookie-based auth and CSRF token. It respects the same table permissions and column permissions \u2014 so once you\u2019ve wired Web API for a table, the AI endpoints can read the same data and add a generative pass on top. The output is a human-readable summary, not raw records.</p><p><strong>Read-only</strong>: neither endpoint mutates Dataverse, so the Secure Action Principle does not apply. <strong>Three-level admin gate</strong>: tenant PowerShell setting, Copilot Hub environment/site governance, and (for Search Summary) the site-level maker toggle must all allow it.</p>',+ diagram: [+ { label: 'Browser', value: 'Opens case detail page' },+ { label: 'AI Web API', value: 'POST /_api/summarization/data/...' },+ { label: 'Table Permissions', value: 'Same as Web API' },+ { label: 'AI Summary', value: 'Rendered in UI card' }+ ],+ whenUse: ['Summary card on a detail page', 'Summary of a list of records', 'Suggested / related records on a page', 'AI-grounded site search with citations'],+ whenAvoid: ['Operations that write data', 'Deterministic / exact data output', 'Data that isn\'t in Dataverse', 'Tenants without generative AI enabled'],+ docs: [+ { label: 'Search Summary API', url: 'https://learn.microsoft.com/power-pages/configure/search/generative-ai' },+ { label: 'Data Summarization API', url: 'https://learn.microsoft.com/power-pages/configure/data-summarization-api' }+ ]+ },{id: 'serverlogic',icon: '⚙',@@ -315,6 +345,7 @@ const CONCEPTS = [const APPROACH_META = {webapi: { label: 'Web API', color: 'var(--webapi)', cls: 'webapi' },+ aiwebapi: { label: 'AI Web API', color: 'var(--aiwebapi)', cls: 'aiwebapi' },serverlogic: { label: 'Server Logic', color: 'var(--serverlogic)', cls: 'serverlogic' },cloudflow: { label: 'Cloud Flow', color: 'var(--cloudflow)', cls: 'cloudflow' },};@@ -352,6 +383,12 @@ function implementBar(approach) {<span class="implement-cmd">/integrate-webapi</span><span class="implement-hint">Generates Web API service code + table permissions</span></div>`;+ } else if (approach === 'aiwebapi') {+ return `<div class="implement-bar">+ <span class="implement-label">Implement with:</span>+ <span class="implement-cmd">/add-ai-webapi</span>+ <span class="implement-hint">Generates summarization service + Summarization/* site settings</span>+ </div>`;} else if (approach === 'serverlogic') {return `<div class="implement-bar"><span class="implement-label">Implement with:</span>@@ -400,10 +437,12 @@ conceptsContainer.innerHTML = CONCEPTS.map(c => {// --- Overview Tab ---const webApiCount = ITEMS.filter(i => i.approach === 'webapi').length;+const aiWebApiCount = ITEMS.filter(i => i.approach === 'aiwebapi').length;const serverLogicCount = ITEMS.filter(i => i.approach === 'serverlogic').length;const cloudFlowCount = ITEMS.filter(i => i.approach === 'cloudflow').length;document.getElementById('statWebApi').textContent = webApiCount;+document.getElementById('statAiWebApi').textContent = aiWebApiCount;document.getElementById('statServerLogic').textContent = serverLogicCount;document.getElementById('statCloudFlow').textContent = cloudFlowCount;document.getElementById('topbarCount').textContent =@@ -457,6 +496,7 @@ const orderContainer = document.getElementById('orderContainer');const PHASE_META = [{ approach: 'serverlogic', title: 'Server Logic', subtitle: 'Server-side validation and business rules', color: 'var(--serverlogic)' },{ approach: 'webapi', title: 'Web API', subtitle: 'Browser-to-Dataverse CRUD operations', color: 'var(--webapi)' },+ { approach: 'aiwebapi', title: 'AI Web API', subtitle: 'Generative summaries and grounded search', color: 'var(--aiwebapi)' },{ approach: 'cloudflow', title: 'Cloud Flows', subtitle: 'Async notifications and background automation', color: 'var(--cloudflow)' },];@@ -522,6 +562,7 @@ orderContainer.innerHTML = phases.map((phase, phaseIdx) => {// --- Items Tab ---const itemParts = [];if (webApiCount) itemParts.push(webApiCount + ' Web API');+if (aiWebApiCount) itemParts.push(aiWebApiCount + ' AI Web API');if (serverLogicCount) itemParts.push(serverLogicCount + ' Server Logic');if (cloudFlowCount) itemParts.push(cloudFlowCount + ' Cloud Flow');document.getElementById('itemsDesc').textContent =diff --git a/plugins/power-pages/skills/integrate-backend/references/decision-framework.md b/plugins/power-pages/skills/integrate-backend/references/decision-framework.mdindex 29755cf2c..69c8aa887 100644--- a/plugins/power-pages/skills/integrate-backend/references/decision-framework.md+++ b/plugins/power-pages/skills/integrate-backend/references/decision-framework.md@@ -1,7 +1,7 @@# Backend Integration Decision FrameworkUse this framework to recommend the right backend integration approach for a Power Pages code site. A single user request may map to one approach or a combination.-## The Three Approaches+## The Four Approaches### Web API (`/integrate-webapi`)@@ -36,6 +36,47 @@ Use this framework to recommend the right backend integration approach for a Pow---+### AI Web API (`/add-ai-webapi`)++**What it is:** A specialization of Web API for AI-augmented reads. Two endpoints: **Search Summary** (`/_api/search/v1.0/summary`) produces a grounded AI answer over the site's search index, and **Data Summarization** (`/_api/summarization/data/v1.0/<entitySet>(<id>)?$select=...`) produces an AI summary of one record or a collection. Microsoft also documents a ready-made Data Summarization configuration for the standard `incident` table (the support-case Copilot summary recipe) — that's an example of Data Summarization, not a separate API.++**How it works:** Same browser-to-portal auth model as Web API — cookie session + CSRF token from `/_layout/tokenhtml`. Data Summarization reads via the portal's `_api` layer, so it respects the same table permissions, column permissions, and Web API field settings as regular Web API. The server adds a generative-AI pass that returns a text summary instead of raw records. Read-only by definition — neither endpoint mutates Dataverse.++**Best for:**+- AI summary of a record on its detail page (e.g., "summarize this case including its portal comments")+- AI summary of a list of records (e.g., "summarize open cases on the dashboard", "trends in this week's orders")+- Related-record discovery on a detail page (e.g., "suggest KB articles relevant to this case", "similar products")+- AI-grounded site search with citations (replaces or augments keyword-only search UIs)++**Not suitable when:**+- The output needs to be deterministic or exact (AI output is probabilistic; use Web API for exact data)+- The operation writes data (these endpoints are read-only — use Web API or Server Logic)+- The data isn't in Dataverse (Search Summary indexes site content; Data Summarization requires a Dataverse entity set)+- The tenant doesn't have generative AI features enabled (these APIs are preview; until an admin enables them, **Data Summarization** returns HTTP 400 with `error.code = 90041001`, while **Search Summary** returns HTTP 200 with an embedded `{ Code, Message }` envelope instead)+- The site uses the Microsoft-shipped search control and just wants AI-summarised search results on it — that's a workspace toggle (`Search/Summary/Title` content snippet), not a code integration++**Key characteristics:**+- Layered on Web API — Data Summarization requires the same `Webapi/<table>/enabled`, `Webapi/<table>/fields`, and table permissions as regular Web API reads. Search Summary has no per-table prereqs.+- Code runs in the browser; the AI pass happens server-side+- Read-only — no validate-and-execute concerns (Secure Action Principle does not apply)+- Preview feature — requires tenant admin to enable generative AI, and (for Search Summary) a site-level Copilot workspace toggle. APIs and admin toggles may change before GA.+- `/add-ai-webapi` delegates Layer 1/2 to `/integrate-webapi` in AI-only read mode — if a Web API item already covers the same table, the AI item detects the existing prereqs and skips the delegation++**Relationship to Web API:** AI Web API items for a given Dataverse table should be ordered **after** any regular Web API item for the same table (Web API sets up Layer 1/2; AI adds Layer 3 on top). Search Summary items can stand alone since they have no per-table prereqs.++**Field-list drift caveat (when both items exist for the same table):** if `/integrate-webapi`+has already configured `Webapi/<table>/fields` for full CRUD (including primary key and+lookup write forms), the follow-up `/add-ai-webapi` run detects Layer 1/2 as `ready` and+skips its delegation — leaving the broader CRUD allowlist in place. The AI surface still+works, but the fields list is broader than AI-only mode would produce. The+`ai-webapi-settings-architect` agent flags this as an advisory in its plan; the user can+narrow the allowlist after the AI surface lands by editing the YAML directly. If a strict+read-only posture matters from day one, run `/add-ai-webapi` *before* `/integrate-webapi`+on the same table — the AI skill will then write the minimal fields list and the later+Web API run will widen it.++---+### Server Logic (`/add-server-logic`)**What it is:** Server-side JavaScript that runs in a sandboxed V8 engine on the Power Pages server. Exposed as REST endpoints at `/_api/serverlogics/<name>`. Code is hidden from the browser.@@ -117,20 +158,24 @@ Use this framework to recommend the right backend integration approach for a PowUse these questions to narrow down the recommendation:-| Question | Web API | Server Logic | Cloud Flow |-|----------|:-------:|:------------:|:----------:|-| Does the UI need to display data from Dataverse? | **Yes** | Possible | No |-| Does it call external APIs (non-Dataverse)? | No | **Yes** | Possible |-| Are credentials/secrets involved? | No | **Yes** | Possible |-| Must business logic be hidden from the browser? | No | **Yes** | N/A |-| Does the write depend on a business rule that must be tamper-proof? | No | **Yes (validate-and-execute)** | No |-| Is the operation async/background (user doesn't wait)? | No | No | **Yes** |-| Is it a simple Dataverse CRUD with no extra logic? | **Yes** | Overkill | Overkill |-| Does it need 400+ connectors (Teams, Outlook, SAP)? | No | No | **Yes** |-| Should the response render immediately in the UI? | **Yes** | **Yes** | No |-| Does it batch multiple queries for performance? | No | **Yes** | No |-| Is it a long-running process (>120 seconds)? | No | No | **Yes** |-| Should non-developers be able to modify the logic? | No | No | **Yes** |+| Question | Web API | AI Web API | Server Logic | Cloud Flow |+|----------|:-------:|:----------:|:------------:|:----------:|+| Does the UI need to display data from Dataverse? | **Yes** | Possible | Possible | No |+| Does the UI need an AI-generated summary of Dataverse data? | No | **Yes** | No | No |+| Does the UI need AI-grounded search with citations? | No | **Yes** | No | No |+| Does a detail page need related-record discovery (e.g., suggested KB articles)? | No | **Yes** | Possible | No |+| Does it call external APIs (non-Dataverse)? | No | No | **Yes** | Possible |+| Are credentials/secrets involved? | No | No | **Yes** | Possible |+| Must business logic be hidden from the browser? | No | No | **Yes** | N/A |+| Does the write depend on a business rule that must be tamper-proof? | No | N/A (read-only) | **Yes (validate-and-execute)** | No |+| Is the operation async/background (user doesn't wait)? | No | No | No | **Yes** |+| Is it a simple Dataverse CRUD with no extra logic? | **Yes** | Overkill | Overkill | Overkill |+| Does it need 400+ connectors (Teams, Outlook, SAP)? | No | No | No | **Yes** |+| Should the response render immediately in the UI? | **Yes** | **Yes** | **Yes** | No |+| Does it batch multiple queries for performance? | No | No | **Yes** | No |+| Is it a long-running process (>120 seconds)? | No | No | No | **Yes** |+| Should non-developers be able to modify the logic? | No | No | No | **Yes** |+| Does the output need to be deterministic / exact? | **Yes** | No (probabilistic) | **Yes** | **Yes** |## The Secure Action Principle@@ -206,10 +251,13 @@ Many real-world scenarios use multiple approaches together:| Combination | When to use | Example ||-------------|-------------|---------|+| **Web API + AI Web API** | UI displays raw Dataverse records directly and also surfaces an AI-generated summary of the same data. Most common AI pattern. | Case detail page shows incident fields and portal comments via Web API, plus a Copilot summary card via AI Web API. Dashboard shows a list of orders and an AI summary of trends. || **Web API + Server Logic** | UI reads/writes non-sensitive fields directly, but security-sensitive operations go through server logic that validates and executes | Dashboard displays records via Web API; status transitions go through server logic that validates and writes |+| **AI Web API + Server Logic** | AI-augmented read surface over data that was computed or prepared by server-side logic | Server logic aggregates raw claims into a curated incident record (validate-and-execute); AI Web API summarises the curated record on the detail page || **Server Logic + Cloud Flow** | Real-time endpoint validates and executes the action, then async processing follows | Server logic validates transition and writes the new status, then a Cloud Flow sends the notification email || **Web API + Cloud Flow** | UI manages data directly (no business rules on the write), and some actions trigger background workflows | User edits a description via Web API; a separate "Submit for Approval" action triggers a Cloud Flow |-| **All three** | Complex application with safe direct writes, secure server-side actions, and automation | Web API for browsing/editing non-sensitive fields, Server Logic for state transitions and payment processing, Cloud Flow for notifications |+| **Web API + AI Web API + Cloud Flow** | Users browse and edit records, see AI summaries, and trigger async workflows | Support portal: list/edit cases (Web API), Copilot case summary with suggested KB articles (AI Web API), async assignment email (Cloud Flow) |+| **All four** | Complex application with safe direct writes, AI-augmented reads, secure server-side actions, and automation | Web API for browsing/editing non-sensitive fields, AI Web API for summaries and grounded search, Server Logic for state transitions and payment processing, Cloud Flow for notifications |## Mapping User Intent to Approach@@ -217,6 +265,10 @@ Many real-world scenarios use multiple approaches together:|--------------|-----------------|-----------|| "Show data from Dataverse" / "display records" / "CRUD" | Web API | Direct data access, real-time UI binding || "Filter and sort products" / "search contacts" | Web API | Standard OData queries, no server logic needed |+| "Summarize this case" / "AI summary on the detail page" / "Copilot summary" | AI Web API | Data Summarization on a single record (the Microsoft-shipped support-case recipe is one option for the standard `incident` table) |+| "Summarize open cases" / "AI summary of this list" / "highlight trends in these records" | AI Web API | Data Summarization over a collection (list-summary pattern) |+| "Show relevant KB articles" / "suggest similar cases" / "related products" | AI Web API | Search Summary for related-record discovery — grounded retrieval returns AI-ranked citations from the site's search index |+| "AI search" / "semantic search" / "search with summary" | AI Web API | Search Summary endpoint returns a grounded AI answer plus citations for a user query || "Call an external API" / "integrate with Stripe/Twilio/etc." | Server Logic | External API calls with credential protection || "Add validation on the server" / "prevent bypassing" | Server Logic | Server-side enforcement (security) || "Rate limit submissions" / "prevent abuse" | Server Logic | Server-side enforcement (security) |diff --git a/plugins/power-pages/skills/integrate-webapi/SKILL.md b/plugins/power-pages/skills/integrate-webapi/SKILL.mdindex 89f7071ea..5ab35eb8c 100644--- a/plugins/power-pages/skills/integrate-webapi/SKILL.md+++ b/plugins/power-pages/skills/integrate-webapi/SKILL.md@@ -21,6 +21,7 @@ Integrate Power Pages Web API into a code site's frontend. This skill orchestrat- **First table sequential, then parallel**: The first table must be processed alone because it creates the shared `powerPagesApi.ts` client. Once that exists, remaining tables can be processed in parallel since each creates independent files (types, service, hooks).- **Parallelize independent agents**: The `table-permissions-architect` and `webapi-settings-architect` agents are independent — invoke them in parallel rather than sequentially.- **Permissions require deployment**: The `.powerpages-site` folder must exist before table permissions and site settings can be configured. Integration code can be written without it, but permissions cannot.+- **AI-only read mode is opt-in**: When invoked by another skill (e.g. `/add-ai-webapi`) with the `[AI-READ-ONLY]` sentinel in `$ARGUMENTS`, the flow produces read-only code and hardens the settings/permissions for AI summarization reads. See Phase 1.6 for the contract. Human invocations never trigger this mode.- **Use TaskCreate/TaskUpdate**: Track all progress throughout all phases — create the todo list upfront with all phases before starting any work.> **Prerequisites:**@@ -83,9 +84,34 @@ Look for the `.powerpages-site` folder:**/.powerpages-site```-**If not found**: Warn the user that the permissions phase (Phase 5) will require deployment first. The integration code (Phases 2–4) can still proceed.+**If not found**: Warn the user that the permissions phase (Phase 6) will require deployment first. The integration code (Phases 2–5) can still proceed.-**Output**: Confirmed project root, framework, data model availability, and deployment status+### 1.6 Detect AI-only read mode (skill-to-skill invocation)++Inspect `$ARGUMENTS`. If the text begins with the sentinel `[AI-READ-ONLY]`, the caller is another skill (typically `/add-ai-webapi`) that has already analysed the site and decided which tables need Layer 1/2 prerequisites for AI summarization reads. Parse the following structured tokens out of `$ARGUMENTS`:++| Token | Required | Meaning |+|-------|----------|---------|+| `mode=ai-read-only` | Yes | Confirms the posture; any other value is rejected with an error. |+| `primary=<logical_name>` | Yes | The primary table being summarised. Missing → stop and report the contract violation to the caller. |+| `tables=<csv>` | Yes | Comma-separated list of all tables in scope (primary + every `$expand` target). |+| `expand-targets=<csv>` | No | Sub-list of `tables` that are `$expand` targets; defaults to empty. |+| `caller=<skill-name>` | No | Informational — used in commit messages and the final summary. |++**When the sentinel is present:**++- Set an internal flag **AI-only read mode = true** that every downstream phase consults.+- Skip the Phase 3 interactive table confirmation and use the provided `tables` list verbatim (user has already confirmed in the caller).+- The Phase 4.1 `webapi-integration` prompt restricts operations to **read-only** (list + get by id).+- The Phase 6 Path B agent prompts apply the hardened AI-only posture documented in each agent's "AI-only read mode" section.+- The Phase 6 Path A script invocations use `--read` only for table permissions and omit primary keys / lookup write forms from `Webapi/<table>/fields`.+- No `AskUserQuestion` prompts are issued for Phase 3 or Phase 6.2 — the caller owns those decisions.+- **Defer all git commits to the caller.** Skip Phase 4.4 (`git add -A && git commit`) and Phase 6.5 (permissions/settings commit) entirely. The caller is batching changes into one or two commits at orchestrator-defined milestones; an unprompted commit here turns one logical change into three. Print the file lists you would have committed so the caller can reproduce them.+- **Suppress the end-of-skill deploy prompt.** Skip Phase 6.1 (deploy-now ask when `.powerpages-site` is missing — the caller has already gated on this), Phase 7.3 (final deploy ask), and Phase 7.4 (post-deploy notes). The caller owns the single end-of-orchestration deploy decision; nesting deploy prompts inside the delegation gives the user 2–3 redundant asks per run. Return the integration summary (Phase 7.2) without trailing deploy/notes.++**When the sentinel is absent**: proceed exactly as today (full CRUD, full interactive flow, auto-commit, deploy prompt). This is the regression guard — no human invocation changes behavior.++**Output**: Confirmed project root, framework, data model availability, deployment status, and (if sentinel present) parsed AI-read-only contract.---@@ -113,6 +139,10 @@ Ask the Explore agent to identify all Dataverse tables that need Web API integra> "Analyze this Power Pages code site and identify all Dataverse tables that need Web API integration. Check `.datamodel-manifest.json` for the data model, then search the source code for: mock data arrays, hardcoded data, placeholder fetch calls to `/_api/`, TypeScript interfaces matching Dataverse column patterns (publisher prefix like `cr*_`), TODO/FIXME comments about API integration, and components that display table data. For each table found, report: the table logical name, the entity set name (plural), which source files reference it, what operations are needed (read/create/update/delete), and whether an existing API client or service already exists in `src/shared/` or `src/services/`. Also check if `src/shared/powerPagesApi.ts` already exists."+**When AI-only read mode is active (Phase 1.6 flag set):** append the following to the prompt above:++> "The caller has specified **AI-READ-ONLY** mode for tables `[tables from sentinel]` (primary=`[primary]`, expand-targets=`[expand-targets]`). Operations needed for every table in that list = **read only**. Do NOT report create/update/delete call sites or mock-data replacement candidates. For each `$expand` target, also report the columns the primary's code `$select`s on that expansion (these become the minimal fields list)."+### 2.2 Identify Existing Integration CodeThe Explore agent should also report:@@ -154,7 +184,9 @@ Show the user:### 3.2 Confirm Tables-Use `AskUserQuestion` to confirm:+**When AI-only read mode is active (Phase 1.6 flag set):** skip this step entirely. Use the `tables` list parsed from the sentinel verbatim — the caller has already confirmed the selection with the user. Do not issue an `AskUserQuestion`.++Otherwise, use `AskUserQuestion` to confirm:| Question | Options ||----------|---------|@@ -162,7 +194,7 @@ Use `AskUserQuestion` to confirm:If the user selects specific tables or adds more, update the integration manifest accordingly.-**Output**: User-confirmed list of tables to integrate+**Output**: User-confirmed list of tables to integrate (or sentinel-supplied list in AI-only read mode)---@@ -190,6 +222,10 @@ For each table, use the `Task` tool to invoke the `webapi-integration` agent at>> Create the TypeScript types, CRUD service layer, and framework-specific hooks/composables. Replace any mock data or placeholder API calls in the referencing source files with the new service."+**When AI-only read mode is active (Phase 1.6 flag set):** replace "Operations needed: [read/create/update/delete]" with `Operations needed: read-only` and append to the prompt:++> "**AI-only read integration.** Do NOT emit create, update, or delete functions. Scaffold only `list<Table>` (paginated) and `get<Table>ById` in the service layer. Create the framework-specific read hook only (e.g. `use<Table>()` with `items`, `isLoading`, `error`, `refetch`; no mutation hooks). Do not wire mock-data replacements beyond what is needed for the AI summarization caller — the upstream skill will add the summarization service on top. The shared `src/shared/powerPagesApi.ts` client is still created if it does not already exist; the caller relies on it for the AI integration's read path."+### 4.2 Process First Table, Then Parallelize RemainingThe **first table** must be processed alone — it creates the shared `powerPagesApi.ts` client that all other tables depend on. After the first table completes and the shared client exists:@@ -209,14 +245,17 @@ After each agent completes (or after all parallel agents complete), verify the o### 4.4 Git Commit-After all integrations are complete, stage and commit:+**Skip when AI-only read mode is active** (Phase 1.6 flag set) — the caller batches commits.+Print the file list this phase would have staged so the caller can reproduce, then move on.++Otherwise, after all integrations are complete, stage and commit:```bashgit add -Agit commit -m "Add Web API integration for [table names]"```-**Output**: Integration code created for all confirmed tables, verified and committed+**Output**: Integration code created for all confirmed tables, verified and (in normal mode) committed---@@ -277,7 +316,14 @@ Present a table summarizing the verification:### 6.1 Check Deployment Prerequisite-Both agents require the `.powerpages-site` folder. If it doesn't exist:+Both agents require the `.powerpages-site` folder.++**When AI-only read mode is active** (Phase 1.6 flag set): the caller has already gated on+`.powerpages-site` existing — re-check it as a guard, and if it is genuinely absent, stop and+report the contract violation back to the caller (the caller will surface this to the user).+Do NOT issue the deploy prompt below — the caller owns the single deploy decision.++Otherwise, if `.powerpages-site` doesn't exist:Use `AskUserQuestion`:@@ -291,7 +337,14 @@ Use `AskUserQuestion`:### 6.2 Choose Permissions Source-Ask the user how they want to define the permissions using the `AskUserQuestion` tool:+**When AI-only read mode is active (Phase 1.6 flag set):** skip the permissions-source question+entirely and default to **Path B (let the architects figure it out)** — proceed directly to+section 6.3. Per the Phase 1.6 contract, no `AskUserQuestion` is issued here; the caller+(`/add-ai-webapi`) owns this decision, and the AI-only architect prompts in 6.3 already encode+the read-only posture. Path A (upload an existing permissions diagram) is an interactive human+path and does not apply to delegated runs.++Otherwise, ask the user how they want to define the permissions using the `AskUserQuestion` tool:**Question**: "How would you like to define the Web API permissions and settings for your site?"@@ -342,10 +395,18 @@ These two agents are **independent** — invoke them in parallel using two `TaskUse the `Task` tool to invoke the `table-permissions-architect` agent at `${CLAUDE_PLUGIN_ROOT}/agents/table-permissions-architect.md`:-**Prompt:**+**Prompt (default — full CRUD):**> "Analyze this Power Pages code site and propose table permissions. The following tables have been integrated with Web API: [list of tables integrated in Phase 4]. Check for existing web roles and table permissions. Propose a complete table permissions plan covering all integrated tables. After I approve the plan, create the web role and table permission YAML files using the deterministic scripts."+**Prompt (AI-only read mode active):** append to the default prompt:++> "**AI-only read integration.** The caller is `/add-ai-webapi` and these tables will be summarised by `/_api/summarization/data/v1.0/` — the endpoint is semantically a read and never mutates Dataverse. Therefore:+>+> - Set `read: true` **only**. Do NOT propose `create`, `write`, or `delete` even if the default convention would include them.+> - For collection-valued `$expand` targets (primary=`[primary]`, expand-targets=`[expand-targets]`), use **Parent scope** with `read: true`, and add `appendTo: true` on the parent table permission so the relationship traversal is allowed.+> - If no suitable web role exists, surface this back to the caller — `/add-ai-webapi` will invoke `/create-webroles` up front; do not block on role creation here."+The agent will:1. Analyze the site and propose a plan (with Mermaid diagram)@@ -358,10 +419,19 @@ The agent will:Use the `Task` tool to invoke the `webapi-settings-architect` agent at `${CLAUDE_PLUGIN_ROOT}/agents/webapi-settings-architect.md`:-**Prompt:**+**Prompt (default — full CRUD):**> "Analyze this Power Pages code site and propose Web API site settings. The following tables have been integrated with Web API: [list of tables integrated in Phase 4]. Check for existing site settings and query Dataverse for exact column LogicalNames. Propose site settings with case-sensitive validated column names. After I approve the plan, create the site setting YAML files using the deterministic scripts."+**Prompt (AI-only read mode active):** append to the default prompt:++> "**AI-only read integration.** These tables will be summarised by `/_api/summarization/data/v1.0/`. The fields list rules are stricter than the default CRUD posture:+>+> - `Webapi/<table>/fields` must contain **exactly** the columns named in the primary's `$select` / `$expand` — no more, no less.+> - Do **not** include the primary key column. The summarization endpoint carries the record id in the URL path; Microsoft's shipped case preset ships `Webapi/incident/fields = description,title` with no `incidentid`.+> - For lookup columns, include **only** the `_<col>_value` OData read form. Do NOT add the write form `<col>` unless the same table has non-AI mutation code elsewhere.+> - Still query Dataverse for exact LogicalNames (case-sensitive) — case mismatches produce 403."+The agent will:1. Analyze the site, query Dataverse for exact column LogicalNames@@ -392,6 +462,8 @@ Capture the JSON output (`{ "id": "<uuid>", "filePath": "<path>" }`) — use theFor each table permission in the plan. Process **parent permissions before child permissions** — children need the parent's UUID from the JSON output.+**When AI-only read mode is active (Phase 1.6 flag set):** the default flag set is `--read` only. Do NOT pass `--create`, `--write`, or `--delete` for any permission in scope — AI summarization reads never mutate. For Parent-scope child permissions, still pass `--parentPermissionId` and `--parentRelationshipName`; on the parent permission add `--appendto` so the AI endpoint can traverse the relationship.+**For Global/Contact/Account/Self scope:**```bash@@ -437,16 +509,26 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" --projectRoot "<PROJ**Lookup columns**: For every lookup column, include **both** the LogicalName (`cr87b_categoryid`) AND the OData computed attribute (`_cr87b_categoryid_value`) in the fields value. The Power Pages Web API does a literal match — the LogicalName is needed for write operations, the `_..._value` form is needed for read operations (`$select`, `$filter`). Missing either form causes 403 errors.+**AI-only read mode (Phase 1.6 flag set)**: the fields-value rules tighten:++- Include only the columns named in the primary's `$select` / `$expand`. Extra columns expand the allowlist without any caller reading them.+- Do NOT include the primary key. The summarization endpoint carries the record id in the URL path; Microsoft's shipped case preset ships `Webapi/incident/fields = description,title` with no `incidentid`.+- For lookup columns, include only the `_<col>_value` read form. Omit the LogicalName write form — no write operations run against these tables in AI mode.+- The aggregate `*` exception still applies if the summarised table also has aggregate OData code elsewhere in the site.+### 6.5 Git Commit-Stage and commit the permission and settings files:+**Skip when AI-only read mode is active** (Phase 1.6 flag set) — the caller batches commits.+Print the file list this phase would have staged so the caller can reproduce, then move on.++Otherwise, stage and commit the permission and settings files:```bashgit add -Agit commit -m "Add table permissions and Web API site settings for [table names]"```-**Output**: Table permissions and site settings created, verified, and committed+**Output**: Table permissions and site settings created, verified, and (in normal mode) committed---@@ -478,7 +560,10 @@ Present a summary of everything that was done:### 7.3 Ask to Deploy-Use `AskUserQuestion`:+**Skip when AI-only read mode is active** (Phase 1.6 flag set) — the caller owns the single+end-of-orchestration deploy decision. Return the Phase 7.2 summary and stop.++Otherwise, use `AskUserQuestion`:| Question | Options ||----------|---------|@@ -492,14 +577,17 @@ Use `AskUserQuestion`:### 7.4 Post-Deploy Notes-After deployment (or if skipped), remind the user:+**Skip when AI-only read mode is active** — the caller emits its own post-deploy guidance+that covers AI-specific concerns (governance hierarchy, runtime version, Bing dependency).++Otherwise, after deployment (or if skipped), remind the user:- **Test the API**: Open the deployed site and verify Web API calls work in the browser's Network tab- **Check permissions**: If any API call returns 403, verify table permissions and site settings are correct. The most common cause of 403 errors is column names in `Webapi/<table>/fields` not matching the exact Dataverse LogicalName (case-sensitive — must be all lowercase). If the failing request uses aggregate OData (`$apply`, `aggregate`, grouped totals), also verify `Webapi/<table>/fields` is set to `*`.- **Disable innererror in production**: If `Webapi/error/innererror` was enabled for debugging, disable it before going live- **Web roles**: Users must be assigned the appropriate web roles to access protected APIs-**Output**: Summary presented, deployment completed or deferred, post-deploy guidance provided+**Output**: Summary presented; deployment completed or deferred (normal mode), or returned to caller (AI-only read mode).---