Skip to content

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

Add enabled skill-usage telemetry for Power Apps Mobile extensions (#726)

Rishipal3cbe9cedb326
diff --git a/.github/workflows/power-apps-mobile-extension-tests.yml b/.github/workflows/power-apps-mobile-extension-tests.yml
new file mode 100644
index 000000000..b7389a8c5
--- /dev/null
+++ b/.github/workflows/power-apps-mobile-extension-tests.yml
@@ -0,0 +1,54 @@
+name: power-apps-mobile-extension-tests
+
+on:
+ pull_request:
+ branches:
+ - main
+ paths:
+ - "plugins/power-apps-mobile-extension/**"
+ - "shared/telemetry/lib/**"
+ - ".github/workflows/power-apps-mobile-extension-tests.yml"
+ push:
+ branches:
+ - main
+ paths:
+ - "plugins/power-apps-mobile-extension/**"
+ - "shared/telemetry/lib/**"
+ - ".github/workflows/power-apps-mobile-extension-tests.yml"
+
+permissions:
+ contents: read
+
+concurrency:
+ group: power-apps-mobile-extension-tests-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ test-power-apps-mobile-extension:
+ name: test-power-apps-mobile-extension (${{ matrix.os }}, node ${{ matrix.node }})
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 15
+ env:
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_APPS_MOBILE_EXTENSION_OPTOUT: "1"
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - ubuntu-latest
+ - windows-latest
+ - macos-latest
+ node:
+ - 20
+ - 22
+ steps:
+ - name: checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+
+ - name: setup-node
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: ${{ matrix.node }}
+
+ - name: run-plugin-tests
+ shell: bash
+ run: node --test plugins/power-apps-mobile-extension/scripts/tests/*.test.js
\ No newline at end of file
diff --git a/.github/workflows/shared-telemetry-tests.yml b/.github/workflows/shared-telemetry-tests.yml
index e0238099b..38ee2d7be 100644
--- a/.github/workflows/shared-telemetry-tests.yml
+++ b/.github/workflows/shared-telemetry-tests.yml
@@ -52,6 +52,7 @@ jobs:
POWER_PLATFORM_SKILLS_TELEMETRY_PCF_OPTOUT: "1"
POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "1"
POWER_PLATFORM_SKILLS_TELEMETRY_POWER_AUTOMATE_OPTOUT: "1"
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_APPS_MOBILE_EXTENSION_OPTOUT: "1"
strategy:
fail-fast: false
matrix:
diff --git a/AGENTS.md b/AGENTS.md
index cdbaa2962..82babf151 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -173,7 +173,7 @@ jobs:
This opt-out suppresses **transmission only** (the local diagnostic mirror is still written), so it is safe and has no effect on what the job actually tests. Tests that need to assert that emission *happens* clear the var in their own spawned-process env and route the event to a local `POWER_PLATFORM_SKILLS_FAKE_HTTPS` probe instead of the real collector — so the job-level opt-out never breaks them. Existing reference: `.github/workflows/power-pages-script-tests.yml`. When you add a new such workflow (or a new emitting step to an existing one), add this env var in the same change; treat a CI job that runs the tests without it as a production-telemetry leak.
-Current adopters: `power-pages`, `mobile-apps`, `model-apps`, and `pcf` (all transmitting; `pcf` shares model-apps' tenant). Others adopt on demand. The library's own tests (`shared/telemetry/tests`) run in `.github/workflows/shared-telemetry-tests.yml` on a change to the source or to any bundled copy, and its `bundled-copies.test.js` fails when any adopter's `plugins/<plugin>/scripts/lib/telemetry/lib` differs from `shared/telemetry/lib`. The workflow sets every adopter's opt-out — add a new adopter's variable there too. power-pages and model-apps also keep a `scripts/tests/telemetry-lib-copy.test.js` that runs the same comparison in their own suites (model-apps also checks its shared skill copies, and lists `shared/telemetry/**` in its workflow's path filter so a source edit runs it too).
+Current adopters: `power-pages`, `mobile-apps`, `model-apps`, `pcf`, `power-automate`, and `power-apps-mobile-extension` (all transmitting; `pcf` shares model-apps' tenant). Others adopt on demand. The library's own tests (`shared/telemetry/tests`) run in `.github/workflows/shared-telemetry-tests.yml` on a change to the source or to any bundled copy, and its `bundled-copies.test.js` fails when any adopter's `plugins/<plugin>/scripts/lib/telemetry/lib` differs from `shared/telemetry/lib`. The workflow sets every adopter's opt-out — add a new adopter's variable there too. power-pages and model-apps also keep a `scripts/tests/telemetry-lib-copy.test.js` that runs the same comparison in their own suites (model-apps also checks its shared skill copies, and lists `shared/telemetry/**` in its workflow's path filter so a source edit runs it too).
## Legacy Marketplace Compatibility
diff --git a/plugins/power-apps-mobile-extension/.claude-plugin/plugin.json b/plugins/power-apps-mobile-extension/.claude-plugin/plugin.json
index cb7f99c44..3415f9a78 100644
--- a/plugins/power-apps-mobile-extension/.claude-plugin/plugin.json
+++ b/plugins/power-apps-mobile-extension/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "power-apps-mobile-extension",
- "version": "0.1.0",
+ "version": "0.2.0",
"description": "Build third-party Power Apps Mobile (PAM) controls into a prebuilt .ppmplugin binary (Android DEX + flat iOS .framework + manifest.json) for the wrap runtime. Public tooling only; recommended build entry point /generate-ppmplugin.",
"author": {
"name": "Microsoft",
diff --git a/plugins/power-apps-mobile-extension/.plugin/plugin.json b/plugins/power-apps-mobile-extension/.plugin/plugin.json
index cb7f99c44..3415f9a78 100644
--- a/plugins/power-apps-mobile-extension/.plugin/plugin.json
+++ b/plugins/power-apps-mobile-extension/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "power-apps-mobile-extension",
- "version": "0.1.0",
+ "version": "0.2.0",
"description": "Build third-party Power Apps Mobile (PAM) controls into a prebuilt .ppmplugin binary (Android DEX + flat iOS .framework + manifest.json) for the wrap runtime. Public tooling only; recommended build entry point /generate-ppmplugin.",
"author": {
"name": "Microsoft",
diff --git a/plugins/power-apps-mobile-extension/AGENTS.md b/plugins/power-apps-mobile-extension/AGENTS.md
index ffc865102..e2f4f9fb1 100644
--- a/plugins/power-apps-mobile-extension/AGENTS.md
+++ b/plugins/power-apps-mobile-extension/AGENTS.md
@@ -19,6 +19,7 @@ publicly available tools and package registries.
- `shared/repo-layout.md` owns the generated control repository structure.
- `shared/naming-conventions.md` owns identifier derivation and reserved-name guidance.
- `shared/error-codes.md` owns stable native and transport error codes.
+- `shared/telemetry.md` owns skill-usage telemetry behavior, controls, fields and release gates.
- `shared/framework-recommendations.md` owns native implementation recommendations.
- `shared/self-critique-protocol.md` owns quality gates used by code-writing skills.
@@ -37,3 +38,22 @@ summary is necessary, keep it synchronized with the owning reference.
When adding the plugin to the public repository, also register
`./plugins/power-apps-mobile-extension` in both root marketplace manifests and add it to the root README. Those
repository-level registrations intentionally remain outside this self-contained plugin payload.
+
+## Telemetry implementation
+
+- Telemetry is enabled in `scripts/lib/telemetry/ikey.json` by explicit maintainer
+ approval. Change the release switch only with explicit approval; preserve its
+ hard-off behavior. Tests must use isolated fixtures, not alter the release switch
+ or send live telemetry. The `telemetry on` command changes only a user preference.
+- Use the strict PAM schema before both local logging and network serialization.
+ Do not add fields or relax the `eventInfo.aadObjectId`-only rule implicitly.
+- Only hook-derived starts are recorded. Do not instrument generated controls or
+ add telemetry commands to individual authoring skills. Telemetry is non-blocking.
+- Run `node --test plugins/power-apps-mobile-extension/scripts/tests/telemetry.test.js`
+ from the repository root and the metadata checks listed in `shared/telemetry.md`.
+ Set `POWER_PLATFORM_SKILLS_TELEMETRY_POWER_APPS_MOBILE_EXTENSION_OPTOUT=1`
+ for automation. Keep the bundled library identical to `shared/telemetry/lib/`.
+- Preserve the fixed wire `clientType` and `pluginName` in `customDimensions` for
+ shared-stream attribution. Instrumentation keys must remain unique across plugins.
+- Live collector tests and backend routing updates are separate actions. Do not
+ run live probes as routine validation.
diff --git a/plugins/power-apps-mobile-extension/README.md b/plugins/power-apps-mobile-extension/README.md
index c96eab2b8..62717c5c3 100644
--- a/plugins/power-apps-mobile-extension/README.md
+++ b/plugins/power-apps-mobile-extension/README.md
@@ -7,6 +7,18 @@ and package registries.
The plugin produces a `.ppmplugin` bundle for the Power Apps Wrap runtime and a matching dispatcher
PCF control for use in a Canvas app.
+## Usage telemetry
+
+**This release enables skill-usage telemetry with transmission on by default.**
+The bundled `/power-apps-mobile-extension:telemetry on|off|status` control manages
+the per-user transmission preference. Node.js 20+ is needed for that control;
+no PAC or sign-in is required.
+
+`telemetry off` stops transmission, **not local diagnostic logging**, which can
+include organization, tenant and Entra user object IDs from existing PAC sign-in.
+The implementation is limited to ROW/EU and honors saved and environment opt-outs.
+See [telemetry details, validation status and controls](shared/telemetry.md).
+
---
## Install & run
@@ -108,6 +120,9 @@ with `/generate-ppmplugin`.
`/assemble-ppmplugin`, and `/audit-ppmplugin` for you. Invoke a stage directly only when you need to
rerun or debug that stage.
+**Support:** `/power-apps-mobile-extension:telemetry on|off|status` manages the
+per-user transmission preference. It is not counted as a workflow invocation.
+
## Integrate the control into an existing Canvas app
### 1. How it fits together
diff --git a/plugins/power-apps-mobile-extension/hooks/hooks.json b/plugins/power-apps-mobile-extension/hooks/hooks.json
new file mode 100644
index 000000000..63e8949b8
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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)process.exit(0);try{require(path.resolve(root,'hooks','run-telemetry.js')).start('pretool');}catch{}\"",
+ "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)process.exit(0);try{require(path.resolve(root,'hooks','run-telemetry.js')).start('prompt');}catch{}\"",
+ "timeout": 30
+ }
+ ]
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/plugins/power-apps-mobile-extension/hooks/run-telemetry.js b/plugins/power-apps-mobile-extension/hooks/run-telemetry.js
new file mode 100644
index 000000000..117374c97
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/hooks/run-telemetry.js
@@ -0,0 +1,101 @@
+"use strict";
+
+const crypto = require("node:crypto");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { runNative } = require("../scripts/lib/telemetry/lib/native-exec");
+const { PLUGIN_NAME, STREAM_NAME, TRACKED_SKILLS, sanitizeData } = require("../scripts/lib/telemetry/schema");
+const { readConfig, enabled } = require("../scripts/lib/telemetry/config");
+const { fireAndForget } = require("../scripts/lib/telemetry/dispatcher");
+const { readPacAuth } = require("../scripts/lib/telemetry/lib/pac-auth");
+const { readAiAgent, readPacCliVersion } = require("../scripts/lib/telemetry/lib/agent-info");
+const { getSessionId, resolveHostSessionId } = require("../scripts/lib/telemetry/lib/session");
+
+function identify(value, pluginHint) {
+ if (typeof value !== "string" || (pluginHint && pluginHint !== PLUGIN_NAME)) return null;
+ const token = value.trim().replace(/^\//, "");
+ const parts = token.split(":");
+ if (parts.length === 2) {
+ if (parts[0] !== PLUGIN_NAME) return null;
+ return TRACKED_SKILLS.includes(parts[1]) ? parts[1] : null;
+ }
+ if (parts.length !== 1) return null;
+ return TRACKED_SKILLS.includes(token) ? token : null;
+}
+
+function invocation(mode, payload) {
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
+ if (mode === "prompt") {
+ if (typeof payload.prompt !== "string") return null;
+ const match = payload.prompt.match(/^\s*\/([^\s]+)(?:\s|$)/);
+ return match ? identify(match[1], payload.pluginName || payload.plugin_name) : null;
+ }
+ if (mode !== "pretool") return null;
+ const tool = payload.tool_name || payload.toolName;
+ if (tool && !["Skill", "skill"].includes(tool)) return null;
+ let input = payload.tool_input || payload.toolInput || payload.toolArgs;
+ if (typeof input === "string") {
+ try { input = JSON.parse(input); } catch { return null; }
+ }
+ if (!input || typeof input !== "object" || Array.isArray(input)) return null;
+ return identify(input.skill || input.skill_name || input.skillName || input.name,
+ input.pluginName || input.plugin_name || payload.pluginName || payload.plugin_name);
+}
+
+function pacExec(executable, args, options, dependencies) {
+ if (executable !== "pac" || !["auth who", "--version"].includes(args.join(" "))) throw new Error("Unsupported PAC command");
+ return runNative(executable, args, options, dependencies);
+}
+
+function handle(mode, payload, options = {}) {
+ if (!enabled(readConfig(options.configPath))) return false;
+ const skillName = invocation(mode, payload);
+ if (!skillName) return false;
+ let manifest;
+ try { manifest = JSON.parse(fs.readFileSync(path.join(__dirname, "../.plugin/plugin.json"), "utf8")); } catch { return false; }
+ let auth = null;
+ let agent = {};
+ let pacCliVersion = "";
+ try { auth = (options.readAuth || (() => readPacAuth({ _exec: pacExec })))(); } catch {}
+ try { agent = (options.readAgent || (() => readAiAgent(options.env || process.env)))() || {}; } catch {}
+ try { pacCliVersion = (options.readPacVersion || (() => readPacCliVersion({ _exec: pacExec })))(); } catch {}
+ const hostId = resolveHostSessionId(payload);
+ const sessionId = getSessionId(/^[A-Za-z0-9_-]{1,128}$/.test(hostId) ? hostId : "");
+ const data = sanitizeData({
+ eventName: "skill_started", eventType: "Trace", severity: "Info",
+ pluginName: PLUGIN_NAME, pluginVersion: manifest.version, skillName,
+ sessionId, correlationId: crypto.randomUUID(),
+ osName: { win32: "Windows", darwin: "Mac", linux: "Linux" }[process.platform],
+ osVersion: os.release(), nodeVersion: "v" + process.versions.node.split(".")[0],
+ aiAgentName: agent.aiAgentName, aiAgentVersion: agent.aiAgentVersion, pacCliVersion,
+ orgId: auth && auth.orgId, tenantId: auth && auth.tenantId,
+ eventInfo: auth && { aadObjectId: auth.objectId },
+ });
+ if (!data) return false;
+ const rawCloud = auth && typeof auth.cloud === "string" ? auth.cloud.trim().toLowerCase() : "";
+ const cloud = rawCloud === "public" ? "Public" : rawCloud ? "unsupported" : "";
+ try {
+ (options.emit || fireAndForget)({ name: STREAM_NAME, data, cloud }, options);
+ return true;
+ } catch { return false; }
+}
+
+function start(mode) {
+ if (!enabled(readConfig())) return;
+ let text = "";
+ const timer = setTimeout(() => process.exit(0), 25000);
+ process.stdin.setEncoding("utf8");
+ process.stdin.on("data", chunk => {
+ text += chunk;
+ if (text.length > 65536) process.exit(0);
+ });
+ process.stdin.on("error", () => process.exit(0));
+ process.stdin.on("end", () => {
+ clearTimeout(timer);
+ try { handle(mode, JSON.parse(text)); } catch {}
+ });
+}
+
+if (require.main === module) start(process.argv[2]);
+module.exports = { start, handle, invocation, pacExec };
\ No newline at end of file
diff --git a/plugins/power-apps-mobile-extension/scripts/lib/telemetry/config.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/config.js
new file mode 100644
index 000000000..46b0ff2c5
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/config.js
@@ -0,0 +1,40 @@
+"use strict";
+
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const { STREAM_NAME } = require("./schema");
+
+const CONFIG_PATH = path.join(__dirname, "ikey.json");
+const COLLECTORS = Object.freeze({
+ us: "https://browser.events.data.microsoft.com/OneCollector/1.0/",
+ eu: "https://eu-mobile.events.data.microsoft.com/OneCollector/1.0/",
+});
+
+function readConfig(configPath = CONFIG_PATH) {
+ try {
+ const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
+ return config && typeof config === "object" && !Array.isArray(config) ? config : null;
+ } catch {
+ return null;
+ }
+}
+
+function destination(config, region) {
+ const entry = config && config.regions && config.regions[region];
+ if (!entry || !COLLECTORS[region] || entry.collector_url !== COLLECTORS[region] ||
+ typeof entry.instrumentation_key !== "string" ||
+ !/^[0-9a-f]{32}-[0-9a-f-]{36}-\d+$/i.test(entry.instrumentation_key)) return null;
+ return { region, iKey: entry.instrumentation_key, collectorUrl: entry.collector_url };
+}
+
+function enabled(config) {
+ return !!(config && config.disabled === false && config.event_stream_name === STREAM_NAME &&
+ config.default_region === "us" && destination(config, "us") && destination(config, "eu"));
+}
+
+function configDir(env = process.env) {
+ return env.POWER_PLATFORM_SKILLS_CONFIG_DIR || path.join(os.homedir(), ".power-platform-skills");
+}
+
+module.exports = { CONFIG_PATH, COLLECTORS, readConfig, destination, enabled, configDir };
\ No newline at end of file
diff --git a/plugins/power-apps-mobile-extension/scripts/lib/telemetry/dispatcher.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/dispatcher.js
new file mode 100644
index 000000000..7b6840955
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/dispatcher.js
@@ -0,0 +1,100 @@
+"use strict";
+
+const { spawn } = require("node:child_process");
+const https = require("node:https");
+const os = require("node:os");
+const { PLUGIN_NAME, STREAM_NAME, sanitizeData, buildEnvelope } = require("./schema");
+const { readConfig, enabled, configDir } = require("./config");
+const { appendLocal } = require("./lib/local-log");
+const { isTransmissionOptedOut, telemetryOptOutEnvVarName } = require("./lib/user-config");
+const { resolveDestination } = require("./routing");
+
+function post(destination, envelope) {
+ const body = JSON.stringify(envelope) + "\n";
+ return new Promise(resolve => {
+ let request;
+ let timer;
+ let settled = false;
+ const finish = sent => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve(sent);
+ };
+ try {
+ request = https.request(destination.collectorUrl, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-json-stream; charset=utf-8",
+ "x-apikey": destination.iKey,
+ "Content-Length": Buffer.byteLength(body),
+ },
+ }, response => {
+ response.resume();
+ response.on("error", () => finish(false));
+ response.on("end", () => finish(response.statusCode >= 200 && response.statusCode < 300));
+ });
+ request.on("error", () => finish(false));
+ timer = setTimeout(() => { finish(false); request.destroy(); }, 4000);
+ request.end(body);
+ } catch { finish(false); }
+ });
+}
+
+async function dispatch(input, options = {}) {
+ const config = readConfig(options.configPath);
+ if (!enabled(config)) return "disabled";
+ if (!input || input.name !== STREAM_NAME) return "invalid";
+ const data = sanitizeData(input.data);
+ if (!data) return "invalid";
+ const env = options.env || process.env;
+ const directory = configDir(env);
+ const time = new Date().toISOString();
+ try { (options.appendLocal || appendLocal)({ time, name: STREAM_NAME, data }, { configDir: directory }); } catch {}
+ if (isTransmissionOptedOut(directory, PLUGIN_NAME, env)) return "opted-out";
+ let target;
+ try { target = await resolveDestination(config, data, input.cloud, directory, options.routing); } catch { return "unresolved"; }
+ if (!target) return "unresolved";
+ const envelope = buildEnvelope(data, time, target.iKey);
+ if (!envelope) return "invalid";
+ try { return await (options.post || post)(target, envelope) ? "accepted" : "failed"; } catch { return "failed"; }
+}
+
+function fireAndForget(event, options = {}) {
+ if (!enabled(readConfig(options.configPath))) return;
+ const data = sanitizeData(event && event.data);
+ if (!data || event.name !== STREAM_NAME) return;
+ const env = options.env || process.env;
+ const childEnv = {};
+ for (const key of ["PATH", "SystemRoot", "HOME", "USERPROFILE", "APPDATA",
+ "POWER_PLATFORM_SKILLS_CONFIG_DIR", telemetryOptOutEnvVarName(PLUGIN_NAME)]) {
+ if (typeof env[key] === "string") childEnv[key] = env[key];
+ }
+ try {
+ const child = (options.spawn || spawn)(process.execPath, [__filename], {
+ cwd: os.tmpdir(), detached: true, stdio: ["pipe", "ignore", "ignore"], env: childEnv,
+ });
+ child.on("error", () => {});
+ child.stdin.on("error", () => {});
+ const cloud = event.cloud === "Public" ? "Public" : event.cloud ? "unsupported" : "";
+ child.stdin.end(JSON.stringify({ name: STREAM_NAME, data, cloud }));
+ child.unref();
+ } catch {}
+}
+
+if (require.main === module) {
+ if (!enabled(readConfig())) process.exit(0);
+ let input = "";
+ process.stdin.setEncoding("utf8");
+ process.stdin.on("data", chunk => {
+ input += chunk;
+ if (input.length > 65536) process.exit(0);
+ });
+ process.stdin.on("error", () => process.exit(0));
+ process.stdin.on("end", async () => {
+ try { await dispatch(JSON.parse(input)); } catch {}
+ process.exit(0);
+ });
+}
+
+module.exports = { dispatch, fireAndForget };
\ No newline at end of file
diff --git a/plugins/power-apps-mobile-extension/scripts/lib/telemetry/ikey.json b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/ikey.json
new file mode 100644
index 000000000..41330efe2
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/ikey.json
@@ -0,0 +1,15 @@
+{
+ "event_stream_name": "event",
+ "disabled": false,
+ "default_region": "us",
+ "regions": {
+ "us": {
+ "instrumentation_key": "5c3a61f48d7c4522912765ae7465ab5c-f9cba087-ed82-4591-93d0-ce7eb8bbfcf5-7021",
+ "collector_url": "https://browser.events.data.microsoft.com/OneCollector/1.0/"
+ },
+ "eu": {
+ "instrumentation_key": "5c3a61f48d7c4522912765ae7465ab5c-f9cba087-ed82-4591-93d0-ce7eb8bbfcf5-7021",
+ "collector_url": "https://eu-mobile.events.data.microsoft.com/OneCollector/1.0/"
+ }
+ }
+}
diff --git a/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/agent-info.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/agent-info.js
new file mode 100644
index 000000000..aa6ec840b
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/emit-dispatcher.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/emit-dispatcher.js
new file mode 100644
index 000000000..fc6571132
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/emit-from-prompt.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/emit-from-prompt.js
new file mode 100644
index 000000000..38113ebd9
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/emit-spawn.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/emit-spawn.js
new file mode 100644
index 000000000..0bd839d8a
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/events.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/events.js
new file mode 100644
index 000000000..f7b2ffc12
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/events.js
@@ -0,0 +1,150 @@
+"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 buildSkillEvent(envelopeName, "skill_started", input, "Info");
+}
+
+function buildSkillEvent(envelopeName, eventName, input, severity = "Info") {
+ return buildEvent(
+ envelopeName,
+ eventName,
+ pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS]),
+ severity
+ );
+}
+
+function buildSkillConfigured(envelopeName, input) {
+ return buildSkillEvent(envelopeName, "skill_configured", input, "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,
+ buildSkillEvent,
+ buildSkillConfigured,
+ buildSkillCompleted,
+ FIELD_TYPES,
+ pick,
+};
diff --git a/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/local-log.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/local-log.js
new file mode 100644
index 000000000..ed61032d4
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/native-exec.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/native-exec.js
new file mode 100644
index 000000000..e7f6d8155
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/pac-auth.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/pac-auth.js
new file mode 100644
index 000000000..0eb4ec6a3
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/prompt-detector.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/prompt-detector.js
new file mode 100644
index 000000000..60474128b
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/resolver-loader.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/resolver-loader.js
new file mode 100644
index 000000000..5c5c2bb67
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/scrubber.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/scrubber.js
new file mode 100644
index 000000000..517188404
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/session.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/session.js
new file mode 100644
index 000000000..cbf89884d
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/telemetry-config.js
new file mode 100644
index 000000000..8950e32c5
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/telemetry-config.js
@@ -0,0 +1,131 @@
+#!/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" +
+ " Telemetry records usage fields for approved create-site/localization\n" +
+ " choices, canonical locales, public package names/versions, stable\n" +
+ " validation outcomes, and localization completion.\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" +
+ " free-text requirements, Dataverse URLs, credentials, usernames,\n" +
+ " hostnames, private-use locale subtags, evidence URLs, or raw errors."
+ );
+}
+
+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-apps-mobile-extension/scripts/lib/telemetry/lib/user-config.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/lib/user-config.js
new file mode 100644
index 000000000..ea0597f73
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/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-apps-mobile-extension/scripts/lib/telemetry/routing.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/routing.js
new file mode 100644
index 000000000..fd7391cbf
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/routing.js
@@ -0,0 +1,101 @@
+"use strict";
+
+const crypto = require("node:crypto");
+const fs = require("node:fs");
+const https = require("node:https");
+const path = require("node:path");
+const { PLUGIN_NAME, UUID } = require("./schema");
+const { destination } = require("./config");
+
+const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
+const EU_GEOS = new Set(["eu", "uk", "de", "fr", "no", "ch"]);
+const ROW_GEOS = new Set(["us", "br", "jp", "in", "au", "ca", "as", "za", "ae", "kr"]);
+
+function fetchGeo(orgId) {
+ const compact = orgId.replace(/-/g, "");
+ const url = `https://${compact.slice(0, -2)}.${compact.slice(-2)}.organization.api.powerplatform.com/gateway/cluster?api-version=1`;
+ return new Promise(resolve => {
+ let request;
+ let timer;
+ let settled = false;
+ const finish = value => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve(value);
+ };
+ try {
+ request = https.get(url, response => {
+ let text = "";
+ response.setEncoding("utf8");
+ response.on("data", chunk => {
+ text += chunk;
+ if (text.length > 16384) { finish(null); request.destroy(); }
+ });
+ response.on("error", () => finish(null));
+ response.on("end", () => {
+ if (response.statusCode !== 200) return finish(null);
+ try { finish(JSON.parse(text).geoName || null); } catch { finish(null); }
+ });
+ });
+ request.on("error", () => finish(null));
+ timer = setTimeout(() => { finish(null); request.destroy(); }, 5000);
+ } catch { finish(null); }
+ });
+}
+
+function cachePath(directory, orgId) {
+ return path.join(directory, "telemetry", PLUGIN_NAME, "region-cache", orgId.toLowerCase() + ".json");
+}
+
+function readCache(directory, orgId, now) {
+ try {
+ const file = cachePath(directory, orgId);
+ const entry = JSON.parse(fs.readFileSync(file, "utf8"));
+ if (["us", "eu"].includes(entry.region) && Number.isFinite(entry.expiresAt) &&
+ entry.expiresAt > now && entry.expiresAt <= now + CACHE_TTL_MS) return entry.region;
+ fs.rmSync(file, { force: true });
+ } catch {}
+ return null;
+}
+
+function writeCache(directory, orgId, region, now) {
+ const file = cachePath(directory, orgId);
+ const temporary = file + "." + crypto.randomUUID() + ".tmp";
+ try {
+ const cacheDir = path.dirname(file);
+ fs.mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
+ for (const entry of fs.readdirSync(cacheDir)) {
+ const candidate = path.join(cacheDir, entry);
+ if ((entry.endsWith(".json") || entry.endsWith(".tmp")) &&
+ fs.statSync(candidate).mtimeMs < now - CACHE_TTL_MS) fs.rmSync(candidate, { force: true });
+ }
+ fs.writeFileSync(temporary, JSON.stringify({ region, expiresAt: now + CACHE_TTL_MS }), { mode: 0o600, flag: "wx" });
+ fs.renameSync(temporary, file);
+ } catch {
+ try { fs.rmSync(temporary, { force: true }); } catch {}
+ }
+}
+
+async function resolveDestination(config, data, cloud, directory, options = {}) {
+ const stamp = typeof cloud === "string" ? cloud.trim().toLowerCase() : "";
+ if (stamp && stamp !== "public") return null;
+ if (!data.orgId) {
+ if (data.tenantId || data.eventInfo?.aadObjectId || stamp) return null;
+ return destination(config, "us");
+ }
+ if (!UUID.test(data.orgId) || stamp !== "public") return null;
+ const now = options.now ?? Date.now();
+ const cached = readCache(directory, data.orgId, now);
+ if (cached) return destination(config, cached);
+ let geo;
+ try { geo = await (options.fetchGeo || fetchGeo)(data.orgId); } catch { return null; }
+ if (typeof geo !== "string") return null;
+ const normalized = geo.toLowerCase();
+ const region = EU_GEOS.has(normalized) ? "eu" : ROW_GEOS.has(normalized) ? "us" : null;
+ if (!region) return null;
+ writeCache(directory, data.orgId, region, now);
+ return destination(config, region);
+}
+
+module.exports = { resolveDestination, CACHE_TTL_MS };
\ No newline at end of file
diff --git a/plugins/power-apps-mobile-extension/scripts/lib/telemetry/schema.js b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/schema.js
new file mode 100644
index 000000000..81dad0417
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/scripts/lib/telemetry/schema.js
@@ -0,0 +1,89 @@
+"use strict";
+
+const PLUGIN_NAME = "power-apps-mobile-extension";
+const STREAM_NAME = "event";
+const TRACKED_SKILLS = Object.freeze([
+ "design-native-extension-feature",
+ "generate-native-extension",
+ "generate-pcf-companion",
+ "test-native-extension",
+ "generate-ppmplugin",
+ "publish-pcf-companion",
+ "debug-extension",
+ "generate-ppmplugin-manifest",
+ "build-android-binary",
+ "build-ios-binary",
+ "assemble-ppmplugin",
+ "audit-ppmplugin",
+]);
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const VERSION = /^v?\d+(?:\.\d+){0,3}(?:[-+][0-9A-Za-z.-]+)?$/;
+const AGENTS = new Set([
+ "Claude Code", "Copilot CLI", "GitHub Copilot", "GitHub Copilot CLI",
+ "Codex", "OpenCode", "Hermes", "OpenClaw",
+]);
+
+function matches(value, pattern, maxLength = 128) {
+ return typeof value === "string" && value.length <= maxLength && pattern.test(value);
+}
+
+function sanitizeData(input) {
+ if (!input || typeof input !== "object" || Array.isArray(input)) return null;
+ if (input.pluginName !== PLUGIN_NAME || input.eventName !== "skill_started" ||
+ input.eventType !== "Trace" || input.severity !== "Info" ||
+ !TRACKED_SKILLS.includes(input.skillName) ||
+ !matches(input.pluginVersion, VERSION, 64) ||
+ !matches(input.sessionId, /^[A-Za-z0-9_-]+$/) ||
+ !matches(input.correlationId, UUID) ||
+ !["Windows", "Mac", "Linux"].includes(input.osName) ||
+ !matches(input.osVersion, /^[0-9][A-Za-z0-9._+-]*$/, 80) ||
+ !matches(input.nodeVersion, /^v\d+$/, 16)) return null;
+
+ const data = {
+ eventName: "skill_started",
+ eventType: "Trace",
+ severity: "Info",
+ pluginName: PLUGIN_NAME,
+ pluginVersion: input.pluginVersion,
+ skillName: input.skillName,
+ sessionId: input.sessionId,
+ correlationId: input.correlationId,
+ osName: input.osName,
+ osVersion: input.osVersion,
+ nodeVersion: input.nodeVersion,
+ };
+ for (const key of ["orgId", "tenantId"]) {
+ if (matches(input[key], UUID)) data[key] = input[key];
+ }
+ if (AGENTS.has(input.aiAgentName)) data.aiAgentName = input.aiAgentName;
+ if (data.aiAgentName && matches(input.aiAgentVersion, VERSION, 64)) {
+ data.aiAgentVersion = input.aiAgentVersion;
+ }
+ if (matches(input.pacCliVersion, VERSION, 64)) data.pacCliVersion = input.pacCliVersion;
+ if (input.eventInfo && !Array.isArray(input.eventInfo) &&
+ matches(input.eventInfo.aadObjectId, UUID)) {
+ data.eventInfo = { aadObjectId: input.eventInfo.aadObjectId };
+ }
+ return data;
+}
+
+function buildEnvelope(data, time, instrumentationKey) {
+ const sanitized = sanitizeData(data);
+ if (!sanitized || !Number.isFinite(Date.parse(time))) return null;
+ const { eventName, ...dimensions } = sanitized;
+ return {
+ ver: "4.0",
+ name: STREAM_NAME,
+ time,
+ iKey: "o:" + instrumentationKey.split("-")[0],
+ data: {
+ clientType: PLUGIN_NAME,
+ event_Name: eventName,
+ timestamp: time,
+ session_Id: sanitized.sessionId,
+ customDimensions: JSON.stringify(dimensions),
+ },
+ };
+}
+
+module.exports = { PLUGIN_NAME, STREAM_NAME, TRACKED_SKILLS, UUID, sanitizeData, buildEnvelope };
diff --git a/plugins/power-apps-mobile-extension/scripts/telemetry-config.js b/plugins/power-apps-mobile-extension/scripts/telemetry-config.js
new file mode 100644
index 000000000..4f230c366
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/scripts/telemetry-config.js
@@ -0,0 +1,51 @@
+"use strict";
+
+const { PLUGIN_NAME } = require("./lib/telemetry/schema");
+const { readConfig, enabled, configDir } = require("./lib/telemetry/config");
+const { effectiveTelemetryChoice, setTelemetryChoice, telemetryOptOutEnvVarName } = require("./lib/telemetry/lib/user-config");
+const { pluginLogDir, latestSessionLog } = require("./lib/telemetry/lib/local-log");
+
+function run(action = "status", options = {}) {
+ const selected = ["on", "off", "status"].includes(action) ? action : "status";
+ const env = options.env || process.env;
+ const directory = configDir(env);
+ if (selected !== "status" && !setTelemetryChoice(directory, PLUGIN_NAME, selected)) {
+ return { code: 1, output: "Could not save the telemetry preference: configuration is not writable." };
+ }
+ const active = enabled(readConfig(options.configPath));
+ const preference = effectiveTelemetryChoice(directory, PLUGIN_NAME, env);
+ const lines = [];
+ if (selected !== "status") lines.push(`Saved transmission preference: ${selected.toUpperCase()}.`);
+ if (!active) {
+ lines.push("Telemetry: HARD-DISABLED by plugin configuration. No event collection, local telemetry logging or transmission.");
+ lines.push("A saved ON preference cannot override the maintainer-controlled release switch.");
+ } else if (preference === "off") {
+ lines.push("Telemetry transmission: OFF. Local diagnostic logging continues, including available identity fields.");
+ } else {
+ lines.push("Telemetry transmission: ON (default). Sending requires a supported, resolved destination.");
+ }
+ lines.push(`Transmission choice after the release gate: ${active && preference !== "off" ? "ON" : "OFF"}.`);
+ lines.push(`Environment override: ${telemetryOptOutEnvVarName(PLUGIN_NAME)}=1 or true forces transmission OFF, even after the on command.`);
+ lines.push("When enabled, events include skill/plugin, OS/Node, agent/PAC versions, session/correlation IDs and available organization, tenant and Entra user object IDs.");
+ lines.push("No prompts, arguments, source code, paths, credentials, free-text errors, outcomes, durations or build targets are recorded.");
+ lines.push("Opt-out stops transmission only, not the local mirror. Neither off nor hard-disable deletes previously collected data.");
+ lines.push(`Logs directory: ${pluginLogDir(directory, PLUGIN_NAME)}`);
+ const latest = latestSessionLog(directory, PLUGIN_NAME);
+ if (latest) lines.push(`Most recent session log: ${latest}`);
+ lines.push(`Control with /${PLUGIN_NAME}:telemetry on|off|status.`);
+ return { code: 0, output: lines.join("\n") };
+}
+
+if (require.main === module) {
+ const index = process.argv.indexOf("--action");
+ try {
+ const result = run(index >= 0 ? process.argv[index + 1] : process.argv[2]);
+ process.stdout.write(result.output + "\n");
+ process.exitCode = result.code;
+ } catch {
+ process.stderr.write("Unable to read or update the telemetry preference.\n");
+ process.exitCode = 1;
+ }
+}
+
+module.exports = { run };
\ No newline at end of file
diff --git a/plugins/power-apps-mobile-extension/scripts/tests/telemetry.test.js b/plugins/power-apps-mobile-extension/scripts/tests/telemetry.test.js
new file mode 100644
index 000000000..c2347e2a8
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/scripts/tests/telemetry.test.js
@@ -0,0 +1,556 @@
+"use strict";
+
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const { test } = require("node:test");
+const { PLUGIN_NAME, STREAM_NAME, TRACKED_SKILLS, sanitizeData, buildEnvelope } = require("../lib/telemetry/schema");
+const os = require("node:os");
+const { dispatch, fireAndForget } = require("../lib/telemetry/dispatcher");
+const { resolveDestination, CACHE_TTL_MS } = require("../lib/telemetry/routing");
+const { setTelemetryChoice, telemetryOptOutEnvVarName } = require("../lib/telemetry/lib/user-config");
+const { handle, invocation } = require("../../hooks/run-telemetry");
+const { run: control } = require("../telemetry-config");
+const { spawnSync } = require("node:child_process");
+const https = require("node:https");
+const { EventEmitter } = require("node:events");
+const { appendLocal, pruneOldSessions, ROTATE_BYTES } = require("../lib/telemetry/lib/local-log");
+
+function fixture(context, disabled = false) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "pam-telemetry-test-"));
+ context.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const config = { ...require("../lib/telemetry/ikey.json"), disabled };
+ const configPath = path.join(directory, "ikey.json");
+ fs.writeFileSync(configPath, JSON.stringify(config));
+ return { directory, config, configPath, env: { POWER_PLATFORM_SKILLS_CONFIG_DIR: directory } };
+}
+
+function sample() {
+ return {
+ eventName: "skill_started", eventType: "Trace", severity: "Info",
+ pluginName: PLUGIN_NAME, pluginVersion: "0.1.0", skillName: "generate-ppmplugin",
+ sessionId: "test-session", correlationId: "00000000-0000-4000-8000-000000000001",
+ osName: "Mac", osVersion: "24.0.0", nodeVersion: "v20",
+ };
+}
+
+test("ships enabled with the agreed stream and only ROW/EU endpoints", () => {
+ const config = require("../lib/telemetry/ikey.json");
+ assert.equal(config.disabled, false);
+ assert.equal(STREAM_NAME, "event");
+ assert.equal(config.event_stream_name, STREAM_NAME);
+ assert.deepEqual(Object.keys(config.regions), ["us", "eu"]);
+ assert.equal(config.regions.us.instrumentation_key,
+ "5c3a61f48d7c4522912765ae7465ab5c-f9cba087-ed82-4591-93d0-ce7eb8bbfcf5-7021");
+ assert.equal(config.regions.us.instrumentation_key, config.regions.eu.instrumentation_key);
+ assert.equal(config.regions.us.collector_url, "https://browser.events.data.microsoft.com/OneCollector/1.0/");
+ assert.equal(config.regions.eu.collector_url, "https://eu-mobile.events.data.microsoft.com/OneCollector/1.0/");
+});
+
+test("PAC wrapper uses absolute native executables without a shell", () => {
+ const script = String.raw`
+ const assert = require("node:assert/strict");
+ const childProcess = require("node:child_process");
+ const calls = [];
+ childProcess.execFileSync = (...args) => { calls.push(args); return "metadata"; };
+ const { pacExec } = require(${JSON.stringify(path.resolve(__dirname, "../../hooks/run-telemetry"))});
+ const executable = "C:\\trusted-tools\\pac.exe";
+ const dependencies = {
+ platform: "win32", env: { PATH: ";.;relative;C:\\trusted-tools", PATHEXT: ".CMD;.BAT" },
+ exists: candidate => candidate === executable,
+ };
+ for (const args of [["auth", "who"], ["--version"]]) {
+ assert.equal(pacExec("pac", args, { timeout: 1000 }, dependencies), "metadata");
+ const call = calls.at(-1);
+ assert.equal(call[0], executable);
+ assert.deepEqual(call[1], args);
+ assert.equal(call[2].shell, false);
+ assert.equal(call[2].windowsHide, true);
+ assert.equal(call[2].timeout, 1000);
+ }
+ assert.throws(() => pacExec("pac", ["auth", "create"], {}, dependencies));
+ assert.throws(() => pacExec("cmd.exe", ["--version"], {}, dependencies));
+ assert.throws(() => pacExec("pac", ["--version"], {}, {
+ ...dependencies, exists: () => false,
+ }), { code: "ENOENT" });
+ assert.equal(calls.length, 2);
+ `;
+ const result = spawnSync(process.execPath, ["-e", script], { encoding: "utf8", timeout: 3000 });
+ assert.equal(result.status, 0, result.stderr);
+});
+
+test("tracks exactly the 12 workflow skills, never the telemetry control", () => {
+ const skillsDir = path.resolve(__dirname, "../../skills");
+ assert.deepEqual([...TRACKED_SKILLS].sort(), fs.readdirSync(skillsDir).filter(name => name !== "telemetry").sort());
+});
+
+test("keeps the reviewed fields and only aadObjectId within eventInfo", () => {
+ const data = sanitizeData({
+ ...sample(), orgId: "00000000-0000-4000-8000-000000000002",
+ tenantId: "00000000-0000-4000-8000-000000000003", aiAgentName: "Copilot CLI",
+ aiAgentVersion: "0.0.1", pacCliVersion: "1.40.1", prompt: "private content",
+ outcome: "success", durationMs: 10, eventInfo: {
+ aadObjectId: "00000000-0000-4000-8000-000000000004",
+ framework: "react", prompt: "private content", nested: { secret: "never" },
+ },
+ });
+ assert.deepEqual(Object.keys(data.eventInfo), ["aadObjectId"]);
+ assert.equal(Object.keys(data).length, 17);
+ assert.ok(!JSON.stringify(data).includes("private"));
+ assert.ok(!("outcome" in data));
+ const envelope = buildEnvelope(data, "2026-09-27T00:00:00.000Z", "project-test-key");
+ assert.equal(envelope.name, STREAM_NAME);
+ assert.equal(envelope.iKey, "o:project");
+ const dimensions = JSON.parse(envelope.data.customDimensions);
+ assert.deepEqual({ eventName: envelope.data.event_Name, ...dimensions }, data);
+ assert.deepEqual(dimensions.eventInfo, data.eventInfo);
+ assert.equal(typeof data.eventInfo, "object");
+});
+
+test("builds the shared event wire shape without changing the local payload", () => {
+ const data = { ...sample(), clientType: "PowerAppsNative", prompt: "private content", eventInfo: { prompt: "private content" } };
+ const original = JSON.stringify(data);
+ const time = "2026-10-08T19:27:21.096Z";
+ const { eventName, ...dimensions } = sample();
+ assert.deepEqual(buildEnvelope(data, time, "project-test-key"), {
+ ver: "4.0", name: "event", time, iKey: "o:project",
+ data: {
+ clientType: "power-apps-mobile-extension",
+ event_Name: eventName, timestamp: time, session_Id: data.sessionId,
+ customDimensions: JSON.stringify(dimensions),
+ },
+ });
+ assert.equal(JSON.stringify(data), original);
+ assert.equal(buildEnvelope(data, "invalid timestamp", "project-test-key"), null);
+ assert.equal(buildEnvelope({ ...data, pluginName: "mobile-app" }, time, "project-test-key"), null);
+});
+
+test("omits absent or invalid optional identifiers and metadata", () => {
+ const data = sanitizeData({ ...sample(), orgId: "https://private.example", tenantId: "[email protected]",
+ eventInfo: [{ aadObjectId: "private" }], aiAgentName: "private host", pacCliVersion: "version with private path" });
+ assert.deepEqual(data, sample());
+});
+
+test("rejects untracked names, invalid event metadata and unsafe session paths", () => {
+ for (const override of [
+ { skillName: "telemetry" }, { skillName: "arbitrary customer name" },
+ { eventName: "skill_completed" }, { pluginName: "power-pages" },
+ { sessionId: "../outside" }, { correlationId: "not-a-uuid" },
+ { osVersion: "private host" }, { nodeVersion: "v20.1.0" }, { pluginVersion: "1.customer-name" },
+ ]) assert.equal(sanitizeData({ ...sample(), ...override }), null);
+});
+
+test("hard-off, missing, malformed and partial config cause no logging, routing or spawn", async context => {
+ const fixtureData = fixture(context);
+ const unexpected = () => { throw new Error("Unexpected telemetry work"); };
+ for (const content of ["{", "null", "[]", "{}", JSON.stringify({ ...fixtureData.config, disabled: true })]) {
+ fs.writeFileSync(fixtureData.configPath, content);
+ const options = { ...fixtureData, appendLocal: unexpected, post: unexpected, spawn: unexpected };
+ assert.equal(await dispatch({ name: STREAM_NAME, data: sample() }, options), "disabled");
+ fireAndForget({ name: STREAM_NAME, data: sample() }, options);
+ }
+ fs.rmSync(fixtureData.configPath);
+ assert.equal(await dispatch({ name: STREAM_NAME, data: sample() }, fixtureData), "disabled");
+ assert.ok(!fs.existsSync(path.join(fixtureData.directory, "telemetry")));
+});
+
+test("user opt-out retains a sanitized mirror with identity but performs no routing or post", async context => {
+ const fixtureData = fixture(context);
+ setTelemetryChoice(fixtureData.directory, PLUGIN_NAME, "off");
+ let networkCalls = 0;
+ const data = { ...sample(), orgId: "00000000-0000-4000-8000-000000000002",
+ eventInfo: { aadObjectId: "00000000-0000-4000-8000-000000000003", prompt: "private" } };
+ const result = await dispatch({ name: STREAM_NAME, data, cloud: "Public" }, {
+ ...fixtureData, routing: { fetchGeo: () => { networkCalls++; return "eu"; } },
+ post: () => { networkCalls++; return true; },
+ });
+ assert.equal(result, "opted-out");
+ assert.equal(networkCalls, 0);
+ const log = path.join(fixtureData.directory, "telemetry", PLUGIN_NAME, "sessions", "test-session", "events.jsonl");
+ const record = JSON.parse(fs.readFileSync(log, "utf8"));
+ assert.equal(record.data.orgId, data.orgId);
+ assert.deepEqual(record.data.eventInfo, { aadObjectId: data.eventInfo.aadObjectId });
+ assert.ok(!fs.existsSync(path.join(fixtureData.directory, "telemetry", PLUGIN_NAME, "region-cache")));
+});
+
+test("env opt-out overrides saved on; disabled env value does not override saved off", async context => {
+ const fixtureData = fixture(context);
+ for (const [choice, envValue] of [["on", "1"], ["on", " TRUE "], ["off", "false"]]) {
+ setTelemetryChoice(fixtureData.directory, PLUGIN_NAME, choice);
+ let posts = 0;
+ assert.equal(await dispatch({ name: STREAM_NAME, data: sample() }, {
+ ...fixtureData, env: { ...fixtureData.env, [telemetryOptOutEnvVarName(PLUGIN_NAME)]: envValue },
+ post: () => { posts++; return true; },
+ }), "opted-out");
+ assert.equal(posts, 0);
+ }
+});
+
+test("enabled unauthenticated event defaults to ROW; enabled public org routes to EU", async context => {
+ const fixtureData = fixture(context);
+ for (const [region, additions, cloud] of [["us", {}, ""], ["eu", { orgId: "00000000-0000-4000-8000-000000000002" }, "Public"]]) {
+ let sent;
+ assert.equal(await dispatch({ name: STREAM_NAME, data: { ...sample(), ...additions }, cloud }, {
+ ...fixtureData, routing: { fetchGeo: async () => "eu" },
+ post: async (target, envelope) => { sent = { target, envelope }; return true; },
+ }), "accepted");
+ assert.equal(sent.target.region, region);
+ assert.equal(sent.envelope.name, STREAM_NAME);
+ const dimensions = JSON.parse(sent.envelope.data.customDimensions);
+ assert.deepEqual({ eventName: sent.envelope.data.event_Name, ...dimensions }, { ...sample(), ...additions });
+ assert.equal(sent.envelope.data.session_Id, sample().sessionId);
+ assert.equal(sent.envelope.data.timestamp, sent.envelope.time);
+ }
+});
+
+test("never routes unsupported clouds or unknown authenticated regions to ROW", async context => {
+ const { config, directory } = fixture(context);
+ const data = { ...sample(), orgId: "00000000-0000-4000-8000-000000000002" };
+ for (const cloud of ["Gov", "USGov", "High", "Dod", "Mooncake", "China", "Internal", "future-cloud", ""]) {
+ let lookups = 0;
+ assert.equal(await resolveDestination(config, data, cloud, directory, { fetchGeo: () => { lookups++; return "us"; } }), null);
+ assert.equal(lookups, 0);
+ }
+ for (const geo of [null, "unrecognized"]) {
+ assert.equal(await resolveDestination(config, data, "Public", directory, { fetchGeo: async () => geo }), null);
+ }
+ assert.equal(await resolveDestination(config, { ...sample(), tenantId: data.orgId }, "", directory), null);
+});
+
+test("region cache avoids repeated lookup, expires and refreshes", async context => {
+ const { config, directory } = fixture(context);
+ const data = { ...sample(), orgId: "00000000-0000-4000-8000-000000000002" };
+ let lookups = 0;
+ const now = Date.now();
+ const fetchGeo = async () => { lookups++; return "eu"; };
+ await resolveDestination(config, data, "Public", directory, { fetchGeo, now });
+ await resolveDestination(config, data, "Public", directory, { fetchGeo, now: now + 100 });
+ assert.equal(lookups, 1);
+ await resolveDestination(config, data, "Public", directory, { fetchGeo, now: now + CACHE_TTL_MS + 1 });
+ assert.equal(lookups, 2);
+});
+
+test("dispatcher rejects malformed events before any mirror or network", async context => {
+ const fixtureData = fixture(context);
+ let writes = 0;
+ for (const input of [null, {}, { name: "PAMAIPluginEvent", data: sample() }, { name: STREAM_NAME, data: { ...sample(), skillName: "telemetry" } }]) {
+ assert.equal(await dispatch(input, { ...fixtureData, appendLocal: () => { writes++; } }), "invalid");
+ }
+ assert.equal(writes, 0);
+});
+
+test("telemetry failures stay non-blocking and do not retry or replay", async context => {
+ const fixtureData = fixture(context);
+ let posts = 0;
+ assert.equal(await dispatch({ name: STREAM_NAME, data: sample() }, {
+ ...fixtureData, appendLocal: () => { throw new Error("disk unavailable"); },
+ post: () => { posts++; throw new Error("offline"); },
+ }), "failed");
+ assert.equal(posts, 1);
+});
+
+test("detached child gets only allowed env and sanitized fields, not secrets", context => {
+ const fixtureData = fixture(context);
+ let options;
+ let serialized;
+ fireAndForget({ name: STREAM_NAME, data: { ...sample(), secret: "private" }, cloud: "private" }, {
+ ...fixtureData, env: { ...fixtureData.env, AZURE_CLIENT_SECRET: "private", NODE_OPTIONS: "--require malicious", PATH: "/bin" },
+ spawn: (executable, args, childOptions) => {
+ options = childOptions;
+ return { on() {}, unref() {}, stdin: { on() {}, end(value) { serialized = value; } } };
+ },
+ });
+ assert.equal(options.env.AZURE_CLIENT_SECRET, undefined);
+ assert.equal(options.env.NODE_OPTIONS, undefined);
+ assert.equal(options.cwd, os.tmpdir());
+ assert.ok(!serialized.includes("private"));
+ assert.equal(JSON.parse(serialized).cloud, "unsupported");
+});
+
+test("transmission controls do not claim success when configuration is unwritable", context => {
+ const { directory } = fixture(context);
+ const notDirectory = path.join(directory, "not-a-directory");
+ fs.writeFileSync(notDirectory, "not a directory");
+ const result = control("off", { env: { POWER_PLATFORM_SKILLS_CONFIG_DIR: notDirectory } });
+ assert.equal(result.code, 1);
+ assert.match(result.output, /not writable/);
+});
+
+test("recognizes qualified prompt and both host tool-input shapes", () => {
+ assert.equal(invocation("prompt", { prompt: `/${PLUGIN_NAME}:generate-native-extension confidential args` }), "generate-native-extension");
+ assert.equal(invocation("pretool", { tool_name: "Skill", tool_input: { skill: `${PLUGIN_NAME}:audit-ppmplugin` } }), "audit-ppmplugin");
+ assert.equal(invocation("pretool", { toolName: "skill", toolArgs: JSON.stringify({ skill: `${PLUGIN_NAME}:test-native-extension` }) }), "test-native-extension");
+ assert.equal(invocation("prompt", { prompt: "/generate-ppmplugin" }), "generate-ppmplugin");
+ assert.equal(invocation("prompt", { prompt: "/generate-native-extension", pluginName: PLUGIN_NAME }), "generate-native-extension");
+});
+
+test("emits a start for every bare workflow skill across prompt and tool payloads", context => {
+ const fixtureData = fixture(context);
+ const captured = [];
+ const options = { ...fixtureData,
+ readAuth: () => null, readAgent: () => ({}), readPacVersion: () => "",
+ emit: event => captured.push(event),
+ };
+ for (const skill of TRACKED_SKILLS) {
+ const invocations = [
+ ["prompt", { prompt: `/${skill} private arguments` }],
+ ["pretool", { tool_name: "Skill", tool_input: { skill } }],
+ ["pretool", { toolName: "skill", toolInput: { skill } }],
+ ["pretool", { toolName: "skill", toolArgs: JSON.stringify({ skill }) }],
+ ];
+ for (const [mode, payload] of invocations) {
+ const before = captured.length;
+ assert.equal(handle(mode, payload, options), true, `${mode}: ${skill}`);
+ assert.equal(captured.length, before + 1);
+ assert.equal(captured[before].name, STREAM_NAME);
+ assert.equal(captured[before].data.eventName, "skill_started");
+ assert.equal(captured[before].data.pluginName, PLUGIN_NAME);
+ assert.equal(captured[before].data.skillName, skill);
+ }
+ }
+ assert.equal(captured.length, TRACKED_SKILLS.length * 4);
+ assert.ok(!JSON.stringify(captured).includes("private arguments"));
+});
+
+test("ignores other plugins, prose, telemetry control and untracked names", () => {
+ for (const prompt of ["please /generate-ppmplugin", "/telemetry off", `/${PLUGIN_NAME}:telemetry off`,
+ "/another-plugin:generate-native-extension", "/power-pages:create-site", "/unrelated"]) {
+ assert.equal(invocation("prompt", { prompt }), null);
+ }
+ assert.equal(invocation("pretool", { tool_name: "Bash", tool_input: { skill: `${PLUGIN_NAME}:generate-ppmplugin` } }), null);
+ assert.equal(invocation("pretool", { toolArgs: "invalid json" }), null);
+});
+
+test("explicit other-plugin hints skip all telemetry work for every tracked skill", context => {
+ const fixtureData = fixture(context);
+ let work = 0;
+ const unexpected = () => { work++; };
+ const options = { ...fixtureData,
+ readAuth: unexpected, readAgent: unexpected, readPacVersion: unexpected, emit: unexpected,
+ };
+ for (const skill of TRACKED_SKILLS) {
+ for (const name of [skill, `${PLUGIN_NAME}:${skill}`]) {
+ const invocations = [
+ ["prompt", { prompt: `/${name}`, pluginName: "another-plugin" }],
+ ["pretool", { toolName: "skill", toolArgs: { skill: name, pluginName: "another-plugin" } }],
+ ["pretool", { tool_name: "Skill", tool_input: JSON.stringify({ skill: name, plugin_name: "another-plugin" }) }],
+ ["pretool", { toolName: "skill", toolInput: { skill: name }, plugin_name: "another-plugin" }],
+ ];
+ for (const [mode, payload] of invocations) {
+ assert.equal(handle(mode, payload, options), false, `${mode}: ${name}`);
+ }
+ }
+ }
+ assert.equal(work, 0);
+});
+
+test("hook hard-off and untracked invocations skip PAC, agent work and emit", context => {
+ const fixtureData = fixture(context);
+ const disabledFixture = fixture(context, true);
+ let work = 0;
+ const options = { readAuth: () => { work++; }, readAgent: () => { work++; }, readPacVersion: () => { work++; }, emit: () => { work++; } };
+ assert.equal(handle("prompt", { prompt: "/generate-ppmplugin" }, { ...disabledFixture, ...options }), false);
+ assert.equal(handle("prompt", { prompt: "/unrelated" }, { ...fixtureData, ...options }), false);
+ assert.equal(work, 0);
+});
+
+test("hook emits starts only, groups host session and generates per-event IDs", context => {
+ const fixtureData = fixture(context);
+ const captured = [];
+ const options = { ...fixtureData,
+ readAuth: () => ({ orgId: "00000000-0000-4000-8000-000000000002", tenantId: "00000000-0000-4000-8000-000000000003",
+ objectId: "00000000-0000-4000-8000-000000000004", cloud: "Public", username: "private" }),
+ readAgent: () => ({ aiAgentName: "Copilot CLI", aiAgentVersion: "0.0.1" }), readPacVersion: () => "1.40.1",
+ emit: event => captured.push(event),
+ };
+ for (let count = 0; count < 2; count++) assert.equal(handle("prompt", { prompt: "/generate-ppmplugin private", session_id: "shared-session" }, options), true);
+ assert.equal(captured[0].data.sessionId, captured[1].data.sessionId);
+ assert.notEqual(captured[0].data.correlationId, captured[1].data.correlationId);
+ assert.equal(captured[0].data.eventName, "skill_started");
+ assert.equal(captured[0].data.pluginVersion, require("../../.plugin/plugin.json").version);
+ assert.equal(captured[0].data.eventInfo.aadObjectId, "00000000-0000-4000-8000-000000000004");
+ assert.ok(!JSON.stringify(captured).includes("private"));
+});
+
+test("PAC and agent failures still produce a minimal start without sign-in", context => {
+ const fixtureData = fixture(context);
+ let captured;
+ const fail = () => { throw new Error("not installed"); };
+ assert.equal(handle("prompt", { prompt: "/audit-ppmplugin" }, {
+ ...fixtureData, readAuth: fail, readAgent: fail, readPacVersion: fail, emit: event => { captured = event; },
+ }), true);
+ assert.equal(captured.data.orgId, undefined);
+ assert.equal(captured.data.eventInfo, undefined);
+ assert.equal(captured.cloud, "");
+});
+
+test("control reports enabled, opted-out and hard-disabled states without changing the release switch", context => {
+ const fixtureData = fixture(context);
+ fs.writeFileSync(path.join(fixtureData.directory, "config.json"), JSON.stringify({ other: 42, telemetry: { "power-pages": "off" } }));
+ assert.match(control("status", { env: fixtureData.env }).output, /transmission: ON \(default\)/);
+ const result = control("on", { env: fixtureData.env });
+ assert.equal(result.code, 0);
+ assert.match(result.output, /transmission: ON/);
+ const saved = JSON.parse(fs.readFileSync(path.join(fixtureData.directory, "config.json"), "utf8"));
+ assert.equal(saved.telemetry[PLUGIN_NAME], "on");
+ assert.equal(saved.telemetry["power-pages"], "off");
+ assert.equal(saved.other, 42);
+ assert.match(control("off", fixtureData).output, /logging continues/);
+ assert.match(control("on", { ...fixtureData, env: { ...fixtureData.env, [telemetryOptOutEnvVarName(PLUGIN_NAME)]: "1" } }).output, /transmission: OFF/);
+ const disabledFixture = fixture(context, true);
+ const disabledOutput = control("on", disabledFixture).output;
+ assert.match(disabledOutput, /HARD-DISABLED/);
+ assert.match(disabledOutput, /Transmission choice after the release gate: OFF/);
+ assert.doesNotMatch(disabledOutput, /Transmission choice after the release gate: ON/);
+ assert.equal(JSON.parse(fs.readFileSync(disabledFixture.configPath, "utf8")).disabled, true);
+ assert.ok(!fs.existsSync(path.join(fixtureData.directory, "telemetry")));
+});
+
+test("control status is read-only and invalid action defaults to status", context => {
+ const fixtureData = fixture(context);
+ assert.equal(control("unexpected", fixtureData).code, 0);
+ assert.ok(!fs.existsSync(path.join(fixtureData.directory, "config.json")));
+});
+
+test("actual shipped hooks and dispatcher ignore untracked or invalid input without side effects", context => {
+ const fixtureData = fixture(context);
+ for (const [script, args] of [["../../hooks/run-telemetry.js", ["prompt"]], ["../lib/telemetry/dispatcher.js", []]]) {
+ const result = spawnSync(process.execPath, [path.resolve(__dirname, script), ...args], {
+ input: JSON.stringify({ prompt: "/unrelated", name: "invalid", data: sample() }),
+ encoding: "utf8", timeout: 3000, env: { PATH: "", ...fixtureData.env },
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, "");
+ assert.equal(result.stderr, "");
+ }
+ assert.ok(!fs.existsSync(path.join(fixtureData.directory, "telemetry")));
+});
+
+test("refuses missing flag, redirected endpoints and unprovisioned keys", async context => {
+ const fixtureData = fixture(context);
+ for (const mutation of [
+ config => { delete config.disabled; },
+ config => { config.regions.eu.collector_url = "https://unapproved.example/"; },
+ config => { config.regions.us.instrumentation_key = "PLACEHOLDER_REPLACE_BEFORE_SHIPPING"; },
+ config => { config.event_stream_name = "PAMAIPluginEvent"; },
+ ]) {
+ const config = JSON.parse(JSON.stringify(fixtureData.config));
+ mutation(config);
+ fs.writeFileSync(fixtureData.configPath, JSON.stringify(config));
+ assert.equal(await dispatch({ name: STREAM_NAME, data: sample() }, fixtureData), "disabled");
+ }
+});
+
+test("real request builder uses CS4.0, approved URL and x-apikey without real network", async context => {
+ const fixtureData = fixture(context);
+ let recorded;
+ let requests = 0;
+ context.mock.method(https, "request", (url, options, callback) => {
+ requests++;
+ const request = new EventEmitter();
+ request.destroy = () => {};
+ request.end = body => {
+ recorded = { url, options, body };
+ queueMicrotask(() => {
+ const response = new EventEmitter();
+ response.statusCode = 200;
+ response.resume = () => {};
+ callback(response);
+ response.emit("end");
+ });
+ };
+ return request;
+ });
+ const data = { ...sample(), eventInfo: { aadObjectId: "00000000-0000-4000-8000-000000000003" },
+ orgId: "00000000-0000-4000-8000-000000000002" };
+ assert.equal(await dispatch({ name: STREAM_NAME, data, cloud: "Public" }, { ...fixtureData, routing: { fetchGeo: async () => "eu" } }), "accepted");
+ assert.equal(requests, 1);
+ assert.equal(recorded.url, fixtureData.config.regions.eu.collector_url);
+ assert.equal(recorded.options.headers["x-apikey"], fixtureData.config.regions.eu.instrumentation_key);
+ assert.equal(recorded.options.headers["Content-Length"], Buffer.byteLength(recorded.body));
+ assert.ok(recorded.body.endsWith("\n"));
+ const envelope = JSON.parse(recorded.body);
+ assert.equal(envelope.name, STREAM_NAME);
+ assert.equal(envelope.ver, "4.0");
+ assert.deepEqual({ eventName: envelope.data.event_Name, ...JSON.parse(envelope.data.customDimensions) }, data);
+ assert.equal(envelope.data.timestamp, envelope.time);
+ assert.equal(envelope.data.session_Id, data.sessionId);
+ const log = path.join(fixtureData.directory, "telemetry", PLUGIN_NAME, "sessions", "test-session", "events.jsonl");
+ const record = JSON.parse(fs.readFileSync(log, "utf8"));
+ assert.equal(envelope.time, record.time);
+ assert.deepEqual(record.data, data);
+});
+
+test("public region lookup uses only validated org URL and parses geo response", async context => {
+ const fixtureData = fixture(context);
+ let requested;
+ context.mock.method(https, "get", (url, callback) => {
+ requested = url;
+ const request = new EventEmitter();
+ request.destroy = () => {};
+ queueMicrotask(() => {
+ const response = new EventEmitter();
+ response.statusCode = 200;
+ response.setEncoding = () => {};
+ callback(response);
+ response.emit("data", JSON.stringify({ geoName: "eu" }));
+ response.emit("end");
+ });
+ return request;
+ });
+ const destination = await resolveDestination(fixtureData.config, { ...sample(), orgId: "00000000-0000-4000-8000-000000000002" }, "Public", fixtureData.directory);
+ assert.equal(destination.region, "eu");
+ assert.equal(new URL(requested).hostname, "000000000000400080000000000000.02.organization.api.powerplatform.com");
+});
+
+test("mirror cleanup prunes stale sessions and rollover preserves old contents", context => {
+ const { directory } = fixture(context);
+ const options = { configDir: directory };
+ appendLocal({ data: sample() }, options);
+ const sessions = path.join(directory, "telemetry", PLUGIN_NAME, "sessions");
+ const old = path.join(sessions, "test-session", "events.jsonl");
+ const staleTime = new Date(Date.now() - 15 * 24 * 60 * 60 * 1000);
+ fs.utimesSync(old, staleTime, staleTime);
+ appendLocal({ data: { ...sample(), sessionId: "new-session" } }, options);
+ assert.ok(!fs.existsSync(old));
+ const recent = path.join(sessions, "new-session", "events.jsonl");
+ fs.truncateSync(recent, ROTATE_BYTES + 1);
+ appendLocal({ data: { ...sample(), sessionId: "new-session" } }, options);
+ assert.equal(fs.readdirSync(path.dirname(recent)).filter(name => name.endsWith(".old")).length, 1);
+ pruneOldSessions(directory, PLUGIN_NAME);
+ assert.ok(fs.existsSync(recent));
+});
+
+test("registered hook commands honor hard-disable even with spaces in plugin root", context => {
+ const fixtureData = fixture(context);
+ const copiedRoot = path.join(fixtureData.directory, "plugin with spaces");
+ fs.cpSync(path.resolve(__dirname, "../.."), copiedRoot, { recursive: true });
+ fs.writeFileSync(path.join(copiedRoot, "scripts/lib/telemetry/ikey.json"), JSON.stringify({ ...fixtureData.config, disabled: true }));
+ const hooks = require("../../hooks/hooks.json").hooks;
+ assert.deepEqual(Object.keys(hooks), ["PreToolUse", "UserPromptSubmit"]);
+ for (const name of Object.keys(hooks)) {
+ const command = hooks[name][0].hooks[0].command;
+ for (const rootVariable of ["PLUGIN_ROOT", "CLAUDE_PLUGIN_ROOT"]) {
+ const result = spawnSync(command, {
+ shell: true, input: JSON.stringify({ prompt: `/${PLUGIN_NAME}:generate-ppmplugin`, tool_input: { skill: `${PLUGIN_NAME}:generate-ppmplugin` } }),
+ env: { PATH: path.dirname(process.execPath), [rootVariable]: copiedRoot, ...fixtureData.env },
+ timeout: 3000, encoding: "utf8",
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, "");
+ assert.equal(result.stderr, "");
+ }
+ }
+ assert.ok(!fs.existsSync(path.join(fixtureData.directory, "telemetry")));
+});
+
+test("support skill and all relative documentation links are self-contained", () => {
+ const root = path.resolve(__dirname, "../..");
+ const skill = fs.readFileSync(path.join(root, "skills/telemetry/SKILL.md"), "utf8");
+ for (const match of skill.matchAll(/\]\(([^)]+)\)/g)) {
+ const target = path.resolve(root, "skills/telemetry", match[1]);
+ assert.ok(target.startsWith(root + path.sep));
+ assert.ok(fs.existsSync(target), target);
+ }
+ assert.equal(fs.readFileSync(path.join(root, ".plugin/plugin.json"), "utf8"), fs.readFileSync(path.join(root, ".claude-plugin/plugin.json"), "utf8"));
+});
diff --git a/plugins/power-apps-mobile-extension/shared/prereq-check.md b/plugins/power-apps-mobile-extension/shared/prereq-check.md
index b6d2403a8..a26e8cc60 100644
--- a/plugins/power-apps-mobile-extension/shared/prereq-check.md
+++ b/plugins/power-apps-mobile-extension/shared/prereq-check.md
@@ -33,6 +33,14 @@ The plugin itself is markdown + scripts (zero install) and uses public tooling a
Each skill runs **only the check below that matches it** (per [`./shared-instructions.md`](./shared-instructions.md) §1.5). When in doubt, run less — a missing build dependency surfaces naturally via the command that fails, whose failure handler points back here.
+### `/telemetry` - Node.js only
+
+The transmission-preference command needs Node.js 20+, not npm, PAC, sign-in,
+native tools or a control project. Check `node --version` only when Node's presence
+is unknown; if missing, give the public Node installation link and stop. Never
+install tools or request authentication solely to collect telemetry. See
+[`telemetry.md`](./telemetry.md) for the current release state and controls.
+
Exit codes: `0` = pass; `1` = hard failure (user must fix, or confirm an auto-fix below).
> **No "baseline" one-liner in this track.** Each skill runs *only its own* check below. No package-feed or source-control authentication is required, so if a skill's Step 1 says "run the baseline one-liner," read it as "run the matching per-skill check below."
diff --git a/plugins/power-apps-mobile-extension/shared/shared-instructions.md b/plugins/power-apps-mobile-extension/shared/shared-instructions.md
index 05814b78e..fe5d94a7f 100644
--- a/plugins/power-apps-mobile-extension/shared/shared-instructions.md
+++ b/plugins/power-apps-mobile-extension/shared/shared-instructions.md
@@ -55,6 +55,11 @@ Every skill operates **entirely on the control's own working tree plus public pa
## 1. Read-first protocol
+The `/telemetry` support skill is an exception to the authoring read-first and
+artifact prerequisites below: after reading this file, follow
+[`telemetry.md`](./telemetry.md) and the skill's local control workflow only.
+It needs Node.js 20+, not PAC, authentication, a control project or native tools.
+
At Step 1 of every skill:
1. Read this file (`shared/shared-instructions.md`).
2. Read [`shared/prereq-check.md`](./prereq-check.md) and run the sanity-check one-liner that matches the skill's needs.
@@ -86,6 +91,7 @@ Per-skill check matrix:
| `/build-ios-binary` | Mac + Xcode | Runs `xcodebuild archive` on a throwaway staging copy. Mac-only. |
| `/assemble-ppmplugin` | `jar` (JDK) | `jar cMf` over the staged manifest + slices. |
| `/audit-ppmplugin` | `jar` (JDK); `dexdump`/`strings` optional | Unzips + static checks against the wrap-runtime contract. |
+| `/telemetry` | Node.js 20+ only | Reads/sets the per-user transmission preference; no auth or native build work. |
**When in doubt, run less.** A missing build dependency surfaces naturally via the command that fails (e.g. a missing `platforms;android-35` makes Gradle fail resource linking → failure handler points back to `prereq-check.md`). Pre-checking is not free — it slows every run and surfaces failures unrelated to what the skill is about to do.
diff --git a/plugins/power-apps-mobile-extension/shared/telemetry.md b/plugins/power-apps-mobile-extension/shared/telemetry.md
new file mode 100644
index 000000000..03db8c057
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/shared/telemetry.md
@@ -0,0 +1,184 @@
+# Skill Usage Telemetry
+
+## Current State
+
+This release has skill-usage telemetry **enabled**, with transmission on by default.
+Recognized skill starts produce local records containing only the fields listed
+below. Transmission honors user/environment opt-outs and requires supported region
+resolution. Opt-out does not stop local logging. Native controls and generated
+PCFs are not instrumented.
+
+The maintainer kill switch remains available: setting `disabled` to `true` stops
+event construction, PAC reads for telemetry, local logging, region resolution,
+dispatcher spawning and transmission. A user preference of `on` cannot override it.
+
+## User Controls
+
+```text
+/power-apps-mobile-extension:telemetry status
+/power-apps-mobile-extension:telemetry off
+/power-apps-mobile-extension:telemetry on
+```
+
+The command uses Node.js 20+ and requires no PAC installation or sign-in. Missing
+or invalid arguments mean `status`. It saves a per-user, per-plugin preference in
+`~/.power-platform-skills/config.json`, leaving other plugin settings intact.
+The configuration root can be overridden with `POWER_PLATFORM_SKILLS_CONFIG_DIR`.
+
+Transmission is **default-on, with no first-run prompt**.
+`off` suppresses future collector transmission and
+region lookup, **not local event construction or logging**. The mirror includes
+available identity fields. A saved choice is read for each event; it does not
+recall requests already in flight or delete old logs/backend data.
+
+For automation, set
+`POWER_PLATFORM_SKILLS_TELEMETRY_POWER_APPS_MOBILE_EXTENSION_OPTOUT=1` or `true`
+in the agent's environment. This overrides a saved `on` choice and stops only
+transmission. Setting it to `0` or `false` does not override a saved `off` choice.
+The plugin team's committed hard-off flag takes precedence over every user choice.
+
+## Events and Fields
+
+The stream is `event`; the only semantic event name is `skill_started`.
+`scripts/lib/telemetry/schema.js` owns the closed schema and 12-skill allowlist.
+
+| Field | Source / restriction |
+|---|---|
+| `time` | UTC timestamp set once by the dispatcher, shared by mirror and wire |
+| `eventName`, `eventType`, `severity` | `skill_started`, `Trace`, `Info` |
+| `pluginName`, `pluginVersion` | This plugin's identity and installed manifest version |
+| `skillName` | One of the 12 recognized authoring or packaging skills |
+| `sessionId` | Host session ID when usable; per-process random fallback |
+| `correlationId` | New UUID per emitted start; not a workflow/completion correlation |
+| `osName`, `osVersion`, `nodeVersion` | OS family/release and Node major version |
+| `aiAgentName`, `aiAgentVersion` | Recognized agent family and version, when available |
+| `pacCliVersion` | Existing PAC CLI version, when available |
+| `orgId`, `tenantId` | GUIDs from existing `pac auth who` output, when available |
+| `eventInfo.aadObjectId` | Existing signed-in user's Entra object GUID, when available |
+
+Missing or invalid optional fields are omitted; telemetry never installs PAC or
+requests authentication. GUIDs and session IDs are not anonymous data. The PAM
+validator runs before dispatch and again before either disk or wire serialization.
+Only `aadObjectId` is allowed inside `eventInfo`. It remains an object in the local
+mirror and inside the serialized dimensions; it is not separately stringified.
+
+Never include prompts, arguments, tool outputs, code, paths, URLs, control/project
+names, usernames, hostnames, credentials, free-text errors, framework, outcomes,
+duration, build targets or arbitrary nested data. Routing cloud context is used
+internally and is not included in the event. The collector can separately observe
+transport metadata; payload filtering is not a claim that infrastructure has no
+additional metadata.
+
+## Hooks and Counting
+
+`hooks/hooks.json` registers `UserPromptSubmit` and `PreToolUse` matching
+`Skill|skill`. There is no completion hook. The host must supply the installed `PLUGIN_ROOT` or
+`CLAUDE_PLUGIN_ROOT`; never infer it from the control's working directory.
+No workspace-global hooks are installed. Host hook support and payload formats
+must be validated in each supported host before release; the tests cover the
+known snake_case and camelCase input variants, not an end-to-end host install.
+
+All 12 tracked workflow skills accept bare names (for example,
+`/generate-native-extension` or the Skill-tool name `generate-native-extension`)
+as well as PAM-qualified names. Explicit other-plugin namespaces or plugin hints
+are rejected, including conflicting hints on PAM-qualified names. The telemetry
+control skill is never tracked.
+
+When a bare name arrives without plugin identity, the hook attributes it to PAM.
+It cannot distinguish another installed plugin reusing that name from the payload
+alone. For installations with overlapping names, use qualified invocations such
+as `/power-apps-mobile-extension:generate-native-extension` where supported, or a
+host that supplies the resolved plugin identity.
+
+Only a leading recognized slash command or a structured Skill-tool invocation is
+tracked; ordinary prose, unknown names and explicitly identified other plugins
+are ignored.
+
+A host can emit both a prompt and a Skill-tool hook for the same visible run.
+Each emitted start has its own correlation ID;
+there is no claim of cross-hook deduplication. Host fallback sessions cannot link
+fresh Node processes. Report the seven main workflows and five packaging stages
+separately; do not sum an orchestrator and its child stages as independent full
+workflows. A start does not establish completion or success.
+
+## Processing and Routing
+
+```text
+Hard-off / invalid config -> stop before event work
+Recognized invocation -> optional existing PAC/agent metadata -> strict schema
+Detached dispatcher -> strict schema -> local mirror -> user/env opt-out
+Region resolution -> CS4.0 envelope -> HTTPS POST
+```
+
+Only the configured US (ROW) and EU OneCollector endpoints are accepted. The child
+receives a minimal environment and sanitized event, never inherited credentials or
+arbitrary hook payloads. It uses a temporary working directory so it does not hold
+the user's project open on Windows. Requests have bounded deadlines; failures
+never fail a skill and there are no retries or local-log replay.
+
+Each transmitted event uses one POST to one resolved collector.
+
+| Context | Destination |
+|---|---|
+| No usable PAC auth context | ROW default |
+| Public cloud, valid organization, recognized EU geo | EU |
+| Public cloud, valid organization, recognized other supported public geo | ROW |
+| Lookup failure, unknown geo/cloud, missing organization with other identity context | Local mirror only |
+| Government, DoD, China or any unsupported cloud | Local mirror only; no cross-cloud lookup or send |
+
+An unresolved authenticated region never falls back to ROW. An authentication read
+failure is indistinguishable from unavailable auth context; it yields an identity-free event
+using the documented ROW default, not a guessed tenant region.
+
+## Local Data
+
+- Mirror: `~/.power-platform-skills/telemetry/power-apps-mobile-extension/sessions/<sessionId>/events.jsonl`.
+- Local log policy: best-effort cleanup after 14 days of last-write
+ inactivity, triggered by a new session; rollover above 10 MiB, not a total cap.
+ Inactive installations can retain files longer. File access follows OS user
+ directory permissions; review permissions/backups before sharing diagnostics.
+- Routing cache: `telemetry/power-apps-mobile-extension/region-cache/<orgId>.json`
+ under the same configuration root. Contains region and expiry; filenames reveal
+ organization IDs. Freshness is 24 hours; expired entries are removed on access
+ and stale files are swept on cache writes. Cleanup is not a wall-clock guarantee.
+- Neither preference changes nor the release kill switch deletes existing data.
+ Users may delete this plugin's session/cache directories separately. Never
+ automatically upload diagnostic logs or treat them as a deferred event queue.
+
+## Maintenance and Validation
+
+The complete shared library in `scripts/lib/telemetry/lib/` is a physical copy of
+the repository's canonical `shared/telemetry/lib/`. Refresh the whole directory
+when the canonical source changes; the shared telemetry CI suite checks parity.
+PAM directly uses its agent, PAC auth, session, user preference and local-log helpers.
+PAM owns the wrappers, strict schema, routing and transport; never replace the
+PAM dispatcher with the generic dispatcher without retaining nested validation.
+The PAC wrapper delegates fixed `pac auth who` / `pac --version` commands to
+`runNative`, which resolves native executables from absolute PATH entries and
+runs without a shell. Windows `.cmd` and `.bat` shims are not executed; missing
+native PAC executables result in omitted PAC metadata, not installation or sign-in.
+
+From the repository root:
+
+```text
+node --test plugins/power-apps-mobile-extension/scripts/tests/telemetry.test.js
+node --test shared/telemetry/tests/bundled-copies.test.js
+node scripts/validate-skill-descriptions.js
+node scripts/validate-hooks-manifests.js
+node scripts/validate-telemetry-ikeys.js
+node scripts/validate-legacy-compatibility.js
+```
+
+The tests inject config, authentication, clock and transport dependencies, using
+temporary directories and synthetic identities. They do not change the committed
+release switch or transmit to a collector. Production command entry points have no
+environment override to enable the release, change the key or redirect collectors.
+
+The plugin's path-filtered CI workflow sets
+`POWER_PLATFORM_SKILLS_TELEMETRY_POWER_APPS_MOBILE_EXTENSION_OPTOUT=1`, as does the
+shared telemetry workflow. Use that opt-out for local automation too.
+
+Automated tests cover known hook payloads, field filtering, routing decisions and
+local event emission. They do not establish end-to-end delivery for every host or
+region. Downstream EU ingestion and additional host integrations remain unverified.
+Server-side storage and retention are not configured or verified by this plugin.
\ No newline at end of file
diff --git a/plugins/power-apps-mobile-extension/skills/telemetry/SKILL.md b/plugins/power-apps-mobile-extension/skills/telemetry/SKILL.md
new file mode 100644
index 000000000..e47ab3628
--- /dev/null
+++ b/plugins/power-apps-mobile-extension/skills/telemetry/SKILL.md
@@ -0,0 +1,32 @@
+---
+name: telemetry
+description: "Enable, disable, or check usage telemetry transmission for Power Apps Mobile Extension skills. Use for 'turn off telemetry', 'opt out', 'enable telemetry', or 'telemetry status'. Opt-out stops transmission only; local diagnostic logs continue when the plugin is enabled."
+user-invocable: true
+argument-hint: "on | off | status"
+allowed-tools: Read, Bash
+---
+
+# Telemetry Transmission Preference
+
+1. Read [shared-instructions.md](../../shared/shared-instructions.md). This control
+ requires Node.js but does not require PAC, authentication or native build tools.
+2. Read the action from the user's request: `on`, `off`, or `status`. Missing or
+ invalid arguments mean `status`.
+3. Run the local control, using the absolute installed plugin root provided by the
+ host (`PLUGIN_ROOT` or `CLAUDE_PLUGIN_ROOT`):
+
+ ```text
+ node "<plugin-root>/scripts/telemetry-config.js" --action <on|off|status>
+ ```
+
+ Resolve the root from the installed skill location if necessary, never from an
+ arbitrary file in the control project. Do not run an install or sign-in command.
+4. Show the command output verbatim. If it fails, report the failure instead of
+ claiming the preference was saved. Do not modify the plugin's telemetry config.
+
+The choice is per-user and per-plugin. `off` stops collector transmission on
+subsequent events; it does not stop local logging or delete existing data.
+The environment opt-out overrides a saved `on` choice. The maintainer-controlled
+hard-disabled configuration overrides both and stops collection and local logging.
+This skill is excluded from usage telemetry. See [telemetry.md](../../shared/telemetry.md)
+for fields, locations, routing and the maintainer-controlled release switch.
\ No newline at end of file
diff --git a/shared/telemetry/README.md b/shared/telemetry/README.md
index a0a94d145..210bed233 100644
--- a/shared/telemetry/README.md
+++ b/shared/telemetry/README.md
@@ -68,6 +68,7 @@ choice cannot override `disabled: true`.
| 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. |
| PCF | `disabled: false` | Enabled and default-on for transmission. Shares Model Apps' tenant and keys through a byte-identical config; routes as model-apps does. Uses `clientType: "PcfAIPlugin"` with `pluginName: "pcf"` in the shared Power Apps client `event` stream; keeps its local mirror after transmission opt-out. | Base fields only (`skill_started`, including `orgId`/`tenantId` when PAC is signed in); no signed-in user object ID or `eventInfo` payload. |
| 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. |
+| Power Apps Mobile Extension | `disabled: false` | Enabled and default-on for transmission. Records starts for 12 workflow skills, not the telemetry control or generated native controls/PCFs. Public-cloud organizations resolve to US or EU; unknown authenticated regions and unsupported clouds remain local-only. Without usable PAC identity, the US default is used. User transmission opt-out retains the local mirror. | `eventInfo.aadObjectId` when available from PAC, with optional `orgId` and `tenantId`. No other nested `eventInfo` fields. Uses fixed `clientType: "power-apps-mobile-extension"` and `pluginName` in the shared `event` stream. |
### Custom routing (the resolver contract)