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
power-automate: release 3.2.1 (#684)
Matt Townsend89d6452b45af
diff --git a/.gitattributes b/.gitattributesindex 2ef85d7ea..6e215e4a3 100644--- a/.gitattributes+++ b/.gitattributes@@ -1,3 +1,4 @@# This generated runtime has a recorded byte-level SHA-256 digest, so Git must# not rewrite its line endings on Windows checkouts.plugins/mcp-apps/assets/self-contained/mcp-app-runtime.min.js -text+plugins/power-automate/server/mcp.mjs text eol=lfdiff --git a/.github/workflows/power-automate-script-tests.yml b/.github/workflows/power-automate-script-tests.ymlnew file mode 100644index 000000000..05478b333--- /dev/null+++ b/.github/workflows/power-automate-script-tests.yml@@ -0,0 +1,53 @@+name: power-automate-script-tests++on:+ pull_request:+ branches:+ - main+ paths:+ - "plugins/power-automate/**"+ - ".github/workflows/power-automate-script-tests.yml"+ push:+ branches:+ - main+ paths:+ - "plugins/power-automate/**"+ - ".github/workflows/power-automate-script-tests.yml"++permissions:+ contents: read++concurrency:+ group: power-automate-script-tests-${{ github.event.pull_request.number || github.ref }}+ cancel-in-progress: true++jobs:+ test-power-automate-scripts:+ name: test-power-automate-scripts (${{ matrix.os }}, node ${{ matrix.node }})+ runs-on: ${{ matrix.os }}+ timeout-minutes: 15+ env:+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_AUTOMATE_OPTOUT: "1"+ strategy:+ fail-fast: false+ matrix:+ os:+ - ubuntu-latest+ - windows-latest+ - macos-latest+ node:+ - 20+ - 22+ steps:+ - name: checkout+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0++ - name: setup-node+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0+ with:+ node-version: ${{ matrix.node }}++ - name: run-power-automate-script-tests+ shell: bash+ working-directory: plugins/power-automate+ run: npm testdiff --git a/.github/workflows/shared-telemetry-tests.yml b/.github/workflows/shared-telemetry-tests.ymlindex 11f4a427a..1d4115326 100644--- a/.github/workflows/shared-telemetry-tests.yml+++ b/.github/workflows/shared-telemetry-tests.yml@@ -50,6 +50,7 @@ jobs:POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: "1"POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: "1"POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "1"+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_AUTOMATE_OPTOUT: "1"strategy:fail-fast: falsematrix:diff --git a/README.md b/README.mdindex ed2354fdc..bf967c7e8 100644--- a/README.md+++ b/README.md@@ -337,6 +337,6 @@ Any use of third-party trademarks or logos are subject to those third-party's po## Telemetry-Power Pages, Mobile Apps, and Model Apps ship 1DS telemetry code, but their committed configurations and event schemas differ. All three are enabled and default-on. Power Pages events can include Dataverse organization and Entra tenant GUIDs when PAC is signed in, plus the signed-in user's Entra object ID when PAC exposes it. Mobile Apps excludes those identity fields and records its documented invocation, project-instance, checkpoint, and App Insights selection fields. Model Apps events can include organization and tenant GUIDs but exclude the signed-in user's Entra object ID.+Power Pages, Mobile Apps, Model Apps, and Power Automate ship 1DS telemetry code, but their committed configurations and event schemas differ. All four are enabled and default-on. Power Pages events can include Dataverse organization and Entra tenant GUIDs when PAC is signed in, plus the signed-in user's Entra object ID when PAC exposes it. Mobile Apps excludes those identity fields and records its documented invocation, project-instance, checkpoint, and App Insights selection fields. Model Apps events can include organization and tenant GUIDs but exclude the signed-in user's Entra object ID. Power Automate records the same identity fields as Power Pages from its skill hooks, and its bundled MCP server and CLI additionally record a per-invocation outcome (success or failure), duration, and, on failure, the error's class name and code — never the error message. Power Automate provisions public-cloud ingestion only, so events outside public cloud stay in the local mirror.For an enabled plugin, users opt out of transmission via `/<plugin>:telemetry off` (for example, `/power-pages:telemetry off`), stored in `~/.power-platform-skills/config.json`. The local diagnostic mirror is still written after this transmission-only opt-out. Each adopting plugin also honors `POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` for automation and CI. The environment variable has highest precedence and disables transmission regardless of the saved command choice. See the [shared telemetry guide](shared/telemetry/README.md) for the full field list, current plugin states, geo-routing behavior, kill-switch semantics, and local-mirror behavior.diff --git a/plugins/power-automate/.claude-plugin/plugin.json b/plugins/power-automate/.claude-plugin/plugin.jsonindex 516a5ba75..bbbdff331 100644--- a/plugins/power-automate/.claude-plugin/plugin.json+++ b/plugins/power-automate/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-automate",- "version": "3.1.0",+ "version": "3.2.1","description": "Build, edit, run, and debug Power Automate cloud flows via the FlowAgent MCP server — connection lifecycle, surgical edits, copy across environments, run management, and validated expressions.","author": {"name": "Microsoft",diff --git a/plugins/power-automate/.plugin/plugin.json b/plugins/power-automate/.plugin/plugin.jsonindex 516a5ba75..bbbdff331 100644--- a/plugins/power-automate/.plugin/plugin.json+++ b/plugins/power-automate/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-automate",- "version": "3.1.0",+ "version": "3.2.1","description": "Build, edit, run, and debug Power Automate cloud flows via the FlowAgent MCP server — connection lifecycle, surgical edits, copy across environments, run management, and validated expressions.","author": {"name": "Microsoft",diff --git a/plugins/power-automate/README.md b/plugins/power-automate/README.mdindex db3c1f4ee..6f11f200c 100644--- a/plugins/power-automate/README.md+++ b/plugins/power-automate/README.md@@ -58,3 +58,17 @@ error if the bundle is missing. That file is a single self-contained ESM bundleAuth uses Azure CLI (`az login`) plus MSAL for connectivity endpoints — see`CLAUDE.md` and `references/connection-patterns.md` in this folder.++## Telemetry logs++Power Automate hook telemetry writes per-session logs under+`~/.power-platform-skills/telemetry/power-automate/sessions/` by default; the+base directory follows `POWER_PLATFORM_SKILLS_CONFIG_DIR` when set. Old+session logs are pruned after 14 days.++The FlowAgent CLI/MCP engine writes a separate local mirror to+`~/.flowagent/telemetry.jsonl` by default. Set `FLOWAGENT_TELEMETRY_LOG` to+change its path. The core log is not automatically pruned. See+[`skills/telemetry/SKILL.md`](skills/telemetry/SKILL.md) for telemetry controls and+[`references/telemetry.md`](references/telemetry.md) for collection and routing+details. Both guides ship inside the plugin.diff --git a/plugins/power-automate/hooks/hooks.json b/plugins/power-automate/hooks/hooks.jsonnew file mode 100644index 000000000..8ce3ef672--- /dev/null+++ b/plugins/power-automate/hooks/hooks.json@@ -0,0 +1,27 @@+{+ "hooks": {+ "PreToolUse": [+ {+ "matcher": "Skill|skill",+ "hooks": [+ {+ "type": "command",+ "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-skill-pretool-telemetry.js'));\"",+ "timeout": 30+ }+ ]+ }+ ],+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-user-prompt-telemetry.js'));\"",+ "timeout": 30+ }+ ]+ }+ ]+ }+}diff --git a/plugins/power-automate/hooks/run-skill-pretool-telemetry.js b/plugins/power-automate/hooks/run-skill-pretool-telemetry.jsnew file mode 100644index 000000000..09ded4007--- /dev/null+++ b/plugins/power-automate/hooks/run-skill-pretool-telemetry.js@@ -0,0 +1,174 @@+#!/usr/bin/env node+"use strict";++const path = require("node:path");+const fs = require("node:fs");+const os = require("node:os");+const crypto = require("node:crypto");++const PLUGIN_ROOT = path.resolve(__dirname, "..");+const TELEMETRY_DIR = path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry");++let emitSpawn, eventsLib, sessionLib, agentInfoLib, resolverLoader, asyncExt;+try {+ emitSpawn = require(path.join(TELEMETRY_DIR, "lib", "emit-spawn"));+ eventsLib = require(path.join(TELEMETRY_DIR, "lib", "events"));+ sessionLib = require(path.join(TELEMETRY_DIR, "lib", "session"));+ agentInfoLib = require(path.join(TELEMETRY_DIR, "lib", "agent-info"));+ resolverLoader = require(path.join(TELEMETRY_DIR, "lib", "resolver-loader"));+ // Non-blocking, disk-cached PAC reads layered on top of the shared library,+ // which exposes only synchronous readers.+ asyncExt = require(path.join(TELEMETRY_DIR, "async-ext"));+} catch {+ process.exit(0);+}++let hookUtils;+try {+ hookUtils = require(path.join(PLUGIN_ROOT, "scripts", "lib", "pa-hook-utils"));+} catch {+ process.exit(0);+}++function readPluginVersion() {+ try {+ const manifest = JSON.parse(+ fs.readFileSync(path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"), "utf8")+ );+ return manifest.version || "unknown";+ } catch {+ return "unknown";+ }+}++function readIkey() {+ // Test/override seam: POWER_PLATFORM_SKILLS_IKEY_JSON points at an alternate+ // ikey.json so tests can flip disabled/region state without mutating the+ // checked-in config file. Mirrors emit-dispatcher.js / emit-from-prompt.js.+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ const ikeyPath =+ override && override.trim()+ ? override+ : path.join(TELEMETRY_DIR, "ikey.json");+ try {+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));+ return { cfg, ikeyPath, eventStreamName: cfg.event_stream_name || "", disabled: cfg.disabled === true };+ } catch {+ // ikey.json missing/unreadable → fail CLOSED (disabled: true), matching the+ // dispatcher's kill-switch semantics so a missing/corrupt config can't be+ // bypassed into an emit attempt.+ return { cfg: null, ikeyPath, eventStreamName: "", disabled: true };+ }+}++function osFriendlyName(platform) {+ if (platform === "win32") return "Windows";+ if (platform === "darwin") return "Mac";+ if (platform === "linux") return "Linux";+ return platform;+}++function readStdin() {+ return new Promise((resolve) => {+ let buf = "";+ process.stdin.setEncoding("utf8");+ process.stdin.on("data", (c) => (buf += c));+ process.stdin.on("end", () => resolve(buf));+ process.stdin.on("error", () => resolve(buf));+ });+}++(async () => {+ const raw = await readStdin();+ let parsed;+ try {+ parsed = JSON.parse(raw);+ } catch {+ process.exit(0);+ }++ const skillName = hookUtils.getTrackedSkillFromToolInput(parsed.tool_input);+ if (!skillName) process.exit(0);++ // Repo-side hard-off / unconfigured: gate BEFORE the pac shell-outs+ // (`pac auth who` ~3s + `pac --version` ~2s) so a disabled or unconfigured+ // plugin costs effectively nothing. The user opt-out is NOT a fast-path: the+ // enriched event is still built and dispatched so the detached dispatcher can+ // write the local diagnostic mirror; it reads the per-plugin config and skips+ // the POST. (Opting out therefore costs the same as an enabled run.)+ const { cfg, ikeyPath, eventStreamName, disabled } = readIkey();+ if (disabled) process.exit(0);+ const resolver = resolverLoader.loadResolver(path.dirname(ikeyPath));+ let provisioned;+ try {+ provisioned =+ resolver && typeof resolver.isProvisioned === "function"+ ? resolver.isProvisioned(cfg)+ : !!(cfg && cfg.instrumentationKey);+ } catch {+ // A plugin resolver threw — treat as not provisioned so a bad resolver+ // can't crash the pretool hook and impact the tool run (fail closed).+ provisioned = false;+ }+ if (!provisioned) process.exit(0);++ const correlation_id = crypto.randomUUID();++ const configDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "";+ const fakeProbe = process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "";++ // Read the active PAC identity fresh on each hook invocation; only the+ // non-identity PAC version is cached on disk. Run both PAC calls in parallel.+ let pacAuth = null;+ let agentInfo = {};+ try {+ const [authResult, versionResult] = await Promise.all([+ asyncExt.readPacAuthAsync().catch(() => null),+ asyncExt.readPacCliVersionAsync().catch(() => ""),+ ]);+ pacAuth = authResult;+ agentInfo = {+ ...agentInfoLib.readAiAgent(),+ pacCliVersion: versionResult,+ };+ } catch {+ pacAuth = null;+ agentInfo = {};+ }++ const fields = {+ pluginName: "power-automate",+ pluginVersion: readPluginVersion(),+ sessionId: sessionLib.getSessionId(sessionLib.resolveHostSessionId(parsed)),+ correlationId: correlation_id,+ osName: osFriendlyName(process.platform),+ osVersion: os.release(),+ nodeVersion: "v" + String(process.versions.node).split(".")[0],+ skillName,+ };+ if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;+ if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;+ if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;+ if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;+ if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;++ try {+ emitSpawn.fireAndForget(+ eventsLib.buildSkillStarted(eventStreamName, fields),+ {+ cloud: (pacAuth && pacAuth.cloud) || "",+ configDir,+ fakeProbe,+ // Point the dispatcher at the same ikey.json readIkey() used — the+ // override seam when set, otherwise this plugin's real config. This keeps+ // shared-source tests and plugin-bundled library copies from accidentally+ // falling back to shared/telemetry's placeholder ikey.json.+ ikeyJsonPath: ikeyPath,+ }+ );+ } catch {+ // fail closed+ }++ process.exit(0);+})().catch(() => process.exit(0));diff --git a/plugins/power-automate/hooks/run-user-prompt-telemetry.js b/plugins/power-automate/hooks/run-user-prompt-telemetry.jsnew file mode 100644index 000000000..d0c7f1a3d--- /dev/null+++ b/plugins/power-automate/hooks/run-user-prompt-telemetry.js@@ -0,0 +1,77 @@+#!/usr/bin/env node+"use strict";++const path = require("node:path");+const fs = require("node:fs");++const PLUGIN_ROOT = path.resolve(__dirname, "..");+const TELEMETRY_DIR = path.join(PLUGIN_ROOT, "scripts", "lib", "telemetry");++let emitFromPrompt, hookUtils, sessionLib;+try {+ // async-ext wraps lib/emit-from-prompt with non-blocking, disk-cached PAC+ // reads; lib/ itself is a byte-identical copy of the shared library.+ emitFromPrompt = require(path.join(TELEMETRY_DIR, "async-ext"));+ hookUtils = require(path.join(+ PLUGIN_ROOT,+ "scripts",+ "lib",+ "pa-hook-utils"+ ));+ sessionLib = require(path.join(TELEMETRY_DIR, "lib", "session"));+} catch {+ process.exit(0);+}++function readPluginVersion() {+ try {+ const manifest = JSON.parse(+ fs.readFileSync(+ path.join(PLUGIN_ROOT, ".claude-plugin", "plugin.json"),+ "utf8"+ )+ );+ return manifest.version || "unknown";+ } catch {+ return "unknown";+ }+}++function readStdin() {+ return new Promise((resolve) => {+ let buf = "";+ process.stdin.setEncoding("utf8");+ process.stdin.on("data", (c) => (buf += c));+ process.stdin.on("end", () => resolve(buf));+ process.stdin.on("error", () => resolve(buf));+ });+}++(async () => {+ const raw = await readStdin();+ if (!raw) process.exit(0);++ let parsed;+ try {+ parsed = JSON.parse(raw);+ } catch {+ process.exit(0);+ }++ const prompt = typeof parsed.prompt === "string" ? parsed.prompt : "";+ if (!prompt) process.exit(0);++ try {+ await emitFromPrompt.emitSkillStartedFromPromptAsync(prompt, {+ pluginName: "power-automate",+ pluginVersion: readPluginVersion(),+ trackedSkills: hookUtils.TRACKED_SKILLS,+ telemetryDir: TELEMETRY_DIR,+ sessionId: sessionLib.resolveHostSessionId(parsed),+ });+ } catch {+ // fail closed — telemetry never blocks the user's prompt+ }++ process.exit(0);+})().catch(() => process.exit(0));diff --git a/plugins/power-automate/package.json b/plugins/power-automate/package.jsonnew file mode 100644index 000000000..6a9c2938a--- /dev/null+++ b/plugins/power-automate/package.json@@ -0,0 +1,9 @@+{+ "name": "@microsoft/power-automate-mcp-plugin",+ "private": true,+ "type": "commonjs",+ "description": "Marketplace plugin assets (hooks + telemetry) for the power-automate plugin. CommonJS scope override — the repo root is type:module.",+ "scripts": {+ "test": "node --test scripts/lib/telemetry/async-ext.test.cjs scripts/release-contract.test.cjs"+ }+}diff --git a/plugins/power-automate/references/telemetry.md b/plugins/power-automate/references/telemetry.mdnew file mode 100644index 000000000..354908e19--- /dev/null+++ b/plugins/power-automate/references/telemetry.md@@ -0,0 +1,73 @@+# Power Automate telemetry++The plugin records usage metadata through two separate paths: skill hooks and+the bundled MCP/CLI engine. Transmission is default-on when that path can+establish an eligible destination. A local diagnostic mirror is retained even+when transmission is opted out.++## Collection and identifiers++Skill hooks record `skill_started`, plugin and agent versions, OS and Node+metadata, and random session/correlation IDs. When PAC exposes them, these+events include the Dataverse organization GUID (`orgId`), Entra tenant GUID+(`tenantId`), and signed-in user's Entra object ID (`eventInfo.aadObjectId`).+Hosts firing both skill hooks can record duplicate starts.++The MCP/CLI engine records tool/command starts and completions and flow+creation. These include names of tools/commands, outcome, duration, error+class/code, random session/correlation IDs, system and agent versions, and+environment GUID/location/region when available. Core events can include a+tenant GUID from `FLOWAGENT_TENANT_ID`; they do not include organization or+Entra user object IDs.++These identifiers are pseudonymous, not anonymous. Events never contain+prompts, skill arguments, tool inputs, request/response bodies, credentials,+usernames, email addresses, flow display names, paths, or error messages.+Top-level event fields are allowlisted; hook `eventInfo` is restricted to the+documented object ID.++## Routing++Hook events are eligible for transmission only when PAC positively identifies+public cloud. Unknown or sovereign clouds remain local. Organization-based+routing selects a configured US or EU collector; without an organization ID,+the configured US default is used, but only after the public-cloud gate passes.++Core MCP/CLI events require an environment ID, recognized environment location,+and positively identified commercial cloud. The location selects the matching+Power Automate collector and ingestion key; unknown locations never fall back+to a US route. Cloud is re-resolved for each eligible event from `PA_CLOUD`,+the CLI configuration, then Azure CLI, so a prior commercial resolution does+not authorize transmission after a cloud switch. Detection failures stay local.+Each detached core collector request has a five-second deadline.++## Opt out++Use `/power-automate:telemetry off` or set+`POWER_PLATFORM_SKILLS_TELEMETRY_POWER_AUTOMATE_OPTOUT=1` (also accepts `true`,+case-insensitive). The environment variable takes precedence over the saved+choice. Both paths stop remote transmission and keep their local mirrors.++The saved choice is `telemetry["power-automate"]` in+`~/.power-platform-skills/config.json`; `POWER_PLATFORM_SKILLS_CONFIG_DIR`+changes that directory. `/power-automate:telemetry on` restores the saved+opt-in but cannot override the environment opt-out.++The engine also honors legacy `FLOWAGENT_TELEMETRY=0` or+`POWER_PLATFORM_SKILLS_TELEMETRY=0` (`false` and `off` also accepted). These+disable core capture, including its local file; they are not the hook+transmission setting. The hook's committed `disabled` configuration is a+separate hard-off switch.++## Local logs++- Hooks: `~/.power-platform-skills/telemetry/power-automate/sessions/`, following+ `POWER_PLATFORM_SKILLS_CONFIG_DIR`. Session directories are pruned after+ 14 days and large logs rotated after 10 MB.+- MCP/CLI: `~/.flowagent/telemetry.jsonl`, overridable with+ `FLOWAGENT_TELEMETRY_LOG`. This log has no automatic retention policy.++`telemetry status` reports the hook choice and log location, not the eligibility+of a particular core event. The [telemetry skill](../skills/telemetry/SKILL.md)+also reports the core log path and existence. Users can inspect or delete+either local log.diff --git a/plugins/power-automate/scripts/lib/pa-hook-utils.js b/plugins/power-automate/scripts/lib/pa-hook-utils.jsnew file mode 100644index 000000000..51045d902--- /dev/null+++ b/plugins/power-automate/scripts/lib/pa-hook-utils.js@@ -0,0 +1,68 @@+const fs = require("fs");+const path = require("path");++const PLUGIN_ROOT = path.resolve(__dirname, "..", "..");+const SKILLS_DIR = path.join(PLUGIN_ROOT, "skills");++// Skills that must never emit usage telemetry about themselves. The telemetry+// control skill is excluded so checking/toggling telemetry does not self-emit.+const EXCLUDED_FROM_TRACKING = new Set(["telemetry"]);++function discoverTrackedSkills() {+ // Null-prototype map so inherited keys (toString/constructor/__proto__) don't+ // test truthy via bracket access.+ const trackedSkills = Object.create(null);+ let entries = [];+ try {+ entries = fs+ .readdirSync(SKILLS_DIR, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .sort((a, b) => a.name.localeCompare(b.name));+ } catch {+ return trackedSkills;+ }+ for (const entry of entries) {+ const skillName = entry.name;+ if (EXCLUDED_FROM_TRACKING.has(skillName)) continue;+ if (!fs.existsSync(path.join(SKILLS_DIR, skillName, "SKILL.md"))) continue;+ trackedSkills[skillName] = {};+ }+ return trackedSkills;+}++const TRACKED_SKILLS = discoverTrackedSkills();++function detectTrackedSkill(value) {+ if (typeof value !== "string") return null;+ const trimmed = value.trim();+ if (TRACKED_SKILLS[trimmed]) return trimmed;++ // Strip leading slash and optional plugin prefix: /create-flow, /power-automate:create-flow+ const normalized = trimmed.replace(/^\/?(?:power-automate:)?/, "").toLowerCase();+ if (TRACKED_SKILLS[normalized]) return normalized;++ // Fall back to searching for power-automate:<skill> anywhere in the string+ const commandMatch = trimmed.match(/power-automate:([a-z0-9-]+)/i);+ if (!commandMatch) return null;+ const skillName = commandMatch[1].toLowerCase();+ return TRACKED_SKILLS[skillName] ? skillName : null;+}++function getTrackedSkillFromToolInput(toolInput) {+ if (!toolInput || typeof toolInput !== "object") return null;+ for (const field of ["skill", "skill_name", "skillName", "name", "commandName", "command"]) {+ const skillName = detectTrackedSkill(toolInput[field]);+ if (skillName) return skillName;+ }+ try {+ return detectTrackedSkill(JSON.stringify(toolInput));+ } catch {+ return null;+ }+}++module.exports = {+ TRACKED_SKILLS,+ detectTrackedSkill,+ getTrackedSkillFromToolInput,+};diff --git a/plugins/power-automate/scripts/lib/telemetry/async-ext.js b/plugins/power-automate/scripts/lib/telemetry/async-ext.jsnew file mode 100644index 000000000..ba1abdd8f--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/async-ext.js@@ -0,0 +1,274 @@+"use strict";++// Non-blocking variants of the shared telemetry library's PAC readers.+//+// Why this file exists: scripts/lib/telemetry/lib is a byte-identical copy of+// shared/telemetry/lib and must stay that way, so plugin-specific additions+// cannot live inside it. The shared readers are synchronous and fork `pac`+// with an 8s timeout; on Windows a cold `pac auth who` is ~4s and+// `pac --version` ~2s, and the hooks run on every tracked prompt. This module+// adds two things on top of the shared library without modifying it:+//+// 1. async execution, so the hook's event loop is not blocked, and+// 2. a disk cache for the non-identity PAC version, so its .NET cold start+// is paid at most once per TTL across hook processes.+//+// Executables are resolved through the shared library's native-exec, so `pac`+// is started by absolute path from PATH with shell:false — never by bare name+// out of the working directory. Every path is best-effort and fail-closed:+// a missing executable, timeout, non-zero exit, or unparseable output all+// resolve to the empty result and never throw.++const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { execFile } = require("node:child_process");++const { resolveNative } = require("./lib/native-exec");+const { readAiAgent } = require("./lib/agent-info");+const { detectSlashCommand } = require("./lib/prompt-detector");+const { loadResolver } = require("./lib/resolver-loader");+const { emitSkillStartedFromPrompt } = require("./lib/emit-from-prompt");++const TIMEOUT_MS = 8000;++// The CLI version changes only when the user updates PAC.+const VERSION_CACHE_TTL_MS = 24 * 60 * 60 * 1000;++const LEGACY_AUTH_CACHE_FILE = "pac-auth-cache.json";+const VERSION_CACHE_FILE = "pac-version-cache.json";++let authCache;+let versionCache;++function _resetCache() {+ authCache = undefined;+ versionCache = undefined;+}++function defaultCacheDir() {+ return (+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR ||+ path.join(os.homedir(), ".power-platform-skills")+ );+}++function cachePath(fileName, configDir) {+ return path.join(configDir || defaultCacheDir(), fileName);+}++// Returns the cached entry's `value`, or null when absent, unreadable, or expired.+function readDiskCache(fileName, configDir) {+ try {+ const entry = JSON.parse(fs.readFileSync(cachePath(fileName, configDir), "utf8"));+ if (!entry || typeof entry.expiresAt !== "number" || entry.expiresAt < Date.now()) {+ return null;+ }+ return "value" in entry ? entry.value : null;+ } catch {+ return null;+ }+}++// Atomic write (tmp + rename) so a concurrent reader never sees a partial file.+let writeSeq = 0;+function writeDiskCache(fileName, value, ttlMs, configDir) {+ const dir = configDir || defaultCacheDir();+ try {+ fs.mkdirSync(dir, { recursive: true });+ } catch {+ return;+ }+ const file = cachePath(fileName, dir);+ const tmp = `${file}.tmp.${process.pid}.${writeSeq++}`;+ try {+ fs.writeFileSync(tmp, JSON.stringify({ value, expiresAt: Date.now() + ttlMs }), "utf8");+ fs.renameSync(tmp, file);+ } catch {+ try {+ fs.unlinkSync(tmp);+ } catch {+ /* ignore */+ }+ }+}++// execFile against an absolute path resolved from PATH. Resolves to stdout, or+// "" when the tool is absent or the run fails without usable output.+function runNativeAsync(name, args) {+ return new Promise((resolve) => {+ let file;+ try {+ file = resolveNative(name);+ } catch {+ file = null;+ }+ if (!file) {+ resolve("");+ return;+ }+ try {+ execFile(+ file,+ args,+ { encoding: "utf8", timeout: TIMEOUT_MS, windowsHide: true, shell: false },+ (err, stdout) => {+ // PAC 2.x prints its banner to stdout and then exits non-zero for an+ // unknown command, so stdout captured alongside an error still parses.+ resolve(stdout || (err && err.stdout ? String(err.stdout) : ""));+ }+ );+ } catch {+ resolve("");+ }+ });+}++function pickLine(text, label) {+ const re = new RegExp("^\\s*" + label + "\\s*:\\s*(\\S.*?)\\s*$", "im");+ const match = text.match(re);+ return match ? match[1] : null;+}++// Mirrors lib/pac-auth.js's banner parse, including `Entra ID Object Id`.+function parseAuth(output) {+ if (typeof output !== "string" || !output) return null;+ const tenantId = pickLine(output, "Tenant Id");+ const orgId = pickLine(output, "Organization Id");+ if (!tenantId && !orgId) return null;+ return {+ orgId: orgId || "",+ tenantId: tenantId || "",+ cloud: pickLine(output, "Cloud") || "",+ objectId: pickLine(output, "Entra ID Object Id") || "",+ };+}++function parseVersion(stdout) {+ const match = String(stdout || "").match(/Version:\s*(\d+\.\d+\.\d+(?:\.\d+)?)/);+ return match ? match[1] : "";+}++// Per-process cache → async `pac auth who`. Identity is never persisted across+// hook processes, so PAC profile switches cannot reuse another profile's IDs.+async function readPacAuthAsync(opts = {}) {+ if (authCache !== undefined) return authCache;+ try {+ fs.unlinkSync(cachePath(LEGACY_AUTH_CACHE_FILE));+ } catch {+ /* no legacy cache to remove, or it is not writable */+ }+ if (opts._exec === false) {+ authCache = null;+ return null;+ }+ const runNative = typeof opts._runNative === "function" ? opts._runNative : runNativeAsync;+ const result = parseAuth(await runNative("pac", ["auth", "who"]));+ authCache = result || null;+ return authCache;+}++// Per-process cache → disk cache → async `pac --version`. Resolves to the+// version string or "".+async function readPacCliVersionAsync(opts = {}) {+ if (versionCache !== undefined) return versionCache;+ if (opts._exec === false) {+ versionCache = "";+ return "";+ }+ if (opts._skipDiskCache !== true) {+ const cached = readDiskCache(VERSION_CACHE_FILE);+ if (typeof cached === "string" && cached) {+ versionCache = cached;+ return versionCache;+ }+ }+ const version = parseVersion(await runNativeAsync("pac", ["--version"]));+ versionCache = version;+ if (version) writeDiskCache(VERSION_CACHE_FILE, version, VERSION_CACHE_TTL_MS);+ return versionCache;+}++// Reads the plugin's telemetry config the same way lib/emit-from-prompt.js's+// readIkey does, so the gates below agree with it. Fails closed.+function readIkeyConfig(telemetryDir) {+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ const overridePath = override && override.trim() ? override : "";+ if (!overridePath && (typeof telemetryDir !== "string" || !telemetryDir)) {+ return { cfg: null, dir: "", disabled: true };+ }+ const ikeyPath = overridePath || path.join(telemetryDir, "ikey.json");+ try {+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));+ return { cfg, dir: path.dirname(ikeyPath), disabled: cfg.disabled === true };+ } catch {+ return { cfg: null, dir: path.dirname(ikeyPath), disabled: true };+ }+}++// Async variant of lib/emit-from-prompt.js's emitSkillStartedFromPrompt.+//+// The two PAC reads run in parallel off the event loop and are then handed to+// the shared implementation through its documented `_readPacAuth` /+// `_readAgentInfo` seams, so event construction and dispatch stay in one place.+// The slash-command, kill-switch, and provisioning gates are evaluated here+// first — matching the shared implementation's ordering — so an untracked+// prompt or a disabled/unprovisioned plugin never forks `pac`.+async function emitSkillStartedFromPromptAsync(promptText, opts = {}) {+ const { pluginName, trackedSkills, telemetryDir, _readPacAuth, _readAgentInfo } = opts;++ const skillName = detectSlashCommand(promptText, { pluginName, trackedSkills });+ if (!skillName) return { emitted: false, skillName: null };++ // Caller supplied its own readers (tests): nothing to prefetch.+ if (typeof _readPacAuth === "function" || typeof _readAgentInfo === "function") {+ return emitSkillStartedFromPrompt(promptText, opts);+ }++ const { cfg, dir, disabled } = readIkeyConfig(telemetryDir);+ if (disabled) return { emitted: false, skillName };++ const resolver = loadResolver(dir);+ let provisioned;+ try {+ provisioned =+ resolver && typeof resolver.isProvisioned === "function"+ ? resolver.isProvisioned(cfg)+ : !!(+ cfg &&+ cfg.instrumentationKey &&+ cfg.instrumentationKey !== "PLACEHOLDER_REPLACE_BEFORE_SHIPPING"+ );+ } catch {+ provisioned = false;+ }+ if (!provisioned) return { emitted: false, skillName };++ let pacAuth = null;+ let agentInfo = {};+ try {+ const [auth, version] = await Promise.all([+ readPacAuthAsync().catch(() => null),+ readPacCliVersionAsync().catch(() => ""),+ ]);+ pacAuth = auth;+ agentInfo = { ...readAiAgent(), pacCliVersion: version };+ } catch {+ pacAuth = null;+ agentInfo = {};+ }++ return emitSkillStartedFromPrompt(promptText, {+ ...opts,+ _readPacAuth: () => pacAuth,+ _readAgentInfo: () => agentInfo,+ });+}++module.exports = {+ readPacAuthAsync,+ readPacCliVersionAsync,+ emitSkillStartedFromPromptAsync,+ _resetCache,+ VERSION_CACHE_TTL_MS,+};diff --git a/plugins/power-automate/scripts/lib/telemetry/async-ext.test.cjs b/plugins/power-automate/scripts/lib/telemetry/async-ext.test.cjsnew file mode 100644index 000000000..dc81e23cf--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/async-ext.test.cjs@@ -0,0 +1,59 @@+"use strict";++const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { test } = require("node:test");++const asyncExt = require("./async-ext");+const resolver = require("./resolver");++test("PAC auth is reread per process and never reads or writes the legacy identity cache", async () => {+ const configDir = fs.mkdtempSync(path.join(os.tmpdir(), "pa-telemetry-auth-"));+ const originalConfigDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ const legacyFile = path.join(configDir, "pac-auth-cache.json");+ const legacyContents = JSON.stringify({+ value: { orgId: "stale-org", tenantId: "stale-tenant", cloud: "Public", objectId: "stale-user" },+ expiresAt: Date.now() + 60_000,+ });+ fs.writeFileSync(legacyFile, legacyContents, "utf8");++ try {+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = configDir;+ let calls = 0;+ const runNative = async (_name, args) => {+ assert.deepEqual(args, ["auth", "who"]);+ calls++;+ return [+ "Cloud: Public",+ `Organization Id: fresh-org-${calls}`,+ `Tenant Id: fresh-tenant-${calls}`,+ `Entra ID Object Id: fresh-user-${calls}`,+ ].join("\n");+ };++ asyncExt._resetCache();+ assert.equal((await asyncExt.readPacAuthAsync({ _runNative: runNative })).orgId, "fresh-org-1");+ assert.equal(calls, 1);+ assert.equal(fs.existsSync(legacyFile), false);++ asyncExt._resetCache();+ assert.equal((await asyncExt.readPacAuthAsync({ _runNative: runNative })).orgId, "fresh-org-2");+ assert.equal(calls, 2);+ assert.equal(fs.existsSync(legacyFile), false);+ } finally {+ asyncExt._resetCache();+ if (originalConfigDir === undefined) delete process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR;+ else process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR = originalConfigDir;+ fs.rmSync(configDir, { recursive: true, force: true });+ }+});++test("telemetry resolver fails closed for missing, unknown, and sovereign clouds", async () => {+ const input = { event: { data: { orgId: "org" } }, cfg: { regions: { us: {} } }, configDir: "" };+ assert.equal(await resolver.resolve({ ...input, cloud: undefined }), null);+ assert.equal(await resolver.resolve({ ...input, cloud: "" }), null);+ assert.equal(await resolver.resolve({ ...input, cloud: "unrecognized" }), null);+ assert.equal(await resolver.resolve({ ...input, cloud: "USGovHigh" }), null);+});diff --git a/plugins/power-automate/scripts/lib/telemetry/ikey.json b/plugins/power-automate/scripts/lib/telemetry/ikey.jsonnew file mode 100644index 000000000..0c77057c1--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/ikey.json@@ -0,0 +1,15 @@+{+ "event_stream_name": "paintegrations.event",+ "disabled": false,+ "default_region": "us",+ "regions": {+ "us": {+ "instrumentation_key": "2e7728f9f7ea42269fee5fbc9ea8a4f7-c026ab0c-92d3-4115-be4f-9d778dbe883f-7400",+ "collector_url": "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/"+ },+ "eu": {+ "instrumentation_key": "2bab69432aa84ef098c68cbc8756e40f-d2c36df3-d2d7-432a-af54-0136a07a0217-7486",+ "collector_url": "https://eu-mobile.events.data.microsoft.com/OneCollector/1.0/"+ }+ }+}diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/agent-info.js b/plugins/power-automate/scripts/lib/telemetry/lib/agent-info.jsnew file mode 100644index 000000000..aa6ec840b--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/agent-info.js@@ -0,0 +1,215 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");+const { runNative } = require("./native-exec");++let pacCliVersionCache;++// Reads the PAC CLI version once per process via `pac --version`, started by+// absolute path from PATH (see native-exec.js). Best-effort+// and fail-closed: missing executable, timeout, or unparseable output all+// resolve to "".+//+// PAC 2.x prints the version banner ("Version: X.Y.Z+...") to stdout as part+// of its preamble but then treats `--version` as an unknown command and+// exits with status 1. execFileSync throws on non-zero exit, attaching the+// captured stdout to err.stdout — so we parse that fallback path too.+function readPacCliVersion(opts = {}) {+ if (pacCliVersionCache !== undefined) return pacCliVersionCache;+ if (opts._exec === false) {+ pacCliVersionCache = "";+ return "";+ }+ const exec = typeof opts._exec === "function" ? opts._exec : runNative;+ let stdout = "";+ try {+ stdout = exec("pac", ["--version"], {+ encoding: "utf8",+ timeout: 8000,+ stdio: ["ignore", "pipe", "pipe"],+ });+ } catch (err) {+ stdout = (err && err.stdout) ? String(err.stdout) : "";+ }+ const match = String(stdout || "").match(/Version:\s*(\d+\.\d+\.\d+(?:\.\d+)?)/);+ pacCliVersionCache = match ? match[1] : "";+ return pacCliVersionCache;+}++// Test seam.+function _resetCache() {+ pacCliVersionCache = undefined;+}++// Parses a dotted semver out of the AI_AGENT env var. Claude Code sets+// AI_AGENT=claude-code_<maj>-<min>-<patch>_agent (e.g.+// "claude-code_2-1-156_agent"); the version segment uses dashes, so we+// normalize separators to dots. The "claude-code" name prefix carries no+// digits, so the first numeric run is the version.+function parseVersionFromAiAgent(aiAgent) {+ if (typeof aiAgent !== "string") return "";+ const match = aiAgent.match(/\d+(?:[._-]\d+)+/);+ return match ? match[0].replace(/[._-]/g, ".") : "";+}++// Reads the Claude Code CLI version. Primary source is the installed+// package.json: the hook subprocess inherits CLAUDE_CODE_EXECPATH from Claude+// Code, and jumping one directory above the executable's bin/ lands on the npm+// package root. That layout only exists for npm-global installs — the native+// installer ships a standalone binary with no sibling package.json — so when+// the read yields nothing, fall back to the version carried in AI_AGENT, which+// Claude Code sets regardless of install method.+function readClaudeCodeVersion(env) {+ const execPath = env.CLAUDE_CODE_EXECPATH;+ if (execPath) {+ try {+ const pkgPath = path.join(path.dirname(execPath), "..", "package.json");+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));+ if (pkg && typeof pkg.version === "string") return pkg.version;+ } catch {+ // pkg unreadable; fall through to the AI_AGENT fallback+ }+ }+ return parseVersionFromAiAgent(env.AI_AGENT);+}++function isTruthyEnv(value) {+ if (typeof value !== "string") return false;+ const normalized = value.trim().toLowerCase();+ return normalized !== "" && normalized !== "0" && normalized !== "false";+}++function firstEnv(env, keys) {+ for (const key of keys) {+ if (typeof env[key] === "string" && env[key]) return env[key];+ }+ return "";+}++function normalizeAgentName(name) {+ return String(name || "").toLowerCase().replace(/[^a-z0-9]/g, "");+}++const AGENT_DETECTORS = [+ {+ name: "Claude Code",+ aliases: ["claude", "claudecode"],+ isPresent: (env) => isTruthyEnv(env.CLAUDECODE),+ version: readClaudeCodeVersion,+ },+ {+ name: "Copilot CLI",+ aliases: ["copilot", "copilotcli", "githubcopilot", "githubcopilotcli"],+ isPresent: (env) => isTruthyEnv(env.COPILOT_CLI),+ version: (env) =>+ firstEnv(env, ["COPILOT_CLI_BINARY_VERSION", "COPILOT_CLI_VERSION"]),+ },+ {+ name: "Codex",+ aliases: ["codex", "codexcli", "openaicodex"],+ isPresent: (env) => isTruthyEnv(env.CODEX_CLI) || isTruthyEnv(env.CODEX),+ version: (env) =>+ firstEnv(env, [+ "CODEX_CLI_BINARY_VERSION",+ "CODEX_CLI_VERSION",+ "CODEX_VERSION",+ ]) || parseVersionFromAiAgent(env.AI_AGENT),+ },+ {+ name: "OpenCode",+ aliases: ["opencode", "opencodecli", "open_code"],+ isPresent: (env) => isTruthyEnv(env.OPENCODE_CLI) || isTruthyEnv(env.OPENCODE),+ version: (env) =>+ firstEnv(env, [+ "OPENCODE_CLI_BINARY_VERSION",+ "OPENCODE_CLI_VERSION",+ "OPENCODE_VERSION",+ ]) || parseVersionFromAiAgent(env.AI_AGENT),+ },+ {+ name: "Hermes",+ aliases: ["hermes", "hermescli", "hermesagent"],+ isPresent: (env) =>+ isTruthyEnv(env.HERMES_CLI) ||+ isTruthyEnv(env.HERMES) ||+ isTruthyEnv(env.HERMES_AGENT),+ version: (env) =>+ firstEnv(env, [+ "HERMES_CLI_BINARY_VERSION",+ "HERMES_CLI_VERSION",+ "HERMES_AGENT_VERSION",+ "HERMES_VERSION",+ ]) || parseVersionFromAiAgent(env.AI_AGENT),+ },+ {+ name: "OpenClaw",+ aliases: ["openclaw", "openclawcli"],+ isPresent: (env) =>+ isTruthyEnv(env.OPENCLAW_CLI) || isTruthyEnv(env.OPENCLAW),+ version: (env) =>+ firstEnv(env, [+ "OPENCLAW_CLI_BINARY_VERSION",+ "OPENCLAW_CLI_VERSION",+ "OPENCLAW_VERSION",+ ]) || parseVersionFromAiAgent(env.AI_AGENT),+ },+];++function detectorForName(name) {+ const normalized = normalizeAgentName(name);+ return AGENT_DETECTORS.find((detector) =>+ detector.aliases.some((alias) => normalizeAgentName(alias) === normalized)+ );+}++function detectFromAiAgent(env) {+ const aiAgent = env.AI_AGENT;+ if (typeof aiAgent !== "string" || !aiAgent) return null;+ const normalized = normalizeAgentName(aiAgent);+ const detector = AGENT_DETECTORS.find((candidate) =>+ candidate.aliases.some((alias) => normalized.includes(normalizeAgentName(alias)))+ );+ if (!detector) return null;+ return {+ aiAgentName: detector.name,+ aiAgentVersion: detector.version(env) || parseVersionFromAiAgent(aiAgent),+ };+}++function detectKnownAgent(env) {+ for (const detector of AGENT_DETECTORS) {+ if (detector.isPresent(env)) {+ return {+ aiAgentName: detector.name,+ aiAgentVersion: detector.version(env) || "",+ };+ }+ }+ return detectFromAiAgent(env);+}++// Detects the AI agent host. Prefers explicit env vars; falls back to+// built-in detection for known CLI hosts. When AI_AGENT_NAME is set explicitly+// but AI_AGENT_VERSION is empty, backfill the version from whichever detector+// matches — avoids emitting an empty aiAgentVersion just because the settings+// file only carried half the pair.+function readAiAgent(env = process.env) {+ const explicitName = env.AI_AGENT_NAME;+ const explicitVersion = env.AI_AGENT_VERSION;+ if (explicitName) {+ let version = explicitVersion || "";+ if (!version) {+ const explicitDetector = detectorForName(explicitName);+ const detected = detectKnownAgent(env);+ if (explicitDetector) version = explicitDetector.version(env) || "";+ if (!version && detected) version = detected.aiAgentVersion || "";+ }+ return { aiAgentName: explicitName, aiAgentVersion: version };+ }+ const detected = detectKnownAgent(env);+ if (detected) return detected;+ return { aiAgentName: "", aiAgentVersion: "" };+}++module.exports = { readPacCliVersion, readAiAgent, _resetCache };diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/emit-dispatcher.js b/plugins/power-automate/scripts/lib/telemetry/lib/emit-dispatcher.jsnew file mode 100644index 000000000..fc6571132--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/emit-dispatcher.js@@ -0,0 +1,280 @@+#!/usr/bin/env node+"use strict";++const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const https = require("node:https");+const { FIELD_TYPES, pick } = require("./events");+const { loadResolver } = require("./resolver-loader");+const { isTransmissionOptedOut } = require("./user-config");++function exitSilently() {+ process.exit(0);+}+process.on("uncaughtException", exitSilently);+process.on("unhandledRejection", exitSilently);+process.stdin.on("error", exitSilently);++const PLACEHOLDER_IKEY = "PLACEHOLDER_REPLACE_BEFORE_SHIPPING";+const DEFAULT_LOCAL_DIR = path.join(os.homedir(), ".power-platform-skills");+const FAKE_PROBE = process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "";+const CONFIG_DIR_ENV = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "";+const CLOUD_ENV = process.env.POWER_PLATFORM_SKILLS_CLOUD || "";+// Override env vars — TEST seams only. Production resolves the iKey/collector+// via the plugin resolver / static config in ikey.json and never sets these.+const IKEY_OVERRIDE = process.env.POWER_PLATFORM_SKILLS_IKEY || "";+const COLLECTOR_OVERRIDE = process.env.POWER_PLATFORM_SKILLS_COLLECTOR || "";++function localConfigDir() {+ return CONFIG_DIR_ENV || DEFAULT_LOCAL_DIR;+}++// Usage telemetry is default-on. The user opt-out is per-plugin and lives in+// config.json (telemetry[<pluginName>] === "off"), written by the telemetry skill.+// It suppresses TRANSMISSION only; the local mirror is written before this gate.+function isUserOptedOut(pluginName) {+ return isTransmissionOptedOut(localConfigDir(), pluginName);+}++// Path to the ikey.json config. Overridable via POWER_PLATFORM_SKILLS_IKEY_JSON+// so tests can point at a temp file with their own disabled / region state.+function ikeyJsonPath() {+ return (+ process.env.POWER_PLATFORM_SKILLS_IKEY_JSON ||+ path.join(__dirname, "..", "ikey.json")+ );+}++// Returns the parsed ikey.json, or null when it is missing/unreadable. null is+// treated as the repo kill switch (fail CLOSED): if we cannot read the config+// we cannot confirm emission is authorized, so we suppress rather than risk a+// POST / local log in an unexpected state.+function readIkeyConfig() {+ try {+ return JSON.parse(fs.readFileSync(ikeyJsonPath(), "utf8"));+ } catch {+ return null;+ }+}++// Repo-side kill switch: a missing/unreadable config (null) or an explicit+// `"disabled": true` suppresses ALL events regardless of opt-out or region+// state. Lets infrastructure PRs land while the tenant-side annotation + Kusto+// table are still being provisioned. Flip `disabled` to false when ready.+function isDisabledByConfig(cfg) {+ return !cfg || cfg.disabled === true;+}++// Reserved meta fields that builders always write into event.data. They are+// not user-facing telemetry columns, so they live outside FIELD_TYPES but+// must survive sanitization.+const RESERVED_META_FIELDS = new Set(["eventName", "eventType", "severity"]);++// Defense-in-depth allowlist filter. The builders in events.js are the+// intended entry point and already enforce FIELD_TYPES, but the dispatcher+// receives JSON over stdin from a separate process and cannot assume that.+// Re-run pick() against FIELD_TYPES here so any field that bypasses the+// builders is dropped before it reaches the wire.+function sanitizeData(data) {+ if (!data || typeof data !== "object") return {};+ const filtered = pick(data, Object.keys(FIELD_TYPES));+ for (const key of RESERVED_META_FIELDS) {+ if (typeof data[key] === "string") filtered[key] = data[key];+ }+ return filtered;+}++// Build the CS4.0 envelope from a pre-sanitized payload + timestamp. `sanitized`+// is shared with the local mirror so `data`/`time` stay byte-identical for+// every field except `eventInfo`: the tenant-side field mapping flattens+// `data.<key>` to a single `data_<key>` leaf and doesn't recurse into nested+// objects, so `eventInfo` is stringified just for the wire to survive that+// flattening. Kusto reads it back with `parse_json()`/`todynamic()`; the+// local mirror keeps the real object for human readability.+function buildEnvelope(eventName, time, sanitized, resolvedIKey, eventStreamName) {+ const wireData = { ...sanitized };+ if (wireData.eventInfo !== undefined) {+ wireData.eventInfo = JSON.stringify(wireData.eventInfo);+ }+ return {+ ver: "4.0",+ name: eventStreamName || eventName || "",+ time,+ iKey: "o:" + String(resolvedIKey || "").split("-")[0],+ data: wireData,+ };+}++// The wire envelope is the shared shape above unless the plugin's resolver.js+// exports an optional `formatEnvelope({ eventName, time, data, iKey,+// eventStreamName })`. That lets a plugin whose tenant ingests a different+// schema (e.g. the Power Apps client `event` table) reshape the payload without+// forking this dispatcher. `data` is the already-sanitized allowlisted payload,+// so a formatter can only rearrange approved fields, never add new sources.+// A formatter that throws or returns nothing sends NOTHING (fail closed): the+// plugin opted into a specific shape, and the default one would not be+// ingested by its pipeline anyway. The local mirror was already written.+function formatEnvelope(resolver, { eventName, time, data, iKey, eventStreamName }) {+ if (resolver && typeof resolver.formatEnvelope === "function") {+ try {+ return resolver.formatEnvelope({ eventName, time, data, iKey, eventStreamName }) || null;+ } catch {+ return null;+ }+ }+ return buildEnvelope(eventName, time, data, iKey, eventStreamName);+}++function writeProbe(filePath, { headers, body }) {+ try {+ fs.writeFileSync(filePath, JSON.stringify({ headers, body }), "utf8");+ } catch {+ // ignore+ }+}++function writeLocalLog(record) {+ try {+ const { appendLocal } = require("./local-log");+ appendLocal(record, { configDir: localConfigDir() });+ } catch {+ // fail closed+ }+}++// ---- Read config + repo-side kill switch (applies before ANY side effect) --+// The `disabled` repo config (and an unreadable config) is the one true+// hard-off: no local log, no POST. The per-plugin user opt-out is NOT checked+// here — it suppresses transmission only, and is applied below AFTER the local+// mirror is written. cfg is reused for resolver context + static fallback in+// the stdin handler.+const cfg = readIkeyConfig();+if (isDisabledByConfig(cfg)) exitSilently();+const resolver = loadResolver(path.dirname(ikeyJsonPath()));++// ---- Read stdin ------------------------------------------------------------+let raw = "";+process.stdin.setEncoding("utf8");+process.stdin.on("data", (c) => (raw += c));+process.stdin.on("end", async () => {+ let event;+ try {+ event = JSON.parse(raw);+ } catch {+ return exitSilently();+ }++ // Compute the sanitized payload + timestamp ONCE. The sanitized data is+ // exactly what lands in Kusto (its field names ARE the Kusto column names),+ // except `eventInfo` which buildEnvelope() re-serializes for the wire only.+ const time = new Date().toISOString();+ const sanitized = sanitizeData(event.data);+ const localRecord = { time, name: event.name, data: sanitized };++ // Mirror to the local log for EVERY event that clears the repo kill switch —+ // irrespective of whether a real iKey resolves AND irrespective of the+ // per-plugin transmission opt-out. The file stays on the user's machine; it+ // is a local diagnostic mirror of what is (or would be) sent to Kusto, not+ // transmitted telemetry. (A `disabled: true` repo config wrote nothing — it+ // short-circuited before stdin was even read.)+ writeLocalLog(localRecord);++ // User opt-out (per plugin) — transmission only; the local mirror above is kept.+ const pluginName = event && event.data && event.data.pluginName;+ if (isUserOptedOut(pluginName)) return exitSilently();++ // Resolve the destination iKey + collector. Precedence: env override (test+ // seam) → plugin resolver.js (region/tenant/etc., owned by the plugin) →+ // static single-key config in ikey.json → none. The shared dispatcher knows+ // nothing about regions; the plugin's resolver.js owns that.+ let iKey = IKEY_OVERRIDE;+ let collectorUrl = COLLECTOR_OVERRIDE;+ if (!iKey || !collectorUrl) {+ if (resolver && typeof resolver.resolve === "function") {+ let resolved = null;+ try {+ resolved = await resolver.resolve({+ event,+ cfg,+ cloud: CLOUD_ENV,+ configDir: CONFIG_DIR_ENV || undefined,+ });+ } catch {+ // A plugin resolver threw/rejected — continue with no resolution rather+ // than letting the global unhandledRejection handler exit. The local+ // mirror was already written above; the static fallback below still+ // runs, so a transient resolver failure degrades to the configured+ // static key (or "no transmission") instead of crashing.+ resolved = null;+ }+ if (resolved) {+ iKey = iKey || resolved.iKey || "";+ collectorUrl = collectorUrl || resolved.collectorUrl || "";+ }+ }+ // Static fallback — documented precedence is resolver → static → none, so+ // this runs whether or not a resolver was present. A resolver that returns+ // nothing (or threw) still falls through to a configured static key rather+ // than silently disabling transmission.+ iKey = iKey || cfg.instrumentationKey || "";+ collectorUrl = collectorUrl || cfg.collector_url || "";+ }++ // Placeholder / unprovisioned mode → local mirror already written; no POST.+ const keyMissing = !iKey || iKey === PLACEHOLDER_IKEY || !collectorUrl;+ if (keyMissing) {+ return exitSilently();+ }++ // Real iKey → Common Schema envelope (reuses the same time + sanitized data+ // as the local mirror) → HTTPS POST.+ const envelope = formatEnvelope(resolver, {+ eventName: event.name,+ time,+ data: sanitized,+ iKey,+ eventStreamName: cfg.event_stream_name,+ });+ if (!envelope) return exitSilently();+ const body = JSON.stringify(envelope) + "\n";+ const headers = {+ "Content-Type": "application/x-json-stream; charset=utf-8",+ "x-apikey": iKey,+ "Content-Length": Buffer.byteLength(body),+ };++ // Test seam: if POWER_PLATFORM_SKILLS_FAKE_HTTPS is set, write the probe+ // payload to that file and exit without calling the real network.+ if (FAKE_PROBE) {+ writeProbe(FAKE_PROBE, { headers, body });+ return exitSilently();+ }++ let url;+ try {+ url = new URL(collectorUrl);+ } catch {+ return exitSilently();+ }+ const req = https.request(+ {+ hostname: url.hostname,+ port: url.port || undefined,+ path: url.pathname + (url.search || ""),+ method: "POST",+ headers,+ },+ (res) => {+ res.on("data", () => {});+ res.on("end", exitSilently);+ }+ );+ req.on("error", exitSilently);+ req.setTimeout(4000, () => {+ req.destroy();+ exitSilently();+ });+ req.write(body);+ req.end();+});diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/emit-from-prompt.js b/plugins/power-automate/scripts/lib/telemetry/lib/emit-from-prompt.jsnew file mode 100644index 000000000..38113ebd9--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/emit-from-prompt.js@@ -0,0 +1,175 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");+const os = require("node:os");+const crypto = require("node:crypto");++const { detectSlashCommand } = require("./prompt-detector");+const { buildSkillStarted } = require("./events");+const { getSessionId } = require("./session");+const { fireAndForget } = require("./emit-spawn");+const { loadResolver } = require("./resolver-loader");+const { readPacAuth } = require("./pac-auth");+const { readPacCliVersion, readAiAgent } = require("./agent-info");++function readIkey(telemetryDir) {+ // Test/override seam: POWER_PLATFORM_SKILLS_IKEY_JSON points at an alternate+ // ikey.json so tests don't have to mutate the checked-in config file.+ const override = process.env.POWER_PLATFORM_SKILLS_IKEY_JSON;+ const overridePath = override && override.trim() ? override : "";+ // Guard a missing/invalid telemetryDir (a caller bug this fail-closed helper+ // must tolerate): with no override there is no config to read, so fail CLOSED+ // (disabled: true) instead of letting path.join throw out of the library.+ if (!overridePath && (typeof telemetryDir !== "string" || !telemetryDir)) {+ return { cfg: null, dir: "", ikeyPath: "", eventStreamName: "", disabled: true };+ }+ const ikeyPath = overridePath || path.join(telemetryDir, "ikey.json");+ const dir = path.dirname(ikeyPath);+ try {+ const cfg = JSON.parse(fs.readFileSync(ikeyPath, "utf8"));+ return { cfg, dir, ikeyPath, eventStreamName: cfg.event_stream_name || "", disabled: cfg.disabled === true };+ } catch {+ // ikey.json missing/unreadable → fail CLOSED (disabled: true), matching+ // emit-dispatcher.js's isDisabledByConfig(). If we can't read the config we+ // cannot confirm emission is authorized, so suppress.+ return { cfg: null, dir, ikeyPath, eventStreamName: "", disabled: true };+ }+}++function osFriendlyName(platform) {+ if (platform === "win32") return "Windows";+ if (platform === "darwin") return "Mac";+ if (platform === "linux") return "Linux";+ return platform;+}++function emitSkillStartedFromPrompt(promptText, opts = {}) {+ const {+ pluginName,+ pluginVersion,+ trackedSkills,+ telemetryDir,+ sessionId, // primed from Claude Code's hook payload (parsed.session_id)+ // Optional plugin-supplied dynamic payload merged into `eventInfo` below.+ // Accepts a plain object, or a thunk returning one. Prefer the thunk: it is+ // invoked only after the slash-command / `disabled` / `isProvisioned` gates+ // below, so a plugin whose payload costs real work (filesystem probing, etc.)+ // pays nothing on untracked prompts or a disabled plugin.+ eventInfo,+ _emit, // test seam; defaults to fireAndForget+ _readPacAuth, // test seam; defaults to lib/pac-auth+ _readAgentInfo, // test seam; defaults to lib/agent-info+ } = opts;++ const skillName = detectSlashCommand(promptText, { pluginName, trackedSkills });+ if (!skillName) return { emitted: false, skillName: null };++ // Repo-side hard-off: short-circuit BEFORE any PAC / agent-info shellouts+ // (~3-5s combined) so a disabled or half-provisioned plugin pays effectively+ // no cost. The user opt-out is NOT checked here: the event is still built and+ // dispatched so the detached dispatcher can write the local diagnostic mirror;+ // the dispatcher reads the per-plugin config and skips the POST when opted out.+ const { cfg, dir, ikeyPath, eventStreamName, disabled } = readIkey(telemetryDir);+ if (disabled) return { emitted: false, skillName };+ // Provisioning fast-gate (generic): a plugin resolver decides "is there a key+ // worth paying the pac shellout for?"; default is "static key present".+ const resolver = loadResolver(dir);+ let provisioned;+ try {+ provisioned =+ resolver && typeof resolver.isProvisioned === "function"+ ? resolver.isProvisioned(cfg)+ // Static-key fallback (no resolver): a real key must be present AND not be+ // the shipped placeholder sentinel — otherwise a plugin that flipped+ // `disabled:false` before replacing the key would be treated as provisioned+ // and pay the pac/agent-info shellouts + dispatch (local-log write) even+ // though the dispatcher can never POST a placeholder key. Matches the+ // dispatcher's PLACEHOLDER_IKEY guard and the pretool hook's gate.+ : !!(cfg && cfg.instrumentationKey && cfg.instrumentationKey !== "PLACEHOLDER_REPLACE_BEFORE_SHIPPING");+ } catch {+ // A plugin-provided resolver threw (or assumed cfg non-null) — treat as not+ // provisioned so a bad resolver can't break prompt handling (fail closed).+ provisioned = false;+ }+ if (!provisioned) return { emitted: false, skillName };++ const pacReader = typeof _readPacAuth === "function" ? _readPacAuth : readPacAuth;+ let pacAuth = null;+ try {+ pacAuth = pacReader();+ } catch {+ pacAuth = null;+ }++ const agentReader =+ typeof _readAgentInfo === "function"+ ? _readAgentInfo+ : () => ({+ ...readAiAgent(),+ pacCliVersion: readPacCliVersion(),+ });+ let agentInfo;+ try {+ agentInfo = agentReader() || {};+ } catch {+ agentInfo = {};+ }++ const fields = {+ pluginName,+ pluginVersion: pluginVersion || "unknown",+ sessionId: getSessionId(sessionId),+ correlationId: crypto.randomUUID(),+ osName: osFriendlyName(process.platform),+ osVersion: os.release(),+ nodeVersion: "v" + String(process.versions.node).split(".")[0],+ skillName,+ };+ if (pacAuth && pacAuth.orgId) fields.orgId = pacAuth.orgId;+ if (pacAuth && pacAuth.tenantId) fields.tenantId = pacAuth.tenantId;+ // `eventInfo` is assembled from two INDEPENDENT sources and assigned only when+ // non-empty. Building it inside the objectId guard instead would drop the+ // caller's payload on every unauthenticated run (`pac auth who` surfaces no+ // object id), and any later `fields.eventInfo.x = ...` would throw on the+ // undefined — a throw the fail-closed wrapper swallows, silently degrading the+ // run to no event at all. The caller owns not putting PII in its payload;+ // `aadObjectId` is written last so the library's own field always wins.+ const mergedEventInfo = {};+ let callerEventInfo = eventInfo;+ if (typeof callerEventInfo === "function") {+ try {+ callerEventInfo = callerEventInfo();+ } catch {+ // A caller thunk threw — drop its contribution rather than lose the whole+ // event. The library's own fields below are unaffected.+ callerEventInfo = null;+ }+ }+ if (callerEventInfo && typeof callerEventInfo === "object" && !Array.isArray(callerEventInfo)) {+ Object.assign(mergedEventInfo, callerEventInfo);+ }+ if (pacAuth && pacAuth.objectId) mergedEventInfo.aadObjectId = pacAuth.objectId;+ if (Object.keys(mergedEventInfo).length > 0) fields.eventInfo = mergedEventInfo;+ if (agentInfo.aiAgentName) fields.aiAgentName = agentInfo.aiAgentName;+ if (agentInfo.aiAgentVersion) fields.aiAgentVersion = agentInfo.aiAgentVersion;+ if (agentInfo.pacCliVersion) fields.pacCliVersion = agentInfo.pacCliVersion;++ const event = buildSkillStarted(eventStreamName, fields);++ const emit = typeof _emit === "function" ? _emit : fireAndForget;+ try {+ emit(event, {+ cloud: (pacAuth && pacAuth.cloud) || "",+ configDir: process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || "",+ fakeProbe: process.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || "",+ ikeyJsonPath: ikeyPath,+ });+ } catch {+ // fail closed — telemetry never propagates errors+ }++ return { emitted: true, skillName };+}++module.exports = { emitSkillStartedFromPrompt };diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/emit-spawn.js b/plugins/power-automate/scripts/lib/telemetry/lib/emit-spawn.jsnew file mode 100644index 000000000..0bd839d8a--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/emit-spawn.js@@ -0,0 +1,72 @@+"use strict";++const { spawn } = require("node:child_process");+const path = require("node:path");+const { telemetryOptOutEnvVarName } = require("./user-config");++const DISPATCHER = path.resolve(__dirname, "emit-dispatcher.js");++function fireAndForget(event, opts = {}) {+ const iKey = opts.iKey || "";+ const collectorUrl = opts.collectorUrl || "";+ const configDir = opts.configDir || "";+ const fakeProbe = opts.fakeProbe || "";+ const cloud = opts.cloud || "";+ const pluginName = event && event.data && event.data.pluginName;+ const optOutVarName = pluginName ? telemetryOptOutEnvVarName(pluginName) : "";+ const optOutValue =+ optOutVarName && process.env[optOutVarName] ? process.env[optOutVarName] : "";+ // Absolute path to the CALLING plugin's ikey.json. Tests and shared-source+ // development can execute this module from shared/telemetry/lib, whose default+ // __dirname-based ikey path is the shared placeholder, not the plugin's real+ // config. Passing the path explicitly makes the dispatcher read the right file+ // regardless of whether this library is running from shared/ or a plugin copy.+ const ikeyJsonPath = opts.ikeyJsonPath || "";++ try {+ const child = spawn(process.execPath, [DISPATCHER], {+ detached: true,+ stdio: ["pipe", "ignore", "ignore"],+ env: {+ // Pass only the minimum env the dispatcher needs. Avoid spreading+ // process.env so secrets (AZURE_CLIENT_SECRET, GITHUB_TOKEN, etc.)+ // never reach the telemetry child.+ PATH: process.env.PATH || "",+ SystemRoot: process.env.SystemRoot || "",+ HOME: process.env.HOME || "",+ USERPROFILE: process.env.USERPROFILE || "",+ APPDATA: process.env.APPDATA || "",+ POWER_PLATFORM_SKILLS_IKEY: iKey,+ POWER_PLATFORM_SKILLS_COLLECTOR: collectorUrl,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: configDir,+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: fakeProbe,+ POWER_PLATFORM_SKILLS_CLOUD: cloud,+ // ikey.json path: an explicit env override (test seam) wins; otherwise+ // the calling plugin's ikey.json path so the dispatcher reads the+ // plugin's real config rather than shared/'s placeholder.+ POWER_PLATFORM_SKILLS_IKEY_JSON:+ process.env.POWER_PLATFORM_SKILLS_IKEY_JSON || ikeyJsonPath || "",+ // The opt-out is enforced in the detached dispatcher, which reads the+ // child's process.env — so the minimal allowlist must forward this var+ // explicitly or the highest-precedence opt-out never reaches it. Forward+ // only when actually set: an empty/unset value is a no-op for the+ // dispatcher's check (it trims and matches only "1"/"true"), so there's+ // no point planting an empty var in the child env.+ ...(optOutVarName && optOutValue+ ? { [optOutVarName]: optOutValue }+ : {}),+ },+ });+ try {+ child.stdin.write(JSON.stringify(event));+ child.stdin.end();+ } catch {+ // child may have already exited; swallow.+ }+ child.unref();+ } catch {+ // spawn failed — fail closed.+ }+}++module.exports = { fireAndForget };diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/events.js b/plugins/power-automate/scripts/lib/telemetry/lib/events.jsnew file mode 100644index 000000000..13f35c3ac--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/events.js@@ -0,0 +1,140 @@+"use strict";++// Per-field type metadata. Drives the type-aware picker so the wire payload+// always matches the Kusto column type. Types and defaults:+//+// "string" — Kusto column type `string`. Empty strings ARE sent (lets+// errorClass/errorDescription distinguish "explicit empty"+// from "not present"). Non-strings are dropped.+// "int" — Kusto column type `int`. Coerced via Number(); non-finite+// or negative values clamp to 0. Sent as number, not string.+// "object" — Kusto column type `dynamic` (JSON). Plain objects and+// arrays pass through; primitives, Date, RegExp, etc. are+// dropped to avoid Kusto type confusion. Validated here as a+// real object; emit-dispatcher.js re-serializes it to a JSON+// string just before it hits the wire (see buildEnvelope),+// so the Kusto side must `parse_json()` / `todynamic()` it.+// "enum:a|b|c" — Kusto column type `string`. Only the listed values are+// accepted; anything else is dropped.+//+// Both `null` and `undefined` are dropped uniformly. Empty string is allowed+// only for "string" types (deliberate — see above).+const FIELD_TYPES = {+ // Common — identity / context+ pluginName: "string",+ pluginVersion: "string",+ sessionId: "string",+ correlationId: "string",+ osName: "string",+ osVersion: "string",+ nodeVersion: "string",+ // Common — PAC + agent+ orgId: "string",+ tenantId: "string",+ pacCliVersion: "string",+ aiAgentName: "string",+ aiAgentVersion: "string",+ // Common — caller-supplied dynamic JSON. This validates only the container,+ // not nested keys. Callers must follow shared/telemetry/README.md's approved+ // eventInfo schema; arbitrary nested payloads can bypass the top-level allowlist.+ eventInfo: "object",+ // Skill+ skillName: "string",+ // Completed-only+ outcome: "enum:success|failure",+ durationMs: "int",+ errorClass: "string",+ errorDescription: "string",+};++const COMMON_FIELDS = [+ "pluginName",+ "pluginVersion",+ "sessionId",+ "correlationId",+ "osName",+ "osVersion",+ "nodeVersion",+ "orgId",+ "tenantId",+ "pacCliVersion",+ "aiAgentName",+ "aiAgentVersion",+ "eventInfo",+];++const SKILL_FIELDS = ["skillName"];+const COMPLETED_FIELDS = ["outcome", "durationMs", "errorClass", "errorDescription"];++function isPlainStructured(v) {+ if (v === null || typeof v !== "object") return false;+ if (Array.isArray(v)) return true;+ // Only plain objects (prototype Object.prototype or null) pass through —+ // class instances like Date, RegExp, Map, Set, and Error are rejected so+ // the dynamic `eventInfo` field can't carry unexpected shapes.+ const proto = Object.getPrototypeOf(v);+ return proto === Object.prototype || proto === null;+}++function clampInt(v) {+ const n = Number(v);+ if (!Number.isFinite(n) || n < 0) return 0;+ return Math.floor(n);+}++// Type-aware pick. Drops null/undefined for every type. For each kept value,+// validates against its declared type and coerces as needed.+function pick(input, keys) {+ const out = {};+ if (!input || typeof input !== "object") return out;+ for (const k of keys) {+ const v = input[k];+ if (v === undefined || v === null) continue;+ const type = FIELD_TYPES[k];+ if (type === "string") {+ if (typeof v === "string") out[k] = v;+ } else if (type === "int") {+ out[k] = clampInt(v);+ } else if (type === "object") {+ if (isPlainStructured(v)) out[k] = v;+ } else if (typeof type === "string" && type.startsWith("enum:")) {+ const allowed = type.slice(5).split("|");+ if (typeof v === "string" && allowed.includes(v)) out[k] = v;+ }+ // unknown types: drop (defensive — no field should hit this branch).+ }+ return out;+}++function buildEvent(envelopeName, eventName, info, severity) {+ return {+ name: envelopeName,+ data: { eventName, eventType: "Trace", severity, ...info },+ };+}++function buildSkillStarted(envelopeName, input) {+ return buildEvent(+ envelopeName,+ "skill_started",+ pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS]),+ "Info"+ );+}++function buildSkillCompleted(envelopeName, input) {+ const severity = input && input.outcome === "failure" ? "Error" : "Info";+ return buildEvent(+ envelopeName,+ "skill_completed",+ pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS, ...COMPLETED_FIELDS]),+ severity+ );+}++module.exports = {+ buildSkillStarted,+ buildSkillCompleted,+ FIELD_TYPES,+ pick,+};diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/local-log.js b/plugins/power-automate/scripts/lib/telemetry/lib/local-log.jsnew file mode 100644index 000000000..ed61032d4--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/local-log.js@@ -0,0 +1,170 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");++const LOG_FILE_NAME = "events.jsonl";+const ROTATE_BYTES = 10 * 1024 * 1024; // 10 MB per-session size safety cap+const MAX_LOG_AGE_DAYS = 14;+const MAX_LOG_AGE_MS = MAX_LOG_AGE_DAYS * 24 * 60 * 60 * 1000;++// pluginName and sessionId become DIRECTORY names, so each is reduced to one safe+// path segment — a malformed record must never write outside telemetry/. Reject+// "." / ".." outright, then collapse anything outside [A-Za-z0-9_-] to "_". Dots+// are excluded so "../evil" can't leave a ".." fragment (it becomes "___evil");+// an empty result falls back to the sentinel.+function sanitizeSegment(value, fallback) {+ if (typeof value !== "string") return fallback;+ if (value === "." || value === "..") return fallback;+ const cleaned = value.replace(/[^A-Za-z0-9_-]/g, "_");+ if (!cleaned) return fallback;+ return cleaned;+}++// <configDir>/telemetry/<plugin>/sessions — the directory that holds one+// subdirectory per session. Pure path helper, no I/O.+function pluginLogDir(configDir, pluginName) {+ const plugin = sanitizeSegment(pluginName, "unknown");+ return path.join(configDir, "telemetry", plugin, "sessions");+}++function sessionDir(configDir, pluginName, sessionId) {+ const session = sanitizeSegment(sessionId, "nosession");+ return path.join(pluginLogDir(configDir, pluginName), session);+}++// events.YYYYMMDDHHMMSS.old — UTC stamp so rolled files sort chronologically.+function rotationName(now = new Date()) {+ const pad = (n) => String(n).padStart(2, "0");+ const stamp =+ now.getUTCFullYear().toString() ++ pad(now.getUTCMonth() + 1) ++ pad(now.getUTCDate()) ++ pad(now.getUTCHours()) ++ pad(now.getUTCMinutes()) ++ pad(now.getUTCSeconds());+ return `events.${stamp}.old`;+}++// Per-session size cap. A single session almost never reaches 10 MB; this is a+// safety valve against a pathological runaway session, not the primary+// retention mechanism (that is age-based pruning of whole session dirs).+function rotateIfNeeded(dir, logFile) {+ try {+ const stat = fs.statSync(logFile);+ if (stat.size > ROTATE_BYTES) {+ try {+ fs.renameSync(logFile, path.join(dir, rotationName()));+ } catch {+ // best effort: if rename fails (file locked, etc.), keep appending.+ }+ }+ } catch {+ // no existing log — nothing to rotate+ }+}++function appendLocal(record, { configDir } = {}) {+ if (!configDir) return;+ const data = (record && record.data) || {};+ // Deterministic path — derived purely from the record. No directory scan, so+ // the many short-lived dispatcher processes that may write the same session+ // concurrently cannot race on "find this session's file".+ const dir = sessionDir(configDir, data.pluginName, data.sessionId);+ let created;+ try {+ // mkdirSync(recursive) returns the first path it created, or undefined if the+ // dir already existed — a free "is this a brand-new session?" signal.+ created = fs.mkdirSync(dir, { recursive: true });+ } catch {+ return;+ }+ const logFile = path.join(dir, LOG_FILE_NAME);+ rotateIfNeeded(dir, logFile);+ try {+ fs.appendFileSync(logFile, JSON.stringify(record) + "\n", "utf8");+ } catch {+ // swallow — fail closed; telemetry must never break a skill run+ }+ // The retention sweep scans every session dir, so run it only on a session's+ // first event (when we just created its dir), not on every append.+ if (created) pruneOldSessions(configDir, data.pluginName);+}++// Best-effort age-based retention — the primary cleanup mechanism. Remove any+// session dir whose events.jsonl was last written more than MAX_LOG_AGE_DAYS ago;+// a dir with no readable log is judged by its OWN mtime, so a just-created dir from+// a concurrent dispatcher isn't deleted out from under it. Never throws.+function pruneOldSessions(configDir, pluginName, now = Date.now()) {+ if (!configDir) return; // fail closed: pluginLogDir -> path.join would throw on undefined+ const sessionsRoot = pluginLogDir(configDir, pluginName);+ let entries;+ try {+ entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });+ } catch {+ return; // no sessions dir yet — nothing to prune+ }+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const dir = path.join(sessionsRoot, entry.name);+ try {+ let mtimeMs;+ try {+ mtimeMs = fs.statSync(path.join(dir, LOG_FILE_NAME)).mtimeMs;+ } catch {+ // No readable log file — fall back to the directory's own mtime.+ mtimeMs = fs.statSync(dir).mtimeMs;+ }+ if (now - mtimeMs > MAX_LOG_AGE_MS) {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ } catch {+ // best effort per dir; skip on any error+ }+ }+}++// Absolute path to the most-recently-written session's events.jsonl for a plugin,+// or null when there are none ("most recent" = highest events.jsonl mtime). Dirs+// without a readable events.jsonl are skipped so the returned path always exists —+// status surfaces it for the user to share, and a phantom path would point them at+// a file that isn't there. Read-only.+function latestSessionLog(configDir, pluginName) {+ if (!configDir) return null; // fail closed: pluginLogDir -> path.join would throw on undefined+ const sessionsRoot = pluginLogDir(configDir, pluginName);+ let entries;+ try {+ entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });+ } catch {+ return null;+ }+ let best = null;+ let bestMtime = -Infinity;+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const logFile = path.join(sessionsRoot, entry.name, LOG_FILE_NAME);+ let mtimeMs;+ try {+ // Skip dirs without a readable events.jsonl so `best` can't point at a missing file.+ mtimeMs = fs.statSync(logFile).mtimeMs;+ } catch {+ continue;+ }+ if (mtimeMs > bestMtime) {+ bestMtime = mtimeMs;+ best = logFile;+ }+ }+ return best;+}++module.exports = {+ appendLocal,+ pluginLogDir,+ latestSessionLog,+ pruneOldSessions,+ sanitizeSegment,+ LOG_FILE_NAME,+ ROTATE_BYTES,+ MAX_LOG_AGE_DAYS,+};diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/native-exec.js b/plugins/power-automate/scripts/lib/telemetry/lib/native-exec.jsnew file mode 100644index 000000000..e7f6d8155--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/native-exec.js@@ -0,0 +1,100 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");+const { execFileSync } = require("node:child_process");++// Starts a native command-line tool (pac) by absolute path, never by bare name.+//+// The telemetry hooks run in the user's project folder. Given a bare name,+// Node 20 on Windows looks for the executable in the working directory before+// PATH (measured: a `pac.exe` in the working directory ran; Node 22 no longer+// looks there), so a `pac.exe` left in a project would run instead of the real+// one. Resolving the name here, against absolute PATH entries only, gives the+// same answer on every Node version and platform.+//+// Only native executables are considered. These calls run without a shell, and+// Windows cannot start a .cmd or .bat that way, so a pac.cmd install is not+// found, as it was not before either.++function isFile(p) {+ try {+ return fs.statSync(p).isFile();+ } catch {+ return false;+ }+}++// A candidate the OS would actually start: a regular file and, off Windows,+// one the user may execute. Node's own lookup skips a non-executable `pac`+// earlier on PATH and keeps searching, so this does too.+function isRunnable(p, platform) {+ if (!isFile(p)) return false;+ if (platform === "win32") return true;+ try {+ fs.accessSync(p, fs.constants.X_OK);+ return true;+ } catch {+ return false;+ }+}++// Windows variable names are case-insensitive. When an env object carries+// several spellings (a copied `Path` plus an added `PATH`), Node passes the+// child the lexicographically first one, so read that same one.+function envValue(env, name, platform) {+ if (platform !== "win32") return env[name];+ const key = Object.keys(env)+ .filter((k) => k.toUpperCase() === name.toUpperCase())+ .sort()[0];+ return key === undefined ? undefined : env[key];+}++/**+ * Absolute path of a native executable found on PATH, or null. Relative PATH+ * entries (an empty entry means "the current directory" on POSIX) are skipped.+ * On Windows `.com` then `.exe` is tried whatever PATHEXT says, as Node's own+ * shell-free lookup does.+ */+function resolveNative(+ name,+ { platform = process.platform, env = process.env, exists = (p) => isRunnable(p, platform) } = {}+) {+ const win = platform === "win32";+ const p = win ? path.win32 : path.posix;+ const dirs = String(envValue(env, "PATH", platform) || "")+ .split(win ? ";" : ":")+ .map((d) => d.trim().replace(/^"(.*)"$/, "$1"))+ .filter((d) => d && p.isAbsolute(d));+ const exts = win ? [".com", ".exe"] : [""];+ for (const dir of dirs) {+ for (const ext of exts) {+ const candidate = p.join(dir, name + ext);+ if (exists(candidate)) return candidate;+ }+ }+ return null;+}++/**+ * execFileSync-shaped: returns stdout, and throws when the tool is not on PATH+ * (code ENOENT) or the run fails (with err.stdout attached, as execFileSync+ * does). Callers treat any throw as "no data".+ */+function runNative(name, args, options = {}, deps = {}) {+ const file = resolveNative(name, deps);+ if (!file) {+ const err = new Error(`${name} was not found on PATH`);+ err.code = "ENOENT";+ throw err;+ }+ return execFileSync(file, args, {+ encoding: options.encoding,+ timeout: options.timeout,+ stdio: options.stdio,+ windowsHide: true,+ shell: false,+ });+}++module.exports = { resolveNative, runNative };diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/pac-auth.js b/plugins/power-automate/scripts/lib/telemetry/lib/pac-auth.jsnew file mode 100644index 000000000..0eb4ec6a3--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/pac-auth.js@@ -0,0 +1,78 @@+"use strict";++const { runNative } = require("./native-exec");++// Reads PAC CLI auth state by running `pac auth who` and parsing the+// banner output. Matches the convention used by+// plugins/power-pages/scripts/lib/validation-helpers.js (getPacAuthInfo /+// getEnvironmentUrl) so telemetry stays consistent with the rest of the repo.+// pac is started by absolute path from PATH, never by bare name (see+// native-exec.js).+//+// PAC's JSON profile files are an internal/undocumented format that varies+// across versions. The banner output is stable and is what other code paths+// already parse via the AUTH_KEYS list documented in the VSCode 1DS extension.+//+// Best-effort and fail-closed: missing executable, timeout, non-zero exit, or+// unparseable output all resolve to null. The result is cached per process so+// repeated hook invocations only fork once.++// Cold-start `pac auth who` on Windows is consistently ~3.5-4s (.NET runtime+// startup + cached-token validation). 3s was too tight and produced silent+// timeouts that surfaced as missing orgId/tenantId in every event. 8s gives+// comfortable headroom while staying well under the hook's 30s budget.+const TIMEOUT_MS = 8000;++let cache;++function _resetCache() {+ cache = undefined;+}++function pickLine(text, label) {+ // Match "Label: value" — case-insensitive, trims whitespace.+ const re = new RegExp("^\\s*" + label + "\\s*:\\s*(\\S.*?)\\s*$", "im");+ const match = text.match(re);+ return match ? match[1] : null;+}++function readPacAuth(opts = {}) {+ if (cache !== undefined) return cache;+ if (opts._exec === false) {+ cache = null;+ return null;+ }+ const exec = typeof opts._exec === "function" ? opts._exec : runNative;+ let output;+ try {+ output = exec("pac", ["auth", "who"], {+ encoding: "utf8",+ timeout: TIMEOUT_MS,+ stdio: ["ignore", "pipe", "ignore"],+ });+ } catch {+ cache = null;+ return null;+ }+ if (typeof output !== "string" || !output) {+ cache = null;+ return null;+ }+ const tenantId = pickLine(output, "Tenant Id");+ const orgId = pickLine(output, "Organization Id");+ const cloud = pickLine(output, "Cloud");+ const objectId = pickLine(output, "Entra ID Object Id");+ if (!tenantId && !orgId) {+ cache = null;+ return null;+ }+ cache = {+ orgId: orgId || "",+ tenantId: tenantId || "",+ cloud: cloud || "",+ objectId: objectId || "",+ };+ return cache;+}++module.exports = { readPacAuth, _resetCache };diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/prompt-detector.js b/plugins/power-automate/scripts/lib/telemetry/lib/prompt-detector.jsnew file mode 100644index 000000000..60474128b--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/prompt-detector.js@@ -0,0 +1,28 @@+"use strict";++function detectSlashCommand(promptText, { pluginName, trackedSkills } = {}) {+ if (typeof promptText !== "string" || !promptText) return null;+ if (!pluginName || !trackedSkills) return null;++ // Match both the namespaced form (`/<plugin>:<skill>`) and the bare form+ // (`/<skill>`). The `pluginName:` prefix is optional because the host tool+ // controls how the slash command is surfaced in the prompt and may emit the+ // bare form without the plugin namespace. Either way the captured skill name+ // is validated against trackedSkills below, so a bare `/foo` only counts when+ // `foo` is a known skill. The trailing boundary lookahead still rejects a+ // different plugin's namespaced command (e.g. `/other-plugin:add-seo`, where+ // `other-plugin` is followed by `:` rather than a word boundary).+ const escapedPlugin = pluginName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ const re = new RegExp(+ String.raw`^\s*\/(?:` + escapedPlugin + String.raw`:)?([a-z0-9-]+)(?=\s|$|\r|\n)`+ );+ const match = promptText.match(re);+ if (!match) return null;++ const skillName = match[1];+ return Object.prototype.hasOwnProperty.call(trackedSkills, skillName)+ ? skillName+ : null;+}++module.exports = { detectSlashCommand };diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/resolver-loader.js b/plugins/power-automate/scripts/lib/telemetry/lib/resolver-loader.jsnew file mode 100644index 000000000..5c5c2bb67--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/resolver-loader.js@@ -0,0 +1,26 @@+"use strict";++const path = require("node:path");++// Discover an optional, plugin-provided resolver module that owns iKey/collector+// selection (region routing, tenant routing, etc.). Convention: a `resolver.js`+// next to the plugin's ikey.json. The shared library never imports a resolver+// directly — it loads whatever the plugin drops here and calls the documented+// contract: { resolve({event, cfg, cloud, configDir}), isProvisioned(cfg) }.+//+// Returns the resolver module, or null when none is present or it fails to load+// (callers then fall back to static config / a generic gate — fail open).+function loadResolver(dir) {+ if (!dir) return null;+ try {+ // path.resolve (not path.join): require() treats a non-"./"-prefixed+ // relative path as a module ID and searches node_modules. A relative `dir`+ // (e.g. from a relative POWER_PLATFORM_SKILLS_IKEY_JSON override) would then+ // miss the intended resolver.js. Resolve to an absolute path first.+ return require(path.resolve(dir, "resolver.js"));+ } catch {+ return null;+ }+}++module.exports = { loadResolver };diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/scrubber.js b/plugins/power-automate/scripts/lib/telemetry/lib/scrubber.jsnew file mode 100644index 000000000..517188404--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/scrubber.js@@ -0,0 +1,11 @@+"use strict";++// Placeholder. The spec allowlist already restricts payload fields to values+// that cannot contain PII. This module exists as a documented seam for a+// future regex-based pass if the allowlist ever needs to carry user strings.++function scrub(value) {+ return value;+}++module.exports = { scrub };diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/session.js b/plugins/power-automate/scripts/lib/telemetry/lib/session.jsnew file mode 100644index 000000000..cbf89884d--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/session.js@@ -0,0 +1,43 @@+"use strict";++const crypto = require("node:crypto");++// Hooks run as fresh Node processes, so a module-level UUID would be unique+// per hook invocation — every event in a Claude Code session would carry a+// different sessionId, breaking session-scoped analysis. Each hook reads+// Claude Code's session_id from the stdin payload and primes this cache+// with it so all events emitted from that hook (and within that process)+// share a single sessionId.+let cached;++function getSessionId(override) {+ if (typeof override === "string" && override) {+ cached = override;+ return cached;+ }+ if (!cached) cached = crypto.randomUUID();+ return cached;+}++// Multi-host session-id resolver. Both Claude Code and GitHub Copilot CLI+// surface their session id through the hook stdin payload. Field-name+// convention may vary by host; check known variants in precedence order.+// Returns "" when no usable id is present so the caller's subsequent+// getSessionId("") falls back to a per-process UUID.+function resolveHostSessionId(payload) {+ if (!payload || typeof payload !== "object") return "";+ if (typeof payload.session_id === "string" && payload.session_id) {+ return payload.session_id;+ }+ if (typeof payload.sessionId === "string" && payload.sessionId) {+ return payload.sessionId;+ }+ return "";+}++// Test seam.+function _resetCache() {+ cached = undefined;+}++module.exports = { getSessionId, resolveHostSessionId, _resetCache };diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.jsnew file mode 100644index 000000000..bf92b8a38--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/telemetry-config.js@@ -0,0 +1,127 @@+#!/usr/bin/env node+"use strict";++const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { setTelemetryChoice, effectiveTelemetryChoice } = require("./user-config");+const { pluginLogDir, latestSessionLog } = require("./local-log");++function dataDisclosure(plugin) {+ const pluginSpecific =+ plugin === "power-pages"+ ? " Power Pages can also record the signed-in user's Entra object ID as\n" ++ " eventInfo.aadObjectId when PAC exposes it, and the SPA framework of the\n" ++ " Power Pages code site being worked in as eventInfo.framework when detected.\n" ++ " The framework is one of react, vue, angular, or astro and describes the\n" ++ " scaffold only — it is never a site name or path.\n"+ : plugin === "model-apps"+ ? " Model Apps excludes the signed-in user's Entra object ID.\n"+ : "";+ return (+ "ℹ️ Usage telemetry records skill, plugin, PAC, agent, OS, Node, session,\n" ++ " and correlation fields, plus Dataverse organization and Entra tenant IDs\n" ++ " when PAC is signed in.\n" ++ pluginSpecific ++ " When plugin telemetry is enabled, the local diagnostic log retains the same\n" ++ " fields even when transmission is off. A plugin whose committed telemetry\n" ++ " config has disabled: true is hard-disabled and writes no log.\n" ++ " Events do not include file paths, prompts, tool inputs, site names,\n" ++ " Dataverse URLs, credentials, usernames, or hostnames."+ );+}++function getArg(name) {+ const i = process.argv.indexOf(`--${name}`);+ return i !== -1 && i + 1 < process.argv.length ? process.argv[i + 1] : null;+}++function configDir() {+ return (+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR ||+ path.join(os.homedir(), ".power-platform-skills")+ );+}++// --plugin wins; otherwise auto-detect from the plugin manifest 4 levels up+// (.../plugins/<plugin>/scripts/lib/telemetry/lib/telemetry-config.js).+function resolvePlugin() {+ const explicit = getArg("plugin");+ if (explicit) return explicit;+ try {+ const manifestPath = path.resolve(+ __dirname, "..", "..", "..", "..", ".claude-plugin", "plugin.json"+ );+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));+ return manifest.name || null;+ } catch {+ return null;+ }+}++function out(s) {+ process.stdout.write(s + "\n");+}++// Print where this plugin's local diagnostic logs live and name the newest+// session file, so a user can hand over exactly the log for the session they+// just hit a problem in. Reuses the shared layout helpers (DRY — no path logic+// is duplicated in the skill).+function emitLogLocations(dir, plugin) {+ out(`Logs directory: ${pluginLogDir(dir, plugin)}`);+ const latest = latestSessionLog(dir, plugin);+ if (latest) {+ out(`Most recent session: ${latest}`);+ out("ℹ️ Share that file when reporting an issue (it covers your latest session).");+ } else {+ out(`No local logs yet for ${plugin}.`);+ }+}++function main() {+ const action = getArg("action");+ const plugin = resolvePlugin();+ if (!plugin || !["on", "off", "status"].includes(action)) {+ out("Usage: telemetry-config.js --action <on|off|status> [--plugin <name>]");+ process.exit(2);+ }+ const dir = configDir();++ if (action === "status") {+ const on = effectiveTelemetryChoice(dir, plugin) !== "off"; // default ON; honors env override when no stored choice+ if (on) {+ out(`Telemetry (${plugin}): ON`);+ out(dataDisclosure(plugin));+ emitLogLocations(dir, plugin);+ } else {+ out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);+ out(`The local diagnostic log is kept whenever telemetry is enabled for this plugin, even when transmission is OFF (opt-out stops transmission only).`);+ emitLogLocations(dir, plugin);+ out(`Re-enable with /${plugin}:telemetry on (an environment opt-out, if set, takes precedence and this command cannot override it).`);+ out(dataDisclosure(plugin));+ }+ process.exit(0);+ }++ if (!setTelemetryChoice(dir, plugin, action)) {+ out(`Could not update the telemetry setting (config dir not writable).`);+ process.exit(1);+ }+ if (action === "off") {+ out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);+ out(`The local diagnostic log is kept whenever telemetry is enabled for this plugin, even when transmission is OFF (opt-out stops transmission only).`);+ emitLogLocations(dir, plugin);+ out(`Re-enable with /${plugin}:telemetry on (an environment opt-out, if set, takes precedence and this command cannot override it).`);+ } else if (effectiveTelemetryChoice(dir, plugin) === "off") {+ // The preference was saved as ON, but the highest-precedence environment+ // opt-out still forces transmission off — report the EFFECTIVE state so we+ // never claim ON while an opt-out is suppressing it.+ out(`Telemetry (${plugin}): preference saved as ON, but an environment opt-out is currently in effect — nothing is transmitted until it is cleared.`);+ } else {+ out(`Telemetry (${plugin}): ON`);+ }+ out(dataDisclosure(plugin));+ process.exit(0);+}++main();diff --git a/plugins/power-automate/scripts/lib/telemetry/lib/user-config.js b/plugins/power-automate/scripts/lib/telemetry/lib/user-config.jsnew file mode 100644index 000000000..ea0597f73--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/lib/user-config.js@@ -0,0 +1,106 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");++const CONFIG_FILE_NAME = "config.json";++function configPath(configDir) {+ return path.join(configDir, CONFIG_FILE_NAME);+}++function isPlainObject(value) {+ return value && typeof value === "object" && !Array.isArray(value);+}++// Reads the whole config object; returns {} on any error (missing/corrupt).+function readConfig(configDir) {+ try {+ const parsed = JSON.parse(fs.readFileSync(configPath(configDir), "utf8"));+ // Arrays pass `typeof === "object"` but break the merge-write: setTelemetryChoice+ // would set `.telemetry` on the array and JSON.stringify would silently drop it,+ // reporting success while persisting nothing. Treat non-plain objects as empty.+ return isPlainObject(parsed) ? parsed : {};+ } catch {+ return {};+ }+}++// Returns "on" | "off" | null (null = unset / not a valid value).+function readTelemetryChoice(configDir, pluginName) {+ if (!configDir || !pluginName) return null;+ const t = readConfig(configDir).telemetry;+ if (!isPlainObject(t)) return null;+ const v = t[pluginName];+ return v === "on" || v === "off" ? v : null;+}++// Builds the per-plugin opt-out var name: POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT+// where <PLUGIN> is the plugin name uppercased with non-alphanumeric runs -> "_".+function telemetryOptOutEnvVarName(pluginName) {+ return (+ "POWER_PLATFORM_SKILLS_TELEMETRY_" ++ String(pluginName).toUpperCase().replace(/[^A-Z0-9]+/g, "_") ++ "_OPTOUT"+ );+}++// True when the per-plugin opt-out env var is set to a truthy value (`1` or+// `true`, case-insensitive). Follows the dotnet `*_TELEMETRY_OPTOUT` convention:+// the var only disables — it is never used to re-enable. Unset / empty / `0` /+// `false` / anything else => not opted out. `env` is injectable so tests never+// mutate the real process.env.+function readTelemetryEnvOptOut(pluginName, env = process.env) {+ if (!pluginName) return false;+ const v = String(env[telemetryOptOutEnvVarName(pluginName)] || "").trim().toLowerCase();+ return v === "1" || v === "true";+}++// Resolves the effective on/off choice by precedence (highest first):+// 1. the env-var opt-out (when truthy => "off"; overrides everything below)+// 2. persisted config.json per-plugin choice (set via the slash skill)+// 3. null = default-on+// The env var has the highest precedence and can only force "off"; it never+// re-enables a config opt-out.+function effectiveTelemetryChoice(configDir, pluginName, env = process.env) {+ if (readTelemetryEnvOptOut(pluginName, env)) return "off";+ return readTelemetryChoice(configDir, pluginName) ?? null;+}++function isTransmissionOptedOut(configDir, pluginName, env = process.env) {+ return effectiveTelemetryChoice(configDir, pluginName, env) === "off";+}++// Merge-writes { telemetry: { [pluginName]: choice } }, preserving every other+// key. Returns true on success, false on bad input or I/O failure. Never throws.+function setTelemetryChoice(configDir, pluginName, choice) {+ if (!configDir || !pluginName) return false;+ if (choice !== "on" && choice !== "off") return false;+ try {+ fs.mkdirSync(configDir, { recursive: true });+ } catch {+ return false;+ }+ const cfg = readConfig(configDir);+ // `telemetry` itself can also be malformed, e.g. `"telemetry": []`. Assigning+ // `cfg.telemetry[pluginName]` on an array creates a non-index property that+ // JSON.stringify drops, so normalize any non-plain telemetry value before write.+ if (!isPlainObject(cfg.telemetry)) cfg.telemetry = {};+ cfg.telemetry[pluginName] = choice;+ try {+ fs.writeFileSync(configPath(configDir), JSON.stringify(cfg, null, 2) + "\n", "utf8");+ return true;+ } catch {+ return false;+ }+}++module.exports = {+ readTelemetryChoice,+ setTelemetryChoice,+ isTransmissionOptedOut,+ telemetryOptOutEnvVarName,+ readTelemetryEnvOptOut,+ effectiveTelemetryChoice,+ CONFIG_FILE_NAME,+};diff --git a/plugins/power-automate/scripts/lib/telemetry/region/artemis-service.js b/plugins/power-automate/scripts/lib/telemetry/region/artemis-service.jsnew file mode 100644index 000000000..29af804ce--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/region/artemis-service.js@@ -0,0 +1,98 @@+"use strict";++const https = require("node:https");++const TIMEOUT_MS = 5000;++function normalizeCloud(cloud) {+ const c = String(cloud || "").toLowerCase();+ // "usgov" is the token `pac auth who` actually emits for GCC (see+ // validation-helpers.js CLOUD_TO_API). The other spellings are defensive+ // aliases. Exact `===` matching means this can't shadow usgovhigh/usgovdod.+ if (c === "usgov" || c === "usgovgcc" || c === "gcc" || c === "gov") return "Gov";+ if (c === "usgovhigh" || c === "high") return "High";+ if (c === "usgovdod" || c === "dod") return "Dod";+ if (c === "china" || c === "mooncake" || c === "chinacloud") return "Mooncake";+ if (c === "tip1" || c === "tip2" || c === "test" || c === "preprod") return "Internal";+ return "Public";+}++function urlFor(orgId, cloud) {+ const noDashes = String(orgId || "").replace(/-/g, "");+ const stamp = normalizeCloud(cloud);+ if (stamp === "Public") {+ const domain = noDashes.slice(0, -2);+ const suffix = noDashes.slice(-2);+ return `https://${domain}.${suffix}.organization.api.powerplatform.com/gateway/cluster?api-version=1`;+ }+ const domain = noDashes.slice(0, -1);+ const suffix = noDashes.slice(-1);+ if (stamp === "Gov") {+ return `https://${domain}.${suffix}.organization.api.gov.powerplatform.microsoft.us/gateway/cluster?api-version=1`;+ }+ if (stamp === "High") {+ return `https://${domain}.${suffix}.organization.api.high.powerplatform.microsoft.us/gateway/cluster?api-version=1`;+ }+ if (stamp === "Dod") {+ return `https://${domain}.${suffix}.organization.api.appsplatform.us/gateway/cluster?api-version=1`;+ }+ if (stamp === "Mooncake") {+ return `https://${domain}.${suffix}.organization.api.powerplatform.partner.microsoftonline.cn/gateway/cluster?api-version=1`;+ }+ // Internal+ return `https://${domain}.${suffix}.organization.api.test.powerplatform.com/gateway/cluster?api-version=1`;+}++function defaultHttpsGet(url) {+ return new Promise((resolve, reject) => {+ let u;+ try {+ u = new URL(url);+ } catch (e) {+ reject(e);+ return;+ }+ const req = https.request(+ {+ hostname: u.hostname,+ path: u.pathname + (u.search || ""),+ method: "GET",+ },+ (res) => {+ let body = "";+ res.setEncoding("utf8");+ res.on("data", (c) => (body += c));+ res.on("end", () => resolve({ statusCode: res.statusCode, body }));+ }+ );+ req.on("error", reject);+ req.setTimeout(TIMEOUT_MS, () => {+ req.destroy(new Error("timeout"));+ });+ req.end();+ });+}++async function fetchGeo(orgId, cloud, opts = {}) {+ if (!orgId) return null;+ const url = urlFor(orgId, cloud);+ const httpsGet = typeof opts._httpsGet === "function" ? opts._httpsGet : defaultHttpsGet;+ let resp;+ try {+ resp = await httpsGet(url);+ } catch {+ return null;+ }+ if (!resp || typeof resp.statusCode !== "number") return null;+ if (resp.statusCode < 200 || resp.statusCode >= 300) return null;+ let body;+ try {+ body = JSON.parse(resp.body || "");+ } catch {+ return null;+ }+ if (!body || typeof body.geoName !== "string" || !body.geoName) return null;+ return { geoName: body.geoName, stamp: normalizeCloud(cloud) };+}++module.exports = { fetchGeo, urlFor, normalizeCloud, TIMEOUT_MS };diff --git a/plugins/power-automate/scripts/lib/telemetry/region/region-cache.js b/plugins/power-automate/scripts/lib/telemetry/region/region-cache.jsnew file mode 100644index 000000000..df378941d--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/region/region-cache.js@@ -0,0 +1,87 @@+"use strict";++const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++const DIR_NAME = "region-cache";+const TTL_MS = 24 * 60 * 60 * 1000;++// orgId comes from `pac auth who` ("Organization Id") — a Dataverse org GUID.+// Validate the shape before using it as a filename: defensive against a+// malformed/spoofed value containing path separators (`/`, `\`, `..`), and it+// doubles as the falsy-orgId guard.+const ORG_ID_RE =+ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;++function defaultDir() {+ return path.join(os.homedir(), ".power-platform-skills");+}++function cacheDir(configDir) {+ return path.join(configDir || defaultDir(), DIR_NAME);+}++function entryFile(orgId, configDir) {+ return path.join(cacheDir(configDir), `${orgId}.json`);+}++// Returns the cached { region } for an org, or null when missing / unreadable /+// malformed / expired. Only the plugin-INDEPENDENT org→region mapping is cached;+// the caller maps region→iKey from its own regionsMap (so a cache shared across+// plugins can never hand one plugin another plugin's key).+function read(orgId, configDir) {+ if (!ORG_ID_RE.test(String(orgId || ""))) return null;+ let entry;+ try {+ entry = JSON.parse(fs.readFileSync(entryFile(orgId, configDir), "utf8"));+ } catch {+ return null;+ }+ if (+ !entry ||+ typeof entry.expiresAt !== "number" ||+ entry.expiresAt < Date.now()+ ) {+ return null;+ }+ return { region: entry.region };+}++// Per-process counter so concurrent writers never collide on the temp name.+let writeSeq = 0;++function write(orgId, entry, configDir) {+ if (!ORG_ID_RE.test(String(orgId || "")) || !entry || !entry.region) return;+ const dir = cacheDir(configDir);+ try {+ fs.mkdirSync(dir, { recursive: true });+ } catch {+ return;+ }+ const file = path.join(dir, `${orgId}.json`);+ const payload = JSON.stringify({+ region: entry.region,+ expiresAt: Date.now() + TTL_MS,+ });+ // Per-org file + atomic rename: each org owns its own file, so concurrent+ // detached dispatchers (one per skill invocation) writing DIFFERENT orgs can+ // never clobber each other — the shared read-modify-write is gone, and+ // same-org concurrent writes are idempotent (identical content). The temp name+ // is per-process so writers don't collide; rename is an atomic replace (incl.+ // Windows via MoveFileEx) so a reader never sees a torn/half-written file.+ const tmp = `${file}.tmp.${process.pid}.${writeSeq++}`;+ try {+ fs.writeFileSync(tmp, payload, "utf8");+ fs.renameSync(tmp, file);+ } catch {+ // fail closed: cache miss next time. Best-effort cleanup of the temp file.+ try {+ fs.unlinkSync(tmp);+ } catch {+ // temp may not have been created; ignore+ }+ }+}++module.exports = { read, write, TTL_MS };diff --git a/plugins/power-automate/scripts/lib/telemetry/region/region-resolver.js b/plugins/power-automate/scripts/lib/telemetry/region/region-resolver.jsnew file mode 100644index 000000000..81cdff74a--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/region/region-resolver.js@@ -0,0 +1,91 @@+"use strict";++const { fetchGeo: defaultFetchGeo, normalizeCloud } = require("./artemis-service");+const defaultCache = require("./region-cache");++// Public-cloud geoName values → routing region. Anything not listed falls+// through to defaultRegion. Sovereign clouds short-circuit via the stamp.+const PUBLIC_US_GEOS = new Set(["us", "br", "jp", "in", "au", "ca", "as", "za", "ae", "kr"]);+const PUBLIC_EU_GEOS = new Set(["eu", "uk", "de", "fr", "no", "ch"]);++// Derive the plugin-INDEPENDENT routing region from the org's cloud stamp + geo,+// or null when the public geo is unrecognized (caller falls back to its own+// defaultRegion). Only a non-null result is safe to cache: it's a property of+// the org, not of any plugin's config.+function deriveRegion(cloud, geoName) {+ const stamp = normalizeCloud(cloud);+ if (stamp === "Gov") return "gov";+ if (stamp === "High") return "high";+ if (stamp === "Dod") return "dod";+ if (stamp === "Mooncake") return "mooncake";+ if (stamp === "Internal") return "internal";+ // stamp === "Public"+ const g = String(geoName || "").toLowerCase();+ if (PUBLIC_US_GEOS.has(g)) return "us";+ if (PUBLIC_EU_GEOS.has(g)) return "eu";+ return null;+}++function mapToRegion(cloud, geoName, defaultRegion) {+ return deriveRegion(cloud, geoName) || defaultRegion;+}++function entryFromMap(regionsMap, region) {+ const e = regionsMap && regionsMap[region];+ if (!e || !e.instrumentation_key) return null;+ return {+ region,+ iKey: e.instrumentation_key,+ collectorUrl: e.collector_url || "",+ };+}++async function resolve({+ orgId,+ cloud,+ regionsMap,+ defaultRegion,+ configDir,+ _fetchGeo,+ _cache,+}) {+ const cache = _cache || defaultCache;+ const fetchGeo = typeof _fetchGeo === "function" ? _fetchGeo : defaultFetchGeo;+ const fallback = entryFromMap(regionsMap, defaultRegion);++ if (!orgId) return fallback;++ // Cache holds only the plugin-independent org→region mapping; map it to THIS+ // plugin's iKey/collector from regionsMap on every hit, so a cache shared+ // across plugins can never hand one plugin another plugin's key.+ const cached = cache.read(orgId, configDir);+ if (cached && cached.region) {+ return entryFromMap(regionsMap, cached.region) || fallback;+ }++ let artemis;+ try {+ artemis = await fetchGeo(orgId, cloud);+ } catch {+ artemis = null;+ }+ if (!artemis) return fallback;++ // Only a region DERIVED from a recognized geo/stamp is plugin-independent and+ // cacheable; an unrecognized geo falls back to this plugin's defaultRegion,+ // which must NOT be cached (another plugin's default may differ).+ const derived = deriveRegion(cloud, artemis.geoName);+ const region = derived || defaultRegion;+ const entry = entryFromMap(regionsMap, region) || fallback;+ if (!entry) return null;+ if (derived) {+ try {+ cache.write(orgId, { region: derived }, configDir);+ } catch {+ // swallow+ }+ }+ return entry;+}++module.exports = { resolve, mapToRegion };diff --git a/plugins/power-automate/scripts/lib/telemetry/resolver.js b/plugins/power-automate/scripts/lib/telemetry/resolver.jsnew file mode 100644index 000000000..d8871e6e1--- /dev/null+++ b/plugins/power-automate/scripts/lib/telemetry/resolver.js@@ -0,0 +1,40 @@+"use strict";++// Power Automate telemetry resolver: region routing via Artemis geo + cloud+// stamp. Implements the shared dispatcher's resolver contract. All+// artemis/region code lives in ./region/ — shared/telemetry knows nothing+// about it.+const { resolve: resolveRegion } = require("./region/region-resolver");+const { normalizeCloud } = require("./region/artemis-service");++// Power Automate provisions public-cloud ingestion only (us/eu). The shared+// region resolver falls back to default_region whenever the derived region has+// no entry in regionsMap, which would route a sovereign-cloud org's events to+// the public US collector. Short-circuit instead: returning null leaves the+// event unresolved, so the dispatcher writes the local mirror and does not+// POST.+async function resolve({ event, cfg, cloud, configDir }) {+ // normalizeCloud treats missing or unrecognized values as Public. Only use+ // the public collector when PAC explicitly identified a known public cloud.+ const cloudName = typeof cloud === "string" ? cloud.trim().toLowerCase() : "";+ if (cloudName !== "public" && cloudName !== "azurecloud") return null;+ if (normalizeCloud(cloud) !== "Public") return null;++ return resolveRegion({+ orgId: (event && event.data && event.data.orgId) || "",+ cloud,+ regionsMap: (cfg && cfg.regions) || {},+ defaultRegion: (cfg && cfg.default_region) || "us",+ configDir,+ });+}++// Sync fast-gate: is the default region's key configured? Lets the hooks skip+// the ~3-5s pac shellout when the plugin isn't provisioned yet.+function isProvisioned(cfg) {+ const dr = (cfg && cfg.default_region) || "us";+ const entry = cfg && cfg.regions && cfg.regions[dr];+ return !!(entry && entry.instrumentation_key);+}++module.exports = { resolve, isProvisioned };diff --git a/plugins/power-automate/scripts/release-contract.test.cjs b/plugins/power-automate/scripts/release-contract.test.cjsnew file mode 100644index 000000000..22ac73b23--- /dev/null+++ b/plugins/power-automate/scripts/release-contract.test.cjs@@ -0,0 +1,71 @@+"use strict";++const assert = require("node:assert/strict");+const fs = require("node:fs");+const path = require("node:path");+const { pathToFileURL } = require("node:url");+const { spawnSync } = require("node:child_process");+const { test } = require("node:test");+const root = path.resolve(__dirname, "..");++test("debug workflows allow bounded action content and describe the public repetition contract", () => {+ for (const name of ["debug-flow", "diagnose-flow"]) {+ const skill = fs.readFileSync(path.join(root, "skills", name, "SKILL.md"), "utf8");+ const allowed = skill.match(/^allowed-tools:\s*(.+)$/m)?.[1].split(/,\s*/);+ assert.ok(allowed?.includes("mcp__flowagent__get_run_action_content"));+ assert.ok(skill.includes('which: "inputs"'));+ assert.ok(skill.includes("{ action, count, truncated, repetitions }"));+ }+});++test("the telemetry guide is portable in a plugin-only installation", () => {+ const readme = fs.readFileSync(path.join(root, "README.md"), "utf8");+ assert.ok(readme.includes("(references/telemetry.md)"));+ const guide = fs.readFileSync(path.join(root, "references", "telemetry.md"), "utf8");+ assert.ok(guide.includes("eventInfo.aadObjectId"));+ assert.ok(guide.includes("no automatic retention policy"));+ assert.ok(guide.includes("POWER_PLATFORM_SKILLS_TELEMETRY_POWER_AUTOMATE_OPTOUT"));+ assert.ok(fs.existsSync(path.join(root, "skills", "telemetry", "SKILL.md")));+});++test("the shipped detached dispatcher aborts stalled fetches without making a network request", () => {+ const dispatcher = pathToFileURL(path.join(root, "server", "emit-dispatcher.mjs")).href;+ const script = `+ const assert = require("node:assert/strict");+ const timer = global.setTimeout;+ let fetched = false;+ let aborted = false;+ global.setTimeout = (fn, ms) => {+ assert.equal(ms, 5000);+ return timer(fn, 0);+ };+ global.fetch = (_url, options) => {+ fetched = true;+ return new Promise((_resolve, reject) => {+ options.signal.addEventListener("abort", () => {+ aborted = true;+ reject(new Error("test abort"));+ }, { once: true });+ });+ };+ process.on("beforeExit", () => {+ assert.equal(fetched, true);+ assert.equal(aborted, true);+ });+ import(${JSON.stringify(dispatcher)});+ `;+ const child = spawnSync(process.execPath, ["-e", script], {+ encoding: "utf8",+ timeout: 10_000,+ env: {+ ...process.env,+ FLOWAGENT_TELEMETRY_PAYLOAD: Buffer.from(JSON.stringify({+ eventName: "tool_completed", toolName: "get_flow",+ })).toString("base64"),+ FLOWAGENT_TELEMETRY_IKEY: "test-key",+ FLOWAGENT_TELEMETRY_COLLECTOR: "https://collector.invalid/OneCollector/1.0/",+ },+ });+ assert.ifError(child.error);+ assert.equal(child.status, 0, child.stderr);+});diff --git a/plugins/power-automate/server/emit-dispatcher.mjs b/plugins/power-automate/server/emit-dispatcher.mjsnew file mode 100644index 000000000..ea07f9ddd--- /dev/null+++ b/plugins/power-automate/server/emit-dispatcher.mjs@@ -0,0 +1,191 @@+import{createRequire}from'module';const require=createRequire(import.meta.url);++// packages/core/dist/telemetry/session.js+import { randomUUID } from "node:crypto";+var SESSION_ID = randomUUID();++// packages/core/dist/telemetry/events.js+var FIELD_TYPES = {+ // Envelope / common+ schemaVersion: "string",+ eventName: "string",+ time: "string",+ pluginName: "string",+ pluginVersion: "string",+ sessionId: "string",+ correlationId: "string",+ osName: "string",+ osVersion: "string",+ nodeVersion: "string",+ tenantId: "string",+ aiAgentName: "string",+ aiAgentVersion: "string",+ surface: "string",+ // "mcp" | "cli"+ // Tool / command identity+ toolName: "string",+ commandName: "string",+ // Outcome+ outcome: "string",+ // "success" | "failure"+ durationMs: "number",+ errorClass: "string",+ errorCode: "string",+ // MCP transport+ mcpTransport: "string",+ // "stdio" | "http"+ mcpClientName: "string",+ // Sizing / shape+ responseBytes: "number",+ actionCount: "number",+ // Flow creation+ templateId: "string",+ envId: "string",+ envLocation: "string",+ envRegion: "string"+};+function pick(input) {+ const out = {};+ for (const [key, type] of Object.entries(FIELD_TYPES)) {+ const v = input[key];+ if (v === void 0 || v === null)+ continue;+ if (type === "number") {+ const n = typeof v === "number" ? v : Number(v);+ if (Number.isFinite(n))+ out[key] = n;+ } else {+ out[key] = typeof v === "string" ? v : String(v);+ }+ }+ return out;+}++// packages/core/dist/telemetry/envelope.js+var PA_EVENT_NAME = "paintegrations.event";+var PA_OWNING_TEAM = "PowerAutomateIntegrations";+var PA_OWNING_TEAM_PRIORITY = "0";+function eventModifier(name, failed) {+ if (name.endsWith("_started"))+ return "Start";+ return failed ? "Failure" : "Complete";+}+function eventSubtype(name) {+ return name === "flow_created" ? "Create" : "Other";+}+var PROMOTED = /* @__PURE__ */ new Set([+ "eventName",+ "correlationId",+ "sessionId",+ "tenantId",+ "pluginName",+ "pluginVersion",+ "outcome",+ "durationMs",+ "errorClass",+ "errorCode",+ "time",+ "envId",+ "envLocation",+ "envRegion"+]);+function str(v) {+ return v === void 0 || v === null ? "" : String(v);+}+function toBodyIKey(fullKey) {+ return `o:${fullKey.split("-")[0]}`;+}+function toPaIntegrationsEnvelope(input, opts) {+ const record = pick(input);+ const now = (opts.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();+ const time = str(record.time) || now;+ const extra = {};+ for (const [k, v] of Object.entries(record)) {+ if (!PROMOTED.has(k) && v !== void 0)+ extra[k] = v;+ }+ const failed = record.outcome === "failure";+ const version = `${str(record.pluginName)}=${str(record.pluginVersion)}`;+ const name = str(record.eventName);+ const body = {+ name: PA_EVENT_NAME,+ time,+ ver: "4.0",+ iKey: toBodyIKey(opts.ikey),+ ext: { sdk: { ver: version } },+ data: {+ baseData: { properties: { version } },+ // Distinct from the envelope `time` above. Required.+ time,+ appName: str(record.pluginName),+ eventName: name,+ eventType: "Scenario",+ eventModifier: eventModifier(name, failed),+ eventSubtype: eventSubtype(name),+ message: name,+ // eventInfo and context are JSON strings, not objects.+ eventInfo: JSON.stringify(extra),+ context: "{}",+ severity: failed ? "Error" : "Information",+ activityId: str(record.correlationId),+ clientSessionId: str(record.sessionId),+ tenantId: str(record.tenantId),+ // durationInMs is a string in this schema; empty on start events.+ durationInMs: record.durationMs === void 0 ? "" : String(record.durationMs),+ errorName: str(record.errorClass),+ errorCode: str(record.errorCode),+ team: PA_OWNING_TEAM,+ teamPriority: PA_OWNING_TEAM_PRIORITY,+ buildNumber: str(record.pluginVersion),+ appLocale: "en-US",+ environmentId: str(record.envId),+ userRegion: str(record.envRegion),+ country: str(record.envLocation),+ appEnvironment: opts.appEnvironment ?? "prod"+ }+ };+ return {+ url: opts.collectorUrl,+ headers: {+ "content-type": "application/x-json-stream",+ apikey: opts.ikey,+ "Client-Id": "NO_AUTH",+ "client-version": version,+ "upload-time": String(Date.now()),+ "cache-control": "no-cache, no-store"+ },+ body: JSON.stringify(body)+ };+}++// packages/core/dist/telemetry/emit-dispatcher.js+async function main() {+ const b64 = process.env.FLOWAGENT_TELEMETRY_PAYLOAD;+ const ikey = process.env.FLOWAGENT_TELEMETRY_IKEY;+ const collector = process.env.FLOWAGENT_TELEMETRY_COLLECTOR;+ const appEnvironment = process.env.FLOWAGENT_TELEMETRY_APP_ENVIRONMENT;+ if (!b64 || !ikey || !collector)+ return;+ let record;+ try {+ record = JSON.parse(Buffer.from(b64, "base64").toString("utf8"));+ } catch {+ return;+ }+ const req = toPaIntegrationsEnvelope(record, { ikey, collectorUrl: collector, appEnvironment });+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 5e3);+ try {+ const response = await fetch(req.url, {+ method: "POST",+ headers: req.headers,+ body: req.body,+ signal: controller.signal+ });+ await response.body?.cancel();+ } catch {+ } finally {+ clearTimeout(timeout);+ }+}+void main();diff --git a/plugins/power-automate/server/mcp.mjs b/plugins/power-automate/server/mcp.mjsindex 7731ebd56..1c1b378c8 100644--- a/plugins/power-automate/server/mcp.mjs+++ b/plugins/power-automate/server/mcp.mjs@@ -10911,9 +10911,9 @@ var require_range = __commonJS({parseRange(range) {const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);const memoKey = memoOpts + ":" + range;- const cached3 = cache.get(memoKey);- if (cached3) {- return cached3;+ const cached2 = cache.get(memoKey);+ if (cached2) {+ return cached2;}const loose = this.options.loose;const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];@@ -18126,8 +18126,8 @@ var require_utils2 = __commonJS({var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" };var HOST_DELIM_RE = /[@/?#:]/g;var HOST_DELIM_NO_COLON_RE = /[@/?#]/g;- function reescapeHostDelimiters(host, isIP) {- const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;+ function reescapeHostDelimiters(host, isIP2) {+ const re = isIP2 ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;re.lastIndex = 0;return host.replace(re, (ch) => HOST_DELIMS[ch]);}@@ -18609,7 +18609,7 @@ var require_fast_uri2 = __commonJS({fragment: void 0};let malformedAuthorityOrPort = false;- let isIP = false;+ let isIP2 = false;if (options.reference === "suffix") {if (options.scheme) {uri = options.scheme + ":" + uri;@@ -18639,9 +18639,9 @@ var require_fast_uri2 = __commonJS({if (ipv4result === false) {const ipv6result = normalizeIPv6(parsed.host);parsed.host = ipv6result.host.toLowerCase();- isIP = ipv6result.isIPV6;+ isIP2 = ipv6result.isIPV6;} else {- isIP = true;+ isIP2 = true;}}if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) {@@ -18658,7 +18658,7 @@ var require_fast_uri2 = __commonJS({}const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {- if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {+ if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP2 === false && nonSimpleDomain(parsed.host)) {try {parsed.host = URL.domainToASCII(parsed.host.toLowerCase());} catch (e) {@@ -18672,7 +18672,7 @@ var require_fast_uri2 = __commonJS({parsed.scheme = unescape(parsed.scheme);}if (parsed.host !== void 0) {- parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP);+ parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP2);}}if (parsed.path) {@@ -21695,12 +21695,12 @@ var require_dist2 = __commonJS({throw new Error(`Unknown format "${name3}"`);return f;};- function addFormats2(ajv, list, fs6, exportName) {+ function addFormats2(ajv, list, fs7, exportName) {var _a3;var _b;(_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;for (const f of list)- ajv.addFormat(f, fs6[f]);+ ajv.addFormat(f, fs7[f]);}module.exports = exports = formatsPlugin;Object.defineProperty(exports, "__esModule", { value: true });@@ -44799,7 +44799,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin((exports, module) => {query: void 0,fragment: void 0};- let isIP = false;+ let isIP2 = false;if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri;else uri = "//" + uri;const matches = uri.match(URI_PARSE);@@ -44815,8 +44815,8 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin((exports, module) => {if (parsed.host) if (isIPv4(parsed.host) === false) {const ipv6result = normalizeIPv6(parsed.host);parsed.host = ipv6result.host.toLowerCase();- isIP = ipv6result.isIPV6;- } else isIP = true;+ isIP2 = ipv6result.isIPV6;+ } else isIP2 = true;if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document";else if (parsed.scheme === void 0) parsed.reference = "relative";else if (parsed.fragment === void 0) parsed.reference = "absolute";@@ -44824,7 +44824,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin((exports, module) => {if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {- if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try {+ if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP2 === false && nonSimpleDomain(parsed.host)) try {parsed.host = URL.domainToASCII(parsed.host.toLowerCase());} catch (e) {parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;@@ -48549,11 +48549,11 @@ var require_dist = /* @__PURE__ */ __commonJSMin((exports, module) => {if (!f) throw new Error(`Unknown format "${name3}"`);return f;};- function addFormats2(ajv, list, fs6, exportName) {+ function addFormats2(ajv, list, fs7, exportName) {var _a3;var _b;(_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`);- for (const f of list) ajv.addFormat(f, fs6[f]);+ for (const f of list) ajv.addFormat(f, fs7[f]);}module.exports = exports = formatsPlugin;Object.defineProperty(exports, "__esModule", { value: true });@@ -49477,6 +49477,23 @@ var StdioServerTransport = class {}};+// packages/core/dist/version.js+var FLOWAGENT_VERSION = "3.2.1";+async function buildId() {+ try {+ const [{ createHash: createHash4 }, { readFile }, { fileURLToPath: fileURLToPath2 }] = await Promise.all([+ import("node:crypto"),+ import("node:fs/promises"),+ import("node:url")+ ]);+ const self = fileURLToPath2(import.meta.url);+ const bytes = await readFile(self);+ return createHash4("sha256").update(bytes).digest("hex").slice(0, 12);+ } catch {+ return null;+ }+}+// packages/core/dist/api/flow-client.jsinit_logger();@@ -49587,6 +49604,51 @@ var PreviewTokenError = class extends Error {}};+// packages/core/dist/utils/fetch-with-network-error.js+function explain(code, hostname3) {+ switch (code) {+ case "UNABLE_TO_VERIFY_LEAF_SIGNATURE":+ case "SELF_SIGNED_CERT_IN_CHAIN":+ case "DEPTH_ZERO_SELF_SIGNED_CERT":+ case "CERT_HAS_EXPIRED":+ case "UNABLE_TO_GET_ISSUER_CERT_LOCALLY":+ case "UNABLE_TO_GET_ISSUER_CERT":+ case "CERT_UNTRUSTED":+ case "ERR_TLS_CERT_ALTNAME_INVALID":+ return `TLS certificate validation failed for ${hostname3}. This usually means a corporate proxy or security appliance is inspecting HTTPS traffic. Point Node at your organisation's CA bundle with NODE_EXTRA_CA_CERTS=/path/to/ca.pem.`;+ case "ENOTFOUND":+ case "EAI_AGAIN":+ return `DNS lookup failed for ${hostname3}. Check your network or VPN connection. If this is a Power Platform API host, verify the environment ID is a valid GUID \u2014 a malformed ID produces a hostname that does not exist.`;+ case "ECONNREFUSED":+ return `Connection refused by ${hostname3}. Check that any required proxy (HTTPS_PROXY) is reachable.`;+ case "ETIMEDOUT":+ case "UND_ERR_CONNECT_TIMEOUT":+ case "UND_ERR_HEADERS_TIMEOUT":+ return `Connection to ${hostname3} timed out. Check your network, VPN, or proxy configuration.`;+ case "ECONNRESET":+ return `Connection to ${hostname3} was reset. This is often a proxy or firewall closing the connection.`;+ default:+ return `Network request to ${hostname3} failed. Check your network, VPN, and proxy configuration.`;+ }+}+function hostnameOf(url2) {+ try {+ return new URL(url2).hostname;+ } catch {+ return url2;+ }+}+async function fetchWithNetworkError(url2, init) {+ try {+ return await fetch(url2, init);+ } catch (err) {+ const cause = err?.cause;+ const hostname3 = cause?.hostname ?? hostnameOf(url2);+ const code = cause?.code ?? (err instanceof TypeError ? "FETCH_FAILED" : "UNKNOWN");+ throw new FlowApiError(0, "NetworkError", `Network request failed: ${code} (hostname: ${hostname3}). ${explain(code, hostname3)}`, url2);+ }+}+// packages/core/dist/utils/odata.jsfunction escapeODataString(s) {return s.replace(/'/g, "''");@@ -49615,27 +49677,27 @@ function connQs(extra) {}return "?" + new URLSearchParams(params).toString();}-function ppapiConnectionsUrl(envId, opts) {- const base = ppapiBaseUrl(envId);+function ppapiConnectionsUrl(envId, opts, baseOverride) {+ const base = baseOverride ?? ppapiBaseUrl(envId);if (opts?.connector) {return `${base}/connectivity/connectors/${opts.connector}/connections${connQs()}`;}return `${base}/connectivity/connections${connQs()}`;}-function ppapiConnectionUrl(envId, connector, connName) {- const base = ppapiBaseUrl(envId);+function ppapiConnectionUrl(envId, connector, connName, baseOverride) {+ const base = baseOverride ?? ppapiBaseUrl(envId);return `${base}/connectivity/connectors/${connector}/connections/${connName}${connQs({ "$filter": `environment eq '${envId}'` })}`;}-function ppapiConnectionConsentUrl(envId, connector, connName) {- const base = ppapiBaseUrl(envId);+function ppapiConnectionConsentUrl(envId, connector, connName, baseOverride) {+ const base = baseOverride ?? ppapiBaseUrl(envId);return `${base}/connectivity/connectors/${connector}/connections/${connName}/getConsentLink${connQs({ "$filter": `environment eq '${envId}'` })}`;}-function ppapiConnectionPermissionsUrl(envId, connector, connName) {- const base = ppapiBaseUrl(envId);+function ppapiConnectionPermissionsUrl(envId, connector, connName, baseOverride) {+ const base = baseOverride ?? ppapiBaseUrl(envId);return `${base}/connectivity/connectors/${connector}/connections/${connName}/permissions${connQs({ "$filter": `environment eq '${envId}'` })}`;}-function ppapiConnectionModifyPermissionsUrl(envId, connector, connName) {- const base = ppapiBaseUrl(envId);+function ppapiConnectionModifyPermissionsUrl(envId, connector, connName, baseOverride) {+ const base = baseOverride ?? ppapiBaseUrl(envId);return `${base}/connectivity/connectors/${connector}/connections/${connName}/modifyPermissions${connQs({ "$filter": `environment eq '${envId}'` })}`;}function dataverseConnectionReferencesUrl(instanceUrl, opts) {@@ -49649,14 +49711,17 @@ function dataverseConnectionReferencesUrl(instanceUrl, opts) {}var PPAPI_API_VERSION = "1";var PPAPI_DEFAULT_SUFFIX = "environment.api.powerplatform.com";-function ppapiBaseUrl(envId, templateOverride, suffixOverride) {+var PPAPI_DEFAULT_SHARD_LENGTH = 2;+function ppapiBaseUrl(envId, templateOverride, suffixOverride, shardLengthOverride) {const isDefault = /^Default-/i.test(envId);const hex3 = envId.replace(/^Default-/i, "").toLowerCase().replace(/-/g, "");if (!/^[0-9a-f]{32}$/.test(hex3)) {throw new InvalidEnvironmentIdError(envId, `Cannot derive a PPAPI URL from environment ID "${envId}": expected a GUID (optionally prefixed with "Default-"), but got ${hex3.length} hex character(s) after removing dashes, not 32. Pass a full environment ID such as "Default-a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d" or "b7c8d9e0-1f2a-4b3c-9d4e-5f6a7b8c9d0e" \u2014 list_environments / resolve_environment return usable values. Environment display names and partial IDs are not accepted.`);}- const prefix = (isDefault ? "default" : "") + hex3.slice(0, 30);- const shard = hex3.slice(30, 32);+ const shardLength = resolveShardLength(shardLengthOverride);+ const splitAt = 32 - shardLength;+ const prefix = (isDefault ? "default" : "") + hex3.slice(0, splitAt);+ const shard = hex3.slice(splitAt);const template = templateOverride ?? process.env.PA_PPAPI_BASE_URL;if (template) {return template.replace(/\{prefix\}/g, prefix).replace(/\{shard\}/g, shard).replace(/\{envId\}/g, envId).replace(/\{hex\}/g, hex3);@@ -49664,6 +49729,18 @@ function ppapiBaseUrl(envId, templateOverride, suffixOverride) {const suffix = process.env.PA_PPAPI_SUFFIX ?? suffixOverride ?? PPAPI_DEFAULT_SUFFIX;return `https://${prefix}.${shard}.${suffix}`;}+function resolveShardLength(shardLengthOverride) {+ const isUsable = (n) => n !== void 0 && Number.isInteger(n) && n >= 1 && n <= 31;+ const fromEnv = process.env.PA_PPAPI_SHARD_LENGTH;+ if (fromEnv !== void 0 && fromEnv !== "") {+ const parsed = Number(fromEnv);+ if (isUsable(parsed))+ return parsed;+ }+ if (isUsable(shardLengthOverride))+ return shardLengthOverride;+ return PPAPI_DEFAULT_SHARD_LENGTH;+}function ppapiQs(extra) {const params = {"api-version": PPAPI_API_VERSION,@@ -49704,8 +49781,8 @@ function ppapiFlowQs(extra) {}return "?" + new URLSearchParams(params).toString();}-function ppapiConnectorUrl(envId, connectorName, opts) {- const base = ppapiBaseUrl(envId);+function ppapiConnectorUrl(envId, connectorName, opts, baseOverride) {+ const base = baseOverride ?? ppapiBaseUrl(envId);return `${base}/powerautomate/apis/${connectorName}${ppapiFlowQs({$expand: opts?.expand})}`;@@ -49900,19 +49977,20 @@ init_backups();// packages/core/dist/api/pagination.jsinit_logger();var DEFAULT_MAX_PAGES = 5;-async function followPagination(fetchPage, maxPages = DEFAULT_MAX_PAGES) {+async function followPagination(fetchPage, maxPages = DEFAULT_MAX_PAGES, stopWhen, onLimitReached) {const allItems = [];let response = await fetchPage();allItems.push(...response.value);let page = 1;- while (response.nextLink && page < maxPages) {+ while (response.nextLink && page < maxPages && !stopWhen?.(allItems)) {logger.debug(`Following pagination page ${page + 1}`);response = await fetchPage(response.nextLink);allItems.push(...response.value);page++;}- if (response.nextLink) {+ if (response.nextLink && page >= maxPages) {logger.debug(`Stopped pagination after ${maxPages} pages, more data available`);+ onLimitReached?.(response.nextLink);}return allItems;}@@ -50636,6 +50714,7 @@ function issueToken(args) {envId: args.envId,flowId: args.flowId,proposalHash: args.proposalHash,+ lastModifiedTime: args.lastModifiedTime,issuedAt: now,expiresAt: now + ttl};@@ -50676,7 +50755,7 @@ function redeemToken(token, expected) {};}store.delete(token);- return { ok: true };+ return { ok: true, lastModifiedTime: rec.lastModifiedTime };}// packages/core/dist/api/flow-edit.js@@ -50913,12 +50992,42 @@ var GATED_REQUEST_TRIGGER_KINDS = /* @__PURE__ */ new Set(["powerpages","skills"]);-async function fetchContentLink(uri) {- const res = await fetch(uri, { method: "GET" });- const text = await res.text();- if (!res.ok) {- throw new FlowApiError(res.status, res.statusText, text, uri);+async function readContentText(response, maxBytes) {+ const contentLength = Number(response.headers.get("content-length"));+ if (maxBytes !== void 0 && Number.isFinite(contentLength) && contentLength > maxBytes) {+ try {+ await response.body?.cancel();+ } catch {+ }+ return { contentSize: contentLength, exceedsLimit: true };+ }+ if (maxBytes === void 0)+ return { text: await response.text() };+ const reader = response.body?.getReader();+ if (!reader) {+ const text = await response.text();+ const contentSize2 = Buffer.byteLength(text, "utf8");+ return contentSize2 > maxBytes ? { contentSize: contentSize2, exceedsLimit: true } : { text, contentSize: contentSize2 };}+ const chunks = [];+ let contentSize = 0;+ while (true) {+ const { done, value } = await reader.read();+ if (done)+ break;+ contentSize += value.byteLength;+ if (contentSize > maxBytes) {+ try {+ await reader.cancel();+ } catch {+ }+ return { contentSize, exceedsLimit: true };+ }+ chunks.push(Buffer.from(value));+ }+ return { text: Buffer.concat(chunks).toString("utf8"), contentSize };+}+function parseContentText(text) {if (!text)return void 0;try {@@ -50927,6 +51036,22 @@ async function fetchContentLink(uri) {return text;}}+async function fetchContentLink(uri, maxBytes) {+ let res;+ try {+ res = await fetchWithNetworkError(uri, { method: "GET" });+ } catch (err) {+ if (err instanceof FlowApiError) {+ throw new FlowApiError(err.statusCode, err.statusText, err.body, "SAS content link");+ }+ throw err;+ }+ const { text, contentSize, exceedsLimit } = await readContentText(res, maxBytes);+ if (!res.ok) {+ throw new FlowApiError(res.status, res.statusText, exceedsLimit ? `Response body exceeded the ${maxBytes}-byte limit.` : text ?? "", "SAS content link");+ }+ return exceedsLimit ? { contentSize, exceedsLimit } : { content: parseContentText(text ?? ""), contentSize };+}function isDirectApiTriggerKind(kind) {return !!kind && DIRECT_API_TRIGGER_KINDS.has(kind.toLowerCase());}@@ -50953,6 +51078,13 @@ function isNoManagementRunEndpoint(err) {return false;return /TriggerNotFound|WorkflowTriggerNotFound|NotSupported|OperationNotSupported/i.test(err.body ?? "");}+function sameInstant(a, b) {+ const ta = Date.parse(a);+ const tb = Date.parse(b);+ if (Number.isNaN(ta) || Number.isNaN(tb))+ return a === b;+ return ta === tb;+}function assertTriggerInputsSatisfied(trigger, body) {const schema = trigger.inputsSchema;if (!schema)@@ -51038,7 +51170,7 @@ var FlowClient = class _FlowClient {}/** Resolve the PPAPI base URL for an environment, respecting config overrides. */ppapiBase(envId) {- return ppapiBaseUrl(envId, this.config.ppapiBaseUrlTemplate, this.config.cloudEndpoints.ppapiSuffix);+ return ppapiBaseUrl(envId, this.config.ppapiBaseUrlTemplate, this.config.cloudEndpoints.ppapiSuffix, this.config.cloudEndpoints.ppapiShardLength);}/*** Check whether a FlowApiError represents a DNS/network resolution failure@@ -51168,34 +51300,36 @@ var FlowClient = class _FlowClient {}}async updateFlow(envId, flowId, body, opts = {}) {- if (opts.previewToken) {- await this.assertPreviewTokenMatches(envId, flowId, body, opts.previewToken);- }+ const expectedLastModifiedTime = opts.previewToken ? this.assertPreviewTokenMatches(envId, flowId, body, opts.previewToken) : void 0;await this.assertNotManaged(envId, flowId, "update_flow", opts);await this.snapshotBeforeMutation(envId, flowId, "update_flow", opts);+ const workingBody = structuredClone(body);let autoMerged = [];- if (opts.autoResolveConnectionRefs !== false && body.properties?.definition) {- autoMerged = await this.autoMergeConnectionRefs(envId, flowId, body);+ if (opts.autoResolveConnectionRefs !== false && workingBody.properties?.definition) {+ autoMerged = await this.autoMergeConnectionRefs(envId, flowId, workingBody);}- this.stripInjectedAuthentication(body);- if (body.properties?.definition) {+ this.stripInjectedAuthentication(workingBody);+ if (workingBody.properties?.definition) {try {const ctx = await this.getFlowContext(envId, flowId);if (ctx.inSolution && ctx.workflowId && !ctx.warning) {- const updated = await this.updateFlowViaDataverse(envId, flowId, ctx.workflowId, body);+ const updated = await this.updateFlowViaDataverse(envId, flowId, ctx.workflowId, workingBody, expectedLastModifiedTime);if (updated) {if (autoMerged.length)updated._autoMergedConnectionRefs = autoMerged;return updated;}}- } catch {+ } catch (err) {+ if (err instanceof PreviewTokenError)+ throw err;logger.debug(`updateFlow: Dataverse path failed, falling through to PPAPI`);}}- this.rewriteConnectionNamesForPpapi(body);+ this.rewriteConnectionNamesForPpapi(workingBody);const path7 = `/powerautomate/flows/${flowId}${this.ppapiFlowQs({})}`;- const result = await this.ppapiRequestWithFallback(envId, path7, "PATCH", body);+ await this.assertPreviewVersionUnchanged(envId, flowId, expectedLastModifiedTime);+ const result = await this.ppapiRequestWithFallback(envId, path7, "PATCH", workingBody);if (autoMerged.length)result._autoMergedConnectionRefs = autoMerged;return result;@@ -51282,7 +51416,7 @@ var FlowClient = class _FlowClient {* This bypasses PPAPI validation issues with connectionName/connectionReferenceName* round-trip (#314 finding 2).*/- async updateFlowViaDataverse(envId, flowId, workflowId, body) {+ async updateFlowViaDataverse(envId, flowId, workflowId, body, expectedLastModifiedTime) {let instanceUrl;try {instanceUrl = await this.getDataverseInstanceUrl(envId);@@ -51301,6 +51435,7 @@ var FlowClient = class _FlowClient {clientdata.properties.displayName = body.properties.displayName;}const patchUrl = `${instanceUrl}/api/data/v9.2/workflows(${workflowId})`;+ await this.assertPreviewVersionUnchanged(envId, flowId, expectedLastModifiedTime);await this.dataversePatch(patchUrl, { clientdata: JSON.stringify(clientdata) }, dvToken);return this.getFlow(envId, flowId);}@@ -51316,11 +51451,12 @@ var FlowClient = class _FlowClient {const def = body.properties?.definition;if (!def)return;+ const isInjectedAuth = (value) => typeof value === "string" && /^(?:@parameters\(\s*'\$authentication'\s*\)|@\{\s*parameters\(\s*'\$authentication'\s*\)\s*\})$/.test(value.trim());const stripAuth = (inputs) => {if (!inputs || typeof inputs !== "object" || Array.isArray(inputs))return;const inp = inputs;- if ("authentication" in inp)+ if ("authentication" in inp && isInjectedAuth(inp.authentication))delete inp.authentication;};const walkActions = (actions) => {@@ -51563,6 +51699,9 @@ var FlowClient = class _FlowClient {envId,flowId,proposalHash,+ // Bind the flow version we diffed against, so apply can detect a+ // concurrent write (#606). Free here — getFlow already ran above.+ lastModifiedTime: current?.properties?.lastModifiedTime,ttlMs: opts.ttlMs});return {@@ -51575,7 +51714,7 @@ var FlowClient = class _FlowClient {note: diff.hasChanges ? "Review the diff above. Re-submit the SAME body to update_flow with previewToken to apply." : "No changes detected vs the live flow. update_flow is a no-op for this body."};}- async assertPreviewTokenMatches(envId, flowId, body, token) {+ assertPreviewTokenMatches(envId, flowId, body, token) {const proposalHash = hashUpdateBody(body);const result = redeemToken(token, { envId, flowId, proposalHash });if (!result.ok) {@@ -51584,6 +51723,24 @@ var FlowClient = class _FlowClient {}throw new PreviewTokenError(result.code);}+ return result.lastModifiedTime;+ }+ async assertPreviewVersionUnchanged(envId, flowId, expectedLastModifiedTime) {+ if (!expectedLastModifiedTime)+ return;+ let actual;+ try {+ const currentFlow = await this.getFlow(envId, flowId);+ actual = currentFlow?.properties?.lastModifiedTime;+ } catch {+ throw new PreviewTokenError("PreviewConcurrencyCheckFailed", "the flow version could not be checked immediately before the update", "Call preview_update again, review the current flow, then retry update_flow with the new token.");+ }+ if (!actual) {+ throw new PreviewTokenError("PreviewConcurrencyCheckFailed", "the final flow read did not include the previewed version timestamp", "Call preview_update again, review the current flow, then retry update_flow with the new token.");+ }+ if (!sameInstant(expectedLastModifiedTime, actual)) {+ throw new PreviewTokenError("PreviewConcurrencyConflict", `the flow changed after preview (previewed lastModifiedTime ${expectedLastModifiedTime}, now ${actual})`, "Re-read the flow, call preview_update again to diff against the current definition, and re-apply only if the change is still what you intend.");+ }}async deleteFlow(envId, flowId, opts = {}) {await this.assertNotManaged(envId, flowId, "delete_flow", opts);@@ -51684,9 +51841,7 @@ var FlowClient = class _FlowClient {try {await this.ppapiRequestWithFallback(envId, path7, "POST");} catch (err) {- if (err instanceof FlowApiError && err.statusCode === 409) {- alreadyStarted = true;- } else if (err instanceof FlowApiError && /CannotStartUnpublishedSolutionFlow/i.test(err.body)) {+ if (err instanceof FlowApiError && /CannotStartUnpublishedSolutionFlow/i.test(err.body)) {logger.info(`[publish-flow] PPAPI blocked with CannotStartUnpublishedSolutionFlow, attempting Dataverse activation`);const ctx = await this.getFlowContext(envId, flowId);if (!ctx.workflowId)@@ -51701,6 +51856,8 @@ var FlowClient = class _FlowClient {logger.warn(`[publish-flow] Dataverse activation failed: ${dvErr instanceof Error ? dvErr.message : dvErr}`);throw err;}+ } else if (err instanceof FlowApiError && err.statusCode === 409) {+ alreadyStarted = true;} else {throw err;}@@ -51875,7 +52032,7 @@ var FlowClient = class _FlowClient {headers.Authorization = `Bearer ${await this.auth.getAccessToken(this.config.cloudEndpoints.flowResource)}`;}logger.debug(`POST ${callbackUrl}${opts.withAuth ? " (SAS + bearer)" : " (SAS only)"}`);- const response = await fetch(callbackUrl, {+ const response = await fetchWithNetworkError(callbackUrl, {method: "POST",headers,body: JSON.stringify(triggerBody)@@ -51913,7 +52070,7 @@ var FlowClient = class _FlowClient {*/async runFlowViaLogicFlowsConnector(envId, flowId, triggerBody, triggerName) {const resolvedTrigger = triggerName ?? await this.resolveTriggerName(envId, flowId);- const connectorUrl = ppapiConnectorUrl(envId, LOGIC_FLOWS_CONNECTOR);+ const connectorUrl = ppapiConnectorUrl(envId, LOGIC_FLOWS_CONNECTOR, void 0, this.ppapiBase(envId));const connector = await this.ppapiRequest("GET", connectorUrl);const runtimeUrl = connector.properties.primaryRuntimeUrl;if (!runtimeUrl) {@@ -51922,7 +52079,7 @@ var FlowClient = class _FlowClient {const url2 = `${runtimeUrl.replace(/\/+$/, "")}/${encodeURIComponent(flowId)}/triggers/${encodeURIComponent(resolvedTrigger)}/run?api-version=2016-11-01`;const apihubToken = await this.auth.getAccessToken(APIHUB_RESOURCE);logger.debug(`POST ${url2} (Logic Flows connector)`);- const response = await fetch(url2, {+ const response = await fetchWithNetworkError(url2, {method: "POST",headers: {Authorization: `Bearer ${apihubToken}`,@@ -52026,13 +52183,94 @@ var FlowClient = class _FlowClient {await this.ppapiRequestWithFallback(envId, path7, "POST");return { resubmitted: true, triggerName };}- async getRunActionRepetitions(envId, flowId, runId, actionName) {+ /**+ * Fetch the recorded inputs or outputs of a single action in a run (#648).+ *+ * The run-actions response carries only `inputsLink`/`outputsLink` — SAS-signed+ * URLs to the content, never the content itself — so there was previously no+ * way to see what an action actually received or produced without leaving the+ * tool. `maxBytes` guards against pulling a multi-megabyte payload into an+ * agent's context; the link's `contentSize` is checked first so an oversized+ * body is reported rather than downloaded.+ */+ async getRunActionContent(envId, flowId, runId, actionName, which, opts = {}) {+ const maxBytes = Math.max(Math.trunc(opts.maxBytes ?? 256e3), 1);+ const actions = await this.getRunActionDetails(envId, flowId, runId);+ const action = actions.find((a) => a.name === actionName);+ if (!action) {+ throw new Error(`Action '${actionName}' not found in run ${runId}. Use get_run_actions to list the action names in this run.`);+ }+ const props = action.properties ?? {};+ const link = which === "inputs" ? props.inputsLink : props.outputsLink;+ if (!link?.uri) {+ return {+ action: actionName,+ which,+ skipped: `This action recorded no ${which}. Actions with no ${which}, or whose content has expired with the run history, carry no link.`+ };+ }+ const contentSize = typeof link.contentSize === "number" ? link.contentSize : void 0;+ if (contentSize !== void 0 && contentSize > maxBytes) {+ return {+ action: actionName,+ which,+ contentSize,+ skipped: `Content is ${contentSize} bytes, over the ${maxBytes}-byte cap. Raise maxBytes to retrieve it.`+ };+ }+ const fetched = await fetchContentLink(link.uri, maxBytes);+ if (fetched.exceedsLimit) {+ const actualSize = fetched.contentSize ?? contentSize;+ return {+ action: actionName,+ which,+ contentSize: actualSize,+ skipped: `Content is at least ${actualSize} bytes, over the ${maxBytes}-byte cap. Raise maxBytes to retrieve it.`+ };+ }+ return {+ action: actionName,+ which,+ contentSize: contentSize ?? fetched.contentSize,+ content: fetched.content+ };+ }+ /**+ * List the per-iteration records for an action inside a loop.+ *+ * A `Do_until` or a large `Apply_to_each` can produce thousands of+ * repetitions, each carrying inputs/outputs links — enough to exhaust an MCP+ * client's context in a single call (#517). The result is therefore bounded+ * by `top` (default 100) and `statusFilter`, applied after retrieval because+ * the API offers no server-side filter, with pagination stopped early once+ * enough rows are in hand.+ */+ async getRunActionRepetitions(envId, flowId, runId, actionName, opts = {}) {+ const top = Math.min(Math.max(Math.trunc(opts.top ?? 100), 1), 1e3);+ const statusFilter = opts.statusFilter ?? "any";+ const includeLinks = opts.includeLinks ?? true;const path7 = `/powerautomate/flows/${flowId}/runs/${runId}/actions/${actionName}/repetitions${this.ppapiFlowQs({})}`;- return followPagination(async (nextUrl) => {+ const matches = (r) => statusFilter === "any" || r?.properties?.status === statusFilter;+ let paginationLimitReached = false;+ const all = await followPagination(async (nextUrl) => {if (nextUrl)return this.ppapiRequest("GET", nextUrl);return this.ppapiRequestWithFallback(envId, path7, "GET");+ }, void 0, (items) => items.filter(matches).length > top, () => {+ paginationLimitReached = true;+ });+ const filtered = all.filter(matches);+ const page = filtered.slice(0, top).map((r) => {+ if (includeLinks)+ return r;+ const { inputsLink, outputsLink, ...rest } = r?.properties ?? {};+ return { ...r, properties: rest };});+ return {+ repetitions: page,+ returned: page.length,+ truncated: filtered.length > top || paginationLimitReached+ };}/** Diagnose a failed run: classify each failed/timed-out action with an actionable remediation. */async diagnoseRun(envId, flowId, runId) {@@ -52074,7 +52312,7 @@ var FlowClient = class _FlowClient {const instanceUrl = await this.getDataverseInstanceUrl(envId);const url2 = `${instanceUrl}/api/data/v9.2/workflows(${ctx.workflowId})/Microsoft.Dynamics.CRM.CancelAllCloudFlowRuns`;const token = await this.auth.getAccessToken(instanceUrl);- const resp = await fetch(url2, {+ const resp = await fetchWithNetworkError(url2, {method: "POST",headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },body: JSON.stringify({})@@ -52161,7 +52399,8 @@ var FlowClient = class _FlowClient {const inputsLink = runTrigger?.inputsLink?.uri ?? matchedAction?.properties?.inputsLink?.uri;if (triggerInputs === void 0 && inputsLink) {try {- triggerInputs = await fetchContentLink(inputsLink);+ const fetched = await fetchContentLink(inputsLink);+ triggerInputs = fetched.content;} catch (err) {triggerInputs = {_note: "inputsLink fetch failed; trigger inputs unavailable for this run",@@ -52407,7 +52646,7 @@ var FlowClient = class _FlowClient {const url2 = governanceUserRoutingUrl(this.config.cloudEndpoints.powerPlatformApiUrl);const token = await this.auth.getAccessToken();logger.debug(`GET ${url2}`);- const response = await fetch(url2, {+ const response = await fetchWithNetworkError(url2, {method: "GET",headers: {Authorization: `Bearer ${token}`,@@ -52425,7 +52664,7 @@ var FlowClient = class _FlowClient {const url2 = governanceRoutingStatusUrl(operationId, this.config.cloudEndpoints.powerPlatformApiUrl);const token = await this.auth.getAccessToken();logger.debug(`GET ${url2}`);- const response = await fetch(url2, {+ const response = await fetchWithNetworkError(url2, {method: "GET",headers: {Authorization: `Bearer ${token}`,@@ -52445,7 +52684,7 @@ var FlowClient = class _FlowClient {const url2 = bapDefaultEnvironmentUrl(this.config.cloudEndpoints.bapBaseUrl);const token = await this.auth.getAccessToken();logger.debug(`GET ${url2}`);- const response = await fetch(url2, {+ const response = await fetchWithNetworkError(url2, {method: "GET",headers: {Authorization: `Bearer ${token}`,@@ -52586,7 +52825,7 @@ var FlowClient = class _FlowClient {};}async invokeOperation(envId, connectorName, connectionId, operationId, params, continuation2) {- const connectorUrl = ppapiConnectorUrl(envId, connectorName, { expand: "swagger" });+ const connectorUrl = ppapiConnectorUrl(envId, connectorName, { expand: "swagger" }, this.ppapiBase(envId));const connector = await this.ppapiRequest("GET", connectorUrl);const runtimeUrl = connector.properties.primaryRuntimeUrl;if (!runtimeUrl) {@@ -53142,7 +53381,7 @@ var FlowClient = class _FlowClient {}// --- PPAPI Connections ---async getConnections(envId, opts) {- const url2 = ppapiConnectionsUrl(envId, opts);+ const url2 = ppapiConnectionsUrl(envId, opts, this.ppapiBase(envId));const data = await this.connectivityRequest("GET", url2);return data.value;}@@ -53485,14 +53724,14 @@ var FlowClient = class _FlowClient {};}async getConnection(envId, connector, connName) {- const url2 = ppapiConnectionUrl(envId, connector, connName);+ const url2 = ppapiConnectionUrl(envId, connector, connName, this.ppapiBase(envId));return this.connectivityRequest("GET", url2);}async createConnection(envId, connector, opts) {const safeName = connector.replace(/_/g, "-").slice(0, 20);const connName = `${safeName}-${randomUUID2().slice(0, 8)}`;logger.info(`Creating connection '${connName}' for connector '${connector}'\u2026`);- const createUrl = ppapiConnectionUrl(envId, connector, connName);+ const createUrl = ppapiConnectionUrl(envId, connector, connName, this.ppapiBase(envId));const createBody = {properties: {connectionParameters: opts?.params ?? {},@@ -53532,17 +53771,17 @@ var FlowClient = class _FlowClient {return this.authenticateConnection(envId, connector, connName, connection, opts);}async deleteConnection(envId, connector, connName) {- const url2 = ppapiConnectionUrl(envId, connector, connName);+ const url2 = ppapiConnectionUrl(envId, connector, connName, this.ppapiBase(envId));await this.connectivityRequest("DELETE", url2);this.invalidateConnectionCache(envId, connector);}async getConnectionPermissions(envId, connector, connName) {- const url2 = ppapiConnectionPermissionsUrl(envId, connector, connName);+ const url2 = ppapiConnectionPermissionsUrl(envId, connector, connName, this.ppapiBase(envId));const data = await this.connectivityRequest("GET", url2);return data.value;}async shareConnection(envId, connector, connName, principalId, roleName, principalType) {- const url2 = ppapiConnectionModifyPermissionsUrl(envId, connector, connName);+ const url2 = ppapiConnectionModifyPermissionsUrl(envId, connector, connName, this.ppapiBase(envId));const body = {put: [{@@ -53559,12 +53798,12 @@ var FlowClient = class _FlowClient {await this.connectivityRequest("POST", url2, body);}async unshareConnection(envId, connector, connName, permissionId) {- const url2 = ppapiConnectionModifyPermissionsUrl(envId, connector, connName);+ const url2 = ppapiConnectionModifyPermissionsUrl(envId, connector, connName, this.ppapiBase(envId));await this.connectivityRequest("POST", url2, { delete: [{ id: permissionId }] });}async updateConnection(envId, connector, connName, opts) {const current = await this.getConnection(envId, connector, connName);- const url2 = ppapiConnectionUrl(envId, connector, connName);+ const url2 = ppapiConnectionUrl(envId, connector, connName, this.ppapiBase(envId));const body = {properties: {...current.properties,@@ -53577,7 +53816,7 @@ var FlowClient = class _FlowClient {}async authenticateConnection(envId, connector, connName, fallbackConnection, opts) {try {- const consentUrl = ppapiConnectionConsentUrl(envId, connector, connName);+ const consentUrl = ppapiConnectionConsentUrl(envId, connector, connName, this.ppapiBase(envId));const consent = await this.connectivityRequest("POST", consentUrl, { redirectUrl: "https://make.powerautomate.com" });if (consent.firstPartyLoginUri) {logger.info("Authenticating connection (first-party silent auth)...");@@ -53656,10 +53895,10 @@ var FlowClient = class _FlowClient {async listConnections(envId, opts) {const connector = opts?.connectorFilter ?? opts?.connector;if (opts?.useCache !== false) {- const cached3 = this.getCachedConnections(envId, connector);- if (cached3) {+ const cached2 = this.getCachedConnections(envId, connector);+ if (cached2) {logger.debug(`listConnections cache hit: ${envId}:${connector ?? "*"}`);- return cached3;+ return cached2;}}const instanceUrl = await this.getDataverseInstanceUrl(envId);@@ -53943,7 +54182,7 @@ var FlowClient = class _FlowClient {// --- Dataverse HTTP ---async dataverseGet(url2, token) {logger.debug(`GET ${url2}`);- const response = await fetch(url2, {+ const response = await fetchWithNetworkError(url2, {method: "GET",headers: {Authorization: `Bearer ${token}`,@@ -53960,7 +54199,7 @@ var FlowClient = class _FlowClient {}async dataversePost(url2, body, token) {logger.debug(`POST ${url2}`);- const response = await fetch(url2, {+ const response = await fetchWithNetworkError(url2, {method: "POST",headers: {Authorization: `Bearer ${token}`,@@ -53982,7 +54221,7 @@ var FlowClient = class _FlowClient {}async dataversePatch(url2, body, token) {logger.debug(`PATCH ${url2}`);- const response = await fetch(url2, {+ const response = await fetchWithNetworkError(url2, {method: "PATCH",headers: {Authorization: `Bearer ${token}`,@@ -54024,25 +54263,11 @@ var FlowClient = class _FlowClient {headers["Content-Type"] = "application/json";}logger.debug(`${method} ${url2}`);- let response;- try {- response = await fetch(url2, {- method,- headers,- body: body !== void 0 ? JSON.stringify(body) : void 0- });- } catch (fetchErr) {- const cause = fetchErr?.cause;- const hostname3 = cause?.hostname ?? (() => {- try {- return new URL(url2).hostname;- } catch {- return url2;- }- })();- const code = cause?.code ?? (fetchErr instanceof TypeError ? "FETCH_FAILED" : "UNKNOWN");- throw new FlowApiError(0, "NetworkError", `Network request failed: ${code} (hostname: ${hostname3}). This often means the environment ID produced an invalid PPAPI URL. Verify the environment ID is a valid GUID.`, url2);- }+ const response = await fetchWithNetworkError(url2, {+ method,+ headers,+ body: body !== void 0 ? JSON.stringify(body) : void 0+ });if (!response.ok) {const responseBody = await response.text();throw new FlowApiError(response.status, response.statusText, responseBody, url2);@@ -54069,7 +54294,7 @@ var FlowClient = class _FlowClient {headers["Content-Type"] = "application/json";}logger.debug(`${method} ${url2}`);- const response = await fetch(url2, {+ const response = await fetchWithNetworkError(url2, {method,headers,body: body !== void 0 ? JSON.stringify(body) : void 0@@ -54221,6 +54446,26 @@ function searchExpressionHelp(opts = {}) {// packages/core/dist/auth/az-cli-auth.jsimport { spawnSync } from "node:child_process";+// packages/core/dist/utils/az-output.js+function decodeAzOutput(raw) {+ if (raw == null)+ return "";+ const text = Buffer.isBuffer(raw) ? raw.toString("utf-8") : String(raw);+ return text.charCodeAt(0) === 65279 ? text.slice(1) : text;+}+function parseAzJson(raw) {+ const text = decodeAzOutput(raw).trim();+ try {+ return JSON.parse(text);+ } catch (err) {+ const start = text.search(/[[{]/);+ if (start > 0) {+ return JSON.parse(text.slice(start));+ }+ throw err;+ }+}+// packages/core/dist/auth/disk-token-cache.jsinit_clear_cache_files();import * as fs2 from "node:fs";@@ -54277,7 +54522,8 @@ function parseJwtClaims(token) {const claims = JSON.parse(payload);return {tenantId: typeof claims.tid === "string" ? claims.tid : void 0,- accountId: typeof claims.oid === "string" && claims.oid || typeof claims.upn === "string" && claims.upn || typeof claims.sub === "string" && claims.sub || void 0+ accountId: typeof claims.oid === "string" && claims.oid || typeof claims.upn === "string" && claims.upn || typeof claims.sub === "string" && claims.sub || void 0,+ username: typeof claims.preferred_username === "string" && claims.preferred_username || typeof claims.upn === "string" && claims.upn || typeof claims.email === "string" && claims.email || typeof claims.unique_name === "string" && claims.unique_name || void 0};} catch {return {};@@ -54473,7 +54719,12 @@ var AzCliTokenProvider = class {}}const isWindows = process.platform === "win32";- const result = spawnSync("az", ["account", "get-access-token", "--resource", res, "--output", "json"], { encoding: "utf-8", shell: isWindows, windowsHide: true });+ const spawned = spawnSync("az", ["account", "get-access-token", "--resource", res, "--output", "json"], { shell: isWindows, windowsHide: true });+ const result = {+ ...spawned,+ stdout: decodeAzOutput(spawned.stdout),+ stderr: decodeAzOutput(spawned.stderr)+ };if (result.error && result.error.code === "ENOENT") {throw new AzCliAuthError("not-installed", "Azure CLI is not installed. Install it from https://aka.ms/installazurecli then run: az login");}@@ -54496,7 +54747,7 @@ ${stdout}`.trim();}let parsed;try {- parsed = JSON.parse(result.stdout);+ parsed = parseAzJson(result.stdout);} catch (err) {throw new AzCliAuthError("token-failed", "Azure CLI returned non-JSON output for get-access-token. Try: az login\nDetail: " + (err instanceof Error ? err.message : String(err)));}@@ -54545,9 +54796,10 @@ function getAzTenantId() {if (cachedTenantId !== null)return cachedTenantId ?? void 0;const isWindows = process.platform === "win32";- const result = spawnSync("az", ["account", "show", "--query", "tenantId", "-o", "tsv"], { encoding: "utf-8", shell: isWindows, windowsHide: true });- if (result.status === 0 && result.stdout) {- cachedTenantId = result.stdout.trim() || void 0;+ const result = spawnSync("az", ["account", "show", "--query", "tenantId", "-o", "tsv"], { shell: isWindows, windowsHide: true });+ const stdout = decodeAzOutput(result.stdout);+ if (result.status === 0 && stdout) {+ cachedTenantId = stdout.trim() || void 0;} else {cachedTenantId = void 0;}@@ -54690,7 +54942,8 @@ var CLOUD_ENDPOINTS = {flowResource: "https://service.flow.microsoft.com",bapBaseUrl: "https://api.bap.microsoft.com",powerPlatformApiUrl: "https://api.powerplatform.com",- ppapiSuffix: "environment.api.powerplatform.com"+ ppapiSuffix: "environment.api.powerplatform.com",+ ppapiShardLength: 2},gcc: {authorityHost: "https://login.microsoftonline.com",@@ -54698,7 +54951,8 @@ var CLOUD_ENDPOINTS = {flowResource: "https://gov.service.flow.microsoft.us",bapBaseUrl: "https://gov.api.bap.microsoft.us",powerPlatformApiUrl: "https://api.gov.powerplatform.microsoft.us",- ppapiSuffix: "environment.api.gov.powerplatform.microsoft.us"+ ppapiSuffix: "environment.api.gov.powerplatform.microsoft.us",+ ppapiShardLength: 1},gcchigh: {authorityHost: "https://login.microsoftonline.us",@@ -54709,7 +54963,8 @@ var CLOUD_ENDPOINTS = {// order here is the opposite of the flow/bap hosts above, and matches// ppapiSuffix below, which already had it right.powerPlatformApiUrl: "https://api.high.powerplatform.microsoft.us",- ppapiSuffix: "environment.api.high.powerplatform.microsoft.us"+ ppapiSuffix: "environment.api.high.powerplatform.microsoft.us",+ ppapiShardLength: 1},// DoD does not use the powerplatform.microsoft.us domain at all - it is// served from appsplatform.us. The previously shipped `dod.*.microsoft.us`@@ -54726,15 +54981,17 @@ var CLOUD_ENDPOINTS = {flowResource: "",bapBaseUrl: "https://api.bap.appsplatform.us",powerPlatformApiUrl: "https://api.appsplatform.us",- ppapiSuffix: "environment.api.appsplatform.us"+ ppapiSuffix: "environment.api.appsplatform.us",+ ppapiShardLength: 1}};function detectAzureCloud() {try {const isWindows = process.platform === "win32";- const result = spawnSync2("az", ["cloud", "show", "--query", "name", "-o", "tsv"], { encoding: "utf-8", shell: isWindows, windowsHide: true, timeout: 1e4 });- if (result.status === 0 && result.stdout) {- const cloudName = result.stdout.trim();+ const result = spawnSync2("az", ["cloud", "show", "--query", "name", "-o", "tsv"], { shell: isWindows, windowsHide: true, timeout: 1e4 });+ const stdout = decodeAzOutput(result.stdout);+ if (result.status === 0 && stdout) {+ const cloudName = stdout.trim();switch (cloudName) {case "AzureUSGovernment":return "gcchigh";@@ -54757,13 +55014,15 @@ function parseCloudEnvVar(value) {case "azurecloud":return "commercial";case "gcc":+ case "usgov":+ case "usgovmoderate":return "gcc";case "gcchigh":case "azureusgovernment":case "usgovhigh":return "gcchigh";case "dod":- case "usgov":+ case "usgovdod":return "dod";default:return void 0;@@ -54829,47 +55088,116 @@ function loadConfig() {// packages/core/dist/telemetry/index.jsimport { spawn } from "node:child_process";+import { existsSync as existsSync4 } from "node:fs";import { fileURLToPath } from "node:url";// packages/core/dist/telemetry/config.js-import os3 from "node:os";+import os4 from "node:os";+import { isIP } from "node:net";import path4 from "node:path";-var TELEMETRY_PLUGIN_NAME = "flow-agent";-var TELEMETRY_PLUGIN_VERSION = "2.0.0";-var TELEMETRY_SCHEMA_VERSION = "1.0";-var DEFAULT_COLLECTOR_URL = "https://mobile.events.data.microsoft.com/OneCollector/1.0/";-function isOptedOut() {- const off = (v) => v === "0" || v === "false" || v === "off";- return off(process.env.FLOWAGENT_TELEMETRY) || off(process.env.POWER_PLATFORM_SKILLS_TELEMETRY);-}-function resolveLocalLogPath() {- const override = process.env.FLOWAGENT_TELEMETRY_LOG;- if (override)- return override;- return path4.join(os3.homedir(), ".flowagent", "telemetry.jsonl");-}-var cached2;-function getTelemetryConfig() {- if (cached2)- return cached2;- const localLogPath = resolveLocalLogPath();- const instrumentationKey = process.env.FLOWAGENT_TELEMETRY_IKEY ?? "";- const collectorUrl = process.env.FLOWAGENT_TELEMETRY_COLLECTOR ?? DEFAULT_COLLECTOR_URL;- let mode;- if (isOptedOut()) {- mode = "off";- } else if (instrumentationKey) {- mode = "collector";- } else {- mode = "local";+import fs4 from "node:fs";+import { spawnSync as spawnSync3 } from "node:child_process";++// packages/core/dist/telemetry/geo-routing.js+var COLLECTOR_QUERY = "?cors=true&content-type=application/x-json-stream";+var GLOBAL_COLLECTOR = "https://mobile.events.data.microsoft.com/OneCollector/1.0/";+var EUROPE_COLLECTOR = "https://eu-mobile.events.data.microsoft.com/OneCollector/1.0/";+var US_COLLECTOR = "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/";+var ROUTES = {+ asia: {+ instrumentationKey: "e37a42e246af412ca5eb93c607097c53-3b84e4a6-27b9-4b17-bef6-85cda475a399-6887",+ collectorUrl: GLOBAL_COLLECTOR+ },+ australia: {+ instrumentationKey: "b1d3ed9c7a67493280ce8721e9bcbff1-9af96f5f-39c3-433c-9436-896511ddb442-6867",+ collectorUrl: GLOBAL_COLLECTOR+ },+ brazil: {+ instrumentationKey: "643794e0d45645b585d80c6ee6951317-f0c0dca4-c013-4db6-a42f-799603d30de4-7103",+ collectorUrl: GLOBAL_COLLECTOR+ },+ canada: {+ instrumentationKey: "f48d500c96514c9da86e86996ed3d317-c3e7047d-0170-4180-baee-31afe75712e5-6589",+ collectorUrl: GLOBAL_COLLECTOR+ },+ europe: {+ instrumentationKey: "2bab69432aa84ef098c68cbc8756e40f-d2c36df3-d2d7-432a-af54-0136a07a0217-7486",+ collectorUrl: EUROPE_COLLECTOR+ },+ france: {+ instrumentationKey: "2b9e8bc097784073806c17da9990a170-e146f635-6fd1-453e-bc49-b21589592be2-6788",+ collectorUrl: EUROPE_COLLECTOR+ },+ germany: {+ instrumentationKey: "0657d51bbb8847a6847e04ffc94a3323-b13a8408-7a26-448d-9cb1-7253b0df93cd-7332",+ collectorUrl: EUROPE_COLLECTOR+ },+ india: {+ instrumentationKey: "de750e33a5e74ffeaa58e575d89be6e6-84ddfe9f-1440-4a49-9f21-41f869fea3c3-7039",+ collectorUrl: GLOBAL_COLLECTOR+ },+ italy: {+ instrumentationKey: "5052dd8e385443d2a5cda4baf71f9df7-9ac5b03c-671e-4ddf-96a7-435bc7d20cd8-7130",+ collectorUrl: EUROPE_COLLECTOR+ },+ japan: {+ instrumentationKey: "09a5e0193d6d4274ba647b886df91945-2e7a3df0-28d3-4522-a616-b12bd9b767f6-7472",+ collectorUrl: GLOBAL_COLLECTOR+ },+ korea: {+ instrumentationKey: "b91951173a5c4a1ea3df7af3063fdbd8-741e4815-e406-4428-bfe6-32dbccfc82c6-7228",+ collectorUrl: GLOBAL_COLLECTOR+ },+ norway: {+ instrumentationKey: "ccf646992e424c9f9de77d8babfac70d-ab60dc0e-09b3-47a4-be19-6b324eb32f5c-7511",+ collectorUrl: EUROPE_COLLECTOR+ },+ poland: {+ instrumentationKey: "14e8c485ec2a44889ff666bd49f284fc-24d48997-b785-4030-81cc-f4bb52548e02-7989",+ collectorUrl: EUROPE_COLLECTOR+ },+ singapore: {+ instrumentationKey: "0326c6530e2e499db1a231b5dccdb2d7-1a4ae717-55f1-449f-ab72-cc15038d7c44-6795",+ collectorUrl: GLOBAL_COLLECTOR+ },+ southafrica: {+ instrumentationKey: "466e31d7e6544dc1b18a5f1c44090efb-f9d5d317-4d14-49ba-a6ee-db15fa52999e-7014",+ collectorUrl: GLOBAL_COLLECTOR+ },+ switzerland: {+ instrumentationKey: "0d7c1e826a7240b586c74d7c7a9bb286-84af3eb3-c900-4bd0-b15a-b9cdbfcf720a-7520",+ collectorUrl: EUROPE_COLLECTOR+ },+ unitedarabemirates: {+ instrumentationKey: "b0512932e0a44c6381e3a132d16d21c0-28605d64-e67f-44f0-aef5-a7b0f6db80e6-7517",+ collectorUrl: GLOBAL_COLLECTOR+ },+ unitedkingdom: {+ instrumentationKey: "982c3fa31fae40cf92fe43548bf19e11-d52e161b-3d0e-4b37-a3ef-81f8352906f1-6890",+ collectorUrl: EUROPE_COLLECTOR+ },+ unitedstates: {+ instrumentationKey: "2e7728f9f7ea42269fee5fbc9ea8a4f7-c026ab0c-92d3-4115-be4f-9d778dbe883f-7400",+ collectorUrl: US_COLLECTOR}- cached2 = { mode, instrumentationKey, collectorUrl, localLogPath };- return cached2;+};+var ALIASES = {+ southamerica: "brazil",+ sweden: "europe",+ unitedstatesfirstrelease: "unitedstates"+};+function resolveTelemetryRoute(location) {+ if (typeof location !== "string" || !location.trim())+ return void 0;+ const normalized = location.trim().toLowerCase();+ const canonical = ALIASES[normalized] ?? normalized;+ const route = ROUTES[canonical];+ return route ? { instrumentationKey: route.instrumentationKey, collectorUrl: `${route.collectorUrl}${COLLECTOR_QUERY}` } : void 0;}// packages/core/dist/telemetry/session.jsimport { randomUUID as randomUUID4 } from "node:crypto";-import os4 from "node:os";+import os3 from "node:os";var SESSION_ID = randomUUID4();function getSessionId() {return SESSION_ID;@@ -54878,8 +55206,8 @@ var hostInfo;function getHostInfo() {if (!hostInfo) {hostInfo = {- osName: os4.platform(),- osVersion: os4.release(),+ osName: os3.platform(),+ osVersion: os3.release(),nodeVersion: process.version};}@@ -54962,7 +55290,9 @@ var FIELD_TYPES = {actionCount: "number",// Flow creationtemplateId: "string",- envId: "string"+ envId: "string",+ envLocation: "string",+ envRegion: "string"};function pick2(input) {const out = {};@@ -55001,13 +55331,173 @@ function buildEvent(eventName, fields) {return pick2({ ...commonFields(), eventName, name: eventName, ...fields });}+// packages/core/dist/telemetry/config.js+var TELEMETRY_PLUGIN_NAME = "flow-agent";+var TELEMETRY_PLUGIN_VERSION = FLOWAGENT_VERSION;+var TELEMETRY_SCHEMA_VERSION = "1.0";+var APPROVED_CLOUDS = /* @__PURE__ */ new Set(["commercial"]);+var OPT_OUT_PLUGIN_NAME = "power-automate";+function resolveTelemetryCloud() {+ const explicit = process.env.PA_CLOUD?.trim().toLowerCase();+ if (explicit) {+ return parseCloudName(explicit);+ }+ const fromFile = readFileConfigCloud();+ if (fromFile)+ return parseCloudName(fromFile);+ try {+ const result = spawnSync3("az", ["cloud", "show", "--query", "name", "-o", "tsv"], {+ shell: process.platform === "win32",+ windowsHide: true,+ timeout: 1e4+ });+ const stdout = decodeAzOutput(result.stdout);+ if (result.status !== 0 || !stdout)+ return "unknown";+ const name3 = stdout.trim();+ if (name3 === "AzureCloud")+ return "commercial";+ if (name3 === "AzureUSGovernment")+ return "gcchigh";+ return "unknown";+ } catch {+ return "unknown";+ }+}+function parseCloudName(value) {+ const v = value.trim().toLowerCase();+ if (["commercial", "public", "azurecloud"].includes(v))+ return "commercial";+ if (["gcc", "usgov", "gcchigh", "gcch", "dod"].includes(v))+ return v;+ return "unknown";+}+function readFileConfigCloud() {+ try {+ const p = path4.join(os4.homedir(), ".power-automate-cli", "config.json");+ const parsed = JSON.parse(fs4.readFileSync(p, "utf-8"));+ return typeof parsed.cloud === "string" && parsed.cloud.trim() ? parsed.cloud : void 0;+ } catch {+ return void 0;+ }+}+function isOptedOut() {+ const off = (v) => v === "0" || v === "false" || v === "off";+ return off(process.env.FLOWAGENT_TELEMETRY) || off(process.env.POWER_PLATFORM_SKILLS_TELEMETRY);+}+function isRecord(value) {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}+function isTransmissionOptedOut() {+ const envValue = process.env.POWER_PLATFORM_SKILLS_TELEMETRY_POWER_AUTOMATE_OPTOUT?.trim().toLowerCase();+ if (envValue === "1" || envValue === "true")+ return true;+ const configDir = process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR || path4.join(os4.homedir(), ".power-platform-skills");+ try {+ const parsed = JSON.parse(fs4.readFileSync(path4.join(configDir, "config.json"), "utf8"));+ if (!isRecord(parsed) || !isRecord(parsed.telemetry))+ return false;+ return parsed.telemetry[OPT_OUT_PLUGIN_NAME] === "off";+ } catch {+ return false;+ }+}+function resolveLocalLogPath() {+ const override = process.env.FLOWAGENT_TELEMETRY_LOG;+ if (override)+ return override;+ return path4.join(os4.homedir(), ".flowagent", "telemetry.jsonl");+}+function resolveTestCollectorUrl(defaultUrl) {+ const override = process.env.FLOWAGENT_TELEMETRY_TEST_COLLECTOR;+ if (!override)+ return defaultUrl;+ if (process.env.NODE_ENV !== "test")+ return void 0;+ try {+ const url2 = new URL(override);+ const hostname3 = url2.hostname.replace(/^\[|\]$/g, "");+ const loopback = hostname3 === "localhost" || isIP(hostname3) === 4 && hostname3.startsWith("127.") || isIP(hostname3) === 6 && hostname3 === "::1";+ if (url2.protocol !== "http:" || !loopback || url2.username || url2.password || url2.hash || !url2.pathname.startsWith("/OneCollector/1.0/")) {+ return void 0;+ }+ return url2.toString();+ } catch {+ return void 0;+ }+}+function getTelemetryConfig(context = {}) {+ const localLogPath = resolveLocalLogPath();+ const base = {+ mode: "local",+ instrumentationKey: "",+ collectorUrl: "",+ localLogPath,+ cloud: "not-evaluated",+ environmentLocation: context.envLocation ?? void 0,+ environmentRegion: context.envRegion ?? void 0,+ environmentId: context.envId ?? void 0,+ appEnvironment: "prod"+ };+ if (isOptedOut())+ return { ...base, mode: "off" };+ if (isTransmissionOptedOut())+ return base;+ const hasEnvironment = typeof context.envId === "string" && context.envId.length > 0;+ if (!hasEnvironment || !context.envLocation?.trim())+ return base;+ const route = resolveTelemetryRoute(context.envLocation);+ if (!route)+ return base;+ const collectorUrl = resolveTestCollectorUrl(route.collectorUrl);+ if (!collectorUrl)+ return base;+ const cloud = resolveTelemetryCloud();+ if (!APPROVED_CLOUDS.has(cloud))+ return { ...base, cloud };+ return {+ ...base,+ mode: "collector",+ instrumentationKey: route.instrumentationKey,+ collectorUrl,+ cloud+ };+}+// packages/core/dist/telemetry/local-log.js-import fs4 from "node:fs";+import fs5 from "node:fs";import path5 from "node:path";function appendLocal(logPath, record2) {const dir = path5.dirname(logPath);- fs4.mkdirSync(dir, { recursive: true });- fs4.appendFileSync(logPath, JSON.stringify(record2) + "\n", "utf8");+ fs5.mkdirSync(dir, { recursive: true });+ fs5.appendFileSync(logPath, JSON.stringify(record2) + "\n", "utf8");+}++// packages/core/dist/telemetry/scrubber.js+function errorClass(err) {+ if (err && typeof err === "object") {+ const ctorName = err.constructor?.name;+ if (ctorName && ctorName !== "Object")+ return ctorName;+ const name3 = err.name;+ if (typeof name3 === "string" && name3)+ return name3;+ }+ return "Error";+}+function errorCode(err) {+ if (!err || typeof err !== "object")+ return void 0;+ const e = err;+ if (typeof e.code === "string" && e.code)+ return e.code;+ if (typeof e.code === "number")+ return String(e.code);+ if (typeof e.statusCode === "number")+ return String(e.statusCode);+ if (typeof e.status === "number")+ return String(e.status);+ return void 0;}// packages/core/dist/templates.js@@ -56459,13 +56949,30 @@ var TEMPLATES = {// packages/core/dist/telemetry/index.jsvar dispatcherPath;function getDispatcherPath() {- if (!dispatcherPath) {- dispatcherPath = fileURLToPath(new URL("./emit-dispatcher.js", import.meta.url));+ if (dispatcherPath === void 0) {+ dispatcherPath = null;+ for (const name3 of ["emit-dispatcher.js", "emit-dispatcher.mjs"]) {+ try {+ const candidate = fileURLToPath(new URL(`./${name3}`, import.meta.url));+ if (existsSync4(candidate)) {+ dispatcherPath = candidate;+ break;+ }+ } catch {+ }+ }}- return dispatcherPath;+ return dispatcherPath ?? void 0;}-function sendToCollector(record2) {- const cfg = getTelemetryConfig();+function dispatcherExists() {+ return getDispatcherPath() !== void 0;+}+function sendToCollector(record2, cfg) {+ const dispatcher = getDispatcherPath();+ if (!dispatcher)+ return;+ if (cfg.mode !== "collector")+ return;const payload = Buffer.from(JSON.stringify(record2), "utf8").toString("base64");const childEnv = {PATH: process.env.PATH,@@ -56474,9 +56981,10 @@ function sendToCollector(record2) {USERPROFILE: process.env.USERPROFILE,FLOWAGENT_TELEMETRY_PAYLOAD: payload,FLOWAGENT_TELEMETRY_IKEY: cfg.instrumentationKey,- FLOWAGENT_TELEMETRY_COLLECTOR: cfg.collectorUrl+ FLOWAGENT_TELEMETRY_COLLECTOR: cfg.collectorUrl,+ FLOWAGENT_TELEMETRY_APP_ENVIRONMENT: cfg.appEnvironment};- const child = spawn(process.execPath, [getDispatcherPath()], {+ const child = spawn(process.execPath, [dispatcher], {detached: true,stdio: "ignore",env: childEnv@@ -56485,14 +56993,22 @@ function sendToCollector(record2) {}function emit(eventName, fields) {try {- const cfg = getTelemetryConfig();+ const record2 = buildEvent(eventName, fields);+ const cfg = getTelemetryConfig({+ envId: typeof record2.envId === "string" ? record2.envId : void 0,+ envLocation: typeof record2.envLocation === "string" ? record2.envLocation : void 0,+ envRegion: typeof record2.envRegion === "string" ? record2.envRegion : void 0+ });if (cfg.mode === "off")return;- const record2 = buildEvent(eventName, fields);- if (cfg.mode === "collector") {- sendToCollector(record2);- } else {+ try {appendLocal(cfg.localLogPath, record2);+ } catch {+ }+ if (cfg.mode === "collector") {+ if (dispatcherExists()) {+ sendToCollector(record2, cfg);+ }}} catch {}@@ -56519,9 +57035,12 @@ function createTelemetryObserver(opts = {}) {}return void 0;}- function envOf(args) {- const e = args?.env;- return typeof e === "string" ? e : void 0;+ function envFields(info) {+ return {+ envId: info.environmentId,+ envLocation: info.environmentLocation ?? void 0,+ envRegion: info.environmentRegion ?? void 0+ };}function responseBytes(result) {try {@@ -56538,7 +57057,7 @@ function createTelemetryObserver(opts = {}) {toolName: info.tool,correlationId: info.correlationId,surface: "mcp",- envId: envOf(info.args)+ ...envFields(info)});},onToolEnd(info) {@@ -56549,7 +57068,8 @@ function createTelemetryObserver(opts = {}) {outcome: info.isError ? "failure" : "success",durationMs: info.durationMs,surface: "mcp",- envId: envOf(info.args),+ ...envFields(info),+ errorClass: info.errorClass,errorCode: info.errorCode,responseBytes: responseBytes(info.result),mcpTransport: transport2,@@ -56563,7 +57083,7 @@ function createTelemetryObserver(opts = {}) {templateId,surface: "mcp",correlationId: info.correlationId,- envId: envOf(info.args),+ ...envFields(info),actionCount,mcpClientName});@@ -56575,6 +57095,7 @@ function createTelemetryObserver(opts = {}) {// packages/core/dist/current-env-store.jsvar CurrentEnvStore = class {state;+ environments = /* @__PURE__ */ new Map();subscribers = /* @__PURE__ */ new Set();constructor(initialEnvId = process.env.PA_DEFAULT_ENVIRONMENT) {this.state = initialEnvId ? { envId: initialEnvId, displayName: null, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), source: "env-var" } : { envId: null, displayName: null, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), source: "none" };@@ -56584,9 +57105,18 @@ var CurrentEnvStore = class {}set(envId, opts) {const prevId = this.state.envId;+ const cached2 = this.environments.get(envId);+ const metadata = {+ displayName: opts.displayName ?? cached2?.displayName,+ location: opts.location !== void 0 ? opts.location : cached2?.location,+ region: opts.region !== void 0 ? opts.region : cached2?.region+ };+ this.environments.set(envId, metadata);this.state = {envId,- displayName: opts.displayName ?? this.state.displayName ?? null,+ displayName: metadata.displayName ?? this.state.displayName ?? null,+ environmentLocation: metadata.location ?? null,+ environmentRegion: metadata.region ?? null,updatedAt: (/* @__PURE__ */ new Date()).toISOString(),source: opts.source};@@ -56600,6 +57130,20 @@ var CurrentEnvStore = class {}return this.state;}+ rememberEnvironment(envId, opts) {+ const previous = this.environments.get(envId);+ this.environments.set(envId, {+ displayName: opts.displayName ?? previous?.displayName,+ location: opts.location !== void 0 ? opts.location : previous?.location,+ region: opts.region !== void 0 ? opts.region : previous?.region+ });+ if (this.state.envId === envId) {+ this.set(envId, { ...this.environments.get(envId), source: this.state.source });+ }+ }+ getEnvironment(envId) {+ return this.environments.get(envId);+ }subscribe(cb) {this.subscribers.add(cb);return () => {@@ -56647,8 +57191,8 @@ var legacyCurrentFlowStore = new CurrentFlowStore();init_trigger_emulators();// packages/core/dist/diagnostics.js-import { spawnSync as spawnSync3 } from "node:child_process";-import fs5 from "node:fs";+import { spawnSync as spawnSync4 } from "node:child_process";+import fs6 from "node:fs";import path6 from "node:path";init_msal_disk_cache();init_msal_auth();@@ -56660,6 +57204,26 @@ function connectivityIdentityMismatch(identity, az) {return false;return Boolean(identity.tenantId && az.tenantId && normalizeIdentity(identity.tenantId) !== normalizeIdentity(az.tenantId) || identity.username && az.user && normalizeIdentity(identity.username) !== normalizeIdentity(az.user));}+function compareTokenIdentity(az, token) {+ if (!az || !token)+ return { mismatch: false, comparedUser: false };+ if (az.tenantId && token.tenantId && normalizeIdentity(az.tenantId) !== normalizeIdentity(token.tenantId)) {+ return {+ mismatch: true,+ comparedUser: false,+ detail: `az is signed in to tenant ${az.tenantId} but the token FlowAgent would send belongs to tenant ${token.tenantId}.`+ };+ }+ if (az.user && token.username) {+ const mismatch = normalizeIdentity(az.user) !== normalizeIdentity(token.username);+ return {+ mismatch,+ comparedUser: true,+ detail: mismatch ? `az is signed in as ${az.user} but the token FlowAgent would send belongs to ${token.username}.` : void 0+ };+ }+ return { mismatch: false, comparedUser: false };+}function effectiveConnectivityIdentity(az, opts = {}) {const state = opts.auth?.getConnectivityAuthState?.();if (state?.account)@@ -56667,8 +57231,8 @@ function effectiveConnectivityIdentity(az, opts = {}) {if (["1", "true"].includes(process.env.FLOWAGENT_DISABLE_MSAL_CACHE ?? ""))return null;const identity = state?.cacheIdentity ?? az?.tenantId ?? process.env.PA_TENANT_ID ?? "common";- const cached3 = readCachedMsalIdentities({ cacheDir: opts.cacheDir, identity });- const selected = selectCachedMsalAccount(cached3, identity);+ const cached2 = readCachedMsalIdentities({ cacheDir: opts.cacheDir, identity });+ const selected = selectCachedMsalAccount(cached2, identity);return selected?.username || selected?.tenantId ? selected : null;}function describeConnectivityIdentity(identity) {@@ -56685,7 +57249,7 @@ async function readTokenIdentity(auth2, resource) {async function whoAmI(auth2, config3, opts = {}) {const azIdentity = readActiveAzIdentity();const tokenIdentity = await readTokenIdentity(auth2, config3.cloudEndpoints.flowResource);- const identityMismatch = Boolean(azIdentity?.tenantId && tokenIdentity?.tenantId && azIdentity.tenantId !== tokenIdentity.tenantId);+ const identityMismatch = compareTokenIdentity(azIdentity, tokenIdentity).mismatch;const connectivityIdentity = readCachedMsalIdentities();const effectiveIdentity = effectiveConnectivityIdentity(azIdentity, { auth: auth2 });return {@@ -56757,7 +57321,7 @@ function describeNextConnectivitySignIn(opts) {function azVersionInstalled() {try {const isWindows = process.platform === "win32";- const r = spawnSync3("az", ["version", "--output", "none"], {+ const r = spawnSync4("az", ["version", "--output", "none"], {encoding: "utf-8",shell: isWindows,windowsHide: true,@@ -56778,7 +57342,7 @@ async function doctor(auth2, config3, opts = {}) {fix: "Install it from https://aka.ms/installazurecli, then run: az login"});const configDir = azureConfigDir();- const profileExists = fs5.existsSync(path6.join(configDir, "azureProfile.json"));+ const profileExists = fs6.existsSync(path6.join(configDir, "azureProfile.json"));const azIdentity = readActiveAzIdentity();if (!profileExists) {checks.push({@@ -56829,11 +57393,12 @@ async function doctor(auth2, config3, opts = {}) {});}if (azIdentity?.tenantId && tokenIdentity?.tenantId) {- const match = azIdentity.tenantId === tokenIdentity.tenantId;+ const cmp = compareTokenIdentity(azIdentity, tokenIdentity);+ const match = !cmp.mismatch;checks.push({name: "identity-match",status: match ? "pass" : "fail",- detail: match ? "The cached token belongs to the account az is signed in as." : `Identity mismatch: az is signed in to tenant ${azIdentity.tenantId} but the token FlowAgent would send belongs to tenant ${tokenIdentity.tenantId}. This is what surfaces as EnvironmentAccessDenied / ServiceToServiceEnvironmentNotFound.`,+ detail: match ? cmp.comparedUser ? "The cached token belongs to the account az is signed in as." : "The cached token belongs to the tenant az is signed in to. The user could not be compared \u2014 the token carries no name claim (expected for a service principal or managed identity)." : `Identity mismatch: ${cmp.detail} This is what surfaces as EnvironmentAccessDenied / ServiceToServiceEnvironmentNotFound.`,fix: match ? void 0 : "Call the reconnect tool (clears the token cache and re-acquires)."});}@@ -56897,15 +57462,15 @@ async function doctor(auth2, config3, opts = {}) {const status = checks.some((c) => c.status === "fail") ? "fail" : checks.some((c) => c.status === "warn") ? "warn" : "pass";const failed = checks.filter((c) => c.status !== "pass");const summary = status === "pass" ? "All checks passed." : `${failed.length} check${failed.length === 1 ? "" : "s"} need attention: ${failed.map((c) => c.name).join(", ")}.`;- return { status, checks, summary };+ return { status, version: FLOWAGENT_VERSION, buildId: await buildId(), checks, summary };}function listAccounts(opts) {const azIdentity = readActiveAzIdentity();const preferredAccount = readPreferredAccount(opts);- const cached3 = readCachedMsalIdentities(opts);+ const cached2 = readCachedMsalIdentities(opts);const effectiveIdentity = effectiveConnectivityIdentity(azIdentity, opts);const nextSignIn = resolveInteractiveAccountOptions(process.env, { storedHint: preferredAccount });- const accounts = cached3.map((i) => ({+ const accounts = cached2.map((i) => ({username: i.username,tenantId: i.tenantId,cacheFile: i.cacheFile,@@ -66711,6 +67276,14 @@ function safeResult(data, opts) {}return { content: [{ type: "text", text }] };}+function safeErrorName(err) {+ if (!(err instanceof Error))+ return void 0;+ if (err.name && err.name !== "Error")+ return err.name;+ const constructorName = err.constructor?.name;+ return constructorName && constructorName !== "Error" ? constructorName : void 0;+}function pageResolvedParams(result, options, context) {const { parameter, query, cursor } = options;if (parameter && !result.parameters.some((p) => p.name === parameter)) {@@ -66785,11 +67358,14 @@ function pageResolvedParams(result, options, context) {}function safeError(err, enhance) {let payload;+ const errorName = safeErrorName(err);if (err && typeof err === "object" && "code" in err && typeof err.code === "string") {const e = err;payload = {code: e.code,message: e.message ?? String(err),+ ...errorName ? { errorName } : {},+ ...typeof e.statusCode === "number" ? { statusCode: e.statusCode } : {},remediation: e.remediation,operation: e.operation,flowId: e.flowId,@@ -66810,7 +67386,8 @@ function safeError(err, enhance) {payload = {code: "tool-error",message,- ...err instanceof Error && err.name && err.name !== "Error" ? { errorName: err.name } : {}+ ...errorName ? { errorName } : {},+ ...err && typeof err === "object" && typeof err.statusCode === "number" ? { statusCode: err.statusCode } : {}};}let text;@@ -67030,6 +67607,21 @@ async function createMcpServer(authProvider, deps = {}) {legacyContext.lastActivityAt = /* @__PURE__ */ new Date();return legacyContext;}+ function telemetryEnvironment(tool, args, mcpCtx) {+ if (tool === "set_current_env")+ return {};+ const current = mcpCtx.currentEnv.get();+ const explicitEnv = typeof args.env === "string" ? args.env : void 0;+ const environmentId = explicitEnv ?? current.envId ?? config3.defaultEnvironmentId ?? void 0;+ if (!environmentId)+ return {};+ const metadata = mcpCtx.currentEnv.getEnvironment(environmentId);+ return {+ environmentId,+ environmentLocation: metadata ? metadata.location ?? null : current.envId === environmentId ? current.environmentLocation ?? null : null,+ environmentRegion: metadata ? metadata.region ?? null : current.envId === environmentId ? current.environmentRegion ?? null : null+ };+ }function getActiveToolContext() {const mcpCtx = getActiveMcpContext();let toolCtx = toolContexts.get(mcpCtx);@@ -67048,7 +67640,7 @@ async function createMcpServer(authProvider, deps = {}) {};const server2 = new McpServer2({name: deps.serverInfo?.name ?? "flowagent-mcp",- version: deps.serverInfo?.version ?? "2.0.0"+ version: deps.serverInfo?.version ?? FLOWAGENT_VERSION});if (deps.getContext || deps.onToolStart || deps.onToolEnd) {const origTool = server2.tool.bind(server2);@@ -67064,21 +67656,28 @@ async function createMcpServer(authProvider, deps = {}) {const correlationId = Math.random().toString(36).slice(2, 10);const args = handlerArgs[0] ?? {};const t0 = Date.now();+ let eventEnvironment = {};try {- getActiveMcpContext(extra?.sessionId);- deps.onToolStart?.({ tool: toolName, args, correlationId });+ const mcpCtx = getActiveMcpContext(extra?.sessionId);+ eventEnvironment = telemetryEnvironment(toolName, args, mcpCtx);+ deps.onToolStart?.({ tool: toolName, args, correlationId, ...eventEnvironment });} catch {}try {const result = await handler(...handlerArgs);const isError = result?.isError === true;+ let errorClass2;let errorCode2;if (isError) {try {const text = result.content?.[0]?.text;if (typeof text === "string") {const parsed = JSON.parse(text);- errorCode2 = parsed?.code;+ const payload = parsed?.error && typeof parsed.error === "object" ? parsed.error : parsed;+ errorClass2 = typeof (payload?.errorClass ?? payload?.className ?? payload?.errorName ?? payload?.name) === "string" ? errorClass({ name: payload.errorClass ?? payload.className ?? payload.errorName ?? payload.name }) : void 0;+ const payloadCode = errorCode(payload);+ const payloadStatus = typeof payload?.statusCode === "number" ? errorCode({ statusCode: payload.statusCode }) : void 0;+ errorCode2 = payloadCode && payloadCode !== "tool-error" ? payloadCode : payloadStatus ?? errorCode(parsed);}} catch {}@@ -67090,8 +67689,10 @@ async function createMcpServer(authProvider, deps = {}) {correlationId,durationMs: Date.now() - t0,isError,+ errorClass: errorClass2,errorCode: errorCode2,- result+ result,+ ...eventEnvironment});} catch {}@@ -67104,7 +67705,9 @@ async function createMcpServer(authProvider, deps = {}) {correlationId,durationMs: Date.now() - t0,isError: true,- errorCode: err?.code+ errorClass: errorClass(err),+ errorCode: errorCode(err),+ ...eventEnvironment});} catch {}@@ -67162,6 +67765,17 @@ async function createMcpServer(authProvider, deps = {}) {server2.tool("list_environments", "List all Power Automate environments. Use query to filter by name.", { query: external_exports.string().optional().describe("Filter by display name (case-insensitive)") }, { readOnlyHint: true, title: "List Environments" }, async ({ query }) => {try {const envs = await ctx.getClient().listEnvironments();+ const envStore = getActiveMcpContext().currentEnv;+ for (const environment of envs) {+ const record2 = environment;+ const properties = record2.properties;+ const region = typeof record2.region === "string" ? record2.region : typeof properties?.region === "string" ? properties.region : null;+ envStore.rememberEnvironment(environment.name, {+ displayName: environment.properties?.displayName ?? null,+ location: typeof environment.location === "string" ? environment.location : null,+ region+ });+ }let s = summarizeList(envs, ["name", "properties.displayName", "properties.isDefault", "properties.environmentSku", "location"], { "properties.displayName": "displayName", "properties.isDefault": "isDefault", "properties.environmentSku": "environmentSku" });if (query) {const q = query.toLowerCase();@@ -67192,7 +67806,14 @@ async function createMcpServer(authProvider, deps = {}) {} catch {}}- return safeResult({ envId: cur.envId, displayName, updatedAt: cur.updatedAt, source: cur.source });+ return safeResult({+ envId: cur.envId,+ displayName,+ location: cur.environmentLocation,+ region: cur.environmentRegion,+ updatedAt: cur.updatedAt,+ source: cur.source+ });} catch (e) {return safeError(e);}@@ -67214,8 +67835,23 @@ async function createMcpServer(authProvider, deps = {}) {}if (!match)return safeError(new Error(`No environment matches "${env}". Call list_environments to see options.`));- const next = getActiveMcpContext().currentEnv.set(match.name, { displayName: match.properties?.displayName ?? null, source: "set_tool" });- return safeResult({ envId: next.envId, displayName: next.displayName, source: next.source, updatedAt: next.updatedAt });+ const record2 = match;+ const properties = record2.properties;+ const region = typeof record2.region === "string" ? record2.region : typeof properties?.region === "string" ? properties.region : null;+ const next = getActiveMcpContext().currentEnv.set(match.name, {+ displayName: match.properties?.displayName ?? null,+ location: typeof match.location === "string" ? match.location : null,+ region,+ source: "set_tool"+ });+ return safeResult({+ envId: next.envId,+ displayName: next.displayName,+ location: next.environmentLocation,+ region: next.environmentRegion,+ source: next.source,+ updatedAt: next.updatedAt+ });} catch (e) {return safeError(e);}@@ -67308,7 +67944,7 @@ async function createMcpServer(authProvider, deps = {}) {return safeError(e, enhanceFlowApiError);}});- server2.tool("update_flow", "Update an existing flow's definition or properties. **Refuses by default if the flow lives in a managed Dataverse solution** (returns ManagedSolutionReadOnly). Pass forceManaged: true only if you understand the change will be overwritten on the next solution import \u2014 see docs/recipes/upgrade-managed-flow.md for the right pattern. **Recommended two-phase update**: call preview_update first to obtain a previewToken bound to the exact change, then pass that token back here. update_flow will only apply if the proposal still matches what was previewed (prevents lost writes from concurrent edits). Auto-captures a backup snapshot before applying (last 10 retained per flow, accessible via list_backups). **Use this for**: any change to an existing flow. **Do NOT use for**: creating a new flow (use create_flow) or starting/stopping a flow (use publish_flow / disable_flow).", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), definition: jsonRecord.optional().describe("Updated definition JSON"), connectionRefs: jsonRecord.optional().describe("Connection references JSON"), name: external_exports.string().optional().describe("New name"), state: external_exports.enum(["Started", "Stopped"]).optional().describe("State"), forceManaged: external_exports.boolean().optional().describe("Override the managed-solution read-only guard. Default false."), autoResolveConnectionRefs: external_exports.boolean().optional().describe("Auto-resolve missing connection refs for new connectors in the definition. Default true. Set false to skip if auto-merge is causing errors."), previewToken: external_exports.string().optional().describe("Token issued by preview_update for this exact (env, flow, body) tuple. When supplied, the update only applies if the proposed change still matches what was previewed; mismatched tokens throw PreviewTokenMismatch.") }, { readOnlyHint: false, title: "Update Flow" }, async ({ env, flow, definition, connectionRefs, name: name3, state, forceManaged, autoResolveConnectionRefs, previewToken }) => {+ server2.tool("update_flow", "Update an existing flow's definition or properties. **Refuses by default if the flow lives in a managed Dataverse solution** (returns ManagedSolutionReadOnly). Pass forceManaged: true only if you understand the change will be overwritten on the next solution import \u2014 see docs/recipes/upgrade-managed-flow.md for the right pattern. **Recommended two-phase update**: call preview_update first to obtain a previewToken bound to the exact change, then pass that token back here. update_flow re-reads the flow's last-modified timestamp immediately before writing and rejects edits already present at that point. PPAPI provides no conditional-write primitive, so a concurrent write after the check can still be missed. Auto-captures a backup snapshot before applying (last 10 retained per flow, accessible via list_backups). **Use this for**: any change to an existing flow. **Do NOT use for**: creating a new flow (use create_flow) or starting/stopping a flow (use publish_flow / disable_flow).", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), definition: jsonRecord.optional().describe("Updated definition JSON"), connectionRefs: jsonRecord.optional().describe("Connection references JSON"), name: external_exports.string().optional().describe("New name"), state: external_exports.enum(["Started", "Stopped"]).optional().describe("State"), forceManaged: external_exports.boolean().optional().describe("Override the managed-solution read-only guard. Default false."), autoResolveConnectionRefs: external_exports.boolean().optional().describe("Auto-resolve missing connection refs for new connectors in the definition. Default true. Set false to skip if auto-merge is causing errors."), previewToken: external_exports.string().optional().describe("Token issued by preview_update for this exact (env, flow, body) tuple. Single-use. It detects edits present at the final version check (otherwise PreviewConcurrencyConflict), but the API has no atomic conditional write and may miss a write after that check.") }, { readOnlyHint: false, title: "Update Flow" }, async ({ env, flow, definition, connectionRefs, name: name3, state, forceManaged, autoResolveConnectionRefs, previewToken }) => {try {const envId = ctx.resolveEnv(env);const props = await buildUpdateProperties(ctx, envId, flow, {@@ -67323,7 +67959,7 @@ async function createMcpServer(authProvider, deps = {}) {return safeError(e, enhanceFlowApiError);}});- server2.tool("preview_update", "Read-only: compute a diff between the live flow and the proposed update body, and return a short-lived single-use token. Use the token with update_flow to apply the change only if the proposal still matches what you reviewed. No mutation is performed by this tool.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), definition: jsonRecord.optional().describe("Proposed updated definition JSON"), connectionRefs: jsonRecord.optional().describe("Proposed connection references JSON"), name: external_exports.string().optional().describe("Proposed new name"), state: external_exports.enum(["Started", "Stopped"]).optional().describe("Proposed state") }, { readOnlyHint: true, title: "Preview Update" }, async ({ env, flow, definition, connectionRefs, name: name3, state }) => {+ server2.tool("preview_update", "Read-only: compute a diff between the live flow and the proposed update body, and return a short-lived single-use token. Use the token with update_flow to detect edits present at the final version check; the API has no atomic conditional write, so a write after that check can still be missed. No mutation is performed by this tool.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), definition: jsonRecord.optional().describe("Proposed updated definition JSON"), connectionRefs: jsonRecord.optional().describe("Proposed connection references JSON"), name: external_exports.string().optional().describe("Proposed new name"), state: external_exports.enum(["Started", "Stopped"]).optional().describe("Proposed state") }, { readOnlyHint: true, title: "Preview Update" }, async ({ env, flow, definition, connectionRefs, name: name3, state }) => {try {const envId = ctx.resolveEnv(env);const props = await buildUpdateProperties(ctx, envId, flow, {@@ -67347,7 +67983,7 @@ async function createMcpServer(authProvider, deps = {}) {value: external_exports.unknown().optional().describe("New value (required for set/add/merge; merge requires an object)")})).describe("Ordered list of edit operations"),dryRun: external_exports.boolean().optional().describe("If true, return a diff + previewToken without writing."),- previewToken: external_exports.string().optional().describe("Token from a prior dryRun for these exact operations; applies only if the flow still matches."),+ previewToken: external_exports.string().optional().describe("Token from a prior dryRun for these exact operations. Single-use; edits present at the final version check are rejected, but the API has no atomic conditional write and may miss a write after that check."),forceManaged: external_exports.boolean().optional().describe("Override the managed-solution read-only guard. Default false."),autoResolveConnectionRefs: external_exports.boolean().optional().describe("Auto-resolve missing connection refs for new connectors in the definition. Default true.")}, { readOnlyHint: false, title: "Edit Flow (surgical)" }, async ({ env, flow, operations, dryRun, previewToken, forceManaged, autoResolveConnectionRefs }) => {@@ -67499,21 +68135,58 @@ async function createMcpServer(authProvider, deps = {}) {return safeError(e);}});- server2.tool("get_run_actions", "Get action-level execution details for a specific flow run", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), run: external_exports.string().describe("Run ID") }, { readOnlyHint: true, title: "Run Actions" }, async ({ env, flow, run }) => {+ server2.tool("get_run_actions", "Get action-level execution details for a specific flow run", {+ env: external_exports.string().optional().describe("Environment ID"),+ flow: external_exports.string().describe("Flow ID"),+ run: external_exports.string().describe("Run ID"),+ includeSizes: external_exports.boolean().optional().describe("Also return the recorded inputs/outputs sizes, so you can pick what to fetch with get_run_action_content")+ }, { readOnlyHint: true, title: "Run Actions" }, async ({ env, flow, run, includeSizes }) => {try {const actions = await ctx.getClient().getRunActionDetails(ctx.resolveEnv(env), flow, run);- return safeResult(summarizeList(actions, ["name", "properties.startTime", "properties.endTime", "properties.status", "properties.code", "properties.error.code", "properties.error.message"], { "properties.startTime": "startTime", "properties.endTime": "endTime", "properties.status": "status", "properties.code": "code", "properties.error.code": "errorCode", "properties.error.message": "errorMessage" }));+ const fields = ["name", "properties.startTime", "properties.endTime", "properties.status", "properties.code", "properties.error.code", "properties.error.message"];+ const labels = { "properties.startTime": "startTime", "properties.endTime": "endTime", "properties.status": "status", "properties.code": "code", "properties.error.code": "errorCode", "properties.error.message": "errorMessage" };+ if (includeSizes) {+ fields.push("properties.inputsLink.contentSize", "properties.outputsLink.contentSize");+ labels["properties.inputsLink.contentSize"] = "inputsBytes";+ labels["properties.outputsLink.contentSize"] = "outputsBytes";+ }+ return safeResult(summarizeList(actions, fields, labels));+ } catch (e) {+ if (isNotFoundError(e))+ return notFoundResult("Run", run, "The run may have expired or the flow was deleted.");+ return safeError(e);+ }+ });+ server2.tool("get_run_action_content", "Fetch what an action in a run actually received (inputs) or produced (outputs). get_run_actions reports only status and error \u2014 this returns the recorded payload, which is usually what tells you WHY an action failed. Capped at maxBytes (default 256000) so a large payload is reported rather than dumped.", {+ env: external_exports.string().optional().describe("Environment ID"),+ flow: external_exports.string().optional().describe("Flow ID (defaults to pinned current flow)"),+ run: external_exports.string().describe("Run ID"),+ action: external_exports.string().describe("Action name, as reported by get_run_actions"),+ which: external_exports.enum(["inputs", "outputs"]).describe("Which side of the action to fetch"),+ maxBytes: external_exports.number().int().optional().describe("Refuse to download content larger than this (default 256000)")+ }, { readOnlyHint: true, title: "Run Action Content" }, async ({ env, flow, run, action, which, maxBytes }) => {+ try {+ const flowId = ctx.resolveFlow(flow);+ return safeResult(await ctx.getClient().getRunActionContent(ctx.resolveEnv(env), flowId, run, action, which, { maxBytes }));} catch (e) {if (isNotFoundError(e))return notFoundResult("Run", run, "The run may have expired or the flow was deleted.");return safeError(e);}});- server2.tool("get_run_action_repetitions", "List iteration-level details for an action that runs inside a loop (Apply_to_each / Do_until) within a run \u2014 the only way to see WHICH iteration failed. Each repetition has its own status, inputs/outputs links, and (on failure) error. Pass the name of an action **inside** the loop (e.g. a Compose within the Apply_to_each), NOT the loop container itself \u2014 the container action returns no repetitions. `flow` defaults to the pinned current flow (set_current_flow).", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().optional().describe("Flow ID (defaults to pinned current flow)"), run: external_exports.string().describe("Run ID"), action: external_exports.string().describe("Loop action name (e.g. Apply_to_each)") }, { readOnlyHint: true, title: "Loop Iteration Details" }, async ({ env, flow, run, action }) => {+ server2.tool("get_run_action_repetitions", 'List iteration-level details for an action that runs inside a loop (Apply_to_each / Do_until) within a run \u2014 the only way to see WHICH iteration failed. Each repetition has its own status, inputs/outputs links, and (on failure) error. Pass the name of an action **inside** the loop (e.g. a Compose within the Apply_to_each), NOT the loop container itself \u2014 the container action returns no repetitions. `flow` defaults to the pinned current flow (set_current_flow). Returns { action, count, truncated, repetitions }; count is the returned count, not the total. Returns at most `top` repetitions (default 100) \u2014 a long-running Do_until can have thousands. Narrow with `status: "Failed"` to find the iteration that broke.', {+ env: external_exports.string().optional().describe("Environment ID"),+ flow: external_exports.string().optional().describe("Flow ID (defaults to pinned current flow)"),+ run: external_exports.string().describe("Run ID"),+ action: external_exports.string().describe("Loop action name (e.g. Apply_to_each)"),+ top: external_exports.number().int().optional().describe("Max repetitions to return (default 100, max 1000)"),+ status: external_exports.enum(["Succeeded", "Failed", "Skipped", "TimedOut", "any"]).optional().describe("Return only repetitions in this state (default any)"),+ includeLinks: external_exports.boolean().optional().describe("Keep the inputs/outputs content links on each repetition (default true)")+ }, { readOnlyHint: true, title: "Loop Iteration Details" }, async ({ env, flow, run, action, top, status, includeLinks }) => {try {const flowId = ctx.resolveFlow(flow);- const reps = await ctx.getClient().getRunActionRepetitions(ctx.resolveEnv(env), flowId, run, action);- return safeResult({ action, count: reps.length, repetitions: reps });+ const r = await ctx.getClient().getRunActionRepetitions(ctx.resolveEnv(env), flowId, run, action, { top, statusFilter: status, includeLinks });+ return safeResult({ action, count: r.returned, truncated: r.truncated, repetitions: r.repetitions });} catch (e) {return safeError(e);}@@ -68230,7 +68903,7 @@ async function createMcpServer(authProvider, deps = {}) {`2. \`preflight_flow definition=<proposed> connectionReferences=<proposed>\` \u2014 must return \`overall != "block"\`.`,`3. \`preview_update env=... flow=... definition=<proposed> connectionReferences=<proposed>\` \u2014 review the diff, capture the \`previewToken\`.`,`4. Show the user the diff summary. Pause for explicit confirmation.`,- `5. On confirmation, \`update_flow ... previewToken=<token>\`. The token binds the apply to the exact diff you previewed \u2014 concurrent edits will reject.`,+ `5. On confirmation, \`update_flow ... previewToken=<token>\`. The final version check detects edits already present before the write; the API has no atomic conditional-write guarantee.`,`6. Optionally \`publish_flow\` if the flow needs to be started.`,`7. If you need to roll back: \`list_backups flow=...\` \u2192 \`restore_backup file=<filename>\`.`,``,@@ -68327,7 +69000,7 @@ async function createMcpServer(authProvider, deps = {}) {};});server2.resource("recipe-content", new ResourceTemplate("flowagent://recipes/{slug}", { list: void 0 }), { description: "Full markdown content of a specific recipe by slug.", mimeType: "text/markdown" }, async (uri, { slug }) => {- const fs6 = await import("node:fs");+ const fs7 = await import("node:fs");const path7 = await import("node:path");const fileURLToPath2 = (await import("node:url")).fileURLToPath;const here = path7.dirname(fileURLToPath2(import.meta.url));@@ -68335,7 +69008,7 @@ async function createMcpServer(authProvider, deps = {}) {const safeSlug = String(slug).replace(/[^a-z0-9-]/gi, "");const file2 = path7.join(recipesDir, `${safeSlug}.md`);try {- const text = fs6.readFileSync(file2, "utf-8");+ const text = fs7.readFileSync(file2, "utf-8");return { contents: [{ uri: uri.href, mimeType: "text/markdown", text }] };} catch {return { contents: [{ uri: uri.href, mimeType: "text/plain", text: `Recipe '${safeSlug}' not found. Available recipes: see flowagent://recipes/index` }] };diff --git a/plugins/power-automate/skills/debug-flow/SKILL.md b/plugins/power-automate/skills/debug-flow/SKILL.mdindex 102a03f12..07ed0532b 100644--- a/plugins/power-automate/skills/debug-flow/SKILL.md+++ b/plugins/power-automate/skills/debug-flow/SKILL.md@@ -3,7 +3,7 @@ name: debug-flowdescription: Debug a failed Power Automate flow run. Use when a flow failed, has errors, or the user wants to troubleshoot a run.user-invocable: trueargument-hint: "[flow-id] [run-id]"-allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators, mcp__flowagent__resolve_entity, mcp__flowagent__list_datasets, mcp__flowagent__list_tables, mcp__flowagent__whoami, mcp__flowagent__doctor, mcp__flowagent__reconnect, mcp__flowagent__list_accounts, mcp__flowagent__switch_account+allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_content, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators, mcp__flowagent__resolve_entity, mcp__flowagent__list_datasets, mcp__flowagent__list_tables, mcp__flowagent__whoami, mcp__flowagent__doctor, mcp__flowagent__reconnect, mcp__flowagent__list_accounts, mcp__flowagent__switch_accountmodel: opus---@@ -26,6 +26,7 @@ CLI-only operations or when no MCP tools are present.| `diagnose_run` | One-shot: classify failed actions with remediations || `get_run_details` | Get details for a specific run || `get_run_actions` | Get action-level execution trace |+| `get_run_action_content` | Retrieve bounded recorded inputs or outputs for one action || `get_run_action_repetitions` | Iteration-level detail for a loop (which iteration failed — pass an action **inside** the loop) || `get_flow` | Get flow definition for context || `get_operation_details` | Confirm the correct action type / parameters |@@ -45,6 +46,8 @@ CLI-only operations or when no MCP tools are present.2. **Fast triage with `diagnose_run`**- Call `diagnose_run` for the run — it returns the failed/timed-out actions already classified with a remediation each. Use this as the starting point.- For deeper analysis, also fetch (in parallel): `get_run_actions` (full trace) and `get_flow` (definition context). For a failed loop, call `get_run_action_repetitions` on an action **inside** the loop to find the failing iteration.+ - Repetition results are `{ action, count, truncated, repetitions }`; `count` is the returned count, not the total. If `truncated` is true, do not infer absence from the returned subset.+ - When recorded payloads are needed, use `get_run_actions` with `includeSizes: true`, then `get_run_action_content` with the action name and `which: "inputs"` or `"outputs"`. The default download cap is 256000 bytes; an oversized result is reported rather than dumped. Retrieve only what the diagnosis needs and avoid reproducing sensitive payloads in the report.3. **Analyze failures**- Identify actions with status != "Succeeded"diff --git a/plugins/power-automate/skills/diagnose-flow/SKILL.md b/plugins/power-automate/skills/diagnose-flow/SKILL.mdindex 52735bf78..7801b88fa 100644--- a/plugins/power-automate/skills/diagnose-flow/SKILL.md+++ b/plugins/power-automate/skills/diagnose-flow/SKILL.md@@ -4,7 +4,7 @@ description: Deep autonomous diagnosis of a failed flow run. Provide environmentuser-invocable: trueargument-hint: "<env-id> <flow-id> <run-id>"context: fork-allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators, mcp__flowagent__resolve_entity, mcp__flowagent__list_datasets, mcp__flowagent__list_tables, mcp__flowagent__whoami, mcp__flowagent__doctor, mcp__flowagent__reconnect, mcp__flowagent__list_accounts, mcp__flowagent__switch_account+allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_content, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators, mcp__flowagent__resolve_entity, mcp__flowagent__list_datasets, mcp__flowagent__list_tables, mcp__flowagent__whoami, mcp__flowagent__doctor, mcp__flowagent__reconnect, mcp__flowagent__list_accounts, mcp__flowagent__switch_accountmodel: opus---@@ -30,6 +30,8 @@ Copilot CLI). If no MCP tools are present, the plugin is not wired up — run th- `get_run_actions` for the full action-level execution trace- `get_flow` for definition context- For a failed loop, `get_run_action_repetitions` on an action **inside** the loop (the container returns none) to find the failing iteration+ - Repetition results are `{ action, count, truncated, repetitions }`; `count` is the returned count, not the total. Treat `truncated: true` as incomplete evidence.+ - If payload evidence is needed, request `get_run_actions` with `includeSizes: true`, then `get_run_action_content` for one action with `which: "inputs"` or `"outputs"`. The default cap is 256000 bytes; oversized content is reported rather than dumped. Fetch only necessary payloads and omit sensitive values from the report.2. **Build execution graph**: Map each action's `runAfter` dependencies. Identify parallel branches.diff --git a/plugins/power-automate/skills/telemetry/SKILL.md b/plugins/power-automate/skills/telemetry/SKILL.mdnew file mode 100644index 000000000..376656b14--- /dev/null+++ b/plugins/power-automate/skills/telemetry/SKILL.md@@ -0,0 +1,55 @@+---+name: telemetry+description: >+ Use this skill when the user wants to enable, disable, turn on or off, opt out+ of, opt in to, or check the status of power-automate telemetry /+ usage data. Triggers: "disable telemetry", "turn off telemetry", "opt out of+ telemetry", "stop collecting usage data", "enable telemetry", "telemetry status".+user-invocable: true+argument-hint: "on | off | status"+allowed-tools: Bash+model: haiku+---++# Power Automate Telemetry Control++Enable, disable, or check the status of pseudonymous usage telemetry for the+`power-automate` plugin.++## What is collected++Telemetry is **pseudonymous**. It records operational fields — skill name,+plugin version, OS/Node versions, agent name/version, Dataverse organization+and Entra tenant IDs, and the signed-in user's Entra object ID when PAC exposes+it. It never includes file paths, prompts, tool inputs, flow names, URLs,+credentials, usernames, hostnames, or error messages. Plugin hook events have a+local diagnostic log, one file per session, under+`~/.power-platform-skills/telemetry/power-automate/sessions/<sessionId>/events.jsonl`+(nothing is transmitted when telemetry is OFF). Session logs older than 14 days+are pruned automatically. This hook log is separate from FlowAgent CLI/MCP+telemetry, whose local mirror is `~/.flowagent/telemetry.jsonl` by default+(`FLOWAGENT_TELEMETRY_LOG` overrides the path) and is not automatically pruned.+The status command below reports the plugin hook's setting and session logs;+it also prints the core log's path and whether the file exists, not whether a+particular CLI/MCP call is eligible for remote collection.++## Workflow++1. Determine the action from the user's request / `$ARGUMENTS`:+ - `on` — opt in+ - `off` — opt out (nothing transmitted; local log still kept)+ - `status` (default) — report current state++2. Run the bundled config CLI and show its output verbatim:++ ```bash+ node "${PLUGIN_ROOT:-$CLAUDE_PLUGIN_ROOT}/scripts/lib/telemetry/lib/telemetry-config.js" --action <on|off|status> --plugin power-automate+ ```++ For `status`, also show the FlowAgent CLI/MCP local log location:++ ```bash+ node -e 'const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const log = process.env.FLOWAGENT_TELEMETRY_LOG || path.join(os.homedir(), ".flowagent", "telemetry.jsonl"); console.log(`FlowAgent CLI/MCP local log: ${log}${fs.existsSync(log) ? "" : " (not created yet)"}`);'+ ```++3. Confirm the result to the user in one sentence.diff --git a/shared/telemetry/README.md b/shared/telemetry/README.mdindex dc7e6ab68..a687edad5 100644--- a/shared/telemetry/README.md+++ b/shared/telemetry/README.md@@ -61,6 +61,7 @@ choice cannot override `disabled: true`.| Power Pages | `disabled: false` | Enabled and default-on for transmission. Organization-based geo routing selects a regional collector; without an organization ID, the configured US default is used. Events are written to the local mirror even after a user transmission opt-out. | `eventInfo.aadObjectId` when PAC exposes the signed-in user's Entra object ID; `eventInfo.framework` when the Power Pages code-site framework can be determined. || Mobile Apps | `disabled: false` | Enabled and default-on for transmission. Its project environment selects the regional collector. Until that cluster is resolved, events remain in the local mirror and are not transmitted. | `eventInfo.invocationSource`; random per-project `eventInfo.appInstanceId` (or `null` outside a prepared project); optional validated checkpoint `eventInfo.additionalInfo`; and `eventInfo.appInsightsSelection`. || Model Apps | `disabled: false` | Enabled and default-on for transmission. A public-cloud organization is geo-routed to the US or EU collector (US default only without an organization ID; an organization whose geo cannot be determined is not transmitted); a sovereign or internal PAC cloud is routed from the cloud stamp alone, never to a public collector; an unrecognized cloud, or a signed-in organization with no cloud, is not transmitted. Events are written to the local mirror even after a user transmission opt-out. | No signed-in user object ID. The base event can include `orgId` and `tenantId` when PAC is signed in. |+| Power Automate | `disabled: false` | Enabled and default-on for transmission. Its resolver returns a destination only for public cloud, so sovereign-cloud events stay in the local mirror. Organization-based geo routing selects the US or EU collector; without an organization ID, the configured US default is used. Events are written to the local mirror even after a user transmission opt-out. | `eventInfo.aadObjectId` when PAC exposes the signed-in user's Entra object ID. The plugin's bundled MCP server and CLI emit on the same stream and additionally record `outcome`, `durationMs`, `errorClass`, and `errorCode`, a random per-invocation `correlationId` and per-process `sessionId`, and `envId`/`envLocation`/`envRegion`. Error messages are never recorded. |### Custom routing (the resolver contract)@@ -113,7 +114,7 @@ Every event carries a fixed allowlist enforced by `lib/events.js`. Field names m**PAC + agent (when available, otherwise omitted):**-- `orgId`, `tenantId` — Dataverse org GUID and Entra tenant GUID, read from `pac auth who` if the user is signed in. Power Pages uses `orgId` for Artemis region routing; Model Apps can include both fields if enabled. Mobile Apps excludes both and routes from its prepared project environment instead.+- `orgId`, `tenantId` — Dataverse org GUID and Entra tenant GUID, read from `pac auth who` if the user is signed in. Power Pages and Power Automate hooks use `orgId` for organization-based region routing; Model Apps can include both fields. Mobile Apps excludes both and routes from its prepared project environment instead. Power Automate core MCP/CLI events can include a tenant GUID from `FLOWAGENT_TENANT_ID`, but not an organization ID.- `pacCliVersion` — semver from `pac --version`- `aiAgentName`, `aiAgentVersion` — host AI agent detected via env in the hook process before the detached dispatcher is spawned. Claude Code (`CLAUDECODE=1`) reports `Claude Code` with the version read from its installed `package.json` via `CLAUDE_CODE_EXECPATH`; that `package.json` only exists for npm-global installs, so when it can't be read (e.g. the native installer's standalone binary) the version falls back to the dotted semver parsed out of `AI_AGENT` (`claude-code_<maj>-<min>-<patch>_agent`), which Claude Code sets regardless of install method. GitHub Copilot CLI (`COPILOT_CLI=1`) reports `Copilot CLI` with the version from `COPILOT_CLI_BINARY_VERSION` or `COPILOT_CLI_VERSION`. Codex, OpenCode, Hermes, and OpenClaw are detected from their agent-specific env flags/version variables (`CODEX_*`, `OPENCODE_*`, `HERMES_*`, `OPENCLAW_*`) or from `AI_AGENT` when it includes a recognizable agent name. Explicit `AI_AGENT_NAME` / `AI_AGENT_VERSION` env vars override detection (used for testing); when `AI_AGENT_NAME` is set but `AI_AGENT_VERSION` is empty, the version is backfilled from whichever detector matches.@@ -129,6 +130,16 @@ Every event carries a fixed allowlist enforced by `lib/events.js`. Field names mEach key is omitted independently when its source is unavailable; `eventInfo` itself is omitted only when every key would be absent.+ **Power Automate**++ - Hook `aadObjectId` — the signed-in user's Entra object ID, when PAC exposes it.+ - Its separate core MCP/CLI event schema records tool/command identity,+ outcome, duration, error class/code, random session/correlation IDs,+ system/agent versions and environment GUID/location/region. Core events+ do not carry organization or Entra user object IDs. See the plugin's+ [bundled telemetry guide](../../plugins/power-automate/references/telemetry.md)+ for the separate routing and log-retention rules.+**Mobile Apps**- `invocationSource` — one of `prompt`, `pretool`, or `checkpoint`.@@ -158,9 +169,9 @@ The dispatcher runs a defense-in-depth allowlist filter against `FIELD_TYPES` be- **Enabled plugins are default-on for transmission.** There is no first-runprompt. A plugin that ships `disabled: true` remains hard-off regardless of auser's saved telemetry choice.-- **Identifiers.** Power Pages and Model Apps can include the Dataverse organization GUID (`orgId`) and Entra tenant GUID (`tenantId`) when PAC is signed in. Power Pages can also include the signed-in user's Entra object ID (`eventInfo.aadObjectId`) when PAC exposes it. Mobile Apps excludes all three identity fields. The local diagnostic mirror retains the same fields as the event produced by each plugin.+- **Identifiers.** Power Pages and Power Automate hooks, and Model Apps, can include the Dataverse organization GUID (`orgId`) and Entra tenant GUID (`tenantId`) when PAC is signed in. Power Pages and Power Automate hooks can also include the signed-in user's Entra object ID (`eventInfo.aadObjectId`) when PAC exposes it. Power Automate core MCP/CLI events can include a tenant GUID and environment GUID/location/region, but not organization or Entra user object IDs. Mobile Apps excludes all three identity fields. The local diagnostic mirror retains the same fields as the event produced by each plugin.- **Authenticated scenario.** When an adopter has the authentication or project-environment context required by its routing implementation, the resolved cloud and geo select the corresponding configured regional collector. Depending on the adopter's documented schema, the transmitted event may include End User Pseudonymous Information (EUPI) or Organization Identifiable Information (OII).-- **Unauthenticated or unresolved scenario.** When PAC provides no authentication context, the organization, tenant, and Entra user object ID fields are absent. Destination behavior when routing context is unavailable is adopter-specific: configurations with a default region use that configured destination, while configurations that require a resolved project cluster retain the event in the local mirror and do not transmit it until a valid cluster is available. The event can still contain the allowlisted operational and system metadata and separately documented non-identity plugin-specific fields.+- **Unauthenticated or unresolved scenario.** Hook identity fields derived from PAC are absent when PAC provides no authentication context. Power Automate core tenant metadata, if supplied separately, does not depend on PAC. Destination behavior when routing context is unavailable is adopter-specific: configurations with a default region use that configured destination, while configurations that require a resolved project cluster retain the event in the local mirror and do not transmit it until a valid cluster is available. Power Automate hooks additionally require positively identified public cloud; its core events require a recognized environment location and positively identified commercial cloud. The event can still contain the allowlisted operational and system metadata and separately documented non-identity plugin-specific fields.- **Opt out of transmission** via `/<plugin>:telemetry off` (per-user, per-plugin). This writes `telemetry[<plugin>] = "off"` into `~/.power-platform-skills/config.json` and stops the network POST to the collector — **nothing leaves the machine** — but the local diagnostic mirror (a per-session `events.jsonl`) is still written so the user/developer can see exactly what would have been sent. It is therefore an opt-out of *transmission*, not of local logging. CI/headless can opt out by writing that file directly. Re-enable with `/<plugin>:telemetry on`.- **Opt out for automation** via the per-plugin opt-out env var`POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` (e.g.