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.

fix(code-apps): isolate plugin CLI attribution (#833)

Steven J01d846cbe2f1
diff --git a/plugins/code-apps/AGENTS.md b/plugins/code-apps/AGENTS.md
index f25218317..650e39a31 100644
--- a/plugins/code-apps/AGENTS.md
+++ b/plugins/code-apps/AGENTS.md
@@ -26,12 +26,11 @@ agents/
com.github.copilot/agents/
code-app-architect.agent.md <- Native Copilot copy with adjusted relative links
com.github.copilot/hooks/
- hooks.json <- Native Copilot hooks for the portable package
-hooks.json <- Native Copilot CLI preToolUse hook
+ hooks.json <- Empty native configuration (no tool interception)
+hooks.json <- Empty legacy Copilot configuration
hooks/
- hooks.json <- Claude Code PreToolUse hook
- set-cli-origin.js <- Narrow leading-invocation attribution (Node only)
- README.md <- Hook contracts and limitations
+ hooks.json <- Empty Claude configuration
+ README.md <- Command-scoped attribution safety
shared/
shared-instructions.md <- Cross-cutting concerns (Windows CLI, safety, planning, memory bank)
connector-reference.md <- Connector patterns and generated service usage
@@ -114,15 +113,12 @@ Always use generated services for data access.
The Power Apps CLI (`@microsoft/power-apps-cli`) is installed into each project as a dev dependency; the Vite template doesn't include it, so `/create-code-app` adds it. It has shipped 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.
+Register no pre-tool hooks. Apply `PA_CLI_ORIGIN=plugin` only to CLI child processes
+initiated by a Code Apps skill. Preserve explicit user origins, including empty values.
+Remove inherited `PA_PLUGIN_REPORT_AGENT` only from that child process.
+The CLI detects the AI tool from its environment. Do not guess agent labels.
+Follow [command-scoped attribution](./shared/cli-binary.md#command-scoped-attribution).
+Do not modify parent environments, user commands, approvals, or unrelated tools.
```bash
pa app push # Deploy app
@@ -155,8 +151,8 @@ node --test plugins/code-apps/scripts/tests/*.test.js
The Code Apps workflow runs these checks on Windows and Ubuntu.
Package checks do not prove that a client can install, update, or execute skills.
Check those actions separately before claiming runtime support.
-The path-filtered `code-apps-script-tests` workflow exercises Bash and PowerShell
-on Windows and Linux with local CLI stubs. These tests never transmit telemetry.
+The path-filtered `code-apps-script-tests` workflow exercises command-scoped Bash
+attribution on Windows and Linux with local CLI stubs. These tests never transmit telemetry.
## Portable Package Rules
@@ -168,4 +164,4 @@ on Windows and Linux with local CLI stubs. These tests never transmit telemetry.
- The repository's `.agents/plugins/marketplace.json` exposes Code Apps only. Do not add unadapted sibling plugins.
- Preserve user approvals when replacing client-specific tools with equivalent capabilities.
- Keep `com.github.copilot/hooks/hooks.json` equal to the legacy root `hooks.json`.
-- Preserve the existing Code Apps attribution hooks. Do not copy Managed Apps attribution variables or agent detection into them.
+- Keep all hook event maps empty. Apply attribution only through the command-scoped CLI instructions. Do not use Managed Apps (`MS_*`) variables.
diff --git a/plugins/code-apps/README.md b/plugins/code-apps/README.md
index c9128d857..f218401ef 100644
--- a/plugins/code-apps/README.md
+++ b/plugins/code-apps/README.md
@@ -58,13 +58,13 @@ The portable manifest alone does not establish client runtime support.
| Shared skills | [skills](./skills) | The same 15 workflows for all clients |
| Legacy architect | [agents/code-app-architect.md](./agents/code-app-architect.md) | Architecture guidance in legacy clients |
| Native Copilot architect | [com.github.copilot/agents/code-app-architect.agent.md](./com.github.copilot/agents/code-app-architect.agent.md) | Copilot-specific agent discovery |
-| Native Copilot hooks | [com.github.copilot/hooks/hooks.json](./com.github.copilot/hooks/hooks.json) | Existing CLI attribution in portable clients |
+| Empty hook configurations | [com.github.copilot/hooks/hooks.json](./com.github.copilot/hooks/hooks.json) | Preserve discovery paths without intercepting tools |
Skills retain their existing tool declarations, model preferences, and invocation settings.
Client-specific metadata support varies. These settings do not establish strict Agent Skills conformance.
Resource links resolve relative to each document, so they do not require client-specific variable expansion.
The architect agent is client-specific, not a portable Agent Plugins component.
-The package retains the existing Code Apps attribution hooks. It does not include MCP servers.
+The package registers no tool hooks. It does not include MCP servers.
## Available Skills
@@ -124,21 +124,20 @@ Use the documented update action for other clients.
## 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).
+Only CLI commands initiated by a Code Apps skill receive `PA_CLI_ORIGIN=plugin`.
+The command-scoped prefix preserves explicit user origins, including empty values.
+It removes an inherited `PA_PLUGIN_REPORT_AGENT` from that child process only.
+The CLI detects the AI tool from its environment. The plugin does not guess agent labels.
+No pre-tool hook intercepts unrelated commands, Node checks, builds, or package installs.
+Attribution does not modify the parent shell or later commands.
+
+Supporting CLI versions map `PA_CLI_ORIGIN` to `power-apps-cli`, `plugin`, or
+`other` in the existing `cliSource` custom dimension
+(`customDimensions.cliSource`). They do not emit raw origin values or add a
+`cliOrigin` column. This plugin does not send telemetry or change CLI consent.
+Supporting CLI versions record a normalized AI-tool label from passive environment detection.
+See [attribution safety](hooks/README.md) and
+[command-scoped instructions](shared/cli-binary.md#command-scoped-attribution).
## Uninstall
diff --git a/plugins/code-apps/com.github.copilot/hooks/hooks.json b/plugins/code-apps/com.github.copilot/hooks/hooks.json
index b4bdbfc9d..08f55622b 100644
--- a/plugins/code-apps/com.github.copilot/hooks/hooks.json
+++ b/plugins/code-apps/com.github.copilot/hooks/hooks.json
@@ -1,13 +1,4 @@
{
"version": 1,
- "hooks": {
- "preToolUse": [
- {
- "type": "command",
- "command": "node -e 'try{const path=require(process.argv[1]);const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT;if(!root)throw new Error(process.argv[3]);process.argv[1]=undefined;require(path.resolve(root,process.argv[2]))}catch(error){console.error(process.argv[4]+error.message)}' node:path hooks/set-cli-origin.js 'Plugin root is not set' '[code-apps] CLI attribution was not applied: '",
- "matcher": "bash|powershell",
- "timeoutSec": 10
- }
- ]
- }
+ "hooks": {}
}
diff --git a/plugins/code-apps/hooks.json b/plugins/code-apps/hooks.json
index b4bdbfc9d..08f55622b 100644
--- a/plugins/code-apps/hooks.json
+++ b/plugins/code-apps/hooks.json
@@ -1,13 +1,4 @@
{
"version": 1,
- "hooks": {
- "preToolUse": [
- {
- "type": "command",
- "command": "node -e 'try{const path=require(process.argv[1]);const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT;if(!root)throw new Error(process.argv[3]);process.argv[1]=undefined;require(path.resolve(root,process.argv[2]))}catch(error){console.error(process.argv[4]+error.message)}' node:path hooks/set-cli-origin.js 'Plugin root is not set' '[code-apps] CLI attribution was not applied: '",
- "matcher": "bash|powershell",
- "timeoutSec": 10
- }
- ]
- }
+ "hooks": {}
}
diff --git a/plugins/code-apps/hooks/README.md b/plugins/code-apps/hooks/README.md
index 76aa21871..a5b7d44da 100644
--- a/plugins/code-apps/hooks/README.md
+++ b/plugins/code-apps/hooks/README.md
@@ -1,75 +1,21 @@
-# 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 `com.github.copilot/hooks/hooks.json` for the portable package,
- or the plugin-root `hooks.json` for the legacy package, with native `preToolUse` events.
- Keep both configurations equal. Clients select one format rather than combining them.
- 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.
+# CLI attribution safety
+
+The plugin registers no pre-tool hooks in Copilot, Claude, or portable clients.
+The empty hook configurations preserve package paths without running commands.
+Installing the plugin must not intercept unrelated commands or require Node
+before the user can inspect or repair their environment.
+
+Only CLI commands initiated by a Code Apps skill receive attribution.
+Follow [CLI binary resolution](../shared/cli-binary.md#command-scoped-attribution).
+The command receives `PA_CLI_ORIGIN=plugin` unless the user supplied an origin.
+The CLI detects the AI tool from its existing environment markers.
+The plugin does not guess host identity or set `PA_PLUGIN_REPORT_AGENT`.
+
+Attribution variables apply to one CLI child process, not the parent shell,
+other commands in a compound call, user settings, or later tasks.
+Commands keep their arguments, exit status, and normal approval requirements.
+Missing Node affects only commands that themselves require Node.
+Attribution does not change telemetry consent or send telemetry independently.
+
+Restart existing client sessions after updating. A running session can retain
+previously loaded hook definitions until it reloads the plugin.
diff --git a/plugins/code-apps/hooks/hooks.json b/plugins/code-apps/hooks/hooks.json
index 46a1765a2..deffac973 100644
--- a/plugins/code-apps/hooks/hooks.json
+++ b/plugins/code-apps/hooks/hooks.json
@@ -1,16 +1,3 @@
{
- "hooks": {
- "PreToolUse": [
- {
- "matcher": "Bash|bash|sh|powershell|PowerShell|pwsh",
- "hooks": [
- {
- "type": "command",
- "command": "node -e 'try{const path=require(process.argv[1]);const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT;if(!root)throw new Error(process.argv[3]);process.argv[1]=undefined;require(path.resolve(root,process.argv[2]))}catch(error){console.error(process.argv[4]+error.message)}' node:path hooks/set-cli-origin.js 'Plugin root is not set' '[code-apps] CLI attribution was not applied: '",
- "timeout": 10
- }
- ]
- }
- ]
- }
+ "hooks": {}
}
diff --git a/plugins/code-apps/hooks/set-cli-origin.js b/plugins/code-apps/hooks/set-cli-origin.js
deleted file mode 100644
index 3ad889758..000000000
--- a/plugins/code-apps/hooks/set-cli-origin.js
+++ /dev/null
@@ -1,93 +0,0 @@
-'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.js
index 9a55748ff..993e17ba8 100644
--- a/plugins/code-apps/scripts/tests/cli-origin.test.js
+++ b/plugins/code-apps/scripts/tests/cli-origin.test.js
@@ -4,262 +4,48 @@ 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');
+test('plugin discovery registers no hooks that can intercept unrelated tools', () => {
+ for (const file of ['hooks.json', 'hooks/hooks.json', 'com.github.copilot/hooks/hooks.json']) {
+ const config = JSON.parse(fs.readFileSync(path.join(pluginRoot, file), 'utf8'));
+ assert.deepEqual(config.hooks, {}, file);
}
- 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(fs.existsSync(path.join(pluginRoot, 'hooks', 'set-cli-origin.js')), false);
+});
+
+const bashInstalled = spawnSync('bash', ['--version'], { stdio: 'ignore' }).status === 0;
+test('CLI attribution affects only its child process and preserves explicit origin and exit status',
+ { skip: !bashInstalled && !process.env.CI }, () => {
+ assert.ok(bashInstalled, 'Bash must be installed in CI');
+ const prefix = 'env -u PA_PLUGIN_REPORT_AGENT PA_CLI_ORIGIN="${PA_CLI_ORIGIN-plugin}"';
+ const instructions = fs.readFileSync(path.join(pluginRoot, 'shared', 'cli-binary.md'), 'utf8');
+ assert.ok(instructions.includes(`${prefix} $PA app list`));
+ const stub = `${prefix} '${process.execPath.replaceAll('\\', '/')}' -e 'console.log(JSON.stringify({origin:process.env.PA_CLI_ORIGIN,report:process.env.PA_PLUGIN_REPORT_AGENT,args:process.argv.slice(1)}));process.exit(Number(process.env.STUB_EXIT||0))'`;
+ const run = (script, env) => spawnSync('bash', ['--noprofile', '--norc', '-c', script], {
+ env, encoding: 'utf8', timeout: 15000,
+ });
+ const baseline = { ...process.env };
+ delete baseline.PA_CLI_ORIGIN;
+ delete baseline.PA_PLUGIN_REPORT_AGENT;
+ delete baseline.STUB_EXIT;
+ for (const origin of [undefined, '', 'user/custom']) {
+ for (const report of [undefined, 'inherited-agent']) {
+ const env = { ...baseline };
+ if (origin !== undefined) env.PA_CLI_ORIGIN = origin;
+ if (report !== undefined) env.PA_PLUGIN_REPORT_AGENT = report;
+ const result = run(`${stub} app list "a b"; printf '\\nparent:%s:%s' "\${PA_CLI_ORIGIN-unset}" "\${PA_PLUGIN_REPORT_AGENT-unset}"`, env);
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'] });
- }
- }
+ const [output, , parent] = result.stdout.trimEnd().split(/\r?\n/);
+ assert.deepEqual(JSON.parse(output), { origin: origin ?? 'plugin', args: ['app', 'list', 'a b'] });
+ assert.equal(parent, `parent:${origin ?? 'unset'}:${report ?? 'unset'}`);
+ const failure = run(stub, { ...env, STUB_EXIT: '7' });
+ assert.equal(failure.status, 7, failure.stderr);
+ const capture = run(`result="$(${stub} app list)"; printf '%s' "$result"`, env);
+ assert.equal(capture.status, 0, capture.stderr);
+ assert.deepEqual(JSON.parse(capture.stdout), { origin: origin ?? 'plugin', 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})$`));
- // Node's shell:true defaults to cmd.exe on Windows, but these hooks run in
- // PowerShell there. cmd.exe does not treat single quotes as quoting.
- const shell = process.platform === 'win32' ? 'powershell.exe' : '/bin/sh';
- const launch = (command, options) => spawnSync(shell,
- process.platform === 'win32'
- ? ['-NoLogo', '-NoProfile', '-Command', command]
- : ['-c', command],
- options);
- for (const [launcher, data] of [
- [claudeHook.hooks[0].command, payload],
- [copilotHook.command, copilot('npx --no-install pa app list')],
- ]) {
- const launched = launch(launcher, { 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 = launch(launcher, { 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/cli-binary.md b/plugins/code-apps/shared/cli-binary.md
index 1bd89d465..8fd3ca0c0 100644
--- a/plugins/code-apps/shared/cli-binary.md
+++ b/plugins/code-apps/shared/cli-binary.md
@@ -88,6 +88,32 @@ $PA --version # prints the installed CLI version, e.g. 1.3.0
- **Most flags are unchanged** — only the selector flags in the flag mapping table are renamed on `pa`. Connection ID (`-c`), dataset (`-d`), environment (`-e`), and display name (`-n` on `init`/`connection create`) are identical on both binaries.
- **Whether `-c` is required depends on the CLI version.** For connector data sources, `-c <connection-id>` is optional only when `PA_INLINE_CONNECTIONS=yes`; otherwise it's required. Follow [connector-reference.md](./connector-reference.md) instead of deciding per skill.
+## Command-scoped attribution
+
+Apply this prefix only when a Code Apps skill initiates a resolved CLI command:
+
+```bash
+env -u PA_PLUGIN_REPORT_AGENT PA_CLI_ORIGIN="${PA_CLI_ORIGIN-plugin}" $PA app list
+```
+
+Replace `app list` with the required operation and retain its arguments.
+Translate flat-binary operations using the mapping table below.
+For output capture, place the prefix inside the command substitution:
+
+```bash
+apps="$(env -u PA_PLUGIN_REPORT_AGENT PA_CLI_ORIGIN="${PA_CLI_ORIGIN-plugin}" $PA app list --json)"
+```
+
+`env` applies these values only to the CLI child process.
+The `${PA_CLI_ORIGIN-plugin}` expression preserves user values, including an empty value.
+Removing an inherited plugin report lets the CLI detect the current AI tool.
+Do not manually select an agent label or set passive detection markers.
+Do not use this prefix for user-authored commands or non-CLI tools.
+Do not export these variables into the parent shell.
+Use Bash for these examples, as with the existing `$PA` resolution contract.
+If Bash is unavailable, run the CLI without attribution rather than modify a shared
+PowerShell environment or block the requested operation.
+
---
## Command mapping table (grouped `pa` ↔ flat `power-apps`)
diff --git a/plugins/code-apps/shared/shared-instructions.md b/plugins/code-apps/shared/shared-instructions.md
index f6ff4bc35..6c21319cd 100644
--- a/plugins/code-apps/shared/shared-instructions.md
+++ b/plugins/code-apps/shared/shared-instructions.md
@@ -16,6 +16,15 @@ Run at the start of every skill execution (at most once per day). Notifies the u
## Safety Guardrails
+### Command-scoped CLI attribution
+
+The plugin must not register global pre-tool hooks or intercept user commands.
+Apply attribution only to Power Apps CLI commands initiated by these skills.
+Follow [command-scoped attribution](./cli-binary.md#command-scoped-attribution).
+Do not export attribution into the parent shell or change user settings.
+Do not attribute Node checks, package installs, Git commands, builds, or other tools.
+The CLI detects the AI tool from its environment. Never guess or inject agent markers.
+
### MUST (required before acting)
- **Confirm before any deployment**: Before running `pa app push` (deploy), ask: _"Ready to deploy to [environment name]? This will update the live app."_ Wait for explicit user confirmation.
@@ -165,10 +174,10 @@ The CLI has shipped two binaries — grouped `pa` (preferred) and flat `power-ap
## 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.
+Apply [command-scoped attribution](./cli-binary.md#command-scoped-attribution)
+only to CLI commands initiated by these skills. Do not register tool hooks.
+The CLI retains its existing telemetry consent and `cliSource` common property.
+The plugin does not send a separate telemetry stream.
The Power Apps code app CLI (`@microsoft/power-apps-cli`) is installed into each project as a dev dependency (the Vite template doesn't include it; see [cli-binary.md](./cli-binary.md)). **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.**
diff --git a/scripts/tests/hook-command-quoting.test.cjs b/scripts/tests/hook-command-quoting.test.cjs
index 66b4851df..480e0c5d9 100644
--- a/scripts/tests/hook-command-quoting.test.cjs
+++ b/scripts/tests/hook-command-quoting.test.cjs
@@ -10,11 +10,10 @@ const PLUGINS = [
{
name: 'code-apps',
manifests: [
- { file: 'plugins/code-apps/hooks.json', files: ['set-cli-origin.js'] },
- { file: 'plugins/code-apps/hooks/hooks.json', files: ['set-cli-origin.js'] },
- { file: 'plugins/code-apps/com.github.copilot/hooks/hooks.json', files: ['set-cli-origin.js'] },
+ { file: 'plugins/code-apps/hooks.json', files: [] },
+ { file: 'plugins/code-apps/hooks/hooks.json', files: [] },
+ { file: 'plugins/code-apps/com.github.copilot/hooks/hooks.json', files: [] },
],
- bestEffortFiles: ['set-cli-origin.js'],
},
{
name: 'mobile-apps',
diff --git a/scripts/validate-code-apps.js b/scripts/validate-code-apps.js
index 29ba987f6..fc82e881d 100644
--- a/scripts/validate-code-apps.js
+++ b/scripts/validate-code-apps.js
@@ -61,6 +61,10 @@ function validate() {
JSON.parse(readPackageFile(path.join(PLUGIN, 'com.github.copilot', 'hooks', 'hooks.json'))),
JSON.parse(readPackageFile(path.join(PLUGIN, 'hooks.json'))),
'portable Copilot hooks must preserve the existing native hook configuration');
+ for (const file of ['hooks.json', 'hooks/hooks.json', 'com.github.copilot/hooks/hooks.json']) {
+ assert.deepEqual(JSON.parse(readPackageFile(path.join(PLUGIN, file))).hooks, {},
+ 'Code Apps must not intercept unrelated tool calls');
+ }
function checkResources(directory) {
assert.ok(fs.lstatSync(directory).isDirectory(), `${directory} must be a regular directory`);