Skip to content

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

mobile-apps: use a generic Windows-aware CLI runner (#711)

Shubham Agarwalacc83f56805c
diff --git a/plugins/mobile-apps/.claude-plugin/plugin.json b/plugins/mobile-apps/.claude-plugin/plugin.json
index 64c153ba4..b520b834d 100644
--- a/plugins/mobile-apps/.claude-plugin/plugin.json
+++ b/plugins/mobile-apps/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mobile-app",
- "version": "0.5.2",
+ "version": "0.5.3",
"description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors",
"author": {
"name": "Microsoft",
diff --git a/plugins/mobile-apps/.plugin/plugin.json b/plugins/mobile-apps/.plugin/plugin.json
index 64c153ba4..b520b834d 100644
--- a/plugins/mobile-apps/.plugin/plugin.json
+++ b/plugins/mobile-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mobile-app",
- "version": "0.5.2",
+ "version": "0.5.3",
"description": "Build and deploy Power Apps code apps for mobile using Expo (React Native), with native device functionality and Power Platform connectors",
"author": {
"name": "Microsoft",
diff --git a/plugins/mobile-apps/AGENTS.md b/plugins/mobile-apps/AGENTS.md
index 16263df4a..f0f90bba5 100644
--- a/plugins/mobile-apps/AGENTS.md
+++ b/plugins/mobile-apps/AGENTS.md
@@ -59,6 +59,9 @@ Do not add preparation rewrites for `scheme`, `package`, `bundleIdentifier`, `sr
plan.
7. **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** — Resolve the Power Apps CLI per [`shared/cli-binary.md`](./shared/cli-binary.md) and run code-app lifecycle and data-source commands as `$PA …` in the canonical grouped `pa` form — never a bare `pa`, `power-apps`, or `npx pa`. Every other agent-run `npx` (`tsc`, `expo`, `qrcode`, …) also uses `--no-install` against a package the template pins; never `npx --yes` or a bare `npx <pkg>` that can download from the registry. 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).
+ Mobile Node helpers use `scripts/lib/process-runner.js` for external CLI
+ execution. Keep arguments separate from commands and reuse its native/batch
+ handling rather than adding per-tool Windows shims or `shell: true`.
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** — `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.
diff --git a/plugins/mobile-apps/scripts/discover-app-registrations.js b/plugins/mobile-apps/scripts/discover-app-registrations.js
index b36ae4b8e..806afc611 100644
--- a/plugins/mobile-apps/scripts/discover-app-registrations.js
+++ b/plugins/mobile-apps/scripts/discover-app-registrations.js
@@ -1,6 +1,6 @@
#!/usr/bin/env node
-const { execFileSync } = require('child_process');
+const { AzureCliLaunchError, runAzureCli } = require('./lib/azure-cli');
const { sanitize } = require('./lib/sanitize-external-content');
const GUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -83,18 +83,19 @@ function parseArgs(argv) {
return options;
}
-function runAzJson(args, timeout = 30000, exec = execFileSync) {
+function runAzJson(args, timeout = 30000, exec = runAzureCli) {
let stdout;
try {
// Graph application pages include permission manifests and can exceed Node's
// 1 MiB default stdout buffer even when the request succeeds.
- stdout = exec('az', args, {
+ stdout = exec(args, {
encoding: 'utf8',
maxBuffer: AZURE_CLI_MAX_BUFFER_BYTES,
timeout,
stdio: ['ignore', 'pipe', 'pipe'],
});
} catch (error) {
+ if (error instanceof AzureCliLaunchError) throw error;
const detail = String(error.stderr || error.message || '').trim();
throw new Error(`Azure CLI command failed${detail ? `: ${detail}` : '.'}`);
}
diff --git a/plugins/mobile-apps/scripts/lib/azure-cli.js b/plugins/mobile-apps/scripts/lib/azure-cli.js
new file mode 100644
index 000000000..a050b2786
--- /dev/null
+++ b/plugins/mobile-apps/scripts/lib/azure-cli.js
@@ -0,0 +1,9 @@
+'use strict';
+
+const { CliLaunchError, runCliSync } = require('./process-runner');
+
+function runAzureCli(args, options, dependencies) {
+ return runCliSync('az', args, options, dependencies);
+}
+
+module.exports = { AzureCliLaunchError: CliLaunchError, runAzureCli };
diff --git a/plugins/mobile-apps/scripts/lib/environment-resolution.js b/plugins/mobile-apps/scripts/lib/environment-resolution.js
index 51a094660..0c1907859 100644
--- a/plugins/mobile-apps/scripts/lib/environment-resolution.js
+++ b/plugins/mobile-apps/scripts/lib/environment-resolution.js
@@ -1,6 +1,6 @@
'use strict';
-const { execFileSync } = require('child_process');
+const { AzureCliLaunchError, runAzureCli } = require('./azure-cli');
const fs = require('fs');
const https = require('https');
const path = require('path');
@@ -145,12 +145,13 @@ function writeCacheIfProject(result, projectRoot, options = {}) {
function getAzTenantId() {
try {
- return execFileSync('az', ['account', 'show', '--query', 'tenantId', '-o', 'tsv'], {
+ return runAzureCli(['account', 'show', '--query', 'tenantId', '-o', 'tsv'], {
encoding: 'utf8',
timeout: 10000,
stdio: ['ignore', 'pipe', 'ignore'],
}).trim() || null;
- } catch {
+ } catch (error) {
+ if (!Number.isInteger(error.status) || error.status <= 0) throw error;
return null;
}
}
@@ -160,12 +161,13 @@ function getAzToken(resource, tenantId = null) {
if (tenantId) args.push('--tenant', tenantId);
args.push('--resource', resource, '--query', 'accessToken', '-o', 'tsv');
try {
- return execFileSync('az', args, {
+ return runAzureCli(args, {
encoding: 'utf8',
timeout: 20000,
stdio: ['ignore', 'pipe', 'ignore'],
}).trim() || null;
- } catch {
+ } catch (error) {
+ if (!Number.isInteger(error.status) || error.status <= 0) throw error;
return null;
}
}
@@ -314,7 +316,6 @@ async function resolveEnvironment(target, projectRoot = process.cwd(), allowLega
return result;
}
- const loginTenantId = getAzTenantId();
let resolved;
if (isUrl(target)) {
const normalizedUrl = normalizeUrl(target);
@@ -329,9 +330,12 @@ async function resolveEnvironment(target, projectRoot = process.cwd(), allowLega
};
} else if (GUID_RE.test(target)) {
try {
- resolved = await resolveEnvironmentId(target, loginTenantId);
+ resolved = await resolveEnvironmentId(target, getAzTenantId());
} catch (error) {
if (cached && cached.environmentUrl) {
+ if (error instanceof AzureCliLaunchError) {
+ process.stderr.write(`${error.message} Using matching cached environment details.\n`);
+ }
resolved = {
environmentUrl: cached.environmentUrl,
environmentId: cached.environmentId || target,
diff --git a/plugins/mobile-apps/scripts/lib/mobile-telemetry-session.js b/plugins/mobile-apps/scripts/lib/mobile-telemetry-session.js
index 3b436f06b..ada5c1aa2 100644
--- a/plugins/mobile-apps/scripts/lib/mobile-telemetry-session.js
+++ b/plugins/mobile-apps/scripts/lib/mobile-telemetry-session.js
@@ -3,14 +3,14 @@
const crypto = require('node:crypto');
const fs = require('node:fs');
const path = require('node:path');
-const { execFileSync } = require('node:child_process');
+const { runCliSync } = require('./process-runner');
const HOST_PROCESS = /^(?:node|nodejs|copilot|claude|codex|opencode|hermes|openclaw|code(?: helper(?: \(plugin\))?)?)(?:\.exe)?$/i;
let cachedScope;
function readProcessScope(opts = {}) {
if (cachedScope !== undefined && !opts.exec) return cachedScope;
- const exec = opts.exec || execFileSync;
+ const exec = opts.exec || runCliSync;
const platform = opts.platform || process.platform;
let scope = '';
try {
diff --git a/plugins/mobile-apps/scripts/lib/process-runner.js b/plugins/mobile-apps/scripts/lib/process-runner.js
new file mode 100644
index 000000000..6f6216274
--- /dev/null
+++ b/plugins/mobile-apps/scripts/lib/process-runner.js
@@ -0,0 +1,167 @@
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const { execFileSync } = require('node:child_process');
+
+// Windows argument escaping is adapted from cross-spawn's MIT-licensed
+// lib/util/escape.js. Keep the notice with these bundled functions.
+//
+// Copyright (c) 2018 Made With MOXY Lda <[email protected]>
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
+
+function escapeArgument(value, doubleEscape) {
+ let result = value.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
+ result = result.replace(/(?=(\\+?)?)\1$/, '$1$1');
+ result = `"${result}"`.replace(CMD_META, '^$1');
+ return doubleEscape ? result.replace(CMD_META, '^$1') : result;
+}
+
+class CliLaunchError extends Error {
+ constructor(message, code) {
+ super(message);
+ this.name = 'CliLaunchError';
+ this.code = code;
+ }
+}
+
+function envValue(env, name, platform) {
+ if (platform !== 'win32') return env[name];
+ const key = Object.keys(env).filter((entry) => entry.toUpperCase() === name.toUpperCase()).sort()[0];
+ return key === undefined ? undefined : env[key];
+}
+
+function isRunnable(file, platform) {
+ try {
+ if (!fs.statSync(file).isFile()) return false;
+ if (platform !== 'win32') fs.accessSync(file, fs.constants.X_OK);
+ return true;
+ } catch (error) {
+ if (['ENOENT', 'ENOTDIR', 'EACCES'].includes(error.code)) return false;
+ throw error;
+ }
+}
+
+function resolveExecutable(command, {
+ platform = process.platform, env = process.env,
+ exists = (file) => isRunnable(file, platform),
+} = {}) {
+ const windows = platform === 'win32';
+ const paths = windows ? path.win32 : path.posix;
+ if (typeof command !== 'string' || !command || /[\u0000-\u001f\u007f]/.test(command)) {
+ throw new TypeError('CLI command must be an executable name or absolute path.');
+ }
+ if (paths.isAbsolute(command)) return exists(command) ? command : null;
+ if (/[\\/]/.test(command) || !/^[\w.-]+$/.test(command)) {
+ throw new TypeError('Relative executable paths and shell command strings are not supported.');
+ }
+ const directories = String(envValue(env, 'PATH', platform) || '')
+ .split(windows ? ';' : ':')
+ .map((directory) => directory.trim().replace(/^"(.*)"$/, '$1'))
+ .filter((directory) => directory && paths.isAbsolute(directory));
+ const extensions = windows
+ ? String(envValue(env, 'PATHEXT', platform) || '.COM;.EXE;.BAT;.CMD')
+ .split(';').map((extension) => extension.toLowerCase())
+ .filter((extension) => /^\.(?:com|exe|bat|cmd)$/.test(extension))
+ : [''];
+ const explicitExtension = windows && /\.(?:com|exe|bat|cmd)$/i.test(command);
+ for (const directory of directories) {
+ for (const extension of explicitExtension ? [''] : extensions) {
+ const candidate = paths.join(directory, command + extension);
+ if (exists(candidate)) return candidate;
+ }
+ }
+ return null;
+}
+
+function cliInvocation(command, args, dependencies = {}) {
+ if (!Array.isArray(args) || args.some((argument) => typeof argument !== 'string' || argument.includes('\0'))) {
+ throw new TypeError('CLI arguments must be strings without NUL characters.');
+ }
+ const { platform = process.platform, env = process.env } = dependencies;
+ const file = resolveExecutable(command, { ...dependencies, platform, env });
+ if (!file) {
+ throw new CliLaunchError(
+ `CLI ${command} was not found on PATH. Install it or correct PATH, then restart the terminal or agent host.`,
+ 'CLI_NOT_FOUND',
+ );
+ }
+ if (platform !== 'win32' || !/\.(?:cmd|bat)$/i.test(file)) {
+ return { file, args, env, windowsVerbatimArguments: false };
+ }
+ if (args.some((argument) => /[\u0000-\u001f\u007f]/.test(argument))) {
+ throw new CliLaunchError('Windows batch arguments cannot contain control characters.', 'CLI_UNSAFE_ARGUMENT');
+ }
+ if (args.some((argument) => argument.includes('!'))) {
+ const readFile = dependencies.readFile || ((filename) => fs.readFileSync(filename, 'utf8'));
+ if (/enabledelayedexpansion/i.test(readFile(file))) {
+ throw new CliLaunchError(
+ 'This batch launcher enables delayed expansion and cannot preserve literal exclamation marks.',
+ 'CLI_UNSAFE_ARGUMENT',
+ );
+ }
+ }
+ const comspec = envValue(env, 'ComSpec', platform) || '';
+ const systemRoot = envValue(env, 'SystemRoot', platform) || envValue(env, 'windir', platform) || '';
+ const interpreter = path.win32.isAbsolute(comspec) && /(?:^|[\\/])cmd\.exe$/i.test(comspec)
+ ? comspec
+ : path.win32.isAbsolute(systemRoot) ? path.win32.join(systemRoot, 'System32', 'cmd.exe') : null;
+ if (!interpreter) throw new CliLaunchError('Windows cmd.exe could not be resolved to an absolute path.', 'CLI_LAUNCH_FAILED');
+
+ // Batch shims need cmd.exe, not shell:true (which concatenates unescaped argv).
+ // npm .bin shims parse forwarded arguments again; cross-spawn escapes that extra layer.
+ // /d disables AutoRun, /v:off disables inherited delayed expansion, and absolute
+ // executable paths avoid Windows' implicit current-directory command lookup.
+ const doubleEscape = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i.test(file);
+ const escapedCommand = path.win32.normalize(file).replace(CMD_META, '^$1');
+ const line = [escapedCommand, ...args.map((argument) => escapeArgument(argument, doubleEscape))].join(' ');
+ return {
+ file: interpreter,
+ args: ['/d', '/s', '/v:off', '/c', `"${line}"`],
+ env: { ...env, NoDefaultCurrentDirectoryInExePath: '1' },
+ windowsVerbatimArguments: true,
+ };
+}
+
+function runCliSync(command, args, options = {}, dependencies = {}) {
+ try {
+ const invocation = cliInvocation(command, args, {
+ ...dependencies, env: options.env || dependencies.env || process.env,
+ });
+ return (dependencies.execFileSync || execFileSync)(invocation.file, invocation.args, {
+ ...options,
+ env: invocation.env,
+ shell: false,
+ windowsHide: true,
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,
+ });
+ } catch (error) {
+ if (error instanceof CliLaunchError || error instanceof TypeError ||
+ (Number.isInteger(error.status) && error.status > 0)) throw error;
+ const code = /^[A-Z_]+$/.test(error.code || '') ? ` (${error.code})` : '';
+ throw new CliLaunchError(
+ `CLI could not be started or completed${code}. Check its installation and executable access; signing in again does not repair a launcher failure.`,
+ 'CLI_LAUNCH_FAILED',
+ );
+ }
+}
+
+module.exports = { CliLaunchError, cliInvocation, resolveExecutable, runCliSync };
diff --git a/plugins/mobile-apps/scripts/lib/validation-helpers.js b/plugins/mobile-apps/scripts/lib/validation-helpers.js
index 7d4e341b9..af9ffe53e 100644
--- a/plugins/mobile-apps/scripts/lib/validation-helpers.js
+++ b/plugins/mobile-apps/scripts/lib/validation-helpers.js
@@ -5,7 +5,7 @@
const fs = require('fs');
const path = require('path');
-const { execFileSync } = require('child_process');
+const { runAzureCli } = require('./azure-cli');
// Exit 0 = success (allow). Exit 2 = blocking error (stderr is fed back to Claude).
const approve = () => { process.exit(0); };
@@ -120,12 +120,13 @@ async function getDataverseTenantFromChallenge(resourceUrl) {
function getAzAccountTenantId() {
try {
- return execFileSync('az', ['account', 'show', '--query', 'tenantId', '-o', 'tsv'], {
+ return runAzureCli(['account', 'show', '--query', 'tenantId', '-o', 'tsv'], {
encoding: 'utf8',
timeout: 10000,
stdio: ['ignore', 'pipe', 'ignore'],
}).trim() || null;
- } catch {
+ } catch (error) {
+ if (!Number.isInteger(error.status) || error.status <= 0) throw error;
return null;
}
}
@@ -135,12 +136,13 @@ function getAzAccessToken(resourceUrl, tenantId = null) {
if (tenantId) args.push('--tenant', tenantId);
args.push('--resource', resourceUrl, '--query', 'accessToken', '-o', 'tsv');
try {
- return execFileSync('az', args, {
+ return runAzureCli(args, {
encoding: 'utf8',
timeout: 15000,
stdio: ['ignore', 'pipe', 'ignore'],
}).trim() || null;
- } catch {
+ } catch (error) {
+ if (!Number.isInteger(error.status) || error.status <= 0) throw error;
return null;
}
}
diff --git a/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.js b/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.js
index 283feda29..5e40a0159 100644
--- a/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.js
+++ b/plugins/mobile-apps/scripts/tests/auth-token-resolution.test.js
@@ -9,9 +9,9 @@
// supplied the answer. A data-model run issues dozens of calls, so the waste
// dominated wall-clock time.
//
-// These tests exercise the real code path rather than mocking internals: a fake
-// `az` executable is placed first on PATH and logs every invocation, so we can
-// assert exactly which subcommands ran. The resource URL points at 127.0.0.1:1
+// These tests exercise token selection through the shared Azure CLI adapter,
+// logging every invocation so we can assert exactly which subcommands ran.
+// Launcher execution is covered separately. The resource URL points at 127.0.0.1:1
// so that if the challenge probe IS reached it fails instantly with
// ECONNREFUSED instead of touching the network.
@@ -28,7 +28,7 @@ const FAKE_AZ_PRELOAD = path.join(__dirname, 'helpers', 'fake-az-preload.js');
// is reached at all) resolves fast and deterministically offline.
const UNREACHABLE_ENV_URL = 'https://127.0.0.1:1';
-// The Node preload intercepts `execFileSync('az', ...)`, writes one line per
+// The Node preload intercepts `runAzureCli(...)`, writes one line per
// invocation to $FAKE_AZ_LOG, then emulates the two subcommands getAuthToken uses:
// az account show --query tenantId -o tsv
// az account get-access-token --resource <url> [--tenant <id>] ...
diff --git a/plugins/mobile-apps/scripts/tests/discover-app-registrations.test.js b/plugins/mobile-apps/scripts/tests/discover-app-registrations.test.js
index 2489ba709..bd7f6a472 100644
--- a/plugins/mobile-apps/scripts/tests/discover-app-registrations.test.js
+++ b/plugins/mobile-apps/scripts/tests/discover-app-registrations.test.js
@@ -2,6 +2,7 @@
const assert = require('assert');
const test = require('node:test');
+const { AzureCliLaunchError } = require('../lib/azure-cli');
const {
AZURE_CLI_MAX_BUFFER_BYTES,
CONNECTOR_PERMISSIONS,
@@ -71,13 +72,19 @@ test('builds encoded Graph URLs without shell interpolation', () => {
test('allows permission-heavy Graph pages within a bounded Azure CLI buffer', () => {
let invocation;
const result = runAzJson(['rest', '--url', 'https://graph.microsoft.com'], 30000,
- (command, args, options) => {
- invocation = { command, args, options };
+ (args, options) => {
+ invocation = { args, options };
return '{"value":[]}';
});
+ test('registration discovery preserves launcher errors rather than reporting an account problem', () => {
+ const failure = new AzureCliLaunchError('Azure CLI executable is missing.', 'CLI_NOT_FOUND');
+ assert.throws(() => runAzJson(['account', 'show'], 30000, () => { throw failure; }),
+ (error) => error === failure);
+ });
+
assert.deepEqual(result, { value: [] });
- assert.equal(invocation.command, 'az');
+ assert.deepEqual(invocation.args, ['rest', '--url', 'https://graph.microsoft.com']);
assert.equal(invocation.options.maxBuffer, AZURE_CLI_MAX_BUFFER_BYTES);
assert.equal(AZURE_CLI_MAX_BUFFER_BYTES, 16 * 1024 * 1024);
});
diff --git a/plugins/mobile-apps/scripts/tests/helpers/fake-az-preload.js b/plugins/mobile-apps/scripts/tests/helpers/fake-az-preload.js
index 3c2a22965..d68105c41 100644
--- a/plugins/mobile-apps/scripts/tests/helpers/fake-az-preload.js
+++ b/plugins/mobile-apps/scripts/tests/helpers/fake-az-preload.js
@@ -1,15 +1,9 @@
'use strict';
-const childProcess = require('node:child_process');
const fs = require('node:fs');
+const azureCli = require('../../lib/azure-cli');
-const originalExecFileSync = childProcess.execFileSync;
-
-childProcess.execFileSync = function fakeAzExecFileSync(command, args, options) {
- if (command !== 'az') {
- return originalExecFileSync.call(this, command, args, options);
- }
-
+azureCli.runAzureCli = function fakeAzureCli(args) {
const cliArgs = Array.isArray(args) ? args : [];
if (process.env.FAKE_AZ_LOG) {
fs.appendFileSync(process.env.FAKE_AZ_LOG, `${cliArgs.join(' ')}\n`);
diff --git a/plugins/mobile-apps/scripts/tests/process-runner.test.js b/plugins/mobile-apps/scripts/tests/process-runner.test.js
new file mode 100644
index 000000000..86d5a09e4
--- /dev/null
+++ b/plugins/mobile-apps/scripts/tests/process-runner.test.js
@@ -0,0 +1,258 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const { spawnSync } = require('node:child_process');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const test = require('node:test');
+const { CliLaunchError, cliInvocation, resolveExecutable, runCliSync } = require('../lib/process-runner');
+const { runAzureCli } = require('../lib/azure-cli');
+
+const graphUrl = 'https://graph.microsoft.com/v1.0/applications?%24select=appId%2CdisplayName&%24filter=appId+eq+%27test%27';
+const literalArguments = [
+ '--tenant', 'selected-tenant', graphUrl, '{user:user.name,tenantId:tenantId}',
+ 'a "quoted" value', '%MOBILE_CLI_SENTINEL%', '!MOBILE_CLI_SENTINEL!',
+ '&|^()<>', '$literal $(text) `text`', '', 'trailing\\', 'space and trailing\\',
+];
+
+function temporary(t) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mobile-cli-runner-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }));
+ return directory;
+}
+
+function envWithPath(directory, extra = {}) {
+ const env = { ...process.env, ...extra };
+ for (const key of Object.keys(env)) if (key.toUpperCase() === 'PATH') delete env[key];
+ return { ...env, PATH: directory };
+}
+
+function windowsOptions(file = 'C:\\CLI tools\\az.cmd', extra = {}) {
+ return {
+ platform: 'win32',
+ env: { Path: path.win32.dirname(file), SystemRoot: 'C:\\Windows' },
+ exists: (candidate) => candidate === file,
+ readFile: () => '@echo off\r\n',
+ ...extra,
+ };
+}
+
+test('native command resolution skips implicit cwd and relative PATH entries on every platform', () => {
+ for (const [platform, env, prefix] of [
+ ['win32', { PATH: '.;;tools;C:relative;C:\\Trusted' }, 'C:\\Trusted\\'],
+ ['linux', { PATH: ':.:tools:/trusted' }, '/trusted/'],
+ ]) {
+ const seen = [];
+ assert.equal(resolveExecutable('az', {
+ platform, env, exists: (file) => { seen.push(file); return false; },
+ }), null);
+ assert.ok(seen.length > 0);
+ assert.ok(seen.every((file) => file.startsWith(prefix)));
+ }
+});
+
+test('Windows resolution follows PATH and PATHEXT order and Node environment-key casing', () => {
+ const files = new Set(['C:\\Preferred\\az.cmd', 'C:\\Preferred\\az.exe', 'C:\\Later\\az.exe']);
+ const options = windowsOptions('', {
+ env: { Path: 'C:\\Old', PATH: '"C:\\Preferred";C:\\Later', PATHEXT: '.CMD;.EXE;.JS' },
+ exists: (file) => files.has(file),
+ });
+ assert.equal(resolveExecutable('az', options), 'C:\\Preferred\\az.cmd');
+ assert.equal(resolveExecutable('az.exe', options), 'C:\\Preferred\\az.exe');
+ assert.equal(resolveExecutable('C:\\Later\\az.exe', options), 'C:\\Later\\az.exe');
+ assert.equal(resolveExecutable('C:\\Missing\\az.exe', options), null);
+});
+
+test('every native executable preserves argv without shell interpolation', () => {
+ for (const [platform, file] of [['win32', 'C:\\tools\\pa.exe'], ['darwin', '/opt/tools/pa'], ['linux', '/opt/tools/pa']]) {
+ const invocation = cliInvocation(file, literalArguments, {
+ platform, env: {}, exists: (candidate) => candidate === file,
+ });
+ assert.equal(invocation.file, file);
+ assert.deepEqual(invocation.args, literalArguments);
+ assert.equal(invocation.windowsVerbatimArguments, false);
+ }
+});
+
+test('generic .cmd and .bat launchers use absolute cmd.exe with no tool-specific layout parsing', () => {
+ for (const command of ['az', 'pa', 'npm', 'custom-cli']) {
+ for (const extension of ['cmd', 'bat']) {
+ const file = `C:\\CLI tools\\${command}.${extension}`;
+ const invocation = cliInvocation(command, ['--version'], windowsOptions(file, {
+ readFile: () => assert.fail('Simple arguments do not require inspecting a launcher'),
+ }));
+ assert.equal(invocation.file, 'C:\\Windows\\System32\\cmd.exe');
+ assert.deepEqual(invocation.args.slice(0, 4), ['/d', '/s', '/v:off', '/c']);
+ assert.equal(invocation.windowsVerbatimArguments, true);
+ assert.equal(invocation.env.NoDefaultCurrentDirectoryInExePath, '1');
+ assert.ok(invocation.args[4].includes(`${command}.${extension}`));
+ }
+ }
+});
+
+test('batch interpreter lookup never falls back to a project-local cmd executable', () => {
+ const file = 'C:\\tools\\az.cmd';
+ const invocation = cliInvocation('az', [], windowsOptions(file, {
+ env: { PATH: 'C:\\tools', ComSpec: 'cmd.exe', SystemRoot: 'D:\\Windows' },
+ }));
+ assert.equal(invocation.file, 'D:\\Windows\\System32\\cmd.exe');
+ assert.throws(() => cliInvocation('az', [], windowsOptions(file, {
+ env: { PATH: 'C:\\tools', ComSpec: 'cmd.exe' },
+ })), (error) => error.code === 'CLI_LAUNCH_FAILED');
+});
+
+test('caller options cannot override the generic batch execution boundary', () => {
+ let received;
+ const result = runCliSync('az', ['version', '--output', 'json'], {
+ encoding: 'utf8', timeout: 30000, maxBuffer: 16 * 1024 * 1024,
+ shell: true, windowsVerbatimArguments: false,
+ }, windowsOptions(undefined, {
+ execFileSync(file, args, options) {
+ received = { file, args, options };
+ return '{"version":"test"}';
+ },
+ }));
+ assert.equal(result, '{"version":"test"}');
+ assert.equal(received.options.shell, false);
+ assert.equal(received.options.windowsVerbatimArguments, true);
+ assert.equal(received.options.windowsHide, true);
+ assert.equal(received.options.timeout, 30000);
+ assert.equal(received.options.maxBuffer, 16 * 1024 * 1024);
+});
+
+test('batch arguments with controls or an unsafe delayed-expansion contract fail before launch', () => {
+ for (const argument of ['line\nbreak', 'line\rbreak', 'tab\there']) {
+ assert.throws(() => runCliSync('az', [argument], {}, windowsOptions(undefined, {
+ execFileSync: () => assert.fail('Unsafe arguments must not launch'),
+ })), (error) => error.code === 'CLI_UNSAFE_ARGUMENT');
+ }
+ assert.throws(() => runCliSync('az', ['!value!'], {}, windowsOptions(undefined, {
+ readFile: () => '@setlocal EnableDelayedExpansion\r\n',
+ execFileSync: () => assert.fail('Unsafe delayed expansion must not launch'),
+ })), (error) => error.code === 'CLI_UNSAFE_ARGUMENT');
+});
+
+test('launcher errors remain distinct from CLI exits without exposing token output', () => {
+ for (const code of ['ENOENT', 'EACCES', 'EINVAL', 'ETIMEDOUT']) {
+ assert.throws(() => runCliSync('az', ['private-argument'], {}, windowsOptions(undefined, {
+ execFileSync() {
+ throw Object.assign(new Error('private-argument'), {
+ code, status: null, stdout: 'private-token', stderr: 'private-diagnostic',
+ });
+ },
+ })), (error) => {
+ assert.ok(error instanceof CliLaunchError);
+ assert.equal(error.code, 'CLI_LAUNCH_FAILED');
+ assert.match(error.message, new RegExp(code));
+ assert.doesNotMatch(error.message, /private-/);
+ return true;
+ });
+ }
+ const rejected = Object.assign(new Error('Sign in to the selected tenant.'), { status: 1 });
+ assert.throws(() => runCliSync('az', ['account', 'show'], {}, windowsOptions(undefined, {
+ execFileSync: () => { throw rejected; },
+ })), (error) => error === rejected);
+});
+
+test('invalid commands and argv fail before launching', () => {
+ for (const command of ['az account show', './az', 'tools/az', 'bad\ncommand']) {
+ assert.throws(() => runCliSync(command, [], {}, { exists: () => false }), TypeError);
+ }
+ for (const args of [null, 'account show', [7], ['bad\0argument']]) {
+ assert.throws(() => runCliSync('az', args, {}, { exists: () => false }), TypeError);
+ }
+});
+
+test('Dataverse authentication preserves a missing-launcher error rather than trying another tenant', (t) => {
+ const helper = path.resolve(__dirname, '../lib/validation-helpers.js');
+ const source = `
+require(${JSON.stringify(helper)}).getAuthToken('https://contoso.crm.dynamics.com', 'selected-tenant')
+ .then(() => { process.exitCode = 2; }, (error) => {
+ process.stderr.write(error.code + ': ' + error.message);
+ process.exitCode = 1;
+ });
+`;
+ const result = spawnSync(process.execPath, ['-e', source], {
+ cwd: temporary(t), env: envWithPath(''), encoding: 'utf8', timeout: 5000,
+ });
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /^CLI_NOT_FOUND: CLI az was not found on PATH/);
+ assert.doesNotMatch(result.stderr, /az login|selected-tenant/);
+ assert.equal(result.stdout, '');
+});
+
+test('native executable fixture uses PATH rather than a same-named command in the project', (t) => {
+ const directory = temporary(t);
+ const bin = path.join(directory, 'trusted bin');
+ const cwd = path.join(directory, "app's folder");
+ fs.mkdirSync(bin);
+ fs.mkdirSync(cwd);
+ const probe = path.join(bin, 'probe.cjs');
+ fs.writeFileSync(probe, 'console.log(JSON.stringify({ args: process.argv.slice(2), cwd: process.cwd() }));');
+ let args = literalArguments;
+ if (process.platform === 'win32') {
+ fs.copyFileSync(process.execPath, path.join(bin, 'sample.exe'));
+ fs.writeFileSync(path.join(cwd, 'sample.exe'), 'not executable');
+ args = [probe, ...args];
+ } else {
+ fs.writeFileSync(path.join(bin, 'sample'), '#!/bin/sh\nexec "$REAL_NODE" "$CLI_TEST_PROBE" "$@"\n', { mode: 0o755 });
+ fs.writeFileSync(path.join(cwd, 'sample'), '#!/bin/sh\nexit 99\n', { mode: 0o755 });
+ }
+ const result = JSON.parse(runCliSync('sample', args, {
+ cwd, env: envWithPath(bin, { REAL_NODE: process.execPath, CLI_TEST_PROBE: probe }),
+ encoding: 'utf8', timeout: 10000,
+ }));
+ assert.deepEqual(result.args, literalArguments);
+ assert.equal(fs.realpathSync(result.cwd), fs.realpathSync(cwd));
+});
+
+test('actual Windows batch launchers preserve argv and local-only flags without an Azure layout', {
+ skip: process.platform !== 'win32' ? 'Requires Windows cmd.exe' : false,
+}, (t) => {
+ const directory = temporary(t);
+ const bin = path.join(directory, "tools's (100%) & literal!");
+ const npmBin = path.join(directory, 'node_modules', '.bin');
+ const cwd = path.join(directory, 'another app');
+ fs.mkdirSync(bin);
+ fs.mkdirSync(npmBin, { recursive: true });
+ fs.mkdirSync(cwd);
+ const probe = path.join(directory, 'probe.cjs');
+ fs.writeFileSync(probe, 'console.log(JSON.stringify({ args: process.argv.slice(2), cwd: process.cwd() })); process.exit(Number(process.env.CLI_TEST_EXIT || 0));');
+ const source = '@echo off\r\n"%CLI_TEST_NODE%" "%CLI_TEST_PROBE%" %*\r\n';
+ for (const file of [path.join(bin, 'az.cmd'), path.join(bin, 'custom.bat'), path.join(npmBin, 'pa.cmd')]) {
+ fs.writeFileSync(file, source);
+ const env = envWithPath(path.dirname(file), {
+ CLI_TEST_NODE: process.execPath, CLI_TEST_PROBE: probe,
+ MOBILE_CLI_SENTINEL: 'MUST_NOT_EXPAND',
+ });
+ fs.writeFileSync(path.join(cwd, path.basename(file)), '@exit /b 99\r\n');
+ const args = ['--no-install', ...literalArguments];
+ const result = JSON.parse(runCliSync(file, args, { env, cwd, encoding: 'utf8', timeout: 15000 }));
+ assert.deepEqual(result.args, args, file);
+ assert.equal(fs.realpathSync(result.cwd), fs.realpathSync(cwd));
+ assert.throws(() => runCliSync(file, ['--version'], {
+ env: { ...env, CLI_TEST_EXIT: '7' }, cwd, encoding: 'utf8', timeout: 15000,
+ }), (error) => error.status === 7);
+ }
+});
+
+test('Windows runs the real installed az.cmd and preserves percent-bearing query arguments', {
+ skip: process.platform !== 'win32' ? 'Windows Azure CLI installation smoke test' : false,
+ timeout: 90000,
+}, (t) => {
+ const directory = temporary(t);
+ const env = {
+ ...process.env, AZURE_CONFIG_DIR: directory,
+ AZURE_CORE_COLLECT_TELEMETRY: 'false', AZURE_EXTENSION_USE_DYNAMIC_INSTALL: 'no',
+ MOBILE_CLI_SENTINEL: 'MUST_NOT_EXPAND',
+ };
+ const launcher = resolveExecutable('az', { env });
+ if (!launcher && !process.env.CI) return t.skip('Azure CLI not installed locally; required in Windows CI');
+ assert.match(launcher || '', /\.cmd$/i);
+ const options = { env, cwd: directory, encoding: 'utf8', timeout: 60000 };
+ const version = JSON.parse(runAzureCli(['version', '--output', 'json'], options));
+ assert.match(version['azure-cli'], /^\d+\.\d+\.\d+/);
+ const expected = '%MOBILE_CLI_SENTINEL% & !MOBILE_CLI_SENTINEL! percent%24value';
+ assert.equal(runAzureCli(['version', '--query', `'${expected}'`, '--output', 'tsv'], options).trim(), expected);
+});
diff --git a/plugins/mobile-apps/scripts/tests/resolve-environment-quality.test.js b/plugins/mobile-apps/scripts/tests/resolve-environment-quality.test.js
index 07d679001..3a632dad1 100644
--- a/plugins/mobile-apps/scripts/tests/resolve-environment-quality.test.js
+++ b/plugins/mobile-apps/scripts/tests/resolve-environment-quality.test.js
@@ -19,6 +19,23 @@ const {
const resolverPath = path.resolve(__dirname, '../resolve-environment.js');
+test('missing Azure CLI reports a launcher failure instead of suggesting login or a different environment', (t) => {
+ const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'environment-cli-missing-'));
+ t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));
+ const env = { ...process.env, PATH: '', POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' };
+ if (process.platform === 'win32') {
+ for (const key of Object.keys(env)) if (key !== 'PATH' && key.toUpperCase() === 'PATH') delete env[key];
+ }
+ const result = spawnSync(process.execPath, [
+ resolverPath, '11111111-1111-1111-1111-111111111111', '--no-cache', '--require-tenant',
+ ], { cwd: projectRoot, env, encoding: 'utf8', timeout: 5000 });
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /CLI az was not found on PATH/);
+ assert.doesNotMatch(result.stderr, /az login|Verify the environment ID|Provide the Dataverse environment URL/);
+ assert.equal(result.stdout, '');
+ assert.deepEqual(fs.readdirSync(projectRoot), []);
+});
+
test('no-cache mode permits reads but performs no filesystem writes', (t) => {
const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'environment-no-cache-'));
t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));
diff --git a/plugins/mobile-apps/scripts/tests/resolve-environment.test.js b/plugins/mobile-apps/scripts/tests/resolve-environment.test.js
index 976fe8153..9c764f726 100644
--- a/plugins/mobile-apps/scripts/tests/resolve-environment.test.js
+++ b/plugins/mobile-apps/scripts/tests/resolve-environment.test.js
@@ -71,6 +71,7 @@ test('failed cluster metadata refresh preserves connection details and auth sett
cwd: root, encoding: 'utf8', timeout: 5000, env: { ...process.env, PATH: '' },
});
assert.equal(result.status, 0, result.stderr);
+ assert.match(result.stderr, /CLI az was not found on PATH.*Using matching cached environment details/);
assert.deepEqual(JSON.parse(result.stdout), { ...cached, clusterEnvironment: null, clusterGeoName: null, source: 'cache-refresh' });
const auth = JSON.parse(fs.readFileSync(path.join(root, 'auth.config.json'), 'utf8'));
assert.equal(auth.msal.clientId, 'preserve');
@@ -205,10 +206,9 @@ test('resolveClusterEnvironment refreshes legacy metadata, skips saved lookups,
const resolverModule = { exports: {} };
let offline = false;
const mockedRequire = (name) => {
- if (name === 'child_process') return { execFileSync(command, args) {
- cliCalls.push({ command, args });
- assert.equal(command, 'az');
- if (offline) throw new Error('offline');
+ if (name === './azure-cli') return { ...requireFromScript(name), runAzureCli(args) {
+ cliCalls.push({ args });
+ if (offline) throw Object.assign(new Error('offline'), { status: 1 });
return args[1] === 'show' ? environmentId : 'test-token';
} };
if (name === 'https') return { request(url, options, callback) {
diff --git a/plugins/mobile-apps/shared/shared-instructions.md b/plugins/mobile-apps/shared/shared-instructions.md
index 07da75ed3..11db6f083 100644
--- a/plugins/mobile-apps/shared/shared-instructions.md
+++ b/plugins/mobile-apps/shared/shared-instructions.md
@@ -220,7 +220,22 @@ All skills in this plugin assume a **POSIX shell** (bash or zsh). Skills shell o
If a skill detects it's running in a non-POSIX shell (e.g. `cp` errors with "command not found"), STOP and instruct the user to switch to Git Bash or WSL before retrying.
-Note on `az`: on Windows where it is installed as a `.cmd` shim and not on the bash PATH, prefix with `pwsh -NoProfile -Command "<command>"`. This works identically from Git Bash and WSL.
+Node helpers use `scripts/lib/process-runner.js` for external CLI execution;
+`scripts/lib/azure-cli.js` is only the Azure-specific callsite adapter.
+The shared runner resolves absolute executable paths, starts POSIX and native
+Windows executables directly, and launches Windows `.cmd`/`.bat` files through
+an absolute `cmd.exe` with checked, escaped arguments. It does not inspect an
+Azure installation layout or depend on a bundled Python path.
+Keep Azure CLI on the agent host's PATH; a working login in a different terminal
+does not prove that the host can find or launch it. WSL uses its Linux Azure CLI
+installation rather than a Windows batch shim.
+
+`CLI_NOT_FOUND`, `CLI_UNSAFE_ARGUMENT`, and `CLI_LAUNCH_FAILED` are installation,
+argument, or process-launch failures, not evidence of a wrong account or missing
+environment. Surface the diagnostic and repair the CLI/PATH before retrying.
+Do not launch login or ask for a different environment to conceal such errors.
+Real CLI authentication failures retain the existing tenant-specific sign-in
+recovery; the adapter neither signs in nor changes the selected tenant.
---
@@ -376,7 +391,9 @@ account. Use `$PA auth switch` or `$PA auth login` only when needed; `$PA auth l
resort for a corrupt cache or explicitly requested sign-out. After correcting
auth state, retry the same supported command once before further triage.
-`az` calls work in bash on macOS/Linux directly. On Windows, wrap with `pwsh -NoProfile -Command "az …"` for consistency.
+Direct foreground sign-in may use the user's supported terminal. Node helpers
+must use the shared CLI runner above, not nested PowerShell commands or
+`shell: true`. A Windows launcher error is not a reason to switch tenants.
---