diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 105a81b..4c7282d 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -13,7 +13,7 @@ "name": "microsoft-managed-apps", "source": "./plugins/microsoft-managed-apps", "description": "[Preview] Create and manage Microsoft Managed Apps using the @microsoft/managed-apps-cli (ms) toolchain.", - "version": "2.1.7" + "version": "2.1.8" } ] } diff --git a/plugins/microsoft-managed-apps/.claude-plugin/plugin.json b/plugins/microsoft-managed-apps/.claude-plugin/plugin.json index a78891d..1d8aa1d 100644 --- a/plugins/microsoft-managed-apps/.claude-plugin/plugin.json +++ b/plugins/microsoft-managed-apps/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "microsoft-managed-apps", - "version": "2.1.7", + "version": "2.1.8", "description": "[Preview] Create and manage Microsoft Managed Apps using the @microsoft/managed-apps-cli (ms) toolchain.", "author": { "name": "Microsoft", diff --git a/plugins/microsoft-managed-apps/AGENTS.md b/plugins/microsoft-managed-apps/AGENTS.md index 03bf68c..d369cf7 100644 --- a/plugins/microsoft-managed-apps/AGENTS.md +++ b/plugins/microsoft-managed-apps/AGENTS.md @@ -159,6 +159,9 @@ Claude and legacy Copilot discover `hooks/hooks.json`. Agent Plugins Copilot discovers `com.github.copilot/hooks/hooks.json`. The latter uses native Copilot events, `${PLUGIN_ROOT}`, and the same scripts. Validation checks both configurations for equivalent scripts, matchers, and timeouts. +Only the native Copilot entry point passes `--github-copilot` / `-GitHubCopilot` to report `MS_PLUGIN_REPORT_AGENT=github-copilot`. +Shared hooks must remove inherited reports. Do not detect the host from environment markers or shell type. +Keep the agent report independent of `MS_CLI_ORIGIN=plugin` and user-provided origin overrides. Keep both hook payload contracts when editing a script. The canonical manifest follows [Agent Plugins 1.0.0](https://agent-plugins.org/specification). diff --git a/plugins/microsoft-managed-apps/QUICKSTART.md b/plugins/microsoft-managed-apps/QUICKSTART.md index 459c89a..1576e73 100644 --- a/plugins/microsoft-managed-apps/QUICKSTART.md +++ b/plugins/microsoft-managed-apps/QUICKSTART.md @@ -113,7 +113,12 @@ After the first `ms app create`, the project folder gets a `memory-bank.md`. Ope ### Telemetry -The plugin tags the `ms` CLI commands it runs (via an `MS_CLI_ORIGIN` attribution prefix) so usage can be attributed to this plugin. It adds no new data collection and you can opt out by setting `MS_CLI_ORIGIN` yourself. See the [Telemetry section in the README](./README.md#telemetry) for details. +The plugin defaults `MS_CLI_ORIGIN` to `plugin` for commands that invoke `ms`. +It preserves existing origin values. +The native Copilot hook separately sets `MS_PLUGIN_REPORT_AGENT=github-copilot`. +Shared hooks remove inherited agent reports. +An origin override does not disable telemetry. +See the [Telemetry section in the README](./README.md#telemetry) for details. ### Uninstall diff --git a/plugins/microsoft-managed-apps/README.md b/plugins/microsoft-managed-apps/README.md index 4d0e959..4246bba 100644 --- a/plugins/microsoft-managed-apps/README.md +++ b/plugins/microsoft-managed-apps/README.md @@ -83,7 +83,8 @@ To evaluate a local checkout containing these changes: **Compatibility status:** the portable package does not establish full Codex runtime support. Skills use document-relative links to shared resources. They do not require `${CLAUDE_PLUGIN_ROOT}`. The package does not provide a Codex architect agent or Codex hooks. -Shared instructions request `plugin/codex` attribution while preserving an existing `MS_CLI_ORIGIN` value. +Shared instructions request `MS_CLI_ORIGIN=plugin` while preserving an existing value. +They do not set `MS_PLUGIN_REPORT_AGENT` because the shared instructions do not identify the host. This attribution depends on the agent following instructions, not hook enforcement. Complete the client checks below before using workflows that change resources. @@ -219,6 +220,8 @@ Run the client's enable/disable actions and confirm that the same components ret For each supported Claude and Copilot runtime, run `ms --version` through a shell tool. Capture the rewritten command or CLI attribution evidence. Repeat with `MS_CLI_ORIGIN=review/custom` already set and confirm that the hook preserves it. +Check that the native Copilot entry point also sets `MS_PLUGIN_REPORT_AGENT=github-copilot`. +Check that shared hooks remove inherited reports, even when agent environment markers exist. Check session-start guidance and the daily version-check instructions. Run `/create-app` and a representative `/add-*` only in an authorized test environment. For Codex, verify the documented instruction-based attribution instead of expecting a hook. @@ -234,14 +237,41 @@ Describe the app in the command and the skill generates its name, plans the comp ## Telemetry -This plugin sets an attribution tag on the `@microsoft/managed-apps-cli` (`ms`) commands it runs. A `PreToolUse` hook (`hooks/pre-tool-use.sh` / `.ps1`) transparently prefixes every shell command that invokes `ms` with `MS_CLI_ORIGIN=plugin/` (e.g. `plugin/claude-code`, `plugin/copilot-cli`). This tells the CLI's telemetry that the invocation originated from this plugin — it does **not** add any new data collection beyond what the `ms` CLI already reports, and it never blocks or alters the behavior of your command. +This plugin marks commands that invoke `@microsoft/managed-apps-cli` (`ms`) with `MS_CLI_ORIGIN=plugin`. +The CLI uses this value as `cliSource`, the source of the command. +The [Bash hook](hooks/pre-tool-use.sh) and [PowerShell hook](hooks/pre-tool-use.ps1) apply this default before tool execution. +They preserve existing origin values, including empty values and inline assignments. +They leave non-`ms` commands unchanged and do not transmit telemetry themselves. -- **What it does:** tags `ms` CLI runs so usage can be attributed to this plugin. -- **What it does not do:** it does not run for non-`ms` commands, and it does not transmit anything itself. -- **Opting out:** set `MS_CLI_ORIGIN` yourself (in your shell environment or inline on the command) and the hook leaves your value untouched. You can also disable the hook by removing/editing `hooks/hooks.json`, or refer to the `ms` CLI documentation for its own telemetry controls. +Agent identity is separate from command origin. +Only a known host-specific entry point supplies `MS_PLUGIN_REPORT_AGENT`. +The plugin does not inspect agent environment markers. -For Agent Plugins Copilot, the hook configuration is `com.github.copilot/hooks/hooks.json`. -Disable hooks in the client's settings rather than editing only the legacy configuration. +| Entry point within this plugin | Agent report | +| --- | --- | +| [com.github.copilot/hooks/hooks.json](com.github.copilot/hooks/hooks.json) | Fixed `github-copilot`, selected by the hook argument `--github-copilot` or `-GitHubCopilot`. | +| [hooks/hooks.json](hooks/hooks.json), shared by Claude Code and legacy Copilot | Omitted. This configuration does not identify one host. | +| Shared skills, including Codex and Cursor consumers | Omitted. No host-specific reporting hook exists. | + +The native report identifies Copilot without claiming CLI or VS Code. +It replaces an inherited report and remains independent of any origin override. +Shared hooks remove inherited reports before the command executes. +They remove the variable rather than set an empty value, so stale reports cannot bypass CLI detection. +The `.claude-plugin` directory and shell type do not identify the host. + +The CLI treats a supplied report as authoritative. +A recognized report determines the agent name without environment-marker detection. +An empty or unrecognized report produces `unknown` without fallback detection. +Only an absent report allows the CLI to detect the agent from environment markers. +This change does not add model detection or a CLI agent-selection option. + +Older CLI versions receive `plugin` instead of `plugin/` and ignore the new report. +Release CLI support for the separate report before this plugin when continuous agent attribution is required. + +To override the origin, set `MS_CLI_ORIGIN` in your shell environment or inline on the command. +An origin override is not a telemetry opt-out. +Use the CLI's telemetry controls to disable telemetry. +To disable hooks, use the client's settings rather than editing only the shared hook configuration. ## Uninstall diff --git a/plugins/microsoft-managed-apps/com.github.copilot/hooks/hooks.json b/plugins/microsoft-managed-apps/com.github.copilot/hooks/hooks.json index f0eaba2..a680b6a 100644 --- a/plugins/microsoft-managed-apps/com.github.copilot/hooks/hooks.json +++ b/plugins/microsoft-managed-apps/com.github.copilot/hooks/hooks.json @@ -6,7 +6,6 @@ "type": "command", "bash": "bash \"${PLUGIN_ROOT}/hooks/session-start.sh\"", "powershell": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}/hooks/session-start.ps1\"", - "env": { "COPILOT_CLI": "1" }, "timeoutSec": 5 } ], @@ -14,9 +13,8 @@ { "type": "command", "matcher": "Bash|bash|shell|sh|execute|execute_command|run_in_terminal|terminal|powershell|PowerShell|pwsh", - "bash": "bash \"${PLUGIN_ROOT}/hooks/pre-tool-use.sh\"", - "powershell": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}/hooks/pre-tool-use.ps1\"", - "env": { "COPILOT_CLI": "1" }, + "bash": "bash \"${PLUGIN_ROOT}/hooks/pre-tool-use.sh\" --github-copilot", + "powershell": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}/hooks/pre-tool-use.ps1\" -GitHubCopilot", "timeoutSec": 5 } ] diff --git a/plugins/microsoft-managed-apps/hooks/pre-tool-use.ps1 b/plugins/microsoft-managed-apps/hooks/pre-tool-use.ps1 index 2be0f09..8769f4a 100644 --- a/plugins/microsoft-managed-apps/hooks/pre-tool-use.ps1 +++ b/plugins/microsoft-managed-apps/hooks/pre-tool-use.ps1 @@ -1,12 +1,12 @@ # PreToolUse hook (PowerShell): for any shell command that invokes the `ms` -# CLI (the @microsoft/managed-apps-cli binary), default MS_CLI_ORIGIN to -# `plugin/` (e.g. plugin/claude-code, plugin/copilot-cli, or -# plugin/unknown) for that invocation. Every CLI command run by this plugin -# or any of its skills is thereby attributed for telemetry. +# CLI (the @microsoft/managed-apps-cli binary), default MS_CLI_ORIGIN to `plugin`. +# Only the native Copilot entry point passes -GitHubCopilot to report +# MS_PLUGIN_REPORT_AGENT=github-copilot. Shared hooks remove inherited reports. # # Behavior: # - If the command does not invoke `ms`, allow unchanged. -# - If the command already sets MS_CLI_ORIGIN inline, allow unchanged. +# - Preserve inline MS_CLI_ORIGIN assignments. A native agent report +# remains independent of the origin override. # - Otherwise, rewrite the command via hookSpecificOutput.updatedInput # (Claude) and modifiedArgs (Copilot). The # rewrite defaults MS_CLI_ORIGIN only when it is truly unset @@ -18,21 +18,11 @@ # The hook never blocks; any failure falls through to the unchanged "allow" # decision (telemetry attribution must never block a developer's workflow). +param([switch]$GitHubCopilot) + $ErrorActionPreference = 'Stop' -$PLUGIN_ID = 'plugin' - -# Detect the host agent so telemetry can split plugin attribution by which -# CLI ran the command. Falls back to "unknown" rather than dropping the -# suffix so the format (plugin/host) is stable for downstream parsers. -if ($env:CLAUDECODE -eq '1' -or $env:CLAUDE_CODE_ENTRYPOINT) { - $HOST_AGENT = 'claude-code' -} elseif ($env:COPILOT_CLI -eq '1' -or $env:COPILOT_AGENT_SESSION_ID) { - $HOST_AGENT = 'copilot-cli' -} else { - $HOST_AGENT = 'unknown' -} -$ORIGIN_VALUE = "$PLUGIN_ID/$HOST_AGENT" +$ORIGIN_VALUE = 'plugin' $ALLOW_UNCHANGED = '{"permissionDecision":"allow","hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow"}}' function Write-AllowUnchanged { @@ -52,13 +42,13 @@ function Write-AllowWithRewrite { $updated['command'] = $NewCommand $payload = @{ permissionDecision = 'allow' - permissionDecisionReason = 'Auto-set MS_CLI_ORIGIN for @microsoft/managed-apps-cli attribution' + permissionDecisionReason = 'Set plugin attribution for @microsoft/managed-apps-cli' updatedInput = $updated modifiedArgs = $updated hookSpecificOutput = @{ hookEventName = 'PreToolUse' permissionDecision = 'allow' - permissionDecisionReason = 'Auto-set MS_CLI_ORIGIN for @microsoft/managed-apps-cli attribution' + permissionDecisionReason = 'Set plugin attribution for @microsoft/managed-apps-cli' updatedInput = $updated } } @@ -112,13 +102,13 @@ try { $msPattern = '(^|[;&|()\n\r])\s*([A-Za-z_][A-Za-z0-9_]*=\S*\s+)*ms(\s+\S|\s*$)' if ($command -notmatch $msPattern) { Write-AllowUnchanged } - # Already explicitly set in the command itself? Don't touch. The boundary + # Preserve explicit origin assignments. The boundary # mirrors $msPattern (start-of-command or a real chain separator, plus any # leading env-prefix assignments) so inline assignments — including ones # that follow other env prefixes like `FOO=bar MS_CLI_ORIGIN=mine ms ...` # — are recognized too. $inlinePattern = '(^|[;&|()\n\r])\s*([A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(export\s+MS_CLI_ORIGIN=|set\s+MS_CLI_ORIGIN=|MS_CLI_ORIGIN=|\$env:MS_CLI_ORIGIN\s*=)' - if ($command -match $inlinePattern) { Write-AllowUnchanged } + $inlineOrigin = $command -match $inlinePattern # Native Copilot payloads identify the actual shell. Legacy payloads # retain the existing platform-based fallback. @@ -127,11 +117,19 @@ try { $isPowerShellTool = $toolName.ToLowerInvariant() -in @('powershell', 'pwsh') } + $prefix = '' if ($isPowerShellTool) { # Assign only when the env var does not exist, so a user-set # $env:MS_CLI_ORIGIN wins at exec time — including an empty value, # which `Test-Path Env:` treats as "set" (unlike `-not $env:...`). - $newCommand = "if (-not (Test-Path Env:MS_CLI_ORIGIN)) { `$env:MS_CLI_ORIGIN = '$ORIGIN_VALUE' }; $command" + if (-not $inlineOrigin) { + $prefix = "if (-not (Test-Path Env:MS_CLI_ORIGIN)) { `$env:MS_CLI_ORIGIN = '$ORIGIN_VALUE' }; " + } + if ($GitHubCopilot) { + $prefix += "`$env:MS_PLUGIN_REPORT_AGENT = 'github-copilot'; " + } else { + $prefix += "`$env:MS_PLUGIN_REPORT_AGENT = `$null; " + } } else { # `${VAR-default}` (no colon) expands to the default ONLY when VAR is # unset, so any pre-existing user value — including an intentionally- @@ -140,10 +138,17 @@ try { # only `$ORIGIN_VALUE` is expanded here. The `&&` chain runs the export # before the user command, and `export` makes the value visible to # chained segments and to the spawned `ms` process. - $newCommand = "export MS_CLI_ORIGIN=`"`${MS_CLI_ORIGIN-$ORIGIN_VALUE}`" && $command" + if (-not $inlineOrigin) { + $prefix = "export MS_CLI_ORIGIN=`"`${MS_CLI_ORIGIN-$ORIGIN_VALUE}`" && " + } + if ($GitHubCopilot) { + $prefix += "export MS_PLUGIN_REPORT_AGENT='github-copilot' && " + } else { + $prefix += "unset -v MS_PLUGIN_REPORT_AGENT && " + } } - Write-AllowWithRewrite -NewCommand $newCommand -OriginalInput $inputHash + Write-AllowWithRewrite -NewCommand ($prefix + $command) -OriginalInput $inputHash } catch { # Any unexpected failure: fall through to allow-unchanged so we never # block the user's command. diff --git a/plugins/microsoft-managed-apps/hooks/pre-tool-use.sh b/plugins/microsoft-managed-apps/hooks/pre-tool-use.sh index 13f5d79..2ce7def 100644 --- a/plugins/microsoft-managed-apps/hooks/pre-tool-use.sh +++ b/plugins/microsoft-managed-apps/hooks/pre-tool-use.sh @@ -1,14 +1,13 @@ #!/usr/bin/env bash # PreToolUse hook: for any shell command that invokes the `ms` CLI (the -# @microsoft/managed-apps-cli binary), default MS_CLI_ORIGIN to -# `plugin/` (e.g. plugin/claude-code, plugin/copilot-cli, or -# plugin/unknown) for that invocation so every CLI call made by this plugin -# (or any of its skills) is attributed for telemetry purposes. +# @microsoft/managed-apps-cli binary), default MS_CLI_ORIGIN to `plugin`. +# Only the native Copilot entry point passes --github-copilot to report +# MS_PLUGIN_REPORT_AGENT=github-copilot. Shared hooks remove inherited reports. # # Behavior: # - If the command does not invoke `ms`, allow unchanged. -# - If the command already sets MS_CLI_ORIGIN= inline (env-prefix, `set`, -# or `$env:`), allow unchanged. +# - Preserve inline MS_CLI_ORIGIN assignments. A native agent report +# remains independent of the origin override. # - Otherwise, rewrite the command via hookSpecificOutput.updatedInput # (Claude) and modifiedArgs (Copilot). The # rewrite defaults MS_CLI_ORIGIN only when it is truly unset @@ -46,7 +45,7 @@ else exit 0 fi -# Single-pass python: parse, detect, decide, emit. Uses stdin for the JSON +# Single-pass python: parse, rewrite, emit. Uses stdin for the JSON # (no argv size limit) and emits exactly one JSON object on stdout. Any # uncaught exception falls through to the bash-level fallback below. PYTHON_SCRIPT=$(cat <<'PY' @@ -56,19 +55,8 @@ ALLOW_UNCHANGED = json.dumps({ "permissionDecision": "allow", "hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "allow"}, }) -PLUGIN_ID = "plugin" - -# Detect the host agent so telemetry can split plugin attribution by which -# CLI ran the command. Falls back to "unknown" rather than dropping the -# suffix so the format (plugin/host) is stable for downstream parsers. -import os -if os.environ.get("CLAUDECODE") == "1" or os.environ.get("CLAUDE_CODE_ENTRYPOINT"): - HOST = "claude-code" -elif os.environ.get("COPILOT_CLI") == "1" or os.environ.get("COPILOT_AGENT_SESSION_ID"): - HOST = "copilot-cli" -else: - HOST = "unknown" -ORIGIN_VALUE = PLUGIN_ID + "/" + HOST +ORIGIN_VALUE = "plugin" +github_copilot = sys.argv[1:] == ["--github-copilot"] def emit_allow(): print(ALLOW_UNCHANGED) @@ -111,7 +99,7 @@ ms_pattern = re.compile( if not ms_pattern.search(command): emit_allow() -# Already explicitly set in the command itself? Don't touch. The boundary +# Preserve explicit origin assignments. The boundary # mirrors ms_pattern (start-of-command or a real chain separator, plus any # leading env-prefix assignments) so inline assignments — including ones that # follow other env prefixes like `FOO=bar MS_CLI_ORIGIN=mine ms ...` — are @@ -119,36 +107,40 @@ if not ms_pattern.search(command): inline_pattern = re.compile( r"(?:^|[;&|()\n\r])\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:export\s+MS_CLI_ORIGIN=|set\s+MS_CLI_ORIGIN=|MS_CLI_ORIGIN=|\$env:MS_CLI_ORIGIN\s*=)" ) -if inline_pattern.search(command): - emit_allow() +inline_origin = bool(inline_pattern.search(command)) is_powershell = tool_name.lower() in ("powershell", "pwsh") +prefix = "" if is_powershell: # PowerShell: assign only when the env var does not exist, so a user-set # $env:MS_CLI_ORIGIN wins at exec time — including an empty value, which # `Test-Path Env:` correctly treats as "set" (unlike `-not $env:...`). - new_command = ( - "if (-not (Test-Path Env:MS_CLI_ORIGIN)) { $env:MS_CLI_ORIGIN = '" - + ORIGIN_VALUE - + "' }; " - + command - ) + if not inline_origin: + prefix = ( + "if (-not (Test-Path Env:MS_CLI_ORIGIN)) { $env:MS_CLI_ORIGIN = '" + + ORIGIN_VALUE + + "' }; " + ) + if github_copilot: + prefix += "$env:MS_PLUGIN_REPORT_AGENT = 'github-copilot'; " + else: + prefix += "$env:MS_PLUGIN_REPORT_AGENT = $null; " else: # Bash: ${VAR-default} (no colon) expands to the default ONLY when VAR is # unset, so any pre-existing user value — including an intentionally-empty # one — is preserved at exec time. The `&&` chain ensures the export runs # before the user command, and `export` makes the value visible to chained # segments (`cd app && ms app deploy`) and to the spawned `ms` process. - new_command = ( - 'export MS_CLI_ORIGIN="${MS_CLI_ORIGIN-' - + ORIGIN_VALUE - + '}" && ' - + command - ) + if not inline_origin: + prefix = 'export MS_CLI_ORIGIN="${MS_CLI_ORIGIN-' + ORIGIN_VALUE + '}" && ' + if github_copilot: + prefix += "export MS_PLUGIN_REPORT_AGENT='github-copilot' && " + else: + prefix += "unset -v MS_PLUGIN_REPORT_AGENT && " updated = dict(tool_input) -updated["command"] = new_command -reason = "Auto-set MS_CLI_ORIGIN for @microsoft/managed-apps-cli attribution" +updated["command"] = prefix + command +reason = "Set plugin attribution for @microsoft/managed-apps-cli" # Keep legacy fields, native Copilot modifiedArgs, and the Claude wrapper. print(json.dumps({ "permissionDecision": "allow", @@ -165,7 +157,7 @@ print(json.dumps({ PY ) -OUTPUT=$(printf '%s' "$INPUT_JSON" | $PYTHON_BIN -c "$PYTHON_SCRIPT" 2>/dev/null) +OUTPUT=$(printf '%s' "$INPUT_JSON" | $PYTHON_BIN -c "$PYTHON_SCRIPT" "$@" 2>/dev/null) if [ -z "$OUTPUT" ]; then printf '%s\n' "$ALLOW_UNCHANGED" else diff --git a/plugins/microsoft-managed-apps/hooks/session-start.ps1 b/plugins/microsoft-managed-apps/hooks/session-start.ps1 index 2942008..260ade5 100644 --- a/plugins/microsoft-managed-apps/hooks/session-start.ps1 +++ b/plugins/microsoft-managed-apps/hooks/session-start.ps1 @@ -3,7 +3,7 @@ # MS_CLI_ORIGIN. The PreToolUse hook enforces this transparently. $ErrorActionPreference = 'SilentlyContinue' -$msg = "[microsoft-managed-apps] CLI attribution is enforced automatically: every shell command that invokes 'ms' (the @microsoft/managed-apps-cli binary) is rewritten by a PreToolUse hook to set MS_CLI_ORIGIN=plugin/ (e.g. plugin/claude-code, plugin/copilot-cli, or plugin/unknown). You do not need to export this variable yourself - the hook handles it on every tool call. If a user has already set MS_CLI_ORIGIN to a different value, the hook leaves their value alone." +$msg = "[microsoft-managed-apps] The PreToolUse hook defaults MS_CLI_ORIGIN to plugin for commands that invoke the ms CLI (@microsoft/managed-apps-cli). It preserves existing origin values, including empty values and inline assignments. The native Copilot hook also sets MS_PLUGIN_REPORT_AGENT=github-copilot from its fixed entry point. Shared hooks remove inherited agent reports so the CLI can detect the agent. The plugin does not detect agents from environment markers. Do not add attribution variables yourself when hooks are active." # Skip re-emitting on compaction so the guidance isn't duplicated. try { diff --git a/plugins/microsoft-managed-apps/hooks/session-start.sh b/plugins/microsoft-managed-apps/hooks/session-start.sh index b32c7df..0c09abf 100644 --- a/plugins/microsoft-managed-apps/hooks/session-start.sh +++ b/plugins/microsoft-managed-apps/hooks/session-start.sh @@ -5,7 +5,7 @@ # message just makes the behavior visible to the agent so it isn't surprised # when the executed command differs from what it requested. -export MSG="[microsoft-managed-apps] CLI attribution is enforced automatically: every shell command that invokes 'ms' (the @microsoft/managed-apps-cli binary) is rewritten by a PreToolUse hook to set MS_CLI_ORIGIN=plugin/ (e.g. plugin/claude-code, plugin/copilot-cli, or plugin/unknown). You do not need to export this variable yourself - the hook handles it on every tool call. If a user has already set MS_CLI_ORIGIN to a different value, the hook leaves their value alone." +export MSG="[microsoft-managed-apps] The PreToolUse hook defaults MS_CLI_ORIGIN to plugin for commands that invoke the ms CLI (@microsoft/managed-apps-cli). It preserves existing origin values, including empty values and inline assignments. The native Copilot hook also sets MS_PLUGIN_REPORT_AGENT=github-copilot from its fixed entry point. Shared hooks remove inherited agent reports so the CLI can detect the agent. The plugin does not detect agents from environment markers. Do not add attribution variables yourself when hooks are active." # Read hook stdin with a bounded single-line `read -t` (payloads are # single-line JSON) so the hook fails open quickly instead of blocking session @@ -51,4 +51,3 @@ print(json.dumps({ ' exit 0 - diff --git a/plugins/microsoft-managed-apps/plugin.json b/plugins/microsoft-managed-apps/plugin.json index 0053bb7..6aa6426 100644 --- a/plugins/microsoft-managed-apps/plugin.json +++ b/plugins/microsoft-managed-apps/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "microsoft-managed-apps", - "version": "2.1.7", + "version": "2.1.8", "description": "[Preview] Create and manage Microsoft Managed Apps using the @microsoft/managed-apps-cli (ms) toolchain.", "author": { "name": "Microsoft", diff --git a/plugins/microsoft-managed-apps/shared/shared-instructions.md b/plugins/microsoft-managed-apps/shared/shared-instructions.md index e87de35..13f9f38 100644 --- a/plugins/microsoft-managed-apps/shared/shared-instructions.md +++ b/plugins/microsoft-managed-apps/shared/shared-instructions.md @@ -12,18 +12,22 @@ The plugin does not select an AI model. Use the model selected in the client. Claude Code and Copilot use the packaged hooks to set CLI attribution. Do not add another attribution prefix when those hooks are active. -The package does not provide Codex hooks. In Codex, default `MS_CLI_ORIGIN` to `plugin/codex` before an `ms` command. +The package does not provide Codex hooks. In Codex, default `MS_CLI_ORIGIN` to `plugin` before an `ms` command. Preserve any existing value, including an empty value. Use the syntax for the active shell: ```bash -export MS_CLI_ORIGIN="${MS_CLI_ORIGIN-plugin/codex}" +export MS_CLI_ORIGIN="${MS_CLI_ORIGIN-plugin}" +unset -v MS_PLUGIN_REPORT_AGENT ``` ```powershell -if (-not (Test-Path Env:MS_CLI_ORIGIN)) { $env:MS_CLI_ORIGIN = 'plugin/codex' } +if (-not (Test-Path Env:MS_CLI_ORIGIN)) { $env:MS_CLI_ORIGIN = 'plugin' } +$env:MS_PLUGIN_REPORT_AGENT = $null ``` This Codex behavior depends on the agent following these instructions. No hook enforces it. +Do not set `MS_PLUGIN_REPORT_AGENT` from these shared instructions. They do not identify a specific host. +Remove an inherited report so the CLI can detect the agent. --- @@ -303,7 +307,8 @@ The rest of this plugin assumes `ms`. | Variable | Purpose | | ------------------------------------- | ----------------------------------------------------------------------------- | -| `MS_CLI_ORIGIN` | Attribution tag for CLI telemetry. **Defaulted when unset by this plugin's PreToolUse hook to `plugin/`** (e.g. `plugin/claude-code`, `plugin/copilot-cli`, or `plugin/unknown`) on every `ms` invocation — no skill action required. A user-provided value (parent environment or inline) is preserved at exec time (see Session Initialization below). | +| `MS_CLI_ORIGIN` | Command source for CLI telemetry (`cliSource`). The PreToolUse hook defaults it to `plugin`. Existing values, including empty values and inline assignments, take precedence. | +| `MS_PLUGIN_REPORT_AGENT` | Agent report from a known host-specific entry point. The native Copilot hook sets `github-copilot`. Shared hooks remove inherited reports. | Environment targeting is never done via environment variables. `ms app create` resolves an environment automatically; pass `--environment-id ` **only** when the user explicitly provides an environment ID. Do not surface, discover, or construct environment IDs otherwise. @@ -313,7 +318,16 @@ Normal flow: pass no environment flag and let `ms app create` resolve an environ ## Session Initialization -`MS_CLI_ORIGIN=plugin/` (e.g. `plugin/claude-code`, `plugin/copilot-cli`, or `plugin/unknown` when the host can't be detected) is set automatically on every `ms` invocation by the plugin's PreToolUse hook (`hooks/pre-tool-use.sh` / `.ps1`). No skill action required. If the executed command in the shell log has a leading `export MS_CLI_ORIGIN=...` / `$env:MS_CLI_ORIGIN=...` that you didn't write, that's the hook — leave it alone. The hook respects any pre-existing `MS_CLI_ORIGIN` value. +The PreToolUse hook (`hooks/pre-tool-use.sh` / `.ps1`) defaults `MS_CLI_ORIGIN` to `plugin` for commands that invoke `ms`. +Do not add this variable when hooks are active unless the user requests an override. +Do not remove attribution assignments that the hook adds to an executed command. +The hook preserves existing origin values. + +The native Copilot entry point sets `MS_PLUGIN_REPORT_AGENT=github-copilot`, even when the origin has an override. +This fixed report identifies Copilot, not a specific Copilot product. +Shared hooks remove inherited reports so the CLI can detect the agent. +Do not infer a report from environment markers, shell type, or the `.claude-plugin` directory. +The CLI owns agent detection and report validation. ## Shell Compatibility diff --git a/scripts/plugin-hooks.test.mjs b/scripts/plugin-hooks.test.mjs index 927588b..ab7e655 100644 --- a/scripts/plugin-hooks.test.mjs +++ b/scripts/plugin-hooks.test.mjs @@ -13,68 +13,94 @@ const directory = mkdtempSync(join(tmpdir(), 'managed apps hooks ')); cpSync(join(root, 'plugins/microsoft-managed-apps/hooks'), join(directory, 'hooks'), { recursive: true }); test.after(() => rmSync(directory, { recursive: true, force: true })); -function run(name, input, host = 'copilot-cli') { +function run(name, input, native = false, markers = {}) { const env = { ...process.env }; - for (const key of ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'COPILOT_CLI', 'COPILOT_AGENT_SESSION_ID']) delete env[key]; - if (host === 'claude-code') env.CLAUDECODE = '1'; - if (host === 'copilot-cli') env.COPILOT_CLI = '1'; + for (const key of ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'COPILOT_CLI', 'COPILOT_AGENT_SESSION_ID', 'MS_PLUGIN_REPORT_AGENT']) delete env[key]; + Object.assign(env, markers); const script = join(directory, 'hooks', `${name}.${windows ? 'ps1' : 'sh'}`); const args = windows ? ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script] : [script]; + if (native && name === 'pre-tool-use') args.push(windows ? '-GitHubCopilot' : '--github-copilot'); const result = spawnSync(shell, args, { env, input: `${JSON.stringify(input)}\n`, encoding: 'utf8', timeout: 10000 }); assert.ifError(result.error); assert.equal(result.status, 0, result.stderr); return result.stdout.trim() ? JSON.parse(result.stdout) : undefined; } -for (const [host, payload] of [ - ['claude-code', command => ({ tool_name: windows ? 'powershell' : 'Bash', tool_input: { command, description: 'keep me' } })], - ['copilot-cli', command => ({ toolName: shell, toolArgs: { command, description: 'keep me' } })], +for (const [host, native, payload] of [ + ['shared Claude', false, command => ({ tool_name: windows ? 'powershell' : 'Bash', tool_input: { command, description: 'keep me' } })], + ['shared Copilot', false, command => ({ toolName: shell, toolArgs: { command, description: 'keep me' } })], + ['native Copilot', true, command => ({ toolName: shell, toolArgs: { command, description: 'keep me' } })], ]) { test(`${host}: attributes ms commands and preserves other arguments`, () => { - const result = run('pre-tool-use', payload('ms app list --json'), host); - assert.match(result.updatedInput.command, new RegExp(`plugin/${host}`)); - assert.equal(result.updatedInput.description, 'keep me'); - assert.deepEqual(result.modifiedArgs, result.updatedInput); - assert.deepEqual(result.hookSpecificOutput.updatedInput, result.updatedInput); + for (const markers of [ + {}, + { CLAUDECODE: '1', CLAUDE_CODE_ENTRYPOINT: 'cli' }, + { COPILOT_CLI: '1', COPILOT_AGENT_SESSION_ID: 'test' }, + { CLAUDECODE: '1', COPILOT_CLI: '1', MS_PLUGIN_REPORT_AGENT: 'cursor' }, + ]) { + const result = run('pre-tool-use', payload('ms app list --json'), native, markers); + assert.match(result.updatedInput.command, windows ? /MS_CLI_ORIGIN = 'plugin'/ : /MS_CLI_ORIGIN-plugin}/); + assert.doesNotMatch(result.updatedInput.command, /plugin\//); + if (native) assert.match(result.updatedInput.command, /MS_PLUGIN_REPORT_AGENT\s*=\s*'github-copilot'/); + else assert.match(result.updatedInput.command, windows ? /MS_PLUGIN_REPORT_AGENT = \$null/ : /unset -v MS_PLUGIN_REPORT_AGENT/); + assert.equal(result.updatedInput.description, 'keep me'); + assert.deepEqual(result.modifiedArgs, result.updatedInput); + assert.deepEqual(result.hookSpecificOutput.updatedInput, result.updatedInput); + } }); - test(`${host}: leaves non-ms commands and explicit attribution unchanged`, () => { + test(`${host}: leaves non-ms commands and explicit origins unchanged`, () => { const explicit = windows ? "$env:MS_CLI_ORIGIN = 'custom'; ms app list" : 'MS_CLI_ORIGIN=custom ms app list'; - for (const command of ['echo ms app list', 'node --version', explicit]) { - const result = run('pre-tool-use', payload(command), host); + for (const command of ['echo ms app list', 'node --version', 'terms list']) { + const result = run('pre-tool-use', payload(command), native); assert.equal(result.updatedInput, undefined); assert.equal(result.modifiedArgs, undefined); } + const result = run('pre-tool-use', payload(explicit), native); + if (native) { + const prefix = windows ? "$env:MS_PLUGIN_REPORT_AGENT = 'github-copilot'; " : "export MS_PLUGIN_REPORT_AGENT='github-copilot' && "; + assert.equal(result.updatedInput.command, prefix + explicit); + } else { + const prefix = windows ? '$env:MS_PLUGIN_REPORT_AGENT = $null; ' : 'unset -v MS_PLUGIN_REPORT_AGENT && '; + assert.equal(result.updatedInput.command, prefix + explicit); + } }); - test(`${host}: preserves inherited attribution at command execution`, () => { - const rewritten = run('pre-tool-use', payload('ms app list'), host).updatedInput.command; + test(`${host}: preserves origins and applies package reports at command execution`, () => { + const rewritten = run('pre-tool-use', payload('ms app list'), native).updatedInput.command; const probe = windows - ? 'function ms { Write-Output $env:MS_CLI_ORIGIN }; ' - : 'ms() { printf "%s" "$MS_CLI_ORIGIN"; }; '; + ? 'function ms { $report = if (Test-Path Env:MS_PLUGIN_REPORT_AGENT) { $env:MS_PLUGIN_REPORT_AGENT } else { "" }; Write-Output "$env:MS_CLI_ORIGIN|$report" }; ' + : 'ms() { printf "%s|%s" "$MS_CLI_ORIGIN" "${MS_PLUGIN_REPORT_AGENT-}"; }; '; for (const origin of [undefined, 'custom', '']) { // Windows PowerShell 5.1 removes empty environment variables. if (windows && origin === '') continue; - const env = { ...process.env }; - if (origin === undefined) delete env.MS_CLI_ORIGIN; - else env.MS_CLI_ORIGIN = origin; - const args = windows ? ['-NoProfile', '-Command', probe + rewritten] : ['-c', probe + rewritten]; - const result = spawnSync(shell, args, { env, encoding: 'utf8', timeout: 10000 }); - assert.ifError(result.error); - assert.equal(result.status, 0, result.stderr); - assert.equal(result.stdout.trim(), origin === undefined ? `plugin/${host}` : origin); + for (const report of [undefined, 'cursor', '']) { + const env = { ...process.env }; + if (origin === undefined) delete env.MS_CLI_ORIGIN; + else env.MS_CLI_ORIGIN = origin; + if (report === undefined) delete env.MS_PLUGIN_REPORT_AGENT; + else env.MS_PLUGIN_REPORT_AGENT = report; + const args = windows ? ['-NoProfile', '-Command', probe + rewritten] : ['-c', probe + rewritten]; + const result = spawnSync(shell, args, { env, encoding: 'utf8', timeout: 10000 }); + assert.ifError(result.error); + assert.equal(result.status, 0, result.stderr); + assert.equal(result.stdout.trim(), `${origin ?? 'plugin'}|${native ? 'github-copilot' : ''}`); + } } }); } test('Copilot native bash input receives bash syntax even on Windows', () => { - const result = run('pre-tool-use', { toolName: 'bash', toolArgs: { command: 'ms app list' } }); + const result = run('pre-tool-use', { toolName: 'bash', toolArgs: { command: 'ms app list' } }, true); assert.match(result.modifiedArgs.command, /^export MS_CLI_ORIGIN=/); + assert.match(result.modifiedArgs.command, /export MS_PLUGIN_REPORT_AGENT='github-copilot' && ms app list$/); }); test('session guidance supports both clients and skips compaction', () => { const result = run('session-start', { source: 'startup' }); assert.match(result.additionalContext, /MS_CLI_ORIGIN/); + assert.match(result.additionalContext, /MS_PLUGIN_REPORT_AGENT=github-copilot/); + assert.doesNotMatch(result.additionalContext, /plugin\//); assert.equal(result.hookSpecificOutput.additionalContext, result.additionalContext); assert.equal(run('session-start', { source: 'compact' }), undefined); }); diff --git a/scripts/validate-plugin-compatibility.mjs b/scripts/validate-plugin-compatibility.mjs index f977848..36c4ad1 100644 --- a/scripts/validate-plugin-compatibility.mjs +++ b/scripts/validate-plugin-compatibility.mjs @@ -61,9 +61,8 @@ function validateComponents(directory) { return { type: hook.type, ...(event === 'PreToolUse' ? { matcher: group.matcher } : {}), - bash: hook.bash.replaceAll('${CLAUDE_PLUGIN_ROOT}', '${PLUGIN_ROOT}'), - powershell: hook.powershell.replaceAll('${CLAUDE_PLUGIN_ROOT}', '${PLUGIN_ROOT}'), - env: { COPILOT_CLI: '1' }, + bash: hook.bash.replaceAll('${CLAUDE_PLUGIN_ROOT}', '${PLUGIN_ROOT}') + (event === 'PreToolUse' ? ' --github-copilot' : ''), + powershell: hook.powershell.replaceAll('${CLAUDE_PLUGIN_ROOT}', '${PLUGIN_ROOT}') + (event === 'PreToolUse' ? ' -GitHubCopilot' : ''), timeoutSec: hook.timeoutSec, }; }); @@ -71,7 +70,7 @@ function validateComponents(directory) { } const copilot = readJson(directory, `${pluginPath}/com.github.copilot/hooks/hooks.json`); assert.deepEqual(copilot, { version: 1, hooks }, - 'Copilot hooks must match the legacy scripts, matchers, and timeouts with native root paths'); + 'Copilot hooks must match the shared scripts with native root paths and fixed agent-report arguments'); for (const base of ['skills', 'shared', 'agents', 'com.github.copilot/agents']) { const visit = folder => { diff --git a/scripts/validate-plugin-compatibility.test.mjs b/scripts/validate-plugin-compatibility.test.mjs index 1845c5b..025065d 100644 --- a/scripts/validate-plugin-compatibility.test.mjs +++ b/scripts/validate-plugin-compatibility.test.mjs @@ -121,10 +121,16 @@ test('rejects Copilot agent drift', t => { }); test('rejects Copilot hook drift', t => { - const directory = fixture(t); - edit(directory, 'plugins/microsoft-managed-apps/com.github.copilot/hooks/hooks.json', - value => { value.hooks.preToolUse[0].bash = 'wrong'; }); - assert.throws(() => validate(directory), /Copilot hooks must match/); + for (const change of [ + value => { value.hooks.preToolUse[0].bash = 'wrong'; }, + value => { value.hooks.preToolUse[0].bash = value.hooks.preToolUse[0].bash.replace(' --github-copilot', ''); }, + value => { value.hooks.preToolUse[0].powershell = value.hooks.preToolUse[0].powershell.replace(' -GitHubCopilot', ''); }, + value => { value.hooks.preToolUse[0].env = { COPILOT_CLI: '1' }; }, + ]) { + const directory = fixture(t); + edit(directory, 'plugins/microsoft-managed-apps/com.github.copilot/hooks/hooks.json', change); + assert.throws(() => validate(directory), /Copilot hooks must match/); + } }); test('rejects missing hook scripts', t => {