A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
feat(mobile-apps): add skill usage telemetry (#355)
Nikhil agrawal283f79ec9d57
diff --git a/.github/workflows/mobile-apps-script-tests.yml b/.github/workflows/mobile-apps-script-tests.ymlindex 0d4ca1b03..42bb54002 100644--- a/.github/workflows/mobile-apps-script-tests.yml+++ b/.github/workflows/mobile-apps-script-tests.yml@@ -15,6 +15,8 @@ jobs:test-mobile-apps-scripts:name: test-mobile-apps-scripts (${{ matrix.os }}, node ${{ matrix.node }})runs-on: ${{ matrix.os }}+ env:+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: "1"strategy:fail-fast: falsematrix:@@ -27,10 +29,10 @@ jobs:- 22steps:- name: checkout- uses: actions/checkout@v4+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0- name: setup-node- uses: actions/setup-node@v4+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0with:node-version: ${{ matrix.node }}diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.mdindex bf67e7ef0..67981985b 100644--- a/plugins/mobile-apps/AGENTS.md+++ b/plugins/mobile-apps/AGENTS.md@@ -26,8 +26,8 @@ README.md ← Plugin overviewagents/ ← native-app-planner, data-model-architect, screen-planner, screen-buildershared/ ← shared-instructions, references, samples, memory-bank templateskills/ ← /create-mobile-app, /add-dataverse, /add-connector, /add-native, ...-scripts/ ← shared helpers, including validate-mobile-files.js for skill-owned changed-file validation-hooks/ ← Validator implementations invoked explicitly by mobile workflows+scripts/ ← shared helpers, including validate-mobile-files.js and bundled telemetry+hooks/ ← Telemetry start hooks plus validators invoked explicitly by mobile workflows```## Template source@@ -56,7 +56,7 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr7. **Persisted plan** — Write `native-app-plan.md` (Mermaid ER + per-screen specs + native capabilities matrix) as the source of truth that sub-skills `Read`.8. **CLI compatibility** — Use `npx power-apps ...` for code-app lifecycle and data-source commands. Use `scripts/resolve-environment.js` plus `az` tokens for Dataverse environment URL/tenant discovery and Azure/Entra operations. See [`shared/shared-instructions.md`](./shared/shared-instructions.md).9. **Agent invocation namespace** — All `Task` invocations of agents in this plugin MUST use the fully-qualified `mobile-app:<agent-name>` form (e.g. `mobile-app:native-app-planner`, `mobile-app:screen-builder`). Bare names like `native-app-planner` return `Agent type 'native-app-planner' not found` because Claude Code namespaces all plugin agents by plugin name.-10. **Plugin isolation** — Do not add `hooks/hooks.json`: Claude loads plugin hooks during unrelated workflows, so a mobile write hook can block Canvas Apps tool calls. Mutating skills follow the changed-file gate in `shared/shared-instructions.md`, and final-artifact agents invoke `scripts/validate-mobile-files.js` directly.+10. **Plugin isolation** — `hooks/hooks.json` is limited to fail-open telemetry start hooks. They never validate, mutate, or block tool calls. Do not add write/validation hooks: mutating skills follow the changed-file gate in `shared/shared-instructions.md`, and final-artifact agents invoke `scripts/validate-mobile-files.js` directly.11. **Invocation metadata** — Public entry skills use `user-invocable: true` and remain model-invocable. Bundled implementation helpers use both `user-invocable: false` and `disable-model-invocation: true`; their owner reads `SKILL.md` directly. Hidden standalone workflows such as `assign-offline-profile` and `preview-offline-scope` use `user-invocable: false` without disabling model invocation because no owner reads them directly. Agents use `user-invocable: false` without `disable-model-invocation` so qualified `Task` delegation remains available.12. **Sub-agent return-status protocol** — Every agent in this plugin (`native-app-planner`, `data-model-architect`, `screen-planner`, `screen-builder`) MUST return a status code as the **literal first line** of its final message. Orchestrators (skills that invoke agents via `Task`) MUST parse the first line and branch:@@ -73,6 +73,17 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr- `DONE_WITH_CONCERNS` requires at least one concern. If none, use `DONE`.- Special early-return signals (`INDUSTRY_CONFIRM_REQUESTED:`, `DESIGN_VIBE_REQUESTED:`) pre-date this protocol and remain in effect — they are special-cased "ask the user one question and re-spawn me" handoffs, not terminal returns.- The canonical orchestrator handler lives in [`skills/create-mobile-app/SKILL.md`](./skills/create-mobile-app/SKILL.md) Step 3.0. Future skills that spawn agents should reference it rather than duplicating the switch.+## Telemetry++Mobile Apps bundles the canonical stdlib-only telemetry helpers from the repo-root `shared/telemetry/lib` at `scripts/lib/telemetry/lib`. Edit the shared source first, then refresh this physical copy in the same change; never copy another plugin's `ikey.json` or resolver.++- **Start-only lifecycle:** `UserPromptSubmit` records explicit slash-command starts and `PreToolUse(Skill)` records programmatic Skill-tool starts; both may fire for one visible slash command. `UserPromptSubmit` payloads differ by host — Claude Code passes the raw `/mobile-app:<skill>` text, Copilot CLI pre-expands it to a `<skill-context name="<skill>">` wrapper and emits no Skill pre-tool event — so both shapes must stay recognized or manual runs go uncaptured. Do not add `skill_completed`, duration, outcome, or persisted correlation state: Power Pages deliberately removed that flow because the hook boundary does not prove the workflow completed.+- **Coverage and attribution:** `scripts/lib/mobileapp-hook-utils.js` discovers every user- or model-invocable top-level skill, including `telemetry`. Direct-read helpers with `disable-model-invocation: true` are not independently invoked and are excluded. Bare and `mobile-app:`-qualified names are both attributed; explicitly foreign plugin namespaces are excluded.+- **Session correlation:** Stable host session ids pass through unchanged. Copilot CLI reports a transient `call_*` id to nested-agent hooks, so `resolveCopilotRootSessionId` in `scripts/lib/mobile-telemetry.js` resolves it to the unique recent UUID session whose local `~/.copilot/session-state/<uuid>/events.jsonl` structurally owns that `agentId`, reading only a bounded tail. Keep host-specific quirks contained in that one function. The verified root is cached as one atomic 30-minute alias file per hashed call id so fresh hook processes reuse it; aliases hold no prompts, cwd, or tool arguments and are never transmitted. Missing, stale, malformed, or ambiguous state fails open to the original id, and Claude Code and Codex ids are not rewritten.+- **Privacy:** Mobile Apps sends no prompt, tool input, cwd, path, URL, credential, username, hostname, Dataverse org/tenant ID, or Entra object ID. The dynamic `eventInfo` contains only `invocationSource` (`prompt` or `pretool`) and a random per-project `appInstanceId` (or `null` outside a prepared project).+- **Destination and controls:** Mobile-owned `scripts/lib/mobile-telemetry-dispatcher.js` maps shared events to the Power Apps `event` stream configured by `scripts/lib/telemetry/ikey.json`. The repository `disabled` switch is a hard-off; user and CI opt-outs suppress transmission while preserving the local diagnostic mirror.+- **CI:** Every Mobile Apps test job must set `POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT=1`. The single positive wire test clears that backstop only in its child process and routes the event to `POWER_PLATFORM_SKILLS_FAKE_HTTPS`; all other positive tests remain opted out and exercise the local mirror.+## Decisions made- ✅ Markdown plan with Mermaid (no HTML rendering)diff --git a/plugins/mobile-apps/README.md b/plugins/mobile-apps/README.mdindex 67d1dd5c1..4fc4ec243 100644--- a/plugins/mobile-apps/README.md+++ b/plugins/mobile-apps/README.md@@ -257,6 +257,7 @@ Example edit flows:| `/deploy` | ✅ v0 | Build + push — `npm run build` then `npx power-apps push` to the env in `power.config.json`. **Does not** drive `expo run:ios` or `expo run:android` (out of scope for v0). || `/open-wrap-url` | ✅ v0 | Opens the Wrap URL in browser for an app ID using `https://make.powerapps.com/environments/<envID>/wrap?appID=<appID>`. Requires both `--app-id` and `--env-id`. || `/report-issue` | ✅ v0 | Read-only diagnostic — collects env / Expo / Node versions, project context, recent errors, and renders a copy-paste-ready GitHub issue body. Sanitizes secrets. |+| `/telemetry` | ✅ v0 | Enable, disable, or show the per-user Mobile Apps telemetry transmission preference. || `/design-system` | ✅ v0 | End-to-end design system — collects brand inputs (logo, brand doc, website, free text, canvas app, code app, Figma), runs a 3-style visual picker, writes `brand/design-system.md` + `brand/tokens.ts`, renders branded screen previews. Auto-invoked at Step 6.75 of `/create-mobile-app`; also standalone. || `/preview-screens` | ✅ v0 | Renders generated TSX screens as a browser-viewable HTML preview (no Metro needed). Uses Tamagui → HTML mapping. || `/add-datasource` | ✅ v0 | Alias for `/add-connector` — discoverable name for "how do I connect to X?" |@@ -278,6 +279,22 @@ Example edit flows:| `screen-builder` | Mutation — writes ONE TSX file per assigned screen, runs N in parallel || `offline-profile-architect` | Read-only — proposes per-table row scope, relationships, selected columns, sync frequency; returns `_offline_section.md` for `/setup-offline-profile` to embed in `native-app-plan.md` |+## Telemetry and privacy++The Mobile Apps plugin sends start-only usage telemetry to Microsoft. A start event can include the skill name, plugin version, session and per-start correlation IDs, OS/Node versions, AI-agent name/version, invocation source, and a random per-project app instance ID. It never includes prompts, skill arguments, tool inputs, file paths, cwd, app/site names, URLs, credentials, usernames, hostnames, Dataverse organization or tenant IDs, or Entra object IDs.++Both host surfaces are covered — an explicit slash command and a programmatic Skill-tool call — so some hosts may produce two `skill_started` records for one visible run. The plugin does not emit `skill_completed`, success/failure, error, or duration data because the available hook boundary does not prove that the workflow itself completed.++Control the per-user transmission preference with:++```text+/mobile-app:telemetry status+/mobile-app:telemetry off+/mobile-app:telemetry on+```++`off` stops network transmission but retains the sanitized local diagnostic mirror under `~/.power-platform-skills/telemetry/mobile-app/sessions/<sessionId>/events.jsonl`. Automation can force transmission off with `POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT=1`; this overrides the saved preference and `on`.+## Known blockers## See alsodiff --git a/plugins/mobile-apps/hooks/hooks.json b/plugins/mobile-apps/hooks/hooks.jsonnew file mode 100644index 000000000..411fccbdc--- /dev/null+++ b/plugins/mobile-apps/hooks/hooks.json@@ -0,0 +1,28 @@+{+ "_comment": "Telemetry-only start hooks. They never validate, mutate, or block tool calls. File validation stays owned by each workflow through scripts/validate-mobile-files.js.",+ "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": 10+ }+ ]+ }+ ],+ "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": 10+ }+ ]+ }+ ]+ }+}diff --git a/plugins/mobile-apps/hooks/run-telemetry.js b/plugins/mobile-apps/hooks/run-telemetry.jsnew file mode 100644index 000000000..6c6d1134e--- /dev/null+++ b/plugins/mobile-apps/hooks/run-telemetry.js@@ -0,0 +1,129 @@+#!/usr/bin/env node+'use strict';++const os = require('node:os');++let telemetry;+let getTrackedSkillFromPrompt;+let getTrackedSkillFromToolInput;+try {+ telemetry = require('../scripts/lib/mobile-telemetry');+ ({+ getTrackedSkillFromPrompt,+ getTrackedSkillFromToolInput,+ } = require('../scripts/lib/mobileapp-hook-utils'));+} catch {+ process.exit(0);+}++function readStdin() {+ return new Promise((resolve) => {+ let input = '';+ process.stdin.setEncoding('utf8');+ process.stdin.on('data', (chunk) => { input += chunk; });+ process.stdin.on('end', () => resolve(input));+ process.stdin.on('error', () => resolve(input));+ });+}++function invocationFor(mode, payload) {+ if (mode === 'prompt') return getTrackedSkillFromPrompt(payload.prompt);+ if (mode === 'pretool') return getTrackedSkillFromToolInput(payload.tool_input);+ return null;+}++function pickString(...values) {+ for (const value of values) {+ if (typeof value === 'string' && value.trim()) return value.trim();+ }+ return '';+}++function parseWorkingDirArg(text) {+ if (typeof text !== 'string' || !text.trim()) return '';+ const match = text.match(/--working-dir(?:=|\s+)(?:"([^"]+)"|'([^']+)'|(\S+))/i);+ return pickString(match && match[1], match && match[2], match && match[3]);+}++function resolveInvocationCwd(payload) {+ const toolInput = payload && typeof payload.tool_input === 'object' ? payload.tool_input : null;+ const fromToolInput = pickString(+ toolInput && toolInput.cwd,+ toolInput && toolInput.working_dir,+ toolInput && toolInput.workingDir,+ );+ if (fromToolInput) return fromToolInput;++ const fromToolArgs = toolInput+ ? pickString(+ parseWorkingDirArg(toolInput.arguments),+ parseWorkingDirArg(toolInput.args),+ parseWorkingDirArg(toolInput.command),+ parseWorkingDirArg(toolInput.prompt),+ )+ : '';+ if (fromToolArgs) return fromToolArgs;++ return pickString(+ payload && payload.working_dir,+ payload && payload.workingDir,+ payload && payload.cwd,+ );+}++function withStableDispatchCwd(callback) {+ const originalCwd = process.cwd();+ let changed = false;+ try {+ // A detached child inherits the hook's cwd. On Windows, keeping a generated+ // app as that cwd can block moving or deleting the app until dispatch exits.+ process.chdir(os.tmpdir());+ changed = true;+ } catch {+ // Telemetry remains fail-open if the host's temp directory is unavailable.+ }++ try {+ return callback();+ } finally {+ if (changed) {+ try {+ process.chdir(originalCwd);+ } catch {+ // This hook process exits immediately after dispatch.+ }+ }+ }+}++async function run(mode) {+ let payload;+ try {+ payload = JSON.parse(await readStdin());+ } catch {+ return;+ }++ const skillName = invocationFor(mode, payload);+ if (!skillName) return;++ const invocationCwd = resolveInvocationCwd(payload);+ withStableDispatchCwd(() => {+ const context = telemetry.createTelemetryContext(payload);+ if (context) {+ telemetry.emitSkillStarted(+ context,+ { skillName, source: mode },+ { cwd: invocationCwd },+ );+ }+ });+}++function start(mode) {+ run(mode).catch(() => {}).finally(() => process.exit(0));+}++if (require.main === module) start(process.argv[2]);++module.exports = { start, withStableDispatchCwd };\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/lib/app-identity.js b/plugins/mobile-apps/scripts/lib/app-identity.jsnew file mode 100644index 000000000..69e996c15--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/app-identity.js@@ -0,0 +1,91 @@+'use strict';++const crypto = require('node:crypto');+const fs = require('node:fs');+const path = require('node:path');++const APP_JSON_FILE = 'app.json';+const APP_INSTANCE_ID =+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;++function isPlainObject(value) {+ return !!value && typeof value === 'object' && !Array.isArray(value);+}++function readJsonFile(filePath) {+ try {+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));+ } catch {+ return null;+ }+}++function appJsonPath(projectRoot) {+ return path.join(path.resolve(projectRoot), APP_JSON_FILE);+}++function appInstanceIdFromConfig(appJson) {+ if (!isPlainObject(appJson) || !isPlainObject(appJson.expo)) return '';++ const extra = appJson.expo.extra;+ const telemetry = isPlainObject(extra) && isPlainObject(extra.telemetry)+ ? extra.telemetry+ : null;+ const appInstanceId = telemetry && typeof telemetry.appInstanceId === 'string'+ ? telemetry.appInstanceId+ : '';++ return APP_INSTANCE_ID.test(appInstanceId) ? appInstanceId : '';+}++function readAppInstanceId(projectRoot) {+ return appInstanceIdFromConfig(readJsonFile(appJsonPath(projectRoot)));+}++function findAppInstanceId(projectRoot = process.cwd()) {+ if (!projectRoot) return '';+ return readAppInstanceId(projectRoot);+}++function ensureAppInstanceId(projectRoot = process.cwd()) {+ const root = path.resolve(projectRoot);+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {+ throw new Error('Cannot create app identity outside an existing directory');+ }++ const filePath = appJsonPath(root);+ const appJson = readJsonFile(filePath);+ // The create workflow gates on the supported Expo template before calling+ // this helper. Refuse to manufacture a minimal config when that invariant is+ // broken because doing so would hide scaffold damage and overwrite evidence.+ if (!isPlainObject(appJson) || !isPlainObject(appJson.expo)) {+ throw new Error('Cannot create app identity without an existing, valid Expo app.json');+ }++ const existing = appInstanceIdFromConfig(appJson);+ if (existing) return existing;++ appJson.expo.extra = isPlainObject(appJson.expo.extra) ? appJson.expo.extra : {};+ const telemetry = isPlainObject(appJson.expo.extra.telemetry)+ ? appJson.expo.extra.telemetry+ : {};++ const appInstanceId = crypto.randomUUID();+ appJson.expo.extra.telemetry = {+ ...telemetry,+ appInstanceId,+ };++ fs.writeFileSync(filePath, `${JSON.stringify(appJson, null, 2)}\n`, 'utf8');+ return appInstanceId;+}++module.exports = {+ APP_JSON_FILE,+ ensureAppInstanceId,+ findAppInstanceId,+};++if (require.main === module) {+ process.stdout.write(`${ensureAppInstanceId(process.argv[2] || process.cwd())}\n`);+}diff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry-config.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry-config.jsnew file mode 100644index 000000000..2fcaf0e4e--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry-config.js@@ -0,0 +1,42 @@+#!/usr/bin/env node+'use strict';++const { spawnSync } = require('node:child_process');+const path = require('node:path');++const TELEMETRY_CLI = path.join(__dirname, 'telemetry', 'lib', 'telemetry-config.js');+const GENERIC_DISCLOSURE =+ '\u2139\ufe0f 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.';+const MOBILE_DISCLOSURE =+ '\u2139\ufe0f Usage telemetry records skill, plugin, agent, OS, Node, session, and\n' ++ ' correlation fields, plus invocation source and a random per-project app\n' ++ ' instance ID. Mobile Apps does not record PAC CLI version, Dataverse\n' ++ ' organization or Entra tenant IDs, or an Entra object ID.';++function run(args = process.argv.slice(2), env = process.env) {+ const result = spawnSync(+ process.execPath,+ [TELEMETRY_CLI, ...args, '--plugin', 'mobile-app'],+ { encoding: 'utf8', env },+ );++ if (result.error) throw result.error;+ const stdout = result.stdout.replace(GENERIC_DISCLOSURE, MOBILE_DISCLOSURE);+ return { ...result, stdout };+}++if (require.main === module) {+ try {+ const result = run();+ process.stdout.write(result.stdout);+ process.stderr.write(result.stderr);+ process.exit(result.status === null ? 1 : result.status);+ } catch (error) {+ process.stderr.write(`${error.message}\n`);+ process.exit(1);+ }+}++module.exports = { run };\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.jsnew file mode 100644index 000000000..6dc9f1d66--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry-dispatcher.js@@ -0,0 +1,226 @@+#!/usr/bin/env node+'use strict';++const { spawn } = require('node:child_process');+const fs = require('node:fs');+const https = require('node:https');+const os = require('node:os');+const path = require('node:path');++const { FIELD_TYPES, pick } = require('./telemetry/lib/events');+const { appendLocal } = require('./telemetry/lib/local-log');+const { loadResolver } = require('./telemetry/lib/resolver-loader');+const {+ isTransmissionOptedOut,+ telemetryOptOutEnvVarName,+} = require('./telemetry/lib/user-config');++const PLACEHOLDER_IKEY = 'PLACEHOLDER_REPLACE_BEFORE_SHIPPING';+const DEFAULT_LOCAL_DIR = path.join(os.homedir(), '.power-platform-skills');+const RESERVED_META_FIELDS = new Set(['eventName', 'eventType', 'severity']);++function fireAndForget(event, opts = {}) {+ const env = opts.env || process.env;+ const pluginName = event && event.data && event.data.pluginName;+ const optOutName = pluginName ? telemetryOptOutEnvVarName(pluginName) : '';+ const optOutValue = optOutName ? env[optOutName] || '' : '';++ try {+ const child = spawn(process.execPath, [__filename], {+ detached: true,+ stdio: ['pipe', 'ignore', 'ignore'],+ env: {+ // Telemetry children receive only operational values. In particular,+ // credentials from the invoking agent process are never inherited.+ PATH: env.PATH || '',+ SystemRoot: env.SystemRoot || '',+ HOME: env.HOME || '',+ USERPROFILE: env.USERPROFILE || '',+ APPDATA: env.APPDATA || '',+ POWER_PLATFORM_SKILLS_CONFIG_DIR: opts.configDir || '',+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: opts.fakeProbe || '',+ POWER_PLATFORM_SKILLS_CLOUD: opts.cloud || '',+ POWER_PLATFORM_SKILLS_IKEY_JSON: opts.ikeyJsonPath || '',+ ...(optOutName && optOutValue ? { [optOutName]: optOutValue } : {}),+ },+ });+ child.stdin.end(JSON.stringify(event));+ child.unref();+ } catch {+ // Telemetry is observational and must never affect skill execution.+ }+}++function readIkeyConfig(env) {+ const configPath = env.POWER_PLATFORM_SKILLS_IKEY_JSON ||+ path.join(__dirname, 'telemetry', 'ikey.json');+ try {+ return { cfg: JSON.parse(fs.readFileSync(configPath, 'utf8')), configPath };+ } catch {+ return { cfg: null, configPath };+ }+}++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;+}++function buildNormalEventData(data, time) {+ const dimensions = { ...data };+ delete dimensions.eventName;+ delete dimensions.eventType;+ delete dimensions.severity;++ // This mirrors the Power Apps native provider's production defaults. The+ // semantic event name is a data column; the envelope name remains `event`.+ return {+ app_Name: 'powerappsclient',+ clientType: 'PowerAppsNative',+ clusterCategory: 'prod',+ device_Id: 'react-native',+ event_Name: data.eventName || '',+ session_Id: data.sessionId || '',+ severity: data.severity || 'Info',+ timestamp: time,+ customDimensions: JSON.stringify(dimensions),+ };+}++function buildEnvelope(data, time, iKey, eventStreamName) {+ const envelope = {+ ver: '4.0',+ name: eventStreamName || 'event',+ time,+ iKey: `o:${String(iKey || '').split('-')[0]}`,+ data: buildNormalEventData(data, time),+ };++ // The native provider adds these Common Schema Part A extensions before+ // transmission. Keep them outside customDimensions so the ingestion mapping+ // can populate the standard app, session, and OS columns.+ envelope.ext = {+ app: {+ sesId: data.sessionId || '',+ ver: data.pluginVersion || '',+ },+ os: {+ name: data.osName || '',+ ver: data.osVersion || '',+ },+ };+ return envelope;+}++function writeProbe(filePath, record) {+ try {+ fs.writeFileSync(filePath, JSON.stringify(record), 'utf8');+ } catch {+ // Test-only probe failures are non-fatal, like real transport failures.+ }+}++async function dispatch(raw, env) {+ const { cfg, configPath } = readIkeyConfig(env);+ // A missing config or disabled repository switch is a true hard-off: no+ // local record and no transmission.+ if (!cfg || cfg.disabled === true) return;++ let event;+ try {+ event = JSON.parse(raw);+ } catch {+ return;+ }++ const data = sanitizeData(event.data);+ const time = new Date().toISOString();+ const configDir = env.POWER_PLATFORM_SKILLS_CONFIG_DIR || DEFAULT_LOCAL_DIR;+ appendLocal({ time, name: event.name, data }, { configDir });++ if (isTransmissionOptedOut(configDir, data.pluginName, env)) return;++ let iKey = '';+ let collectorUrl = '';+ const resolver = loadResolver(path.dirname(configPath));+ if (resolver && typeof resolver.resolve === 'function') {+ try {+ const resolved = await resolver.resolve({+ event,+ cfg,+ cloud: env.POWER_PLATFORM_SKILLS_CLOUD || '',+ configDir,+ });+ iKey = resolved && resolved.iKey || '';+ collectorUrl = resolved && resolved.collectorUrl || '';+ } catch {+ // A resolver failure falls through to the static Mobile configuration.+ }+ }+ iKey = iKey || cfg.instrumentationKey || '';+ collectorUrl = collectorUrl || cfg.collector_url || '';+ if (!iKey || iKey === PLACEHOLDER_IKEY || !collectorUrl) return;++ const envelope = buildEnvelope(data, time, iKey, cfg.event_stream_name);+ 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),+ };++ if (env.POWER_PLATFORM_SKILLS_FAKE_HTTPS) {+ writeProbe(env.POWER_PLATFORM_SKILLS_FAKE_HTTPS, { headers, body });+ return;+ }++ let url;+ try {+ url = new URL(collectorUrl);+ } catch {+ return;+ }++ await new Promise((resolve) => {+ const request = https.request({+ hostname: url.hostname,+ port: url.port || undefined,+ path: url.pathname + url.search,+ method: 'POST',+ headers,+ }, (response) => {+ response.on('data', () => {});+ response.on('end', resolve);+ });+ request.on('error', resolve);+ request.setTimeout(4000, () => {+ request.destroy();+ resolve();+ });+ request.end(body);+ });+}++function runDispatcher() {+ let raw = '';+ process.on('uncaughtException', () => process.exit(0));+ process.on('unhandledRejection', () => process.exit(0));+ process.stdin.setEncoding('utf8');+ process.stdin.on('data', (chunk) => { raw += chunk; });+ process.stdin.on('error', () => process.exit(0));+ process.stdin.on('end', () => {+ dispatch(raw, process.env).finally(() => process.exit(0));+ });+}++if (require.main === module) runDispatcher();++module.exports = {+ buildEnvelope,+ buildNormalEventData,+ fireAndForget,+};\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry.jsnew file mode 100644index 000000000..f13070a04--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry.js@@ -0,0 +1,286 @@+'use strict';++const crypto = require('node:crypto');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');++const TELEMETRY_DIR = path.join(__dirname, 'telemetry');+const PLACEHOLDER_IKEY = 'PLACEHOLDER_REPLACE_BEFORE_SHIPPING';++const agentInfo = require('./telemetry/lib/agent-info');+const events = require('./telemetry/lib/events');+const { fireAndForget } = require('./mobile-telemetry-dispatcher');+const { loadResolver } = require('./telemetry/lib/resolver-loader');+const session = require('./telemetry/lib/session');+const { findAppInstanceId } = require('./app-identity');++function readPluginVersion() {+ const manifestPath = path.resolve(__dirname, '..', '..', '.claude-plugin', 'plugin.json');+ try {+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ return typeof manifest.version === 'string' ? manifest.version : 'unknown';+ } catch {+ return 'unknown';+ }+}++function readIkey(env = process.env) {+ const configuredPath = typeof env.POWER_PLATFORM_SKILLS_IKEY_JSON === 'string'+ ? env.POWER_PLATFORM_SKILLS_IKEY_JSON.trim()+ : '';+ const ikeyPath = configuredPath+ ? path.resolve(configuredPath)+ : path.join(TELEMETRY_DIR, 'ikey.json');+ try {+ return { cfg: JSON.parse(fs.readFileSync(ikeyPath, 'utf8')), ikeyPath };+ } catch {+ return { cfg: null, ikeyPath };+ }+}++function isProvisioned(cfg, ikeyPath) {+ if (!cfg || cfg.disabled === true || !cfg.event_stream_name) return false;+ const resolver = loadResolver(path.dirname(ikeyPath));+ try {+ if (resolver && typeof resolver.isProvisioned === 'function') {+ return resolver.isProvisioned(cfg) === true;+ }+ } catch {+ return false;+ }+ return !!(+ cfg.instrumentationKey &&+ cfg.instrumentationKey !== PLACEHOLDER_IKEY &&+ cfg.collector_url+ );+}++function configDir(env = process.env) {+ return env.POWER_PLATFORM_SKILLS_CONFIG_DIR ||+ path.join(os.homedir(), '.power-platform-skills');+}++function readFileTail(filePath, maxBytes) {+ const descriptor = fs.openSync(filePath, 'r');+ try {+ const { size } = fs.fstatSync(descriptor);+ const start = Math.max(0, size - maxBytes);+ const buffer = Buffer.allocUnsafe(size - start);+ const bytesRead = fs.readSync(descriptor, buffer, 0, buffer.length, start);+ const text = buffer.toString('utf8', 0, bytesRead);+ // A bounded tail can begin inside a line, so drop that partial first record.+ // Without a newline there is no record boundary, so none of the fragment+ // can be trusted as a complete JSONL record even if it parses by chance.+ if (start > 0) {+ const firstNewline = text.indexOf('\n');+ return firstNewline === -1 ? '' : text.slice(firstNewline + 1);+ }+ return text;+ } finally {+ fs.closeSync(descriptor);+ }+}++// GitHub Copilot CLI hands nested-agent hooks a transient `call_*` id instead of+// the CLI run's session UUID, which would scatter one run across many session+// ids. Resolve it to the session that owns the agent. Every other host, and any+// local state that cannot prove a single owner, returns `hostSessionId` as-is.+function resolveCopilotRootSessionId(hostSessionId, opts) {+ const NESTED_ID = /^call_[A-Za-z0-9_-]+$/;+ const ROOT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+ const MAX_SESSION_AGE_MS = 5 * 60 * 1000;+ const MAX_TAIL_BYTES = 4 * 1024 * 1024;+ const ALIAS_TTL_MS = 30 * 60 * 1000;++ if (!NESTED_ID.test(hostSessionId)) return hostSessionId;++ const now = Number.isFinite(opts.now) ? opts.now : Date.now();+ const aliasDir = opts.copilotSessionAliasDir ||+ path.join(configDir(opts.env), 'telemetry', 'mobile-app', 'session-aliases');+ const aliasPath = path.join(+ aliasDir,+ `${crypto.createHash('sha256').update(hostSessionId).digest('hex')}.json`,+ );++ // Every hook is a fresh process, so the verified owner is cached on disk.+ const readAlias = () => {+ try {+ const alias = JSON.parse(fs.readFileSync(aliasPath, 'utf8'));+ if (+ alias.nestedSessionId === hostSessionId &&+ ROOT_ID.test(alias.rootSessionId) &&+ Number.isFinite(alias.expiresAt) &&+ alias.expiresAt > now+ ) {+ return alias.rootSessionId;+ }+ fs.rmSync(aliasPath, { force: true });+ } catch {+ // A cache miss or malformed entry falls through to the host-state lookup.+ }+ return '';+ };++ const writeAlias = (rootSessionId) => {+ const temporaryPath = `${aliasPath}.${process.pid}.${crypto.randomUUID()}.tmp`;+ try {+ fs.mkdirSync(aliasDir, { recursive: true, mode: 0o700 });+ for (const entry of fs.readdirSync(aliasDir)) {+ const stale = path.join(aliasDir, entry);+ if (entry.endsWith('.json') && fs.statSync(stale).mtimeMs <= now - ALIAS_TTL_MS) {+ fs.rmSync(stale, { force: true });+ }+ }+ fs.writeFileSync(temporaryPath, JSON.stringify({+ nestedSessionId: hostSessionId,+ rootSessionId,+ expiresAt: now + ALIAS_TTL_MS,+ }), { encoding: 'utf8', flag: 'wx', mode: 0o600 });+ fs.renameSync(temporaryPath, aliasPath);+ } catch {+ // Concurrent writers resolve the same call id, so either file is valid.+ try {+ fs.rmSync(temporaryPath, { force: true });+ } catch { /* best effort */ }+ }+ };++ const ownsAgent = (eventsPath) => {+ let tail;+ try {+ tail = readFileTail(eventsPath, MAX_TAIL_BYTES);+ } catch {+ return false;+ }+ for (const line of tail.split('\n')) {+ if (!line) continue;+ try {+ if (JSON.parse(line).agentId === hostSessionId) return true;+ } catch {+ // A concurrently appended final record can be incomplete; ignore it.+ }+ }+ return false;+ };++ const cachedRootSessionId = readAlias();+ if (cachedRootSessionId) return cachedRootSessionId;++ // Copilot records the nested agent under the owning session's events.jsonl+ // before invoking the hook. Only structural agent ids are read from those+ // logs; prompts, cwd, and tool arguments never leave the file.+ const stateDir = opts.copilotSessionStateDir ||+ path.join(os.homedir(), '.copilot', 'session-state');+ let owner = '';+ try {+ for (const entry of fs.readdirSync(stateDir, { withFileTypes: true })) {+ if (!entry.isDirectory() || !ROOT_ID.test(entry.name)) continue;+ const eventsPath = path.join(stateDir, entry.name, 'events.jsonl');+ let mtimeMs;+ try {+ mtimeMs = fs.statSync(eventsPath).mtimeMs;+ } catch {+ continue;+ }+ if (mtimeMs < now - MAX_SESSION_AGE_MS || !ownsAgent(eventsPath)) continue;+ // Duplicate ownership means corrupt or copied host state. Keeping the+ // transient id beats merging two unrelated debugging sessions.+ if (owner && owner !== entry.name) return hostSessionId;+ owner = entry.name;+ }+ } catch {+ return hostSessionId;+ }++ if (!owner) return hostSessionId;+ writeAlias(owner);+ return owner;+}++function resolveSessionId(payload, opts = {}) {+ const hostSessionId = session.resolveHostSessionId(payload);+ return session.getSessionId(resolveCopilotRootSessionId(hostSessionId, opts));+}++function createTelemetryContext(payload, opts = {}) {+ const env = opts.env || process.env;+ const { cfg, ikeyPath } = readIkey(env);+ if (!isProvisioned(cfg, ikeyPath)) return null;+ return {+ cfg,+ ikeyPath,+ eventStreamName: cfg.event_stream_name,+ configDir: configDir(env),+ env,+ sessionId: resolveSessionId(payload, opts),+ };+}++function osFriendlyName(platform) {+ if (platform === 'win32') return 'Windows';+ if (platform === 'darwin') return 'Mac';+ if (platform === 'linux') return 'Linux';+ return platform;+}++function commonFields(context, invocation, opts = {}) {+ let ai = {};+ try {+ const readAiAgent = opts.readAiAgent || agentInfo.readAiAgent;+ ai = readAiAgent() || {};+ } catch {+ ai = {};+ }++ const fields = {+ pluginName: 'mobile-app',+ pluginVersion: readPluginVersion(),+ sessionId: context.sessionId,+ correlationId: opts.correlationId || crypto.randomUUID(),+ osName: osFriendlyName(process.platform),+ osVersion: os.release(),+ nodeVersion: `v${String(process.versions.node).split('.')[0]}`,+ skillName: invocation.skillName,+ };++ // `eventInfo` is the shared schema's caller-supplied JSON field, so app+ // identity rides here rather than needing a new allowlisted column.+ const eventInfo = {};+ if (invocation.source) eventInfo.invocationSource = invocation.source;+ const appInstanceId = findAppInstanceId(opts.cwd) || null;+ eventInfo.appInstanceId = appInstanceId;+ if (Object.keys(eventInfo).length) fields.eventInfo = eventInfo;++ if (ai.aiAgentName) fields.aiAgentName = ai.aiAgentName;+ if (ai.aiAgentVersion) fields.aiAgentVersion = ai.aiAgentVersion;+ return fields;+}++function dispatch(context, event, opts = {}) {+ const emit = opts.emit || fireAndForget;+ try {+ emit(event, {+ configDir: context.configDir,+ fakeProbe: context.env.POWER_PLATFORM_SKILLS_FAKE_HTTPS || '',+ ikeyJsonPath: context.ikeyPath,+ env: context.env,+ });+ } catch {+ // Telemetry is observational and must never affect a skill invocation.+ }+}++function emitSkillStarted(context, invocation, opts = {}) {+ const event = events.buildSkillStarted(+ context.eventStreamName,+ commonFields(context, invocation, opts),+ );+ dispatch(context, event, opts);+ return event;+}++module.exports = {+ createTelemetryContext,+ emitSkillStarted,+};\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.js b/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.jsnew file mode 100644index 000000000..c960ab463--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/mobileapp-hook-utils.js@@ -0,0 +1,110 @@+'use strict';++const fs = require('node:fs');+const path = require('node:path');++const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');+const SKILLS_DIR = path.join(PLUGIN_ROOT, 'skills');++function readInvocationMetadata(skillFile) {+ let text;+ try {+ text = fs.readFileSync(skillFile, 'utf8');+ } catch {+ return null;+ }++ const frontmatter = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);+ if (!frontmatter) return null;++ const values = Object.create(null);+ for (const line of frontmatter[1].split(/\r?\n/)) {+ const match = line.match(/^([a-z][a-z0-9-]*):\s*(true|false)\s*(?:#.*)?$/i);+ if (match) values[match[1].toLowerCase()] = match[2].toLowerCase() === 'true';+ }++ return {+ userInvocable: values['user-invocable'],+ disableModelInvocation: values['disable-model-invocation'],+ };+}++function isInvocable(metadata) {+ if (!metadata) return false;+ return metadata.userInvocable === true ||+ (metadata.userInvocable === false && metadata.disableModelInvocation !== true);+}++function discoverTrackedSkills() {+ const tracked = new Set();+ let entries;+ try {+ entries = fs.readdirSync(SKILLS_DIR, { withFileTypes: true });+ } catch {+ return tracked;+ }++ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {+ if (!entry.isDirectory()) continue;+ const skillFile = path.join(SKILLS_DIR, entry.name, 'SKILL.md');+ if (isInvocable(readInvocationMetadata(skillFile))) tracked.add(entry.name);+ }+ return tracked;+}++const TRACKED_SKILLS = discoverTrackedSkills();+const TRACKED_SKILL_NAMES = Object.freeze([...TRACKED_SKILLS]);++// A Set lookup also keeps inherited names such as `toString` from matching.+function trackedName(name) {+ const normalized = String(name || '').toLowerCase();+ return TRACKED_SKILLS.has(normalized) ? normalized : null;+}++function detectTrackedSkill(value) {+ if (typeof value !== 'string') return null;+ const trimmed = value.trim();++ const namespaced = trimmed.match(/(?:^|\s)\/?mobile-app:([a-z0-9-]+)(?=\s|$)/i);+ if (namespaced) return trackedName(namespaced[1]);++ const bare = trimmed.match(/^\/?([a-z0-9-]+)(?=\s|$)/i);+ return bare ? trackedName(bare[1]) : null;+}++function getTrackedSkillFromToolInput(toolInput) {+ if (!toolInput || typeof toolInput !== 'object') return null;+ for (const field of ['skill', 'skill_name', 'skillName', 'name', 'commandName', 'command']) {+ const skillName = detectTrackedSkill(toolInput[field]);+ if (skillName) return skillName;+ }++ try {+ const namespaced = JSON.stringify(toolInput).match(/\/?mobile-app:([a-z0-9-]+)/i);+ return namespaced ? trackedName(namespaced[1]) : null;+ } catch {+ return null;+ }+}++function getTrackedSkillFromPrompt(prompt) {+ if (typeof prompt !== 'string') return null;++ // Copilot CLI expands a manual slash command before the hook runs and emits no+ // Skill pre-tool event, so the raw `/mobile-app:<skill>` text never arrives:+ // <skill-context name="add-connector">\n<instructions>...+ const expanded = prompt.match(/^\s*<skill-context\s+name="(?:mobile-app:)?([a-z0-9-]+)"/i);+ if (expanded) return trackedName(expanded[1]);++ const command = prompt.match(/^\s*(\/(?:mobile-app:)?[a-z0-9-]+)(?=\s|$)/i);+ return command ? detectTrackedSkill(command[1]) : null;+}++module.exports = {+ TRACKED_SKILL_NAMES,+ detectTrackedSkill,+ getTrackedSkillFromPrompt,+ getTrackedSkillFromToolInput,+ isInvocable,+ readInvocationMetadata,+};\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/lib/telemetry/ikey.json b/plugins/mobile-apps/scripts/lib/telemetry/ikey.jsonnew file mode 100644index 000000000..f16921aa5--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/telemetry/ikey.json@@ -0,0 +1,6 @@+{+ "instrumentationKey": "5c3a61f48d7c4522912765ae7465ab5c-fb3d6606-fe59-4d6b-9bb1-5e993d889672-7138",+ "collector_url": "https://us-mobile.events.data.microsoft.com/OneCollector/1.0/",+ "event_stream_name": "event",+ "disabled": false+}\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/lib/telemetry/lib/agent-info.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/agent-info.jsnew file mode 100644index 000000000..3904f5bc1--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/agent-info.js@@ -0,0 +1,214 @@+"use strict";++const fs = require("node:fs");+const path = require("node:path");+const { execFileSync } = require("node:child_process");++let pacCliVersionCache;++// Reads the PAC CLI version once per process via `pac --version`. 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 : execFileSync;+ 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/mobile-apps/scripts/lib/telemetry/lib/emit-dispatcher.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/emit-dispatcher.jsnew file mode 100644index 000000000..1d0d14e2d--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/emit-dispatcher.js@@ -0,0 +1,253 @@+#!/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,+ };+}++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 = buildEnvelope(event.name, time, sanitized, iKey, cfg.event_stream_name);+ 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/mobile-apps/scripts/lib/telemetry/lib/emit-from-prompt.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/emit-from-prompt.jsnew file mode 100644index 000000000..38113ebd9--- /dev/null+++ b/plugins/mobile-apps/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/mobile-apps/scripts/lib/telemetry/lib/emit-spawn.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/emit-spawn.jsnew file mode 100644index 000000000..0bd839d8a--- /dev/null+++ b/plugins/mobile-apps/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/mobile-apps/scripts/lib/telemetry/lib/events.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/events.jsnew file mode 100644index 000000000..13f35c3ac--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/events.js@@ -0,0 +1,140 @@+"use strict";++// Per-field type metadata. Drives the type-aware picker so the wire payload+// always matches the Kusto column type. Types and defaults:+//+// "string" — Kusto column type `string`. Empty strings ARE sent (lets+// errorClass/errorDescription distinguish "explicit empty"+// from "not present"). Non-strings are dropped.+// "int" — Kusto column type `int`. Coerced via Number(); non-finite+// or negative values clamp to 0. Sent as number, not string.+// "object" — Kusto column type `dynamic` (JSON). Plain objects and+// arrays pass through; primitives, Date, RegExp, etc. are+// dropped to avoid Kusto type confusion. Validated here as a+// real object; emit-dispatcher.js re-serializes it to a JSON+// string just before it hits the wire (see buildEnvelope),+// so the Kusto side must `parse_json()` / `todynamic()` it.+// "enum:a|b|c" — Kusto column type `string`. Only the listed values are+// accepted; anything else is dropped.+//+// Both `null` and `undefined` are dropped uniformly. Empty string is allowed+// only for "string" types (deliberate — see above).+const FIELD_TYPES = {+ // Common — identity / context+ pluginName: "string",+ pluginVersion: "string",+ sessionId: "string",+ correlationId: "string",+ osName: "string",+ osVersion: "string",+ nodeVersion: "string",+ // Common — PAC + agent+ orgId: "string",+ tenantId: "string",+ pacCliVersion: "string",+ aiAgentName: "string",+ aiAgentVersion: "string",+ // Common — caller-supplied dynamic JSON. This validates only the container,+ // not nested keys. Callers must follow shared/telemetry/README.md's approved+ // eventInfo schema; arbitrary nested payloads can bypass the top-level allowlist.+ eventInfo: "object",+ // Skill+ skillName: "string",+ // Completed-only+ outcome: "enum:success|failure",+ durationMs: "int",+ errorClass: "string",+ errorDescription: "string",+};++const COMMON_FIELDS = [+ "pluginName",+ "pluginVersion",+ "sessionId",+ "correlationId",+ "osName",+ "osVersion",+ "nodeVersion",+ "orgId",+ "tenantId",+ "pacCliVersion",+ "aiAgentName",+ "aiAgentVersion",+ "eventInfo",+];++const SKILL_FIELDS = ["skillName"];+const COMPLETED_FIELDS = ["outcome", "durationMs", "errorClass", "errorDescription"];++function isPlainStructured(v) {+ if (v === null || typeof v !== "object") return false;+ if (Array.isArray(v)) return true;+ // Only plain objects (prototype Object.prototype or null) pass through —+ // class instances like Date, RegExp, Map, Set, and Error are rejected so+ // the dynamic `eventInfo` field can't carry unexpected shapes.+ const proto = Object.getPrototypeOf(v);+ return proto === Object.prototype || proto === null;+}++function clampInt(v) {+ const n = Number(v);+ if (!Number.isFinite(n) || n < 0) return 0;+ return Math.floor(n);+}++// Type-aware pick. Drops null/undefined for every type. For each kept value,+// validates against its declared type and coerces as needed.+function pick(input, keys) {+ const out = {};+ if (!input || typeof input !== "object") return out;+ for (const k of keys) {+ const v = input[k];+ if (v === undefined || v === null) continue;+ const type = FIELD_TYPES[k];+ if (type === "string") {+ if (typeof v === "string") out[k] = v;+ } else if (type === "int") {+ out[k] = clampInt(v);+ } else if (type === "object") {+ if (isPlainStructured(v)) out[k] = v;+ } else if (typeof type === "string" && type.startsWith("enum:")) {+ const allowed = type.slice(5).split("|");+ if (typeof v === "string" && allowed.includes(v)) out[k] = v;+ }+ // unknown types: drop (defensive — no field should hit this branch).+ }+ return out;+}++function buildEvent(envelopeName, eventName, info, severity) {+ return {+ name: envelopeName,+ data: { eventName, eventType: "Trace", severity, ...info },+ };+}++function buildSkillStarted(envelopeName, input) {+ return buildEvent(+ envelopeName,+ "skill_started",+ pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS]),+ "Info"+ );+}++function buildSkillCompleted(envelopeName, input) {+ const severity = input && input.outcome === "failure" ? "Error" : "Info";+ return buildEvent(+ envelopeName,+ "skill_completed",+ pick(input, [...COMMON_FIELDS, ...SKILL_FIELDS, ...COMPLETED_FIELDS]),+ severity+ );+}++module.exports = {+ buildSkillStarted,+ buildSkillCompleted,+ FIELD_TYPES,+ pick,+};diff --git a/plugins/mobile-apps/scripts/lib/telemetry/lib/local-log.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/local-log.jsnew file mode 100644index 000000000..ed61032d4--- /dev/null+++ b/plugins/mobile-apps/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/mobile-apps/scripts/lib/telemetry/lib/pac-auth.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/pac-auth.jsnew file mode 100644index 000000000..71b268b59--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/pac-auth.js@@ -0,0 +1,76 @@+"use strict";++const { execFileSync } = require("node:child_process");++// Reads PAC CLI auth state by shelling out to `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'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 : execFileSync;+ 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/mobile-apps/scripts/lib/telemetry/lib/prompt-detector.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/prompt-detector.jsnew file mode 100644index 000000000..60474128b--- /dev/null+++ b/plugins/mobile-apps/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/mobile-apps/scripts/lib/telemetry/lib/resolver-loader.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/resolver-loader.jsnew file mode 100644index 000000000..5c5c2bb67--- /dev/null+++ b/plugins/mobile-apps/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/mobile-apps/scripts/lib/telemetry/lib/scrubber.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/scrubber.jsnew file mode 100644index 000000000..517188404--- /dev/null+++ b/plugins/mobile-apps/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/mobile-apps/scripts/lib/telemetry/lib/session.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/session.jsnew file mode 100644index 000000000..cbf89884d--- /dev/null+++ b/plugins/mobile-apps/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/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.jsnew file mode 100644index 000000000..bf92b8a38--- /dev/null+++ b/plugins/mobile-apps/scripts/lib/telemetry/lib/telemetry-config.js@@ -0,0 +1,127 @@+#!/usr/bin/env node+"use strict";++const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const { setTelemetryChoice, effectiveTelemetryChoice } = require("./user-config");+const { pluginLogDir, latestSessionLog } = require("./local-log");++function dataDisclosure(plugin) {+ const pluginSpecific =+ plugin === "power-pages"+ ? " Power Pages can also record the signed-in user's Entra object ID as\n" ++ " eventInfo.aadObjectId when PAC exposes it, and the SPA framework of the\n" ++ " Power Pages code site being worked in as eventInfo.framework when detected.\n" ++ " The framework is one of react, vue, angular, or astro and describes the\n" ++ " scaffold only — it is never a site name or path.\n"+ : plugin === "model-apps"+ ? " Model Apps excludes the signed-in user's Entra object ID.\n"+ : "";+ return (+ "ℹ️ Usage telemetry records skill, plugin, PAC, agent, OS, Node, session,\n" ++ " and correlation fields, plus Dataverse organization and Entra tenant IDs\n" ++ " when PAC is signed in.\n" ++ pluginSpecific ++ " When plugin telemetry is enabled, the local diagnostic log retains the same\n" ++ " fields even when transmission is off. A plugin whose committed telemetry\n" ++ " config has disabled: true is hard-disabled and writes no log.\n" ++ " Events do not include file paths, prompts, tool inputs, site names,\n" ++ " Dataverse URLs, credentials, usernames, or hostnames."+ );+}++function getArg(name) {+ const i = process.argv.indexOf(`--${name}`);+ return i !== -1 && i + 1 < process.argv.length ? process.argv[i + 1] : null;+}++function configDir() {+ return (+ process.env.POWER_PLATFORM_SKILLS_CONFIG_DIR ||+ path.join(os.homedir(), ".power-platform-skills")+ );+}++// --plugin wins; otherwise auto-detect from the plugin manifest 4 levels up+// (.../plugins/<plugin>/scripts/lib/telemetry/lib/telemetry-config.js).+function resolvePlugin() {+ const explicit = getArg("plugin");+ if (explicit) return explicit;+ try {+ const manifestPath = path.resolve(+ __dirname, "..", "..", "..", "..", ".claude-plugin", "plugin.json"+ );+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));+ return manifest.name || null;+ } catch {+ return null;+ }+}++function out(s) {+ process.stdout.write(s + "\n");+}++// Print where this plugin's local diagnostic logs live and name the newest+// session file, so a user can hand over exactly the log for the session they+// just hit a problem in. Reuses the shared layout helpers (DRY — no path logic+// is duplicated in the skill).+function emitLogLocations(dir, plugin) {+ out(`Logs directory: ${pluginLogDir(dir, plugin)}`);+ const latest = latestSessionLog(dir, plugin);+ if (latest) {+ out(`Most recent session: ${latest}`);+ out("ℹ️ Share that file when reporting an issue (it covers your latest session).");+ } else {+ out(`No local logs yet for ${plugin}.`);+ }+}++function main() {+ const action = getArg("action");+ const plugin = resolvePlugin();+ if (!plugin || !["on", "off", "status"].includes(action)) {+ out("Usage: telemetry-config.js --action <on|off|status> [--plugin <name>]");+ process.exit(2);+ }+ const dir = configDir();++ if (action === "status") {+ const on = effectiveTelemetryChoice(dir, plugin) !== "off"; // default ON; honors env override when no stored choice+ if (on) {+ out(`Telemetry (${plugin}): ON`);+ out(dataDisclosure(plugin));+ emitLogLocations(dir, plugin);+ } else {+ out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);+ out(`The local diagnostic log is kept whenever telemetry is enabled for this plugin, even when transmission is OFF (opt-out stops transmission only).`);+ emitLogLocations(dir, plugin);+ out(`Re-enable with /${plugin}:telemetry on (an environment opt-out, if set, takes precedence and this command cannot override it).`);+ out(dataDisclosure(plugin));+ }+ process.exit(0);+ }++ if (!setTelemetryChoice(dir, plugin, action)) {+ out(`Could not update the telemetry setting (config dir not writable).`);+ process.exit(1);+ }+ if (action === "off") {+ out(`Telemetry (${plugin}): OFF — nothing is transmitted.`);+ out(`The local diagnostic log is kept whenever telemetry is enabled for this plugin, even when transmission is OFF (opt-out stops transmission only).`);+ emitLogLocations(dir, plugin);+ out(`Re-enable with /${plugin}:telemetry on (an environment opt-out, if set, takes precedence and this command cannot override it).`);+ } else if (effectiveTelemetryChoice(dir, plugin) === "off") {+ // The preference was saved as ON, but the highest-precedence environment+ // opt-out still forces transmission off — report the EFFECTIVE state so we+ // never claim ON while an opt-out is suppressing it.+ out(`Telemetry (${plugin}): preference saved as ON, but an environment opt-out is currently in effect — nothing is transmitted until it is cleared.`);+ } else {+ out(`Telemetry (${plugin}): ON`);+ }+ out(dataDisclosure(plugin));+ process.exit(0);+}++main();diff --git a/plugins/mobile-apps/scripts/lib/telemetry/lib/user-config.js b/plugins/mobile-apps/scripts/lib/telemetry/lib/user-config.jsnew file mode 100644index 000000000..ea0597f73--- /dev/null+++ b/plugins/mobile-apps/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/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.js b/plugins/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.jsnew file mode 100644index 000000000..6cf959c37--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/mobile-telemetry-hooks.test.js@@ -0,0 +1,438 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');+const { TRACKED_SKILL_NAMES } = require('../lib/mobileapp-hook-utils');+const { withStableDispatchCwd } = require('../../hooks/run-telemetry');++const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');+const PLUGIN_VERSION = JSON.parse(+ fs.readFileSync(path.join(PLUGIN_ROOT, '.claude-plugin', 'plugin.json'), 'utf8'),+).version;+const HOOKS = path.join(PLUGIN_ROOT, 'hooks');++function fixture(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-telemetry-hooks-'));+ const projectRoot = path.join(root, 'project');+ const configDir = path.join(root, 'config');+ fs.mkdirSync(projectRoot, { recursive: true });+ fs.mkdirSync(configDir, { recursive: true });+ fs.writeFileSync(+ path.join(projectRoot, 'package.json'),+ JSON.stringify({ dependencies: { expo: '^55', '@microsoft/power-apps-native-host': '^1' } }),+ );+ const ikeyPath = path.join(root, 'ikey.json');+ fs.writeFileSync(ikeyPath, JSON.stringify({+ instrumentationKey: 'test-mobile-key',+ collector_url: 'https://example.invalid/OneCollector/1.0/',+ event_stream_name: 'MobileAppsTestEvent',+ disabled: false,+ }));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ return { root, projectRoot, configDir, ikeyPath };+}++function runHook(mode, payload, context, extraEnv = {}) {+ return spawnSync(process.execPath, [path.join(HOOKS, 'run-telemetry.js'), mode], {+ cwd: context.projectRoot,+ input: JSON.stringify(payload),+ encoding: 'utf8',+ timeout: 10_000,+ env: {+ ...process.env,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: context.configDir,+ POWER_PLATFORM_SKILLS_IKEY_JSON: context.ikeyPath,+ // Positive tests keep the local mirror but can never contact OneCollector.+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1',+ ...extraEnv,+ },+ });+}++function sleep(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++function logPath(context, sessionId = 'session-1') {+ return path.join(+ context.configDir,+ 'telemetry',+ 'mobile-app',+ 'sessions',+ sessionId,+ 'events.jsonl',+ );+}++function waitForEvents(context, expected, sessionId = 'session-1') {+ const filePath = logPath(context, sessionId);+ const deadline = Date.now() + 5000;+ while (Date.now() < deadline) {+ try {+ const lines = fs.readFileSync(filePath, 'utf8').trim().split('\n').filter(Boolean);+ if (lines.length >= expected) return lines.map((line) => JSON.parse(line));+ } catch {+ // The detached dispatcher has not written yet.+ }+ sleep(25);+ }+ return [];+}++function waitForJson(filePath) {+ const deadline = Date.now() + 5000;+ while (Date.now() < deadline) {+ try {+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));+ } catch {+ // The detached dispatcher has not finished writing the probe yet.+ }+ sleep(25);+ }+ return null;+}++function toolPayload(context) {+ return {+ cwd: context.projectRoot,+ session_id: 'session-1',+ tool_input: { skill: 'deploy' },+ };+}++test('hook dispatch runs outside the caller project and restores its cwd', () => {+ const originalCwd = process.cwd();+ let dispatchCwd;++ withStableDispatchCwd(() => {+ dispatchCwd = fs.realpathSync(process.cwd());+ });++ assert.equal(dispatchCwd, fs.realpathSync(os.tmpdir()));+ assert.equal(process.cwd(), originalCwd);+});++test('prompt and pretool paths emit independent start signals', (t) => {+ const context = fixture(t);+ assert.equal(runHook('prompt', {+ cwd: context.projectRoot,+ session_id: 'session-1',+ prompt: '/deploy',+ }, context).status, 0);+ assert.equal(runHook('pretool', toolPayload(context), context).status, 0);++ const records = waitForEvents(context, 2);+ assert.equal(records.length, 2);+ assert.ok(records.every((record) => record.data.eventName === 'skill_started'));+ assert.deepEqual(+ records.map((record) => record.data.eventInfo.invocationSource).sort(),+ ['pretool', 'prompt'],+ );+ assert.equal(new Set(records.map((record) => record.data.correlationId)).size, 2);+});++test('pretool-only invocation emits one start', (t) => {+ const context = fixture(t);+ assert.equal(runHook('pretool', toolPayload(context), context).status, 0);+ const records = waitForEvents(context, 1);+ assert.equal(records.filter((record) => record.data.eventName === 'skill_started').length, 1);+ assert.equal(records[0].data.eventInfo.invocationSource, 'pretool');+});++function seedCopilotSession(homeDir, rootSessionId, nestedSessionId) {+ const sessionDir = path.join(homeDir, '.copilot', 'session-state', rootSessionId);+ fs.mkdirSync(sessionDir, { recursive: true });+ fs.writeFileSync(+ path.join(sessionDir, 'events.jsonl'),+ `${JSON.stringify({ type: 'hook.start', agentId: nestedSessionId })}\n`,+ );+}++test('nested Copilot agents log under their own owning root session', (t) => {+ const context = fixture(t);+ const homeDir = path.join(context.root, 'home');+ const sessions = [+ { root: 'e58e3db3-8361-4516-ac4b-6b143c22100a', nested: 'call_firstAgent', skill: 'deploy' },+ { root: '97bd0a1b-a83b-4e59-a23e-1c6688626401', nested: 'call_secondAgent', skill: 'debug-app' },+ ];+ const invoke = (current) => assert.equal(runHook('pretool', {+ cwd: context.projectRoot,+ sessionId: current.nested,+ tool_input: { skill: current.skill },+ }, context, {+ HOME: homeDir,+ // os.homedir() uses USERPROFILE rather than HOME on Windows.+ USERPROFILE: homeDir,+ }).status, 0);++ for (const current of sessions) {+ seedCopilotSession(homeDir, current.root, current.nested);+ invoke(current);+ }+ for (const current of sessions) {+ assert.equal(waitForEvents(context, 1, current.root).length, 1);+ }++ // Every hook runs in a fresh Node process, so removing the host state proves+ // the second round resolves only through the cross-process alias cache.+ fs.rmSync(path.join(homeDir, '.copilot'), { recursive: true, force: true });+ for (const current of sessions) invoke(current);++ for (const current of sessions) {+ const records = waitForEvents(context, 2, current.root);+ assert.equal(records.length, 2);+ assert.ok(records.every((record) => record.data.sessionId === current.root));+ assert.equal(fs.existsSync(logPath(context, current.nested)), false);+ }+});++test('pretool hook emits every tracked skill from bare and qualified names', (t) => {+ const context = fixture(t);+ for (const skillName of TRACKED_SKILL_NAMES) {+ for (const reportedName of [skillName, `mobile-app:${skillName}`]) {+ assert.equal(runHook('pretool', {+ cwd: context.root,+ session_id: 'session-1',+ tool_input: { skill: reportedName },+ }, context).status, 0);+ }+ }++ const records = waitForEvents(context, TRACKED_SKILL_NAMES.length * 2);+ assert.deepEqual(+ records.map((record) => record.data.skillName).sort(),+ TRACKED_SKILL_NAMES.flatMap((skillName) => [skillName, skillName]).sort(),+ );+ assert.ok(records.every(+ (record) => record.data.eventInfo.invocationSource === 'pretool',+ ));+});++test('bare nested skill emits when the session cwd is outside the mobile project', (t) => {+ const context = fixture(t);+ assert.equal(runHook('pretool', {+ cwd: context.root,+ session_id: 'session-1',+ tool_input: { skill: 'design-system' },+ }, context).status, 0);++ const records = waitForEvents(context, 1);+ assert.equal(records.length, 1);+ assert.equal(records[0].data.skillName, 'design-system');+ assert.equal(records[0].data.eventInfo.invocationSource, 'pretool');+});++test('prompt hook builds the Power Apps normal-event envelope without real network access', (t) => {+ const context = fixture(t);+ const probePath = path.join(context.root, 'probe.json');+ const result = runHook('prompt', {+ cwd: context.projectRoot,+ session_id: 'session-1',+ prompt: '/mobile-app:deploy',+ }, context, {+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,+ // The fake probe is the only positive transmission test. It clears the CI+ // backstop in this child while the dispatcher remains unable to reach a URL.+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '',+ });++ assert.equal(result.status, 0);+ const probe = waitForJson(probePath);+ assert.ok(probe, 'dispatcher should write the fake HTTPS probe');+ assert.equal(probe.headers['Content-Type'], 'application/x-json-stream; charset=utf-8');+ assert.equal(probe.headers['x-apikey'], 'test-mobile-key');+ assert.ok(probe.body.endsWith('\n'));+ const envelope = JSON.parse(probe.body);+ assert.deepEqual(Object.keys(envelope).sort(), ['data', 'ext', 'iKey', 'name', 'time', 'ver']);+ assert.equal(envelope.ver, '4.0');+ assert.equal(envelope.name, 'MobileAppsTestEvent');+ assert.equal(envelope.iKey, 'o:test');+ assert.equal(envelope.data.app_Name, 'powerappsclient');+ assert.equal(envelope.data.clientType, 'PowerAppsNative');+ assert.equal(envelope.data.clusterCategory, 'prod');+ assert.equal(envelope.data.device_Id, 'react-native');+ assert.equal(envelope.data.event_Name, 'skill_started');+ assert.equal(envelope.data.session_Id, 'session-1');+ assert.equal(envelope.data.severity, 'Info');+ assert.equal(envelope.data.timestamp, envelope.time);+ assert.equal(envelope.ext.app.sesId, 'session-1');+ assert.equal(envelope.ext.app.ver, PLUGIN_VERSION);+ assert.ok(envelope.ext.os.name);+ assert.ok(envelope.ext.os.ver);++ const dimensions = JSON.parse(envelope.data.customDimensions);+ assert.equal(dimensions.pluginName, 'mobile-app');+ assert.equal(dimensions.pluginVersion, PLUGIN_VERSION);+ assert.equal(dimensions.sessionId, 'session-1');+ assert.match(dimensions.correlationId, /^[0-9a-f-]{36}$/);+ assert.ok(dimensions.osName);+ assert.ok(dimensions.osVersion);+ assert.match(dimensions.nodeVersion, /^v\d+$/);+ assert.equal(dimensions.skillName, 'deploy');+ assert.deepEqual(dimensions.eventInfo, {+ invocationSource: 'prompt',+ appInstanceId: null,+ });+ for (const legacy of ['eventName', 'eventType', 'pluginName', 'sessionId', 'skillName']) {+ assert.equal(Object.prototype.hasOwnProperty.call(envelope.data, legacy), false);+ }+ for (const forbidden of [+ 'orgId',+ 'tenantId',+ 'pacCliVersion',+ 'aadObjectId',+ 'prompt',+ 'cwd',+ 'path',+ 'outcome',+ 'durationMs',+ 'errorClass',+ 'errorDescription',+ ]) {+ assert.equal(Object.prototype.hasOwnProperty.call(dimensions, forbidden), false);+ }+});++test('environment opt-out keeps the local mirror and suppresses transmission', (t) => {+ const context = fixture(t);+ const probePath = path.join(context.root, 'opted-out-probe.json');+ const result = runHook('pretool', toolPayload(context), context, {+ POWER_PLATFORM_SKILLS_FAKE_HTTPS: probePath,+ });++ assert.equal(result.status, 0);+ assert.equal(waitForEvents(context, 1).length, 1);+ assert.equal(fs.existsSync(probePath), false);+});++test('bare command outside a mobile project emits a start', (t) => {+ const context = fixture(t);+ const unrelated = path.join(context.root, 'unrelated');+ fs.mkdirSync(unrelated);+ runHook('prompt', {+ cwd: unrelated,+ session_id: 'session-1',+ prompt: '/deploy',+ }, context);++ const records = waitForEvents(context, 1);+ assert.equal(records.length, 1);+ assert.equal(records[0].data.skillName, 'deploy');+ assert.equal(records[0].data.eventInfo.invocationSource, 'prompt');+ assert.equal(records[0].data.eventInfo.appInstanceId, null);+});++test('manual Copilot slash command emits after host expansion', (t) => {+ const context = fixture(t);+ assert.equal(runHook('prompt', {+ cwd: context.projectRoot,+ session_id: 'session-1',+ prompt: '<skill-context name="add-connector">\n<instructions>redacted</instructions>',+ }, context).status, 0);++ const records = waitForEvents(context, 1);+ assert.equal(records.length, 1);+ assert.equal(records[0].data.skillName, 'add-connector');+ assert.equal(records[0].data.eventInfo.invocationSource, 'prompt');+ assert.equal(records[0].data.eventInfo.appInstanceId, null);+});++test('hook attaches app identity from app.json when cwd is a project root', (t) => {+ const context = fixture(t);+ fs.writeFileSync(+ path.join(context.projectRoot, 'app.json'),+ JSON.stringify({+ expo: {+ extra: {+ telemetry: {+ appInstanceId: '5d7e71b1-61d6-4a91-9c2e-cba5db983e38',+ },+ },+ },+ }),+ );++ assert.equal(runHook('pretool', {+ cwd: context.projectRoot,+ session_id: 'session-1',+ tool_input: { skill: 'deploy' },+ }, context).status, 0);++ const records = waitForEvents(context, 1);+ assert.equal(records.length, 1);+ assert.equal(records[0].data.eventInfo.invocationSource, 'pretool');+ assert.equal(+ records[0].data.eventInfo.appInstanceId,+ '5d7e71b1-61d6-4a91-9c2e-cba5db983e38',+ );+});++test('hook resolves --working-dir from tool input when cwd is outside the project', (t) => {+ const context = fixture(t);+ fs.writeFileSync(+ path.join(context.projectRoot, 'app.json'),+ JSON.stringify({+ expo: {+ extra: {+ telemetry: {+ appInstanceId: 'e5b2f43c-fa9f-44a0-b8a7-54e4f956f9db',+ },+ },+ },+ }),+ );+ const unrelated = path.join(context.root, 'outside');+ fs.mkdirSync(unrelated);++ assert.equal(runHook('pretool', {+ cwd: unrelated,+ session_id: 'session-1',+ tool_input: {+ skill: 'deploy',+ arguments: `--working-dir "${context.projectRoot}" --non-interactive`,+ },+ }, context).status, 0);++ const records = waitForEvents(context, 1);+ assert.equal(records.length, 1);+ assert.equal(+ records[0].data.eventInfo.appInstanceId,+ 'e5b2f43c-fa9f-44a0-b8a7-54e4f956f9db',+ );+});++test('another plugin namespace and embedded command are no-ops', (t) => {+ const context = fixture(t);+ runHook('prompt', {+ cwd: context.projectRoot,+ session_id: 'session-1',+ prompt: '/code-apps:deploy',+ }, context);+ runHook('prompt', {+ cwd: context.projectRoot,+ session_id: 'session-1',+ prompt: 'please run /mobile-app:deploy',+ }, context);+ sleep(300);+ assert.equal(fs.existsSync(logPath(context)), false);+});++test('disabled repository config creates no telemetry artifacts', (t) => {+ const context = fixture(t);+ const disabledIkey = path.join(context.root, 'disabled-ikey.json');+ fs.writeFileSync(disabledIkey, JSON.stringify({+ instrumentationKey: 'test-mobile-key',+ collector_url: 'https://example.invalid/OneCollector/1.0/',+ event_stream_name: 'MobileAppsTestEvent',+ disabled: true,+ }));+ runHook('pretool', toolPayload(context), context, {+ POWER_PLATFORM_SKILLS_IKEY_JSON: disabledIkey,+ });+ sleep(300);+ assert.equal(fs.existsSync(path.join(context.configDir, 'telemetry')), false);+});\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/tests/mobile-telemetry.test.js b/plugins/mobile-apps/scripts/tests/mobile-telemetry.test.jsnew file mode 100644index 000000000..a9c285643--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/mobile-telemetry.test.js@@ -0,0 +1,355 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');++const {+ createTelemetryContext,+ emitSkillStarted,+} = require('../lib/mobile-telemetry');+const { ensureAppInstanceId, findAppInstanceId } = require('../lib/app-identity');++const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');+const TELEMETRY_CLI = path.join(+ PLUGIN_ROOT,+ 'scripts',+ 'lib',+ 'mobile-telemetry-config.js',+);+const BUNDLED_TELEMETRY_LIB = path.join(PLUGIN_ROOT, 'scripts', 'lib', 'telemetry', 'lib');+const SHARED_TELEMETRY_LIB = path.resolve(PLUGIN_ROOT, '..', '..', 'shared', 'telemetry', 'lib');++function tempConfig(config) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-telemetry-'));+ const ikeyPath = path.join(dir, 'ikey.json');+ fs.writeFileSync(ikeyPath, JSON.stringify(config));+ return { dir, ikeyPath };+}++// An empty directory keeps app-identity lookup out of the repo checkout, so+// event assertions do not depend on where the suite happens to run.+function tempProject(t) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-app-project-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ return dir;+}++function contextFor(config) {+ const { dir, ikeyPath } = tempConfig(config);+ return createTelemetryContext(+ { session_id: 'session-1' },+ {+ env: {+ POWER_PLATFORM_SKILLS_CONFIG_DIR: dir,+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,+ },+ },+ );+}++function copilotOpts(t, roots, now = Date.now()) {+ const { dir, ikeyPath } = tempConfig(provisioned);+ const copilotSessionStateDir = path.join(dir, 'copilot-session-state');+ for (const root of roots) {+ const eventsPath = path.join(copilotSessionStateDir, root.id, 'events.jsonl');+ fs.mkdirSync(path.dirname(eventsPath), { recursive: true });+ fs.writeFileSync(+ eventsPath,+ `${JSON.stringify({ type: 'hook.start', agentId: root.agentId })}\n`,+ );+ const modified = new Date(root.mtimeMs === undefined ? now : root.mtimeMs);+ fs.utimesSync(eventsPath, modified, modified);+ }+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ return {+ env: {+ POWER_PLATFORM_SKILLS_CONFIG_DIR: dir,+ POWER_PLATFORM_SKILLS_IKEY_JSON: ikeyPath,+ },+ copilotSessionAliasDir: path.join(dir, 'session-aliases'),+ copilotSessionStateDir,+ now,+ };+}++function copilotSessionId(t, roots, nestedSessionId, now) {+ const context = createTelemetryContext(+ { sessionId: nestedSessionId },+ copilotOpts(t, roots, now),+ );+ assert.ok(context);+ return context.sessionId;+}++const provisioned = {+ instrumentationKey: 'test-mobile-key',+ collector_url: 'https://example.invalid/OneCollector/1.0/',+ event_stream_name: 'MobileAppsTestEvent',+ disabled: false,+};++const invocation = {+ skillName: 'deploy',+ source: 'pretool',+};++function relativeFiles(root, current = root) {+ const files = [];+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {+ const absolute = path.join(current, entry.name);+ if (entry.isDirectory()) files.push(...relativeFiles(root, absolute));+ if (entry.isFile()) files.push(path.relative(root, absolute));+ }+ return files.sort();+}++test('hard-off and placeholder configurations create no telemetry context', () => {+ assert.equal(contextFor({ ...provisioned, disabled: true }), null);+ assert.equal(contextFor({ ...provisioned, instrumentationKey: 'PLACEHOLDER_REPLACE_BEFORE_SHIPPING' }), null);+ assert.equal(contextFor({ ...provisioned, collector_url: '' }), null);+});++test('provisioned context uses host session and isolated config paths', () => {+ const context = contextFor(provisioned);+ assert.ok(context);+ assert.equal(context.sessionId, 'session-1');+ assert.equal(context.eventStreamName, 'MobileAppsTestEvent');+});++test('nested Copilot call resolves to its owning root session', (t) => {+ const rootSessionId = 'e58e3db3-8361-4516-ac4b-6b143c22100a';+ const nestedSessionId = 'call_ayAuxKIYLLOtpejidbHsMAmu';+ assert.equal(copilotSessionId(t, [+ { id: rootSessionId, agentId: nestedSessionId },+ { id: '97bd0a1b-a83b-4e59-a23e-1c6688626401', agentId: 'call_unrelatedAgent' },+ ], nestedSessionId), rootSessionId);+});++test('oversized partial Copilot record cannot claim a nested session', (t) => {+ const rootSessionId = 'e58e3db3-8361-4516-ac4b-6b143c22100a';+ const nestedSessionId = 'call_partialRecord';+ const opts = copilotOpts(t, [{ id: rootSessionId, agentId: 'call_unrelatedAgent' }]);+ const eventsPath = path.join(opts.copilotSessionStateDir, rootSessionId, 'events.jsonl');+ const parseableFragment = JSON.stringify({ agentId: nestedSessionId });+ const maxTailBytes = 4 * 1024 * 1024;++ // The bounded read starts after the leading byte, making its entire tail look+ // like valid JSON even though no newline proves that it starts at a record.+ fs.writeFileSync(+ eventsPath,+ `x${parseableFragment}${' '.repeat(maxTailBytes - parseableFragment.length)}`,+ );++ const context = createTelemetryContext({ sessionId: nestedSessionId }, opts);+ assert.ok(context);+ assert.equal(context.sessionId, nestedSessionId);+});++test('stale Copilot state does not absorb a nested session', (t) => {+ const now = Date.now();+ const nestedSessionId = 'call_staleNestedAgent';+ assert.equal(copilotSessionId(t, [{+ id: 'e58e3db3-8361-4516-ac4b-6b143c22100a',+ agentId: nestedSessionId,+ mtimeMs: now - (10 * 60 * 1000),+ }], nestedSessionId, now), nestedSessionId);+});++test('ambiguous Copilot ownership does not merge root sessions', (t) => {+ const nestedSessionId = 'call_duplicatedNestedAgent';+ assert.equal(copilotSessionId(t, [+ { id: 'e58e3db3-8361-4516-ac4b-6b143c22100a', agentId: nestedSessionId },+ { id: '97bd0a1b-a83b-4e59-a23e-1c6688626401', agentId: nestedSessionId },+ ], nestedSessionId), nestedSessionId);+});++test('expired Copilot alias does not outlive unavailable host state', (t) => {+ const rootSessionId = 'e58e3db3-8361-4516-ac4b-6b143c22100a';+ const nestedSessionId = 'call_expiringNestedAgent';+ const now = Date.now();+ const opts = copilotOpts(t, [{ id: rootSessionId, agentId: nestedSessionId }], now);++ const initial = createTelemetryContext({ sessionId: nestedSessionId }, opts);+ assert.ok(initial);+ assert.equal(initial.sessionId, rootSessionId);++ fs.rmSync(opts.copilotSessionStateDir, { recursive: true, force: true });+ const expired = createTelemetryContext(+ { sessionId: nestedSessionId },+ { ...opts, now: now + (31 * 60 * 1000) },+ );+ assert.ok(expired);+ assert.equal(expired.sessionId, nestedSessionId);+});++test('started event is allowlisted and carries no user, tenant, prompt, or path data', (t) => {+ const context = contextFor(provisioned);+ let captured;+ const event = emitSkillStarted(context, invocation, {+ emit: (value) => { captured = value; },+ readAiAgent: () => ({ aiAgentName: 'GitHub Copilot', aiAgentVersion: '1.2.3' }),+ correlationId: 'correlation-1',+ cwd: tempProject(t),+ });+ assert.equal(captured, event);+ assert.equal(event.data.eventName, 'skill_started');+ assert.equal(event.data.pluginName, 'mobile-app');+ assert.equal(event.data.skillName, 'deploy');+ assert.equal(event.data.sessionId, 'session-1');+ assert.equal(event.data.correlationId, 'correlation-1');+ assert.deepEqual(event.data.eventInfo, { invocationSource: 'pretool', appInstanceId: null });+ for (const forbidden of ['orgId', 'tenantId', 'pacCliVersion', 'aadObjectId', 'prompt', 'cwd', 'path']) {+ assert.equal(Object.prototype.hasOwnProperty.call(event.data, forbidden), false);+ }+});++test('app instance id is minted once and reused by later skill runs', (t) => {+ const project = tempProject(t);+ fs.writeFileSync(+ path.join(project, 'app.json'),+ JSON.stringify({+ expo: {+ extra: {+ powerappsNative: {+ schemaVersion: 1,+ templateVersion: 1,+ },+ },+ },+ }),+ );+ const appInstanceId = ensureAppInstanceId(project);+ assert.match(appInstanceId, /^[0-9a-f-]{36}$/);+ assert.equal(ensureAppInstanceId(project), appInstanceId);+ assert.equal(findAppInstanceId(project), appInstanceId);+ assert.equal(findAppInstanceId(path.join(project, 'src', 'screens')), '');+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(project, 'app.json'), 'utf8')), {+ expo: {+ extra: {+ powerappsNative: {+ schemaVersion: 1,+ templateVersion: 1,+ },+ telemetry: { appInstanceId },+ },+ },+ });+});++test('app identity refuses missing or invalid Expo app.json files', (t) => {+ const invalidProjects = [+ { project: tempProject(t), contents: null },+ { project: tempProject(t), contents: '{ invalid json' },+ { project: tempProject(t), contents: '{}' },+ ];++ for (const { project, contents } of invalidProjects) {+ const filePath = path.join(project, 'app.json');+ if (contents !== null) fs.writeFileSync(filePath, contents);++ assert.throws(+ () => ensureAppInstanceId(project),+ /existing, valid Expo app\.json/,+ );+ assert.equal(+ fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : null,+ contents,+ );+ }+});++test('events outside a project carry no app identity', (t) => {+ assert.equal(findAppInstanceId(tempProject(t)), '');+});++test('a hand-edited app identity is ignored rather than emitted', (t) => {+ const project = tempProject(t);+ fs.writeFileSync(+ path.join(project, 'app.json'),+ JSON.stringify({+ expo: {+ extra: {+ telemetry: {+ appInstanceId: 'contoso-field-inspections',+ },+ },+ },+ }),+ );+ assert.equal(findAppInstanceId(project), '');+});++test('two apps in one session emit distinct app identities', (t) => {+ const context = contextFor(provisioned);+ const emitFrom = (project) => emitSkillStarted(context, invocation, {+ emit: () => {},+ readAiAgent: () => ({}),+ cwd: project,+ }).data;++ const first = emitFrom(tempProject(t));+ const second = emitFrom(tempProject(t));+ assert.equal(first.sessionId, second.sessionId);+ assert.equal(first.eventInfo.appInstanceId, null);++ const projectA = tempProject(t);+ const projectB = tempProject(t);+ fs.writeFileSync(path.join(projectA, 'app.json'), JSON.stringify({ expo: {} }));+ fs.writeFileSync(path.join(projectB, 'app.json'), JSON.stringify({ expo: {} }));+ ensureAppInstanceId(projectA);+ ensureAppInstanceId(projectB);+ const a = emitFrom(projectA);+ const b = emitFrom(projectB);+ assert.notEqual(a.eventInfo.appInstanceId, b.eventInfo.appInstanceId);+ assert.equal(a.sessionId, b.sessionId);+});++test('bundled telemetry library is byte-identical to the canonical shared source', (t) => {+ if (!fs.existsSync(SHARED_TELEMETRY_LIB)) {+ t.skip('canonical shared source is unavailable in an installed plugin');+ return;+ }++ const expectedFiles = relativeFiles(SHARED_TELEMETRY_LIB);+ assert.deepEqual(relativeFiles(BUNDLED_TELEMETRY_LIB), expectedFiles);+ for (const relativePath of expectedFiles) {+ assert.deepEqual(+ fs.readFileSync(path.join(BUNDLED_TELEMETRY_LIB, relativePath)),+ fs.readFileSync(path.join(SHARED_TELEMETRY_LIB, relativePath)),+ `${relativePath} must be refreshed from shared/telemetry/lib`,+ );+ }+});++test('Mobile control wrapper updates preference with accurate disclosure', (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-telemetry-control-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const env = {+ ...process.env,+ POWER_PLATFORM_SKILLS_CONFIG_DIR: dir,+ POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '',+ };++ const status = spawnSync(process.execPath, [TELEMETRY_CLI, '--action', 'status'], {+ encoding: 'utf8',+ env,+ });+ assert.equal(status.status, 0);+ assert.match(status.stdout, /Telemetry \(mobile-app\): ON/);+ assert.match(status.stdout, /does not record PAC CLI version/);+ assert.match(status.stdout, /organization or Entra tenant IDs/);+ assert.doesNotMatch(status.stdout, /when PAC is signed in/);++ const off = spawnSync(process.execPath, [TELEMETRY_CLI, '--action', 'off'], {+ encoding: 'utf8',+ env,+ });+ assert.equal(off.status, 0);+ assert.match(off.stdout, /Telemetry \(mobile-app\): OFF/);+ const saved = JSON.parse(fs.readFileSync(path.join(dir, 'config.json'), 'utf8'));+ assert.equal(saved.telemetry['mobile-app'], 'off');+});\ No newline at end of filediff --git a/plugins/mobile-apps/scripts/tests/mobileapp-hook-utils.test.js b/plugins/mobile-apps/scripts/tests/mobileapp-hook-utils.test.jsnew file mode 100644index 000000000..767833c41--- /dev/null+++ b/plugins/mobile-apps/scripts/tests/mobileapp-hook-utils.test.js@@ -0,0 +1,106 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');++const {+ TRACKED_SKILL_NAMES,+ detectTrackedSkill,+ getTrackedSkillFromPrompt,+ getTrackedSkillFromToolInput,+ isInvocable,+ readInvocationMetadata,+} = require('../lib/mobileapp-hook-utils');++const PLUGIN_ROOT = path.resolve(__dirname, '..', '..');+const SKILLS_DIR = path.join(PLUGIN_ROOT, 'skills');++test('discovers every invocable top-level skill without tracking direct-read helpers', () => {+ const expected = fs+ .readdirSync(SKILLS_DIR, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .filter((entry) => isInvocable(+ readInvocationMetadata(path.join(SKILLS_DIR, entry.name, 'SKILL.md')),+ ))+ .map((entry) => entry.name)+ .sort();++ assert.deepEqual([...TRACKED_SKILL_NAMES].sort(), expected);+ assert.ok(TRACKED_SKILL_NAMES.includes('create-mobile-app'));+ assert.ok(TRACKED_SKILL_NAMES.includes('deploy'));+ assert.ok(TRACKED_SKILL_NAMES.includes('assign-offline-profile'));+ assert.ok(TRACKED_SKILL_NAMES.includes('preview-offline-scope'));+ assert.ok(TRACKED_SKILL_NAMES.includes('telemetry'));+ assert.equal(TRACKED_SKILL_NAMES.includes('add-camera'), false);+ assert.equal(TRACKED_SKILL_NAMES.includes('add-table-to-offline-profile'), false);+});++test('hook manifest registers start telemetry surfaces only', () => {+ const manifest = JSON.parse(fs.readFileSync(path.join(PLUGIN_ROOT, 'hooks', 'hooks.json'), 'utf8'));+ assert.deepEqual(Object.keys(manifest.hooks).sort(), ['PreToolUse', 'UserPromptSubmit']);+ const pretoolCommand = manifest.hooks.PreToolUse[0].hooks[0].command;+ const promptCommand = manifest.hooks.UserPromptSubmit[0].hooks[0].command;+ assert.match(pretoolCommand, /run-telemetry\.js.+start\('pretool'\)/);+ assert.match(promptCommand, /run-telemetry\.js.+start\('prompt'\)/);+});++test('accepts every tracked skill in bare and qualified forms regardless of cwd', () => {+ for (const skillName of TRACKED_SKILL_NAMES) {+ assert.equal(detectTrackedSkill(`/${skillName}`), skillName);+ assert.equal(detectTrackedSkill(`/mobile-app:${skillName}`), skillName);+ assert.equal(getTrackedSkillFromPrompt(`/${skillName}`), skillName);+ assert.equal(getTrackedSkillFromPrompt(`/mobile-app:${skillName}`), skillName);+ assert.equal(getTrackedSkillFromToolInput({ skill: skillName }), skillName);+ assert.equal(+ getTrackedSkillFromToolInput({ skill: `mobile-app:${skillName}` }),+ skillName,+ );+ }+});++test('does not attribute another plugin command to mobile-app', () => {+ assert.equal(detectTrackedSkill('/code-apps:deploy'), null);+ assert.equal(getTrackedSkillFromPrompt('/power-pages:setup-datamodel'), null);+ assert.equal(getTrackedSkillFromToolInput({ skill: 'other-plugin:report-issue' }), null);+});++test('prompt detection requires an explicit leading slash command', () => {+ assert.equal(getTrackedSkillFromPrompt('/mobile-app:deploy now'), 'deploy');+ assert.equal(getTrackedSkillFromPrompt(' /deploy now'), 'deploy');+ assert.equal(getTrackedSkillFromPrompt('please run /mobile-app:deploy'), null);+ assert.equal(getTrackedSkillFromPrompt('mobile-app:deploy'), null);+});++test('prompt detection accepts Copilot manual skill-context wrappers', () => {+ assert.equal(+ getTrackedSkillFromPrompt('<skill-context name="add-connector">\nredacted instructions'),+ 'add-connector',+ );+ assert.equal(+ getTrackedSkillFromPrompt('<skill-context name="create-mobile-app">\nredacted instructions'),+ 'create-mobile-app',+ );+ assert.equal(getTrackedSkillFromPrompt('<skill-context name="not-mobile">'), null);+ assert.equal(+ getTrackedSkillFromPrompt('text before <skill-context name="add-connector">'),+ null,+ );+});++test('reads known host tool-input field variants', () => {+ assert.equal(getTrackedSkillFromToolInput({ skill: 'deploy' }), 'deploy');+ assert.equal(getTrackedSkillFromToolInput({ skill_name: 'mobile-app:debug-app' }), 'debug-app');+ assert.equal(+ getTrackedSkillFromToolInput({ command: '/mobile-app:preview-screens now' }),+ 'preview-screens',+ );+});++test('rejects prototype names and malformed input', () => {+ assert.equal(detectTrackedSkill('toString'), null);+ assert.equal(detectTrackedSkill('__proto__'), null);+ assert.equal(getTrackedSkillFromToolInput(null), null);+ assert.equal(getTrackedSkillFromPrompt(null), null);+});\ No newline at end of filediff --git a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md b/plugins/mobile-apps/skills/create-mobile-app/SKILL.mdindex c72b8fb5c..7d8d7ed9d 100644--- a/plugins/mobile-apps/skills/create-mobile-app/SKILL.md+++ b/plugins/mobile-apps/skills/create-mobile-app/SKILL.md@@ -87,6 +87,14 @@ After the resume check, run the **fresh-template gate** from the section above.**Do not silently copy a bundled template over the user's folder.** A fresh `pa-wrap-tools-1` template may contain placeholder `power.config.json` with an empty `environmentId`; Step 5 removes that placeholder immediately before Step 6 runs `npx power-apps init`.+After the fresh-template gate succeeds, or after the user confirms a resume, initialize the app identity before continuing:++```bash+node "${CLAUDE_SKILL_DIR}/../../scripts/lib/app-identity.js" "<working_dir>"+```++`app-identity.js` mints `app.json` `expo.extra.telemetry.appInstanceId` — a random per-project ID that lets usage telemetry tell this app apart from other apps built in the same session, and recognize it again in later sessions. It is idempotent, so a resume or re-run keeps the original ID. It contains no app name, path, or environment data. Commit it: it is the app's identity, not a per-machine cache.+### Step 1 — PrerequisitesRun all checks first — no point gathering requirements if the toolchain isn't ready.diff --git a/plugins/mobile-apps/skills/telemetry/SKILL.md b/plugins/mobile-apps/skills/telemetry/SKILL.mdnew file mode 100644index 000000000..6e07b006e--- /dev/null+++ b/plugins/mobile-apps/skills/telemetry/SKILL.md@@ -0,0 +1,14 @@+---+name: telemetry+description: >+ Use this skill when the user wants to enable, disable, turn on or off, opt out+ of, opt in to, or check the status of mobile-app usage+ data. Triggers: "disable telemetry", "turn off telemetry", "opt out of+ telemetry", "stop collecting usage data", "enable telemetry", "telemetry status".+user-invocable: true+argument-hint: "on | off | status"+allowed-tools: Bash+model: haiku+---++**Workflow: [telemetry-workflow.md](${PLUGIN_ROOT}/skills/telemetry/telemetry-workflow.md)** — Read and follow all steps defined in that bundled file.\ No newline at end of filediff --git a/plugins/mobile-apps/skills/telemetry/telemetry-workflow.md b/plugins/mobile-apps/skills/telemetry/telemetry-workflow.mdnew file mode 100644index 000000000..04ddf8eed--- /dev/null+++ b/plugins/mobile-apps/skills/telemetry/telemetry-workflow.md@@ -0,0 +1,40 @@+# Telemetry control workflow++The user invoked `/<plugin>:telemetry [on | off | status]` to control+usage telemetry for this plugin. Default to `status` when no argument is given.++## Steps++1. Read the action from `$ARGUMENTS`. It must be one of `on`, `off`, or `status`.+ If it is empty or anything else, use `status`.+2. Run the Mobile Apps telemetry-control wrapper. It delegates preference and+ log handling to the synced CLI, then replaces the generic PAC-aware disclosure+ with Mobile Apps' actual identifier-free payload description:++ ```bash+ node "${PLUGIN_ROOT}/scripts/lib/mobile-telemetry-config.js" --action <action>+ ```++3. Show the command's stdout to the user verbatim. Do not add or remove lines.++## What to know (for answering follow-ups)++- `off` stops transmission to Microsoft. **Nothing leaves the machine.** When+ the repository telemetry configuration is enabled, the sanitized local mirror+ remains under `~/.power-platform-skills/telemetry/<plugin>/sessions/`.+- `on` re-enables transmission. The choice is **per-user and per-plugin** and+ takes effect on the next event (no restart).+- Mobile Apps records start-only operational fields such as skill name, plugin+ version, session and correlation IDs, OS/Node versions, AI-agent name/version,+ invocation source, and a random per-project app instance ID. It never includes+ file paths, prompts, tool inputs, site names, URLs, credentials, usernames,+ hostnames, Dataverse organization or tenant IDs, or Entra object IDs.+- A repository configuration with `disabled: true` is a hard-off: it writes no+ local mirror and sends no event, regardless of the saved user preference.+- **Automation/CI** can disable telemetry by setting the opt-out env var+ `POWER_PLATFORM_SKILLS_TELEMETRY_<PLUGIN>_OPTOUT` (for Mobile Apps,+ `POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT=1`) instead of running this+ command. Set it to `1` or `true` (the dotnet `*_TELEMETRY_OPTOUT` convention).+ `<PLUGIN>` is the plugin name uppercased with non-alphanumerics collapsed to `_`.+ This opt-out has the highest precedence — it overrides a saved choice from this+ command and even `on`. It suppresses transmission only, like `off`.\ No newline at end of file