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
fix(code-apps): attribute CLI calls to the plugin host (#743)
Anshul Jain4076781a3c68
diff --git a/.github/workflows/code-apps-script-tests.yml b/.github/workflows/code-apps-script-tests.ymlnew file mode 100644index 000000000..d0fd62b36--- /dev/null+++ b/.github/workflows/code-apps-script-tests.yml@@ -0,0 +1,42 @@+name: code-apps-script-tests++on:+ pull_request:+ branches:+ - main+ paths:+ - "plugins/code-apps/**"+ - ".github/workflows/code-apps-script-tests.yml"+ push:+ branches:+ - main+ paths:+ - "plugins/code-apps/**"+ - ".github/workflows/code-apps-script-tests.yml"++permissions:+ contents: read++concurrency:+ group: code-apps-script-tests-${{ github.event.pull_request.number || github.ref }}+ cancel-in-progress: true++jobs:+ test-code-apps-hooks:+ runs-on: ${{ matrix.os }}+ timeout-minutes: 10+ strategy:+ fail-fast: false+ matrix:+ os:+ - ubuntu-latest+ - windows-latest+ steps:+ - name: checkout+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - name: setup-node+ uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0+ with:+ node-version: 22+ - name: run-hook-tests+ run: node --test plugins/code-apps/scripts/tests/*.test.jsdiff --git a/plugins/code-apps/.claude-plugin/plugin.json b/plugins/code-apps/.claude-plugin/plugin.jsonindex f87058138..50548a8af 100644--- a/plugins/code-apps/.claude-plugin/plugin.json+++ b/plugins/code-apps/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "code-apps-preview",- "version": "1.1.0",+ "version": "1.1.1","description": "Build and deploy Power Apps code apps using React, Vite, and Power Platform connectors.","author": {"name": "Microsoft",diff --git a/plugins/code-apps/.plugin/plugin.json b/plugins/code-apps/.plugin/plugin.jsonindex f87058138..50548a8af 100644--- a/plugins/code-apps/.plugin/plugin.json+++ b/plugins/code-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "code-apps-preview",- "version": "1.1.0",+ "version": "1.1.1","description": "Build and deploy Power Apps code apps using React, Vite, and Power Platform connectors.","author": {"name": "Microsoft",diff --git a/plugins/code-apps/AGENTS.md b/plugins/code-apps/AGENTS.mdindex 259e33a07..26013b6a2 100644--- a/plugins/code-apps/AGENTS.md+++ b/plugins/code-apps/AGENTS.md@@ -21,6 +21,11 @@ claude --plugin-dir /path/to/plugins/power-appsAGENTS.md <- Plugin guidance for AI agents (this file)agents/code-app-architect.md <- Agent persona for architecture decisions+hooks.json <- Native Copilot CLI preToolUse hook+hooks/+ hooks.json <- Claude Code PreToolUse hook+ set-cli-origin.js <- Narrow leading-invocation attribution (Node only)+ README.md <- Hook contracts and limitationsshared/shared-instructions.md <- Cross-cutting concerns (Windows CLI, safety, planning, memory bank)connector-reference.md <- Connector patterns and generated service usage@@ -99,6 +104,16 @@ Always use generated services for data access.The Power Apps CLI (`@microsoft/power-apps-cli`) is installed locally via `npm install` as part of the app template. It ships two binaries — grouped **`pa`** (preferred) and flat **`power-apps`** (fallback). **Resolve which one the project has via [shared/cli-binary.md](./shared/cli-binary.md) first**, then invoke it with `npx --no-install <pa|power-apps>` from the project directory — runs natively in bash on all platforms, no PowerShell wrapper needed. Commands below use the canonical grouped `pa` form:+Shell hooks automatically supply `PA_CLI_ORIGIN=plugin/<host-agent>` for recognized+CLI invocations without replacing explicit user values. Do not manually export+attribution in skills. Keep both host hook configurations in sync; native Copilot+events preserve shell identity, whereas its Claude-compatible `Bash` alias does+not distinguish Bash from PowerShell. See [hooks/README.md](./hooks/README.md).+Keep detection conservative and tokenizer-free: match supported single-line+leading invocations and simple output captures, not arbitrary shell programs.+Leave PowerShell `using` preambles unchanged. Handled hook/launcher failures must+report stderr diagnostics but complete successfully without rewriting the call.+```bashpa app push # Deploy apppa app add data-source --connector ... # Add connector@@ -117,6 +132,11 @@ npx degit microsoft/PowerAppsCodeApps/templates/vite {folder} --forceAfter modifying this plugin:+Run `node --test plugins/code-apps/scripts/tests/*.test.js` from the repository+root. The path-filtered `code-apps-script-tests` workflow exercises Bash and+PowerShell execution on Windows and Linux; these tests use local CLI stubs and+never transmit telemetry.+1. Run `claude --debug` to see plugin loading details2. Test skill invocation with `/create-code-app`3. Verify connector-first guardrails are enforceddiff --git a/plugins/code-apps/README.md b/plugins/code-apps/README.mdindex e0959998f..0349bddb2 100644--- a/plugins/code-apps/README.md+++ b/plugins/code-apps/README.md@@ -42,6 +42,24 @@ Open GitHub Copilot CLI or Claude Code in any folder and run the following commaStart with `/create-code-app` — it walks you through everything.+## CLI attribution++Before recognized Power Apps CLI shell commands, the plugin supplies+`PA_CLI_ORIGIN=plugin/<host-agent>` (`claude-code`, `copilot-cli`, or `unknown`).+It supports Bash and PowerShell, both `npx --no-install pa` and the+`npx --no-install power-apps` fallback, direct binaries, and the resolved `$PA`+prefix, plus simple Bash and PowerShell output captures. Detection is limited to+leading invocations on a single line (optionally after a simple `cd`); complex+scripts and PowerShell `using` preambles are left unchanged. Existing+parent-environment values and inline assignments take precedence. Unrelated+commands are not rewritten; no model information is collected.++CLI versions that support `PA_CLI_ORIGIN` record the complete value in the existing+`cliSource` telemetry common property (queried as `customDimensions.cliSource`),+not a new `cliOrigin` column. This plugin does not send its own telemetry or change+the CLI's telemetry consent settings. Older CLI versions ignore the variable.+See [hook behavior and limitations](hooks/README.md).+## Uninstall```diff --git a/plugins/code-apps/hooks.json b/plugins/code-apps/hooks.jsonnew file mode 100644index 000000000..b5bd1e216--- /dev/null+++ b/plugins/code-apps/hooks.json@@ -0,0 +1,13 @@+{+ "version": 1,+ "hooks": {+ "preToolUse": [+ {+ "type": "command",+ "command": "node -e \"try { const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root) throw new Error('Plugin root is not set'); require(path.resolve(root,'hooks','set-cli-origin.js')); } catch(error) { console.error('[code-apps] CLI attribution was not applied: '+error.message); }\"",+ "matcher": "bash|powershell",+ "timeoutSec": 10+ }+ ]+ }+}diff --git a/plugins/code-apps/hooks/README.md b/plugins/code-apps/hooks/README.mdnew file mode 100644index 000000000..c2f8c3797--- /dev/null+++ b/plugins/code-apps/hooks/README.md@@ -0,0 +1,73 @@+# CLI origin hook++The plugin supplies `PA_CLI_ORIGIN=plugin/claude-code`, `plugin/copilot-cli`, or+`plugin/unknown` before recognized Power Apps CLI invocations. Node (already a+plugin prerequisite) is the only hook interpreter; Python and jq are not needed.+Host detection uses `CLAUDECODE` / `CLAUDE_CODE_ENTRYPOINT`, then `COPILOT_CLI` /+`COPILOT_AGENT_SESSION_ID`. It does not inspect models, prompts, or user identity.++## Host contracts++- Copilot CLI loads the plugin-root `hooks.json` with native `preToolUse` events.+ The hook reads `toolName` / `toolArgs`, chooses syntax from the actual `bash` or+ `powershell` tool name, and returns `modifiedArgs`.+- Claude Code loads `hooks/hooks.json` with `PreToolUse` events. The hook reads+ `tool_name` / `tool_input` and returns `hookSpecificOutput.updatedInput`.+ Copilot's Claude-compatible event is deliberately ignored when Copilot host+ signals are present: its `Bash` alias represents both Bash and PowerShell.++The hook leaves permission decisions to the host, preserves all other tool input+fields, and never chooses target shell syntax from the operating system or the+shell executing the hook itself. Unknown tool names are unchanged.++References: [Copilot hooks](https://docs.github.com/en/copilot/reference/hooks-reference)+and [Claude hooks](https://code.claude.com/docs/en/hooks#pretooluse-decision-control).++## Detection and scope++Detection uses anchored checks for single-line commands, not a tokenizer or shell+parser. It recognizes these leading invocation forms:++- `npx --no-install pa ...` and `npx --no-install power-apps ...`.+- Direct `pa` / `power-apps`, optionally under `./node_modules/.bin/`, with+ `.cmd`, `.exe`, or `.ps1` suffixes; `npx.cmd` / `npx.exe` also work.+- Bash's documented `$PA` / `${PA}` resolved prefix.+- Bash captures such as `result="$(npx --no-install pa app list)"`, optionally+ followed by `; ...`. The substitution must be simple: no nested parentheses,+ quoted arguments, escapes, or backticks.+- PowerShell captures such as `$apps = npx --no-install pa app list` and+ `$apps=power-apps list-codeapps`.++An optional `cd app && ...` prefix is supported in either shell, as is+`cd app; ...` in PowerShell. The path must be simple and unquoted or a literal+single-quoted path (for example, `cd 'my app' && ...`). Arguments, pipelines, and+later commands are retained verbatim once a leading CLI invocation is found.+Literal quoted messages and comments mentioning a CLI do not trigger attribution.++**Deliberate narrowing:** the hook no longer searches arbitrary command chains,+conditionals, function bodies, arbitrary executable paths, call operators, or shell wrappers+(`bash -c` / `pwsh -Command`). Multiline scripts, line continuations, heredocs,+here-strings, PowerShell block comments, backticks, and more complex captures are+left unchanged. Likewise, a CLI appearing only after another command (other than+the simple `cd` prefix) is not detected. Resolve `$PA` separately from its+invocation. Use a supported leading invocation when automatic attribution is+needed; unsupported syntax still executes normally without added attribution.++PowerShell scripts beginning with `using` declarations are left unchanged. The+hook never inserts a statement before, moves, or parses a required preamble.++For a matching shell tool call, a conditional environment assignment is prepended+to the original command, without wrapping or reconstructing it. The variable is+scoped to that tool's shell process and inherited child processes (including+other commands in the same compound call). It does not modify the user's parent+shell. Parent values, even empty ones, are not replaced; later inline assignments+still win. Directory changes, quoting, pipelines, and command exit status retain+their original semantics.++Handled failures (including malformed input, a missing plugin root, or failure to+load the hook module) report a diagnostic on stderr and exit successfully with no+rewrite, never a permission denial. Node must be available to run the launcher;+interpreter launch failures and host timeouts are outside the script's control.+The hook does not send telemetry. Supporting CLI versions trim the+variable, default to `standalone` when empty/unset, and emit its entire value as+the existing `cliSource` common property, subject to CLI telemetry consent.diff --git a/plugins/code-apps/hooks/hooks.json b/plugins/code-apps/hooks/hooks.jsonnew file mode 100644index 000000000..25614c895--- /dev/null+++ b/plugins/code-apps/hooks/hooks.json@@ -0,0 +1,16 @@+{+ "hooks": {+ "PreToolUse": [+ {+ "matcher": "Bash|bash|sh|powershell|PowerShell|pwsh",+ "hooks": [+ {+ "type": "command",+ "command": "node -e \"try { const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root) throw new Error('Plugin root is not set'); require(path.resolve(root,'hooks','set-cli-origin.js')); } catch(error) { console.error('[code-apps] CLI attribution was not applied: '+error.message); }\"",+ "timeout": 10+ }+ ]+ }+ ]+ }+}diff --git a/plugins/code-apps/hooks/set-cli-origin.js b/plugins/code-apps/hooks/set-cli-origin.jsnew file mode 100644index 000000000..3ad889758--- /dev/null+++ b/plugins/code-apps/hooks/set-cli-origin.js@@ -0,0 +1,93 @@+'use strict';++// Node is already a plugin prerequisite. One launcher works on both platforms;+// the target tool name, NOT the shell running this hook, chooses command syntax.+const SHELLS = new Map([+ ['bash', 'bash'], ['sh', 'bash'],+ ['powershell', 'powershell'], ['pwsh', 'powershell'],+]);++function hostAgent(env) {+ if (env.CLAUDECODE === '1' || env.CLAUDE_CODE_ENTRYPOINT) return 'claude-code';+ if (env.COPILOT_CLI === '1' || env.COPILOT_AGENT_SESSION_ID) return 'copilot-cli';+ return 'unknown';+}++function invokesCli(command, shell) {+ // Deliberately match only single-line, leading invocations, not shell grammar.+ // Skipping scripts also avoids treating multiline strings/comments as code.+ if (/[\r\n]/.test(command)) return false;+ if (shell === 'bash' ? /<<|`/.test(command) : /<#|#>|@\s*['"]|`/.test(command)) return false;+ let candidate = command.trimStart();+ // `using namespace System; ...` must stay ahead of executable statements.+ // Do not try to relocate declarations or parse a PowerShell preamble.+ if (shell === 'powershell' && /^using\b/i.test(candidate)) return false;++ // The only supported prelude is `cd app && ...` (or `cd app; ...` in+ // PowerShell), with a simple unquoted path or a literal single-quoted path.+ candidate = candidate.replace(+ shell === 'bash'+ ? /^cd\s+(?:[A-Za-z0-9_./\\:-]+|'[^'\r\n]+')\s*&&\s*/+ : /^cd\s+(?:[A-Za-z0-9_./\\:-]+|'[^'\r\n]+')\s*(?:&&|;)\s*/i,+ '',+ );+ if (shell === 'bash') {+ // Exact capture form: result="$(npx --no-install pa app list)".+ // Reject nested/escaped expressions rather than interpreting their contents.+ const capture = candidate.match(/^[A-Za-z_][A-Za-z_0-9]*="\$\(([^()"'`\\\r\n]+)\)"(?:\s*;|$)/);+ if (capture) candidate = capture[1].trimStart();+ } else {+ // PowerShell executes the RHS in both `$apps = npx ...` and `$apps=npx ...`.+ candidate = candidate.replace(/^\$[A-Za-z_][A-Za-z_0-9]*\s*=\s*/, '');+ }+ const cli = /^(?:npx(?:\.cmd|\.exe)?\s+--no-install\s+(?:pa|power-apps)|(?:\.\/node_modules\/\.bin\/)?(?:pa|power-apps)(?:\.cmd|\.exe|\.ps1)?)(?:\s+(?!\s*\()|$)/;+ return (shell === 'powershell' ? new RegExp(cli.source, 'i') : cli).test(candidate)+ || (shell === 'bash' && /^\$(?:PA|\{PA\})(?:\s+|$)/.test(candidate));+}++function rewrite(payload, env = process.env) {+ if (!payload || typeof payload !== 'object') return null;+ const native = typeof payload.toolName === 'string' && payload.toolArgs !== undefined;+ const toolName = payload.tool_name || payload.toolName || '';+ if (typeof toolName !== 'string') return null;+ const shell = SHELLS.get(toolName.toLowerCase());+ let input = payload.tool_input || payload.toolInput || payload.input || payload.toolArgs;+ // Some hook clients serialize toolArgs as JSON rather than an object.+ if (typeof input === 'string') input = JSON.parse(input);+ if (!shell || !input || typeof input.command !== 'string') return null;+ // Copilot's Claude-compatible event maps BOTH native bash and powershell to+ // "Bash". Only its native camelCase event retains the actual shell identity.+ // https://docs.github.com/en/copilot/reference/hooks-reference+ if (!native && hostAgent(env) === 'copilot-cli') return null;+ if (Object.hasOwn(env, 'PA_CLI_ORIGIN') || !invokesCli(input.command, shell)) return null;+ const origin = `plugin/${hostAgent(env)}`;+ // A prefix, rather than a subshell/script block, preserves cd, variable scope,+ // pipelines and the original command's exit status. Runtime checks also honor+ // values supplied by the tool environment; later inline assignments win.+ const prefix = shell === 'bash'+ ? `if [ "\${PA_CLI_ORIGIN+x}" != x ]; then export PA_CLI_ORIGIN='${origin}'; fi\n`+ : `if (-not (Test-Path Env:PA_CLI_ORIGIN)) { $env:PA_CLI_ORIGIN = '${origin}' }\n`;+ if (input.command.startsWith(prefix)) return null;+ const updatedInput = { ...input, command: prefix + input.command };+ // Native Copilot hooks use modifiedArgs, not Claude's updatedInput. Do not grant+ // permission as a side effect: leave normal shell approval policy intact.+ // https://code.claude.com/docs/en/hooks#pretooluse-decision-control+ return native ? { modifiedArgs: updatedInput }+ : { hookSpecificOutput: { hookEventName: 'PreToolUse', updatedInput } };+}++async function main() {+ try {+ let source = '';+ process.stdin.setEncoding('utf8');+ for await (const chunk of process.stdin) source += chunk;+ const output = rewrite(JSON.parse(source));+ if (output) process.stdout.write(JSON.stringify(output));+ } catch (error) {+ // Attribution must not block a user's command, but failures must be visible.+ process.stderr.write(`[code-apps] CLI attribution was not applied: ${error.message}\n`);+ }+}++module.exports = { hostAgent, invokesCli, rewrite };+if (require.main === module || process.argv[1] === undefined) main();diff --git a/plugins/code-apps/scripts/tests/cli-origin.test.js b/plugins/code-apps/scripts/tests/cli-origin.test.jsnew file mode 100644index 000000000..1b0afc0a6--- /dev/null+++ b/plugins/code-apps/scripts/tests/cli-origin.test.js@@ -0,0 +1,257 @@+'use strict';++const assert = require('node:assert/strict');+const { test } = require('node:test');+const { spawnSync } = require('node:child_process');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { hostAgent, invokesCli, rewrite } = require('../../hooks/set-cli-origin');++const pluginRoot = path.resolve(__dirname, '../..');+const hook = path.join(pluginRoot, 'hooks', 'set-cli-origin.js');+const claude = (command) => ({ tool_name: 'Bash', tool_input: { command, timeout: 1000 } });+const copilot = (command, toolName = 'powershell') => ({ toolName, toolArgs: { command, description: 'CLI' } });+const updated = (result) => result?.modifiedArgs || result?.hookSpecificOutput.updatedInput;++test('detects host only from host signals, never collects model information', () => {+ for (const env of [{ CLAUDECODE: '1' }, { CLAUDE_CODE_ENTRYPOINT: 'cli' }]) {+ assert.equal(hostAgent(env), 'claude-code');+ }+ for (const env of [{ COPILOT_CLI: '1' }, { COPILOT_AGENT_SESSION_ID: 'session' }]) {+ assert.equal(hostAgent(env), 'copilot-cli');+ }+ assert.equal(hostAgent({ MODEL: 'anything' }), 'unknown');+});++test('detects leading CLI invocations and simple directory changes', () => {+ for (const command of [+ 'npx --no-install pa app list', 'npx --no-install power-apps list-codeapps',+ 'cd app && npx --no-install pa app list',+ "cd 'my app' && npx --no-install pa app list",+ '$PA app list', '${PA} app list',+ 'pa app list', './node_modules/.bin/power-apps list-codeapps',+ 'pa app list | cat', 'pa app list && echo done',+ ]) assert.equal(invokesCli(command, 'bash'), true, command);+ for (const command of [+ 'npx.cmd --no-install pa app list', 'power-apps.exe list-codeapps',+ "cd 'my app'; npx --no-install pa app list", 'PA app list',+ ]) assert.equal(invokesCli(command, 'powershell'), true, command);+});++test('recognizes only simple executable captures, never literal quoted messages', () => {+ for (const binary of ['pa', 'power-apps']) {+ for (const prefix of [`npx --no-install ${binary}`, binary]) {+ assert.equal(invokesCli(`result="$(${prefix} app list)"`, 'bash'), true);+ for (const assignment of ['$apps = ', '$apps=']) {+ assert.equal(invokesCli(`${assignment}${prefix} app list`, 'powershell'), true);+ }+ }+ }+ assert.equal(invokesCli('result="$($PA app list)"', 'bash'), true);+ assert.equal(invokesCli('result="$(${PA} app list)"', 'bash'), true);+ for (const command of [+ 'echo "npx --no-install pa app list"', 'printf "%s" pa',+ 'echo "hello; npx --no-install pa app list"',+ 'result="npx --no-install pa app list"',+ 'result=\'$(npx --no-install pa app list)\'',+ 'echo \'result="$(npx --no-install pa app list)"\'',+ 'result="\\$(npx --no-install pa app list)"',+ 'result="$(echo npx --no-install pa app list)"',+ '# npx --no-install pa app list\necho hi',+ '# result="$(npx --no-install pa app list)"',+ 'npx --no-install parallel', 'npx --no-install pa-other',+ 'git diff -- pa', 'node -e "console.log(\'pa app list\')"',+ 'PA="npx --no-install pa"; echo "$PA"',+ 'pa() { echo hello; }; echo defined',+ 'pa () { echo hello; }; echo defined',+ ]) assert.equal(invokesCli(command, 'bash'), false, command);+ for (const command of [+ "Write-Output 'npx --no-install pa app list'",+ '$apps = "npx --no-install pa app list"',+ "$apps='power-apps list-codeapps'",+ '$apps = Write-Output "npx --no-install pa app list"',+ '# $apps=npx --no-install pa app list',+ "<# comment #> $apps=npx --no-install pa app list",+ ]) assert.equal(invokesCli(command, 'powershell'), false, command);+});++test('leaves scripts and broader shell syntax outside the detection contract unchanged', () => {+ for (const command of [+ 'npx --no-install tsc; npx --no-install pa app list',+ 'if true; then npx --no-install pa app list; fi',+ 'command npx --no-install pa app list',+ 'env PA_CLI_ORIGIN=custom npx --no-install pa app list',+ 'PA="npx --no-install pa"; $PA app list',+ 'npx \\\n --no-install pa app list',+ 'bash -c "npx --no-install pa app list"',+ 'cat <<EOF\npa app list\nEOF',+ 'message="\npa app list\n"',+ 'result="$(echo "$(npx --no-install pa app list)")"',+ 'result=`npx --no-install pa app list`',+ 'function run() { pa app list; }',+ 'npx pa app list',+ "'/tools/pa' app list",+ ]) assert.equal(invokesCli(command, 'bash'), false, command);+ for (const command of [+ "using namespace System; npx --no-install pa app list",+ " USING namespace System; power-apps list-codeapps",+ "# comment\nusing namespace System\npa app list",+ "<# comment #> using namespace System; pa app list",+ '$message = @"\npa app list\n"@',+ '<#\npa app list\n#>',+ "& 'C:\\tools\\pa.cmd' app list",+ 'pwsh -Command "pa app list"',+ ]) assert.equal(rewrite(copilot(command), {}), null, command);+});++test('uses each host output contract, preserving non-command fields and approval policy', () => {+ const command = 'npx --no-install pa app list';+ const a = rewrite(claude(command), { CLAUDECODE: '1' });+ assert.equal(a.hookSpecificOutput.hookEventName, 'PreToolUse');+ assert.equal(updated(a).timeout, 1000);+ assert.match(updated(a).command, /plugin\/claude-code/);+ assert.ok(updated(a).command.endsWith(command));+ const b = rewrite(copilot(command), { COPILOT_CLI: '1' });+ assert.equal(b.modifiedArgs.description, 'CLI');+ assert.match(updated(b).command, /\$env:PA_CLI_ORIGIN = 'plugin\/copilot-cli'/);+ assert.equal(b.permissionDecision, undefined);+ assert.equal(a.hookSpecificOutput.permissionDecision, undefined);+ assert.deepEqual(rewrite({ toolName: 'powershell', toolArgs: JSON.stringify(copilot(command).toolArgs) }, { COPILOT_CLI: '1' }), b);+ assert.match(updated(rewrite(claude(command), {})).command, /plugin\/unknown/);+});++test('does not confuse hook runtime, host identity and target shell', () => {+ assert.match(updated(rewrite(copilot('pa app list', 'bash'), { COPILOT_CLI: '1' })).command, /export PA_CLI_ORIGIN/);+ assert.equal(rewrite(claude('pa app list'), { COPILOT_CLI: '1' }), null);+ assert.equal(rewrite(copilot('pa app list', 'shell'), {}), null);+ assert.equal(rewrite({ tool_name: 'Write', tool_input: { command: 'pa app list' } }, {}), null);+});++test('preserves explicitly set parent values including empty values, and is idempotent', () => {+ for (const value of ['', 'custom-origin', ' plugin/custom ']) {+ assert.equal(rewrite(claude('pa app list'), { PA_CLI_ORIGIN: value }), null);+ }+ const input = claude('pa app list');+ input.tool_input = updated(rewrite(input, {}));+ assert.equal(rewrite(input, {}), null);+ for (const payload of [null, {}, { tool_name: 42 }, { tool_name: 'Bash', tool_input: {} }]) {+ assert.equal(rewrite(payload, {}), null);+ }+});++const available = (shell) => !spawnSync(shell, ['--version'], { stdio: 'ignore' }).error;++for (const shell of ['bash', 'pwsh']) {+ const installed = available(shell);+ test(`${shell}: rewritten command delivers origin to stub CLI and preserves behavior`, { skip: !installed && !process.env.CI }, () => {+ assert.ok(installed, `${shell} must be installed in CI`);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'code-apps-origin-'));+ try {+ fs.writeFileSync(path.join(dir, 'stub.cjs'), 'console.log(JSON.stringify({origin:process.env.PA_CLI_ORIGIN,args:process.argv.slice(2)}));process.exit(Number(process.env.STUB_EXIT||0));');+ const isBash = shell === 'bash';+ const setup = isBash+ ? 'pa() { node stub.cjs "$@"; }; power-apps() { node stub.cjs "$@"; }; npx() { shift; "$@"; }; '+ : 'function pa { node stub.cjs @args }; function power-apps { node stub.cjs @args }; function npx { $binary=$args[1]; & $binary @($args | Select-Object -Skip 2) }; ';+ const env = { ...process.env, COPILOT_CLI: '1' };+ delete env.PA_CLI_ORIGIN;+ const run = (command, extra = {}, prelude = setup) => {+ const result = rewrite(copilot(command, isBash ? 'bash' : 'powershell'), env);+ // Stub functions are test harness setup, not part of the hook input.+ const script = prelude + (updated(result)?.command || command);+ const args = isBash ? ['--noprofile', '--norc', '-c', script]+ : ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script];+ return spawnSync(shell, args, { cwd: dir, env: { ...env, ...extra }, encoding: 'utf8', timeout: 15000 });+ };+ const check = (command, origin, extra) => {+ const result = run(command, extra);+ assert.equal(result.status, 0, result.stderr);+ const output = JSON.parse(result.stdout.trim());+ assert.equal(output.origin, origin);+ assert.deepEqual(output.args, ['app', 'list', 'a b']);+ };+ const call = 'npx --no-install pa app list "a b"';+ for (const binary of ['pa', 'power-apps']) {+ check(`npx --no-install ${binary} app list "a b"`, 'plugin/copilot-cli');+ }+ if (isBash) {+ check('$PA app list "a b"', 'plugin/copilot-cli', { PA: 'npx --no-install pa' });+ check('${PA} app list "a b"', 'plugin/copilot-cli', { PA: 'npx --no-install pa' });+ }+ check(`cd . ${isBash ? '&&' : ';'} ${call}`, 'plugin/copilot-cli');+ check(call, 'parent/custom', { PA_CLI_ORIGIN: 'parent/custom' });+ check(call, '', { PA_CLI_ORIGIN: '' });+ check((isBash ? 'PA_CLI_ORIGIN=inline/custom ' : "$env:PA_CLI_ORIGIN='inline/custom'; ") + call, 'inline/custom');+ check((isBash ? 'export PA_CLI_ORIGIN=script/custom; ' : "$env:PA_CLI_ORIGIN='script/custom'; ") + call, 'script/custom');+ const override = run(call + (isBash ? '; PA_CLI_ORIGIN=inline/custom ' : "; $env:PA_CLI_ORIGIN='inline/custom'; ") + call);+ assert.equal(override.status, 0, override.stderr);+ assert.deepEqual(override.stdout.trim().split(/\r?\n/).map((line) => JSON.parse(line).origin),+ ['plugin/copilot-cli', 'inline/custom']);+ const failure = run(call + (isBash ? '' : '; exit $LASTEXITCODE'), { STUB_EXIT: '7' });+ assert.equal(failure.status, 7, failure.stderr);+ for (const binary of ['pa', 'power-apps']) {+ for (const prefix of [`npx --no-install ${binary}`, binary]) {+ const captures = isBash+ ? [`result="$(${prefix} app list)"; printf '%s' "$result"`]+ : [`$apps = ${prefix} app list; $apps`, `$apps=${prefix} app list; $apps`];+ for (const capture of captures) {+ const result = run(capture);+ assert.equal(result.status, 0, result.stderr);+ assert.deepEqual(JSON.parse(result.stdout.trim()), { origin: 'plugin/copilot-cli', args: ['app', 'list'] });+ }+ }+ }+ if (!isBash) {+ const command = `using namespace System; ${setup}${call}`;+ assert.equal(rewrite(copilot(command), env), null);+ const result = run(command, {}, '');+ assert.equal(result.status, 0, result.stderr);+ assert.deepEqual(JSON.parse(result.stdout.trim()), { args: ['app', 'list', 'a b'] });+ }+ const unrelated = isBash ? 'printf "%s" "${PA_CLI_ORIGIN-unset}"' : "if (Test-Path Env:PA_CLI_ORIGIN) { $env:PA_CLI_ORIGIN } else { 'unset' }";+ assert.equal(run(unrelated).stdout.trim(), 'unset');+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ });+}++test('hook process reads UTF-8 JSON, reports malformed input, and runs from bundled root', () => {+ const env = { ...process.env, CLAUDECODE: '1', PLUGIN_ROOT: pluginRoot };+ delete env.PA_CLI_ORIGIN;+ const payload = claude('npx --no-install pa app list --search "caf\u00e9"');+ const result = spawnSync(process.execPath, [hook], { input: JSON.stringify(payload), env, encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr);+ assert.ok(updated(JSON.parse(result.stdout)).command.endsWith(payload.tool_input.command));+ for (const input of ['{', JSON.stringify({ toolName: 'powershell', toolArgs: '{' })]) {+ const bad = spawnSync(process.execPath, [hook], { input, env, encoding: 'utf8' });+ assert.equal(bad.status, 0);+ assert.match(bad.stderr, /CLI attribution was not applied/);+ assert.equal(bad.stdout, '');+ }+ const claudeHook = require('../../hooks/hooks.json').hooks.PreToolUse[0];+ const nativeManifest = require('../../hooks.json');+ const copilotHook = nativeManifest.hooks.preToolUse[0];+ assert.equal(nativeManifest.version, 1);+ assert.match('Bash', new RegExp(`^(?:${claudeHook.matcher})$`));+ for (const tool of ['bash', 'powershell']) assert.match(tool, new RegExp(`^(?:${copilotHook.matcher})$`));+ for (const tool of ['Write', 'shell']) assert.doesNotMatch(tool, new RegExp(`^(?:${copilotHook.matcher})$`));+ for (const [launcher, data] of [+ [claudeHook.hooks[0].command, payload],+ [copilotHook.command, copilot('npx --no-install pa app list')],+ ]) {+ const launched = spawnSync(launcher, { shell: true, input: JSON.stringify(data), env, encoding: 'utf8' });+ assert.equal(launched.status, 0, launched.stderr);+ assert.ok(updated(JSON.parse(launched.stdout)).command.endsWith(data.tool_input?.command || data.toolArgs.command));+ for (const root of [undefined, path.join(pluginRoot, 'missing-plugin-root')]) {+ const badEnv = { ...env };+ delete badEnv.PLUGIN_ROOT;+ delete badEnv.CLAUDE_PLUGIN_ROOT;+ if (root) badEnv.PLUGIN_ROOT = root;+ const failed = spawnSync(launcher, { shell: true, input: JSON.stringify(data), env: badEnv, encoding: 'utf8' });+ assert.equal(failed.status, 0, failed.stderr);+ assert.equal(failed.stdout, '');+ assert.match(failed.stderr, /CLI attribution was not applied/);+ }+ }+});diff --git a/plugins/code-apps/shared/shared-instructions.md b/plugins/code-apps/shared/shared-instructions.mdindex 7a6c36453..f28b6ec61 100644--- a/plugins/code-apps/shared/shared-instructions.md+++ b/plugins/code-apps/shared/shared-instructions.md@@ -140,6 +140,11 @@ The CLI ships two binaries — grouped `pa` (preferred) and flat `power-apps` (f## CLI Commands+The plugin's shell hooks supply `PA_CLI_ORIGIN=plugin/<host-agent>` automatically+for recognized CLI commands. Do not add manual attribution exports. Explicit+user-supplied values win; this attribution uses the CLI's existing telemetry+consent and `cliSource` common property, not a separate plugin telemetry stream.+The Power Apps code app CLI (`@microsoft/power-apps-cli`) is installed locally as part of `npm install` when a project is scaffolded with the template. **Never invoke a bare `pa`/`power-apps`** — always run the locally-installed CLI through the resolved `$PA` prefix (`npx --no-install …`) from within the project directory. **Resolve the binary first (see [cli-binary.md](./cli-binary.md)); the commands below are canonical grouped `pa` templates — substitute `$PA` for the leading `pa`, and when `PA_KIND=power-apps` translate the verb path and renamed flags via the mapping tables before running.****Core commands (canonical `pa` form — translate to flat `power-apps` via [cli-binary.md](./cli-binary.md) when only `power-apps` is installed):**